code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
var fb = "https://glaring-fire-5349.firebaseio.com";
var TodoCheck = React.createClass({displayName: "TodoCheck",
getInitialState: function() {
this.checked = false;
return {checked: this.checked};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/checked");
// Update the checked state when it changes.
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
this.checked = snap.val();
this.setState({
checked: this.checked
});
this.props.todo.setDone(this.checked);
} else {
this.ref.set(false);
this.props.todo.setDone(false);
}
}.bind(this));
},
toggleCheck: function(event) {
this.ref.set(!this.checked);
event.preventDefault();
},
render: function() {
return (
React.createElement("a", {
onClick: this.toggleCheck,
href: "#",
className: "pull-left todo-check"},
React.createElement("span", {
className: "todo-check-mark glyphicon glyphicon-ok",
"aria-hidden": "true"}
)
)
);
},
});
var TodoText = React.createClass({displayName: "TodoText",
componentWillUnmount: function() {
this.ref.off();
$("#" + this.props.todoKey + "-text").off('blur');
},
setText: function(text) {
this.text = text;
this.props.todo.setHasText(!!text);
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/text");
// Update the todo's text when it changes.
this.setText("");
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
$("#" + this.props.todoKey + "-text").text(snap.val());
this.setText(snap.val());
} else {
this.ref.set("");
}
}.bind(this));
},
onTextBlur: function(event) {
this.ref.set($(event.target).text());
},
render: function() {
setTimeout(function() {
$("#" + this.props.todoKey + "-text").text(this.text);
}.bind(this), 0);
return (
React.createElement("span", {
id: this.props.todoKey + "-text",
onBlur: this.onTextBlur,
contentEditable: "plaintext-only",
"data-ph": "Todo",
className: "todo-text"}
)
);
},
});
var TodoDelete = React.createClass({displayName: "TodoDelete",
getInitialState: function() {
return {};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/deleted");
},
onClick: function() {
this.ref.set(true);
},
render: function() {
if (this.props.isLast) {
return null;
}
return (
React.createElement("button", {
onClick: this.onClick, type: "button",
className: "close", "aria-label": "Close"},
React.createElement("span", {
"aria-hidden": "true",
dangerouslySetInnerHTML: {__html: '×'}})
)
);
},
});
var Todo = React.createClass({displayName: "Todo",
getInitialState: function() {
return {};
},
setDone: function(done) {
this.setState({
done: done
});
},
setHasText: function(hasText) {
this.setState({
hasText: hasText
});
},
render: function() {
var doneClass = this.state.done ? "todo-done" : "todo-not-done";
return (
React.createElement("li", {
id: this.props.todoKey,
className: "list-group-item todo " + doneClass},
React.createElement(TodoCheck, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoText, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoDelete, {isLast: false, todoKey: this.props.todoKey})
)
);
}
});
var TodoList = React.createClass({displayName: "TodoList",
getInitialState: function() {
this.todos = [];
return {todos: this.todos};
},
componentWillMount: function() {
this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/");
// Add an empty todo if none currently exist.
this.ref.on("value", function(snap) {
if (snap.val() === null) {
this.ref.push({
text: "",
});
return;
}
// Add a new todo if no undeleted ones exist.
var returnedTrue = snap.forEach(function(data) {
if (!data.val().deleted) {
return true;
}
});
if (!returnedTrue) {
this.ref.push({
text: "",
});
return;
}
}.bind(this));
// Add an added child to this.todos.
this.ref.on("child_added", function(childSnap) {
this.todos.push({
k: childSnap.key(),
val: childSnap.val()
});
this.replaceState({
todos: this.todos
});
}.bind(this));
this.ref.on("child_removed", function(childSnap) {
var key = childSnap.key();
var i;
for (i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
break;
}
}
this.todos.splice(i, 1);
this.replaceState({
todos: this.todos,
});
}.bind(this));
this.ref.on("child_changed", function(childSnap) {
var key = childSnap.key();
for (var i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
this.todos[i].val = childSnap.val();
this.replaceState({
todos: this.todos,
});
break;
}
}
}.bind(this));
},
componentWillUnmount: function() {
this.ref.off();
},
render: function() {
console.log(this.todos);
var todos = this.state.todos.map(function (todo) {
if (todo.val.deleted) {
return null;
}
return (
React.createElement(Todo, {todoKey: todo.k})
);
}).filter(function(todo) { return todo !== null; });
console.log(todos);
return (
React.createElement("div", null,
React.createElement("h1", {id: "list_title"}, this.props.title),
React.createElement("ul", {id: "todo-list", className: "list-group"},
todos
)
)
);
}
});
var ListPage = React.createClass({displayName: "ListPage",
render: function() {
return (
React.createElement("div", null,
React.createElement("div", {id: "list_page"},
React.createElement("a", {
onClick: this.props.app.navOnClick({page: "LISTS"}),
href: "/#/lists",
id: "lists_link",
className: "btn btn-primary"},
"Back to Lists"
)
),
React.createElement("div", {className: "page-header"},
this.props.children
)
)
);
}
});
var Nav = React.createClass({displayName: "Nav",
render: function() {
return (
React.createElement("nav", {className: "navbar navbar-default navbar-static-top"},
React.createElement("div", {className: "container"},
React.createElement("div", {className: "navbar-header"},
React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), className: "navbar-brand", href: "/#/lists"}, "Firebase Todo")
),
React.createElement("ul", {className: "nav navbar-nav"},
React.createElement("li", null, React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), href: "/#/lists"}, "Lists"))
)
)
)
);
},
});
var App = React.createClass({displayName: "App",
getInitialState: function() {
var state = this.getState();
this.setHistory(state, true);
return this.getState();
},
setHistory: function(state, replace) {
// Don't bother pushing a history entry if the latest state is
// the same.
if (_.isEqual(state, this.state)) {
return;
}
var histFunc = replace ?
history.replaceState.bind(history) :
history.pushState.bind(history);
if (state.page === "LIST") {
histFunc(state, "", "#/list/" + state.todoListKey);
} else if (state.page === "LISTS") {
histFunc(state, "", "#/lists");
} else {
console.log("Unknown page: " + state.page);
}
},
getState: function() {
var url = document.location.toString();
if (url.match(/#/)) {
var path = url.split("#")[1];
var res = path.match(/\/list\/([^\/]*)$/);
if (res) {
return {
page: "LIST",
todoListKey: res[1],
};
}
res = path.match(/lists$/);
if (res) {
return {
page: "LISTS"
}
}
}
return {
page: "LISTS"
}
},
componentWillMount: function() {
// Register history listeners.
var app = this;
window.onpopstate = function(event) {
app.replaceState(event.state);
};
},
navOnClick: function(state) {
return function(event) {
this.setHistory(state, false);
this.replaceState(state);
event.preventDefault();
}.bind(this);
},
getPage: function() {
if (this.state.page === "LIST") {
return (
React.createElement(ListPage, {app: this},
React.createElement(TodoList, {todoListKey: this.state.todoListKey})
)
);
} else if (this.state.page === "LISTS") {
return (
React.createElement("a", {onClick: this.navOnClick({page: "LIST", todoListKey: "-JjcFYgp1LyD5oDNNSe2"}), href: "/#/list/-JjcFYgp1LyD5oDNNSe2"}, "hi")
);
} else {
console.log("Unknown page: " + this.state.page);
}
},
render: function() {
return (
React.createElement("div", null,
React.createElement(Nav, {app: this}),
React.createElement("div", {className: "container", role: "main"},
this.getPage()
)
)
);
}
});
React.render(
React.createElement(App, null),
document.getElementById('content')
); | jasharpe/firebase-react-todo | build/.module-cache/55ef8d641456cf304b91346e5672f316c68f8da9.js | JavaScript | mit | 10,058 |
// bundles everything except TS files which will be built by rollup.
// webpack stuff
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var failPlugin = require('webpack-fail-plugin');
var helpers = require('./helpers');
const basePlugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.optimize.CommonsChunkPlugin('globals'),
new HtmlWebpackPlugin({
template: 'index.template.html',
favicon: 'favicon.ico'
}),
new ExtractTextPlugin("styles.css"),
failPlugin
];
const devPlugins = [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
})
];
const plugins = basePlugins
.concat((process.env.NODE_ENV === 'development') ? devPlugins: []);
module.exports = {
entry: {
globals: [
'core-js',
'zone.js',
'reflect-metadata'
]
},
output: {
path: helpers.root(''),
publicPath: '',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
resolve: {
extensions: [
'.webpack.js', '.web.js', '.js', '.html'
]
},
module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.html$/, loader: 'raw' },
{ test: /\.(ico)$/, loader: 'file' },
{ test: /\.(png|jpe?g|gif)$/, loader: 'file', query: {name: 'assets/[name].[hash].[ext]'} },
{ test: /\.css$/, exclude: helpers.root('src', 'app'), loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader"
}) },
{ test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw' },
{ test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'application/font-woff'} },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'application/octet-stream'} },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'image/svg+xml'} }
]
},
plugins: plugins
};
// gulp tasks
var gulp = require('gulp');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
gulp.task('build', function () {
console.log('build Working!');
});
gulp.task('watch', function () {
watch('**/*.ts', batch(function (events, done) {
gulp.start('build', done);
}));
}); | samdevx1029/angular-ts-webpack-ngc-rollup | config/webpack.dev.js | JavaScript | mit | 2,491 |
exports.up = function (knex, Promise) {
return Promise.all([
knex.schema.createTable('locations', function (table) {
table.uuid('id').notNullable().primary()
table.string('title').notNullable().unique()
table.text('description')
table.string('address_1')
table.string('address_2')
table.string('town')
table.string('county')
table.string('zipcode')
table.string('country')
}),
knex.schema.createTable('conferences', function (table) {
table.uuid('id').notNullable().primary()
table.string('title').notNullable().unique()
table.text('description')
table.string('organiser').notNullable().unique()
table.dateTime('startTime')
table.dateTime('endTime')
table.uuid('location').references('locations.id')
})
])
}
exports.down = function (knex, Promise) {
return Promise.all([
knex.schema.dropTable('conferences'),
knex.schema.dropTable('locations')
])
}
| ztolley/conference-digital-web | src/db/migrations/20161212145712_location_conference.js | JavaScript | mit | 978 |
(function( window, $, undefined ) {
// http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
$.fn.touchwipe = function(settings) {
var config = {
min_move_x: 20,
min_move_y: 20,
wipeLeft: function() { },
wipeRight: function() { },
wipeUp: function() { },
wipeDown: function() { },
preventDefaultEvents: true
};
if (settings) $.extend(config, settings);
this.each(function() {
var startX;
var startY;
var isMoving = false;
function cancelTouch() {
this.removeEventListener('touchmove', onTouchMove);
startX = null;
isMoving = false;
}
function onTouchMove(e) {
if(config.preventDefaultEvents) {
e.preventDefault();
}
if(isMoving) {
var x = e.touches[0].pageX;
var y = e.touches[0].pageY;
var dx = startX - x;
var dy = startY - y;
if(Math.abs(dx) >= config.min_move_x) {
cancelTouch();
if(dx > 0) {
config.wipeLeft();
}
else {
config.wipeRight();
}
}
else if(Math.abs(dy) >= config.min_move_y) {
cancelTouch();
if(dy > 0) {
config.wipeDown();
}
else {
config.wipeUp();
}
}
}
}
function onTouchStart(e)
{
if (e.touches.length == 1) {
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
isMoving = true;
this.addEventListener('touchmove', onTouchMove, false);
}
}
if ('ontouchstart' in document.documentElement) {
this.addEventListener('touchstart', onTouchStart, false);
}
});
return this;
};
$.elastislide = function( options, element ) {
this.$el = $( element );
this._init( options );
};
$.elastislide.defaults = {
speed : 450, // animation speed
easing : '', // animation easing effect
imageW : 190, // the images width
margin : 3, // image margin right
border : 2, // image border
minItems : 1, // the minimum number of items to show.
// when we resize the window, this will make sure minItems are always shown
// (unless of course minItems is higher than the total number of elements)
current : 0, // index of the current item
// when we resize the window, the carousel will make sure this item is visible
navPrev :'<span class="es-nav-prev">Prev</span>',
navNext :'<span class="es-nav-next">Next</span>',
onClick : function() { return false; } // click item callback
};
$.elastislide.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.elastislide.defaults, options );
// <ul>
this.$slider = this.$el.find('ul');
// <li>
this.$items = this.$slider.children('li');
// total number of elements / images
this.itemsCount = this.$items.length;
// cache the <ul>'s parent, since we will eventually need to recalculate its width on window resize
this.$esCarousel = this.$slider.parent();
// validate options
this._validateOptions();
// set sizes and initialize some vars...
this._configure();
// add navigation buttons
this._addControls();
// initialize the events
this._initEvents();
// show the <ul>
this.$slider.show();
// slide to current's position
this._slideToCurrent( false );
},
_validateOptions : function() {
if( this.options.speed < 0 )
this.options.speed = 450;
if( this.options.margin < 0 )
this.options.margin = 4;
if( this.options.border < 0 )
this.options.border = 1;
if( this.options.minItems < 1 || this.options.minItems > this.itemsCount )
this.options.minItems = 1;
if( this.options.current > this.itemsCount - 1 )
this.options.current = 0;
},
_configure : function() {
// current item's index
this.current = this.options.current;
// the ul's parent's (div.es-carousel) width is the "visible" width
this.visibleWidth = this.$esCarousel.width();
// test to see if we need to initially resize the items
if( this.visibleWidth < this.options.minItems * ( this.options.imageW + 2 * this.options.border ) + ( this.options.minItems - 1 ) * this.options.margin ) {
this._setDim( ( this.visibleWidth - ( this.options.minItems - 1 ) * this.options.margin ) / this.options.minItems );
this._setCurrentValues();
// how many items fit with the current width
this.fitCount = this.options.minItems;
}
else {
this._setDim();
this._setCurrentValues();
}
// set the <ul> width
this.$slider.css({
width : this.sliderW
});
},
_setDim : function( elW ) {
// <li> style
this.$items.css({
marginRight : this.options.margin,
width : ( elW ) ? elW : this.options.imageW + 2 * this.options.border
}).children('a').css({ // <a> style
borderWidth : this.options.border
});
},
_setCurrentValues : function() {
// the total space occupied by one item
this.itemW = this.$items.outerWidth(true);
// total width of the slider / <ul>
// this will eventually change on window resize
this.sliderW = this.itemW * this.itemsCount;
// the ul parent's (div.es-carousel) width is the "visible" width
this.visibleWidth = this.$esCarousel.width();
// how many items fit with the current width
this.fitCount = Math.floor( this.visibleWidth / this.itemW );
},
_addControls : function() {
this.$navNext = $(this.options.navNext);
this.$navPrev = $(this.options.navPrev);
$('<div class="es-nav"/>')
.append( this.$navPrev )
.append( this.$navNext )
.appendTo( this.$el );
//this._toggleControls();
},
_toggleControls : function( dir, status ) {
// show / hide navigation buttons
if( dir && status ) {
if( status === 1 )
( dir === 'right' ) ? this.$navNext.show() : this.$navPrev.show();
else
( dir === 'right' ) ? this.$navNext.hide() : this.$navPrev.hide();
}
else if( this.current === this.itemsCount - 1 || this.fitCount >= this.itemsCount )
this.$navNext.hide();
},
_initEvents : function() {
var instance = this;
// window resize
$(window).on('resize.elastislide', function( event ) {
instance._reload();
// slide to the current element
clearTimeout( instance.resetTimeout );
instance.resetTimeout = setTimeout(function() {
instance._slideToCurrent();
}, 200);
});
// navigation buttons events
this.$navNext.on('click.elastislide', function( event ) {
instance._slide('right');
});
this.$navPrev.on('click.elastislide', function( event ) {
instance._slide('left');
});
// item click event
this.$slider.on('click.elastislide', 'li', function( event ) {
instance.options.onClick( $(this) );
return false;
});
// touch events
instance.$slider.touchwipe({
wipeLeft : function() {
instance._slide('right');
},
wipeRight : function() {
instance._slide('left');
}
});
},
reload : function( callback ) {
this._reload();
if ( callback ) callback.call();
},
_reload : function() {
var instance = this;
// set values again
instance._setCurrentValues();
// need to resize items
if( instance.visibleWidth < instance.options.minItems * ( instance.options.imageW + 2 * instance.options.border ) + ( instance.options.minItems - 1 ) * instance.options.margin ) {
instance._setDim( ( instance.visibleWidth - ( instance.options.minItems - 1 ) * instance.options.margin ) / instance.options.minItems );
instance._setCurrentValues();
instance.fitCount = instance.options.minItems;
}
else{
instance._setDim();
instance._setCurrentValues();
}
instance.$slider.css({
width : instance.sliderW + 10 // TODO: +10px seems to solve a firefox "bug" :S
});
},
_slide : function( dir, val, anim, callback ) {
// if animating return
//if( this.$slider.is(':animated') )
//return false;
// current margin left
var ml = parseFloat( this.$slider.css('margin-left') );
// val is just passed when we want an exact value for the margin left (used in the _slideToCurrent function)
if( val === undefined ) {
// how much to slide?
var amount = this.fitCount * this.itemW, val;
if( amount < 0 ) return false;
// make sure not to leave a space between the last item / first item and the end / beggining of the slider available width
if( dir === 'right' && this.sliderW - ( Math.abs( ml ) + amount ) < this.visibleWidth ) {
amount = this.sliderW - ( Math.abs( ml ) + this.visibleWidth ) - this.options.margin; // decrease the margin left
// show / hide navigation buttons
this._toggleControls( 'right', -1 );
this._toggleControls( 'left', 1 );
}
else if( dir === 'left' && Math.abs( ml ) - amount < 0 ) {
amount = Math.abs( ml );
// show / hide navigation buttons
this._toggleControls( 'left', -1 );
this._toggleControls( 'right', 1 );
}
else {
var fml; // future margin left
( dir === 'right' )
? fml = Math.abs( ml ) + this.options.margin + Math.abs( amount )
: fml = Math.abs( ml ) - this.options.margin - Math.abs( amount );
// show / hide navigation buttons
if( fml > 0 )
this._toggleControls( 'left', 1 );
else
this._toggleControls( 'left', -1 );
if( fml < this.sliderW - this.visibleWidth )
this._toggleControls( 'right', 1 );
else
this._toggleControls( 'right', -1 );
}
( dir === 'right' ) ? val = '-=' + amount : val = '+=' + amount
}
else {
var fml = Math.abs( val ); // future margin left
if( Math.max( this.sliderW, this.visibleWidth ) - fml < this.visibleWidth ) {
val = - ( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth );
if( val !== 0 )
val += this.options.margin; // decrease the margin left if not on the first position
// show / hide navigation buttons
this._toggleControls( 'right', -1 );
fml = Math.abs( val );
}
// show / hide navigation buttons
if( fml > 0 )
this._toggleControls( 'left', 1 );
else
this._toggleControls( 'left', -1 );
if( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth > fml + this.options.margin )
this._toggleControls( 'right', 1 );
else
this._toggleControls( 'right', -1 );
}
$.fn.applyStyle = ( anim === undefined ) ? $.fn.animate : $.fn.css;
var sliderCSS = { marginLeft : val };
var instance = this;
this.$slider.stop().applyStyle( sliderCSS, $.extend( true, [], { duration : this.options.speed, easing : this.options.easing, complete : function() {
if( callback ) callback.call();
} } ) );
},
_slideToCurrent : function( anim ) {
// how much to slide?
var amount = this.current * this.itemW;
this._slide('', -amount, anim );
},
add : function( $newelems, callback ) {
// adds new items to the carousel
this.$items = this.$items.add( $newelems );
this.itemsCount = this.$items.length;
this._setDim();
this._setCurrentValues();
this.$slider.css({
width : this.sliderW
});
this._slideToCurrent();
if ( callback ) callback.call( $newelems );
},
setCurrent : function( idx, callback ) {
this.current = idx;
var ml = Math.abs( parseFloat( this.$slider.css('margin-left') ) ),
posR = ml + this.visibleWidth,
fml = Math.abs( this.current * this.itemW );
if( fml + this.itemW > posR || fml < ml ) {
this._slideToCurrent();
}
if ( callback ) callback.call();
},
destroy : function( callback ) {
this._destroy( callback );
},
_destroy : function( callback ) {
this.$el.off('.elastislide').removeData('elastislide');
$(window).off('.elastislide');
if ( callback ) callback.call();
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.elastislide = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'elastislide' );
if ( !instance ) {
logError( "cannot call methods on elastislide prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for elastislide instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'elastislide' );
if ( !instance ) {
$.data( this, 'elastislide', new $.elastislide( options, this ) );
}
});
}
return this;
};
})( window, jQuery ); | LechDutkiewicz/serfenta_theme | lib/extensions/rg-gallery/jquery.elastislide.js | JavaScript | mit | 13,063 |
#!/usr/bin/env node
var _ = require('lodash');
var async = require('async-chainable');
var asyncFlush = require('async-chainable-flush');
var colors = require('chalk');
var doop = require('.');
var glob = require('glob');
var fs = require('fs');
var fspath = require('path');
var program = require('commander');
var sha1 = require('node-sha1');
program
.version(require('./package.json').version)
.description('List units installed for the current project')
.option('-b, --basic', 'Display a simple list, do not attempt to hash file differences')
.option('-v, --verbose', 'Be verbose. Specify multiple times for increasing verbosity', function(i, v) { return v + 1 }, 0)
.parse(process.argv);
async()
.use(asyncFlush)
.then(doop.chProjectRoot)
.then(doop.getUserSettings)
// Get the list of units {{{
.then('units', function(next) {
doop.getUnits(function(err, units) {
if (err) return next(err);
next(null, units.map(u => { return {
id: u,
path: fspath.join(doop.settings.paths.units, u),
files: {},
} }));
});
})
// }}}
// Hash file comparisons unless program.basic {{{
// Get repo {{{
.then('repo', function(next) {
if (program.basic) return next();
doop.getDoopPath(next, program.repo);
})
.then(function(next) {
if (program.basic) return next();
if (program.verbose) console.log('Using Doop source:', colors.cyan(this.repo));
next();
})
// }}}
// Scan project + Doop file list and hash all files (unless !program.basic) {{{
.then(function(next) {
if (program.basic) return next();
// Make a list of all files in both this project and in the doop repo
// For each file create an object with a `local` sha1 hash and `doop` sha1 hash
var hashQueue = async(); // Hash tasks to perform
async()
.forEach(this.units, function(next, unit) {
async()
.parallel([
// Hash all project files {{{
function(next) {
glob(fspath.join(unit.path, '**'), {nodir: true}, function(err, files) {
if (files.length) {
unit.existsInProject = true;
files.forEach(function(file) {
hashQueue.defer(file, function(next) {
if (program.verbose) console.log('Hash file (Proj)', colors.cyan(file));
sha1(fs.createReadStream(file), function(err, hash) {
if (!unit.files[file]) unit.files[file] = {path: file};
unit.files[file].project = hash;
next();
});
});
});
} else {
unit.existsInProject = false;
}
next();
});
},
// }}}
// Hash all Doop files {{{
function(next) {
glob(fspath.join(doop.settings.paths.doop, unit.path, '**'), {nodir: true}, function(err, files) {
if (files.length) {
unit.existsInDoop = true;
files.forEach(function(rawFile) {
var croppedPath = rawFile.substr(doop.settings.paths.doop.length + 1);
var file = fspath.join(doop.settings.paths.doop, croppedPath);
hashQueue.defer(file, function(next) {
if (program.verbose) console.log('Hash file (Doop)', colors.cyan(croppedPath));
sha1(fs.createReadStream(file), function(err, hash) {
if (!unit.files[croppedPath]) unit.files[croppedPath] = {path: file};
unit.files[croppedPath].doop = hash;
next();
});
});
});
} else {
unit.existsInDoop = false;
}
next();
});
},
// }}}
])
.end(next)
})
.end(function(err) {
if (err) return next(err);
// Wait for hashing queue to finish
hashQueue.await().end(next);
});
})
// }}}
// }}}
// Present the list {{{
.then(function(next) {
var task = this;
if (program.verbose > 1) console.log();
this.units.forEach(function(unit) {
if (unit.existsInProject && !unit.existsInDoop) {
console.log(colors.grey(' -', unit.id));
} else if (!unit.existsInProject && unit.existsInDoop) {
console.log(colors.red(' -', unit.id));
} else { // In both Doop + Project - examine file differences
var changes = [];
// Edited {{{
var items = _.filter(unit.files, f => f.project && f.doop && f.project != f.doop);
if (_.get(doop.settings, 'list.changes.maxEdited') && items.length > doop.settings.list.changes.maxEdited) {
changes.push(colors.yellow.bold('~' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.yellow.bold('~') + f.path.substr(unit.path.length+1)));
}
// }}}
// Created {{{
var items = _.filter(unit.files, f => f.project && !f.doop);
if (_.get(doop.settings, 'list.changes.maxCreated') && items.length > doop.settings.list.changes.maxCreated) {
changes.push(colors.green.bold('+' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.green.bold('+') + f.path.substr(unit.path.length+1)));
}
// }}}
// Deleted {{{
var items = _.filter(unit.files, f => f.doop && !f.project);
if (_.get(doop.settings, 'list.changes.maxDeleted') && items.length > doop.settings.list.changes.maxDeleted) {
changes.push(colors.red.bold('-' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.red.bold('-') + f.path.substr(doop.settings.paths.doop.length+unit.path.length+2)));
}
// }}}
if (changes.length) {
console.log(' -', unit.id, colors.blue('('), changes.join(', '), colors.blue(')'));
} else {
console.log(' -', unit.id);
}
}
});
next();
})
// }}}
// End {{{
.flush()
.end(function(err) {
if (err) {
console.log(colors.red('Doop Error'), err.toString());
process.exit(1);
} else {
process.exit(0);
}
});
// }}}
| MomsFriendlyDevCo/doop-cli | doop-list.js | JavaScript | mit | 5,758 |
if(!Hummingbird) { var Hummingbird = {}; }
Hummingbird.Base = function() {};
Hummingbird.Base.prototype = {
validMessageCount: 0,
messageRate: 20,
initialize: function() {
this.averageLog = [];
this.setFilter();
this.registerHandler();
},
registerHandler: function() {
this.socket.registerHandler(this.onData, this);
},
onMessage: function(message) {
console.log("Base class says: " + JSON.stringify(message));
},
onData: function(fullData) {
var average;
var message = this.extract(fullData);
if(typeof(message) != "undefined") {
this.validMessageCount += 1;
// Calculate the average over N seconds if the averageOver option is set
if(this.options.averageOver) { average = this.addToAverage(message); }
if((!this.options.every) || (this.validMessageCount % this.options.every == 0)) {
this.onMessage(message, this.average());
}
}
},
extract: function(data) {
if(typeof(data) == "undefined") { return; }
var obj = data;
for(var i = 0, len = this.filter.length; i < len; i++) {
obj = obj[this.filter[i]];
if(typeof(obj) == "undefined") { return; }
}
return obj;
},
setFilter: function() {
// TODO: extend this (and extract) to support multiple filters
var obj = this.options.data;
this.filter = [];
while(typeof(obj) == "object") {
for(var i in obj) {
this.filter.push(i);
obj = obj[i];
break;
}
}
},
addToAverage: function(newValue) {
var averageCount = this.options.averageOver * this.messageRate;
this.averageLog.push(newValue);
if(this.averageLog.length > averageCount) {
this.averageLog.shift();
}
},
average: function() {
if(this.averageLog.length == 0) { return 0; }
return this.averageLog.sum() * 1.0 / this.averageLog.length * this.messageRate;
}
};
| mikejihbe/hummingbird | public/js/widgets/base.js | JavaScript | mit | 1,907 |
define([
'knockout'
],function(
ko
){
ko.bindingHandlers.withfirst = {
'init' : function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var savedNodes;
ko.computed(function() {
var dataValue = ko.utils.unwrapObservable(valueAccessor());
var shouldDisplay = typeof dataValue.length == "number" && dataValue.length;
var isFirstRender = !savedNodes;
// Save a copy of the inner nodes on the initial update,
// but only if we have dependencies.
if (isFirstRender && ko.computedContext.getDependenciesCount()) {
savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
}
if (shouldDisplay) {
if (!isFirstRender) {
ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
}
ko.applyBindingsToDescendants( bindingContext['createChildContext'](dataValue && dataValue[0]), element);
} else {
ko.virtualElements.emptyNode(element);
}
}, null).extend({ rateLimit: 50 });
return { 'controlsDescendantBindings': true };
}
}
}); | ssddi456/ko_custom_bindings | ko.withfirst.js | JavaScript | mit | 1,190 |
var bunyanConfig = require('../index');
var bunyan = require('bunyan');
var path = require('path');
describe('bunyan-config', function () {
it('should not convert things it does not understand', function () {
bunyanConfig({
name: 'test',
streams: [{
path: '/tmp/log.log'
}, {
type: 'raw',
stream: 'unknown'
}],
serializers: 5
}).should.deep.equal({
name: 'test',
streams: [{
path: '/tmp/log.log'
}, {
type: 'raw',
stream: 'unknown'
}],
serializers: 5
});
});
describe('streams', function () {
it('should convert stdout and stderr', function () {
bunyanConfig({
streams: [{
level: 'info',
stream: 'stdout'
}, {
stream: {name: 'stderr'}
}]
}).should.deep.equal({
streams: [{
level: 'info',
stream: process.stdout
}, {
stream: process.stderr
}]
});
});
it('should convert bunyan-logstash', function () {
bunyanConfig({
streams: [{
level: 'error',
type: 'raw',
stream: {
name: 'bunyan-logstash',
params: {
host: 'example.com',
port: 1234
}
}
}]
}).should.deep.equal({
streams: [{
level: 'error',
type: 'raw',
stream: require('bunyan-logstash').createStream({
host: 'example.com',
port: 1234
})
}]
});
});
it('should convert bunyan-redis stream', function () {
var config = bunyanConfig({
streams: [{
type: 'raw',
stream: {
name: 'bunyan-redis',
params: {
host: 'example.com',
port: 1234
}
}
}]
});
config.streams[0].stream.should.be.an.instanceof(require('events').EventEmitter);
config.streams[0].stream._client.host.should.equal('example.com');
config.streams[0].stream._client.port.should.equal(1234);
config.streams[0].stream._client.end();
});
});
describe('serializers', function () {
it('should convert serializers property, if it is a string', function () {
bunyanConfig({
serializers: 'bunyan:stdSerializers'
}).should.deep.equal({
serializers: bunyan.stdSerializers
});
});
it('should not convert serializers, if it is an empty string', function () {
bunyanConfig({
serializers: ''
}).should.deep.equal({
serializers: ''
});
});
it('should convert serializers object', function () {
var absolutePathWithProps = path.resolve(__dirname, './fixtures/dummySerializerWithProps');
var relativePathWithProps = './' + path.relative(process.cwd(), absolutePathWithProps);
var absolutePathWithoutProps = path.resolve(__dirname, './fixtures/dummySerializerWithoutProps');
var relativePathWithoutProps = './' + path.relative(process.cwd(), absolutePathWithoutProps);
bunyanConfig({
serializers: {
moduleWithProps: 'bunyan:stdSerializers.req',
moduleWithoutProps: 'bunyan',
absoluteWithProps: relativePathWithProps + ':c',
relativeWithProps: relativePathWithProps + ':a.b',
absoluteWithoutProps: absolutePathWithoutProps,
relativeWithoutProps: relativePathWithoutProps,
empty: '',
noModuleId: ':abc'
}
}).should.deep.equal({
serializers: {
moduleWithProps: bunyan.stdSerializers.req,
moduleWithoutProps: bunyan,
absoluteWithProps: require('./fixtures/dummySerializerWithProps').c,
relativeWithProps: require('./fixtures/dummySerializerWithProps').a.b,
absoluteWithoutProps: require('./fixtures/dummySerializerWithoutProps'),
relativeWithoutProps: require('./fixtures/dummySerializerWithoutProps'),
empty: '',
noModuleId: ':abc'
}
});
});
});
});
| LSEducation/bunyan-config | test/bunyanConfig.test.js | JavaScript | mit | 5,253 |
'use strict';
var http = require('http');
var Logger = require('bunyan');
var log = new Logger({
name: 'test-server',
level: 'debug'
});
var server = http.createServer(function (request) {
var data = '';
log.info({ url: request.url }, 'Incoming Request');
request.on('data', function (chunk) {
data += chunk;
});
throw new Error('expected error');
});
var port = 3000;
server.listen(port);
log.info({
port: port
}, 'listening');
| timemachine3030/jenkman | test/test-server-errors.js | JavaScript | mit | 476 |
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import EmailField from '../EmailField';
// EmailField
// props: inputId
// behavior: renders a <Field /> component
// test: renders a <Field /> component
describe('<EmailField />', () => {
it('should render a Field component', () => {
let wrapper = shallow(<EmailField inputId='testField'/>);
expect(toJson(wrapper)).toMatchSnapshot();
});
}); | F-Ruxton/taskata | src/components/EmailField/__test__/EmailField.test.js | JavaScript | mit | 461 |
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
addFavorite() {
this.sendAction('addFavorite', this.get('newFavorite'));
}
}
});
| fostertheweb/kappa-client | app/components/add-channel-form.js | JavaScript | mit | 178 |
(function ($) {
'use strict';
// Device check for limiting resize handling.
var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
function FullHeight(el, options) {
this.el = $(el);
var data = {};
$.each(this.el.data(), function (attr, value) {
if (/^fullheight/.test(attr)) {
var key = attr.replace('fullheight', '').toLowerCase();
data[key] = value;
}
});
options = $.extend({}, FullHeight.defaults, options, data);
this.debug = options.debug;
this.container = $(options.container);
this.property = options.property;
this.propertyBefore = this.el.css(this.property);
// Chrome for Android resizes the browser a lot when scrolling due to the address bar collapsing.
// This causes a lot of arbitrary layout jumps and slow image resize operations with this plugin.
// So for device UA where height should not change, we only update if the width changes as well (f.ex.
// orientation changes).
this.allowDeviceHeightResize = !(
options.allowDeviceHeightResize === null ||
options.allowDeviceHeightResize === false ||
options.allowDeviceHeightResize === 'false'
);
this.lastWidth = this.container.innerWidth();
this.timerResize = 0;
this.container.on('resize.yrkup3.fullheight', $.proxy(this, '_onResize'));
this.update();
}
FullHeight.defaults = {
debug: false,
allowDeviceHeightResize: false,
container: window,
property: 'min-height'
};
FullHeight.prototype._onResize = function () {
var newWidth = this.container.innerWidth();
var allowResize = !IS_DEVICE || this.allowDeviceHeightResize || newWidth !== this.lastWidth;
// Do the update if expected.
if (allowResize) {
var root = this;
clearTimeout(this.timerResize);
this.timerResize = setTimeout(function () {
root.update();
}, 200);
}
this.lastWidth = newWidth;
};
FullHeight.prototype.update = function () {
if (this.debug) {
console.log('update', this.el);
}
var newHeight;
var offset = this.container.offset();
if (typeof offset == 'undefined') {
newHeight = $(window).innerHeight();
} else {
newHeight = this.container.innerHeight() - (this.el.offset().top - offset.top);
}
if (newHeight !== this.lastHeight) {
if (this.debug) {
console.log('set `' + this.property + '` to ' + newHeight);
}
this.el.css(this.property, newHeight);
this.lastHeight = newHeight;
}
};
FullHeight.prototype.dispose = function () {
if (this.debug) {
console.log('dispose');
}
this.container.off('.yrkup3.fullheight');
this.el.css(this.property, this.propertyBefore);
};
$.fn.fullheight = function (options) {
this.each(function () {
var el = $(this);
// Store data
var data = el.data('yrkup3.fullheight');
if (!data) {
el.data('yrkup3.fullheight', (data = new FullHeight(el, options)));
}
// Run command
if (typeof options == 'string') {
data[options]();
}
});
return this;
};
})(jQuery);
| yrkup3/jquery-fullheight | src/jquery-fullheight.js | JavaScript | mit | 2,998 |
var _ = require('lodash'),
restify = require('restify'),
async = require('async');
module.exports = function(settings, server, db){
var globalLogger = require(settings.path.root('logger'));
var auth = require(settings.path.lib('auth'))(settings, db);
var api = require(settings.path.lib('api'))(settings, db);
var vAlpha = function(path){ return {path: path, version: settings.get("versions:alpha")} };
function context(req){
return {logger: req.log};
}
server.get(vAlpha('/ping'), function(req, res, next){
res.json();
next();
});
/**
* API to create or update an email template. If a template exists (accountId + Name pair), it will be updated. Otherwise a new one will be created
*/
server.post(vAlpha('/email/:name'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params || !params.name || !params.htmlData || !params.htmlType || !params.cssData || !params.cssType){
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
api.email.createOrUpdate.call(context(req), params.accountId, params.name, params.htmlData, params.htmlType, params.cssData, params.cssType, function(err){
if (err) {
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json();
}
next();
});
});
server.put(vAlpha('/trigger/:name/on/event'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.actionId || !params.eventName) {
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
var eventCondition = {
name: params.eventName,
attrs: params.eventAttrs
};
api.trigger.create.call(context(req),
params.accountId, params.name, eventCondition, null, params.actionId,
function(err, triggerDoc){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json({id: triggerDoc.id})
}
next();
})
});
server.put(vAlpha('/trigger/:name/on/time'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.actionId || (!params.next && !params.every)) {
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
var timeCondition = {
next: params.next,
every: params.every
};
api.trigger.create.call(context(req),
params.accountId, params.name, null, timeCondition, params.actionId,
function(err, triggerDoc){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json({id: triggerDoc.id})
}
next();
})
});
server.post(vAlpha('/event/:name'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.userId){
var err = restify.BadRequestError("Invalid Arguments");
logger.info(err, params);
return res.send(err);
}
api.event.add.call(context(req),
params.accountId, params.name, params.userId, params.attrs,
function(err){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.send();
}
next();
});
});
};
| prokilogrammer/keet | routes.js | JavaScript | mit | 4,425 |
'use strict';
/**
* @ngdoc directive
* @name SubSnoopApp.directive:pieChart
* @description
* # pieChart
*/
angular.module('SubSnoopApp')
.directive('donutChart', ['d3Service', '$window', '$document', 'subFactory', '$filter', 'moment', 'sentiMood', 'reaction',
function (d3Service, $window, $document, subFactory, $filter, moment, sentiMood, reaction) {
/*
Based on http://embed.plnkr.co/YICxe0/
*/
var windowWidth = $window.innerWidth;
var $win = angular.element($window);
return {
restrict: 'EA',
replace: true,
scope: true,
link: function(scope, element, attrs) {
scope.chartReady = false;
scope.loaderImg = '../images/103.gif';
var subname = scope.subreddit;
d3Service.d3().then(function(d3) {
/*
Set dimensions for pie charts
*/
var height;
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
height = 375;
} else {
height = 475;
}
function configChart(scope_chart, window_width) {
if (window_width < 700) {
scope_chart = setChartConfig(300);
} else {
scope_chart = setChartConfig(260);
}
return scope_chart;
}
/*
Default configuration for pie chart
*/
function setChartConfig(chart_width) {
return {
width: chart_width,
height: height,
thickness: 30,
grow: 10,
labelPadding: 35,
duration: 0,
margin: {
top: 50, right: 50, bottom: -50, left: 50
}
};
};
function init() {
// --------------------------------------------------------
/*
Get data to populate pie charts
*/
var user;
var chartData;
var d3ChartEl;
// --------------------------------------------------------
scope.getChart = function() {
d3ChartEl = d3.select(element[0]);
user = subFactory.getUser();
if (subname && attrs.type === 'sentiment') {
sentiMood.setSubData(subname, subFactory.getEntries(subname, null), user);
chartData = sentiMood.getData(subname);
} else if (subname && attrs.type === 'reaction') {
reaction.setSubData(subname, subFactory.getEntries(subname, null), user);
chartData = reaction.getData(subname);
}
scope.chartReady = true;
scope.chartConfig = configChart(scope.chartConfig, windowWidth);
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'w': w.width()
};
};
try {
drawChart(chartData, scope.chartConfig);
w.bind('resize', function() {
scope.$apply();
drawChart(chartData, scope.chartConfig);
});
} catch(error) {
console.log(error);
}
}
}
/*
Draw the pie chart with center text and mouse over events
*/
function drawChart(chartData, chartConfig) {
var width = chartConfig.width,
height = chartConfig.height,
margin = chartConfig.margin,
grow = chartConfig.grow,
labelRadius,
radius,
duration = chartConfig.duration;
width = width - margin.left - margin.right;
height = height - margin.top - margin.bottom,
radius = Math.min(width, height) / 2,
labelRadius = radius + chartConfig.labelPadding;
var thickness = chartConfig.thickness || Math.floor(radius / 5);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - thickness);
var arcOver = d3.svg.arc()
.outerRadius(radius + grow)
.innerRadius(radius - thickness);
var pieFn = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var centerValue = (!!chartData.center.value) ? chartData.center.value : '';
var centerValue2 = (!!chartData.center.value2) ? chartData.center.value2 : '';
var d3ChartEl = d3.select(element[0]);
d3ChartEl.select('svg').remove();
var gRoot = d3ChartEl.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g');
gRoot.attr('transform', 'translate(' + (width / 2 + margin.left) + ',' + (height / 2 + margin.top) + ')');
var middleCircle = gRoot.append('svg:circle')
.attr('cx', 0)
.attr('cy', 0)
.attr('r', radius)
.style('fill', '#1F2327');
/*
Display percentage and center text statistics when hovering over an arc
*/
scope.mouseOverPath = function(d) {
d3.select(this)
.transition()
.duration(duration)
.each("end", function(d) {
d3.select('.center-value-' + attrs.type).text(d.data.label);
var line1;
if (attrs.type === 'upvotes') {
line1 = 'Points: ' + $filter('number')(d.data.value);
} else {
line1 = 'Entries: ' + $filter('number')(d.data.value);
}
d3.select('.line-1-' + attrs.type)
.text(line1);
d3.selectAll('.arc-' + attrs.type + ' .legend .percent')
.transition()
.duration(duration)
.style('fill-opacity', 0);
d3.select(this.parentNode).select('.legend .percent')
.transition()
.duration(duration)
.style("fill-opacity", 1);
d3.selectAll('.arc-' + attrs.type).style('opacity', function(e) {
return e.data.label === d.data.label ? '1' : '0.3';
});
})
.attr("d", arcOver);
};
/*
Shrink the arc back to original width of pie chart ring
*/
scope.reduceArc = function(d) {
try {
if (d) {
d3.select(this)
.transition()
.attr("d", arc);
} else {
d3.selectAll('.arc-' + attrs.type + ' path')
.each(function() {
d3.select(this)
.transition()
.attr("d", arc);
});
}
} catch(error) {
console.log("Error: " + error);
}
}
/*
The state of the chart when the mouse is not hovered over it
*/
scope.restoreCircle = function() {
d3.selectAll('.arc-' + attrs.type).style('opacity', '1');
d3.select('.center-value-' + attrs.type).text(centerValue);
d3.select('.line-1-' + attrs.type).text(centerValue2);
d3.selectAll('.arc-' + attrs.type + ' .legend .percent')
.transition()
.duration(duration)
.style("fill-opacity", 0);
scope.reduceArc();
};
gRoot.on('mouseleave', function(e) {
if (!e) {
scope.restoreCircle();
}
});
middleCircle.on('mouseover', function() {
scope.restoreCircle();
});
var arcs = gRoot.selectAll('g.arc')
.data(pieFn(chartData.values))
.enter()
.append('g')
.attr('class', 'arc-' + attrs.type);
var partition = arcs.append('svg:path')
.style('fill', function(d) {
return chartData.colors[d.data.label];
})
.on("mouseover", scope.mouseOverPath)
.each(function() {
this._current = {
startAngle: 0,
endAngle: 0
};
})
.on("mouseleave", scope.reduceArc)
.attr('d', arc)
.transition()
.duration(duration)
.attrTween('d', function(d) {
try {
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
} catch(error) {
console.log(e);
}
});
/*
Set up center text for pie chart with name of chart and number of posts
*/
var centerText = gRoot.append('svg:text')
.attr('class', 'center-label');
var titleSize = '14px';
var dataSize = '14px';
centerText.append('tspan')
.text(centerValue)
.attr('x', 0)
.attr('dy', '0em')
.attr("text-anchor", "middle")
.attr("class", 'center-value-' + attrs.type)
.attr("font-size", titleSize)
.attr("fill", "#fff")
.attr("font-weight", "bold");
centerText.append('tspan')
.text(centerValue2)
.attr('x', 0)
.attr('dy', '1em')
.attr("text-anchor", "middle")
.attr("class", 'line-1-' + attrs.type)
.attr("font-size", dataSize)
.attr("fill", "#9099A1")
.attr("font-weight", "400");
var percents = arcs.append("svg:text")
.style('fill-opacity', 0)
.attr('class', 'legend')
.attr("transform", function(d) {
var c = arc.centroid(d),
x = c[0],
y = c[1],
height = Math.sqrt(x * x + y * y);
return "translate(" + ((x-13) / height * labelRadius) + ',' +
((y+5) / height * labelRadius) + ")";
});
percents.append('tspan')
.attr('class', 'percent')
.attr('x', 0)
.attr('font-size', '13px')
.attr('font-weight', '400')
.attr('fill', '#fff')
.style("fill-opacity", 0)
.text(function(d, i) {
return d.data.percent + '%';
});
var legend = gRoot.append('g')
.attr('class', 'legend')
.selectAll('text')
.data(chartData.values)
.enter();
/*
Displays legend indicating what color represents what category
*/
legend.append('rect')
.attr('height', 10)
.attr('width', 10)
.attr('x', function(d) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return 0 - radius - 35;
} else {
return 0 - radius - 20;
}
})
.attr('y', function(d, i) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return (20 * (i + 1) - 210);
} else {
return (20 * (i + 1)) - 260;
}
})
.on('mouseover', function(d, i) {
var sel = d3.selectAll('.arc-' + attrs.type).filter(function(d) {
return d.data.id === i;
});
scope.mouseOverPath.call(sel.select('path')[0][0], sel.datum());
})
.style('fill', function(d) {
return chartData.colors[d.label];
});
legend.append('text')
.attr('x', function(d) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return 0 - radius - 15;
} else {
return 0 - radius;
}
})
.attr('y', function(d, i) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return (20 * (i + 1) - 200);
} else {
return (20 * (i + 1)) - 250;
}
})
.attr('font-size', '12px')
.attr('fill', '#9099A1')
.on('mouseover', function(d, i) {
var sel = d3.selectAll('.arc-' + attrs.type).filter(function(d) {
return d.data.id === i;
});
scope.mouseOverPath.call(sel.select('path')[0][0], sel.datum());
})
.text(function(d) { return d.label; });
}
init();
$document.ready(function() {
var chart = angular.element('#piecharts-' + subname);
var donutElem = element.parent().parent().parent();
var prevElem = donutElem[0].previousElementSibling;
var idName = '#' + prevElem.id + ' .graph';
// If no activity in the last year, there will be no charts, get top entries instead
if (prevElem.id.length == 0) {
var prevElem = prevElem.previousElementSibling;
if (angular.element('#top-post-' + subname).length > 0) {
idName = '#' + prevElem.id + ' .post-content';
} else {
idName = '#' + prevElem.id + ' .post-body';
}
}
var winHeight = $win.innerHeight();
var listener = scope.$watch(function() { return angular.element(idName).height() > 0 }, function() {
var e = angular.element(idName);
if (!scope.chartReady && e.length > 0 && e[0].clientHeight > 0) {
var boxTop = chart[0].offsetTop - winHeight + 100;
$win.on('scroll', function (e) {
var scrollY = $win.scrollTop();
if (!scope.chartReady && (scrollY >= boxTop)) {
scope.getChart();
scope.$apply();
return;
}
});
}
});
});
});
}
};
}]);
| sharibarboza/SubSnoop | app/scripts/directives/donutchart.js | JavaScript | mit | 14,247 |
// Description:
// There are two lists of different length. The first one consists of keys,
// the second one consists of values. Write a function
//createDict(keys, values) that returns a dictionary created from keys and
// values. If there are not enough values, the rest of keys should have a
//None (JS null)value. If there not enough keys, just ignore the rest of values.
// Example 1:
// keys = ['a', 'b', 'c', 'd']
// values = [1, 2, 3]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3, 'd': null}
// Example 2:
// keys = ['a', 'b', 'c']
// values = [1, 2, 3, 4]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3}
function createDict(keys, values){
var result = {};
for(var i = 0;i<keys.length;i++){
result[keys[i]] = values[i]!=undefined ? values[i] : null;
}
return result;
}
| kanor1306/scrapyard | CodeWars Katas/7kyu/DictionaryTwoLists.js | JavaScript | mit | 832 |
"use strict";
const { ParserError } = require("../util/errors");
const yaml = require("js-yaml");
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 200,
/**
* Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
*
* @type {boolean}
*/
allowEmpty: true,
/**
* Determines whether this parser can parse a given file reference.
* Parsers that match will be tried, in order, until one successfully parses the file.
* Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
* every parser will be tried.
*
* @type {RegExp|string[]|function}
*/
canParse: [".yaml", ".yml", ".json"], // JSON is valid YAML
/**
* Parses the given file as YAML
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {Promise}
*/
async parse (file) { // eslint-disable-line require-await
let data = file.data;
if (Buffer.isBuffer(data)) {
data = data.toString();
}
if (typeof data === "string") {
try {
return yaml.load(data);
}
catch (e) {
throw new ParserError(e.message, file.url);
}
}
else {
// data is already a JavaScript value (object, array, number, null, NaN, etc.)
return data;
}
}
};
| BigstickCarpet/json-schema-ref-parser | lib/parsers/yaml.js | JavaScript | mit | 1,730 |
define([
'jquery',
'underscore',
'backbone',
'collections/users/students',
'collections/users/classes',
'collections/users/streams',
'text!templates/students/studentnew.html',
'text!templates/students/classes.html',
'text!templates/students/streams.html',
'jqueryui',
'bootstrap'
], function($, _, Backbone, Students, Classes, Streams, StudentTpl, classesTpl, streamsTpl){
var NewStudent = Backbone.View.extend({
tagName: 'div',
title: "New Student - Student Information System",
events: {
'submit form#new-student' : 'addStudent',
'change #class_id' : 'getStreams'
},
template: _.template(StudentTpl),
classesTpl: _.template(classesTpl),
streamsTpl: _.template(streamsTpl),
initialize: function(){
$("title").html(this.title);
//fetch list of all classes for this class from the database
var self = this;
Classes.fetch({
data: $.param({
token: tokenString
}),
success: function(data){
self.setClasses();
}
});
//fetch list of all streams for this client from the database
Streams.fetch({
data: $.param({
token: tokenString
})
});
},
render: function(){
this.$el.html(this.template());
this.$classes = this.$("#classes-list");
this.$streams = this.$("#streams-list");
return this;
},
addStudent: function(evt){
evt.preventDefault();
var student = {
reg_number: $("#reg_number").val(),
first_name: $("#first_name").val(),
middle_name: $("#middle_name").val(),
last_name: $("#last_name").val(),
dob: $("#dob").val(),
pob: $("#pob").val(),
bcn: $("#bcn").val(),
sex: $("#sex").val(),
nationality: $("#nationality").val(),
doa: $("#doa").val(),
class_id: $("#class_id").val(),
stream_id: ($("#stream_id").val()) ? $("#stream_id").val() : '',
address: $("#address").val(),
code: $("#code").val(),
town: $("#town").val(),
pg_f_name: $("#pg_f_name").val(),
pg_l_name: $("#pg_l_name").val(),
pg_email: $("#pg_email").val(),
pg_phone: $("#pg_phone").val()
};
$(".submit-button").html("Please wait...");
$(".error-message").hide(200);
$(".success-message").hide(200);
Students.create(student, {
url: baseURL + 'students/students?token=' + tokenString,
success: function(){
$(".success-message").html("Student added successfully!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
//empty the form
$("#reg_number").val(''),
$("#first_name").val(''),
$("#middle_name").val(''),
$("#last_name").val(''),
$("#dob").val(''),
$("#pob").val(''),
$("#bcn").val(''),
$("#sex").val(''),
$("#nationality").val(''),
$("#doa").val(''),
$("#class_id").val(''),
$("#stream_id").val(''),
$("#address").val(''),
$("#code").val(''),
$("#town").val(''),
$("#pg_f_name").val(''),
$("#pg_l_name").val(''),
$("#pg_email").val(''),
$("#pg_phone").val('')
},
error : function(jqXHR, textStatus, errorThrown) {
if(textStatus.status != 401 && textStatus.status != 403) {
$(".error-message").html("Please check the errors below!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
}
}
});
},
setClasses: function(){
this.$classes.empty();
var regClasses = [];
Classes.each(function(oneClass){
regClasses.push(oneClass.toJSON());
}, this);
this.$classes.html(this.classesTpl({
regClasses: regClasses
}));
},
getStreams: function(){
var classID = $("#class_id").val();
var regStreams = [];
var streams = Streams.where({
class_id: classID
});
$.each(streams, function(key, oneStream){
regStreams.push(oneStream.toJSON());
});
this.$streams.html(this.streamsTpl({
regStreams: regStreams
}));
}
});
return NewStudent;
}); | geoffreybans/student-is | public/js/views/students/studentnew.js | JavaScript | mit | 3,985 |
/* global describe */
/* global module */
/* global beforeEach */
/* global inject */
/* global it */
/* global expect */
describe('PanZoom specs', function () {
var $scope = null;
var $compile = null;
var $interval = null;
var PanZoomService = null;
var deferred = null;
var $document = null;
// copied from jquery but makes it use the angular $interval instead of setInterval for its timer
var timerId = null;
jQuery.fx.start = function () {
//console.log('jQuery.fx.start');
if (!timerId) {
timerId = $interval(jQuery.fx.tick, jQuery.fx.interval);
}
};
jQuery.fx.stop = function () {
//console.log('jQuery.fx.stop');
$interval.cancel(timerId);
timerId = null;
};
// copied from jQuery but makes it possible to pretend to be in the future
var now = 0;
jQuery.now = function () {
return now;
};
var shark = {
x: 391,
y: 371,
width: 206,
height: 136
};
var chopper = {
x: 88,
y: 213,
width: 660,
height: 144
};
var ladder = {
x: 333,
y: 325,
width: 75,
height: 200
};
var testApp = angular.module('testApp', ['panzoom', 'panzoomwidget']);
beforeEach(module('testApp'));
beforeEach(inject(function ($rootScope, _$compile_, _$interval_, _PanZoomService_, $q, _$document_) {
$scope = $rootScope;
$compile = _$compile_;
$interval = _$interval_;
PanZoomService = _PanZoomService_;
deferred = $q.defer();
$document = _$document_;
$scope.rects = [chopper, shark, ladder];
// Instantiate models which will be passed to <panzoom> and <panzoomwidget>
// The panzoom config model can be used to override default configuration values
$scope.panzoomConfig = {
zoomLevels: 10,
neutralZoomLevel: 5,
scalePerZoomLevel: 1.5
};
// The panzoom model should initially be empty; it is initialized by the <panzoom>
// directive. It can be used to read the current state of pan and zoom. Also, it will
// contain methods for manipulating this state.
$scope.panzoomModel = {};
}));
afterEach(function () {
$scope.$broadcast('$destroy');
$interval.flush(jQuery.fx.interval); // wait for the first event tick to complete as this will do the actual unregistering
});
it('should create markup', function () {
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom>');
$compile(element)($scope);
$scope.$digest();
expect(element.html()).toMatch(/<div.*<\/div>/);
});
it('should not zoom when using neutral zoom level', function () {
$scope.panzoomConfig.neutralZoomLevel = 3;
$scope.panzoomConfig.initialZoomLevel = 3;
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom>');
$compile(element)($scope);
$scope.$digest();
expect($(element).find('.zoom-element').css('-webkit-transform')).toBe('scale(1)');
$scope.panzoomConfig.neutralZoomLevel = 5;
$scope.panzoomConfig.initialZoomLevel = 5;
element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom>');
$compile(element)($scope);
$scope.$digest();
expect($(element).find('.zoom-element').css('-webkit-transform')).toBe('scale(1)');
});
it('Should pan when the mouse is dragged', function () {
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"><div id="WrappedElement"/></panzoom>');
$compile(element)($scope);
$scope.$digest();
var overlay = $document.find('#PanZoomOverlay');
function createMouseEvent(type, clientX, clientY) {
var e = document.createEvent('MouseEvents');
// type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget
e.initMouseEvent(type, true, true, window, 1, 0, 0, clientX || 0, clientY || 0, false, false, false, false, 0, null);
e.preventDefault = undefined;
e.stopPropagation = undefined;
return e;
}
element.find('#WrappedElement').trigger(createMouseEvent('mousedown', 100, 100));
expect($scope.panzoomModel.pan).toEqual({
x: 0,
y: 0
});
now += 40; // pretend that time passed
overlay.trigger(createMouseEvent('mousemove', 110, 100));
expect($scope.panzoomModel.pan).toEqual({
x: 10,
y: 0
});
overlay.trigger(createMouseEvent('mouseup', 120, 120));
for (var i = 0; i < 10; i++) {
$interval.flush(jQuery.fx.interval);
now += jQuery.fx.interval;
}
expect($scope.panzoomModel.pan.x).toBeGreaterThan(10); // due to sliding effects; specific value doesn't matter
expect($scope.panzoomModel.pan.y).toEqual(0);
});
it('should pan when dragging the finger (touch)', function () {
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"><div id="WrappedElement"/></panzoom>');
$compile(element)($scope);
$scope.$digest();
var overlay = $document.find('#PanZoomOverlay');
function createTouchEvent(type, touches) {
var e = document.createEvent('MouseEvents');
// type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget
e.initMouseEvent(type, true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
e.touches = touches || [];
//e.preventDefault = undefined;
//e.stopPropagation = undefined;
return $.event.fix(e);
}
element.find('#WrappedElement').trigger(createTouchEvent('touchstart', [{pageX: 100, pageY: 100}]));
expect($scope.panzoomModel.pan).toEqual({
x: 0,
y: 0
});
now += 40; // pretend that time passed
overlay.trigger(createTouchEvent('touchmove', [{pageX: 110, pageY: 100}]));
expect($scope.panzoomModel.pan).toEqual({
x: 10,
y: 0
});
overlay.trigger(createTouchEvent('touchend'));
for (var i = 0; i < 10; i++) {
$interval.flush(jQuery.fx.interval);
now += jQuery.fx.interval;
}
expect($scope.panzoomModel.pan.x).toBeGreaterThan(10); // due to sliding effects; specific value doesn't matter
expect($scope.panzoomModel.pan.y).toEqual(0);
});
it('should use {{interpolated}} value for panzoomid', function () {
var element = angular.element('<panzoom id="{{panZoomElementId}}" config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"><div id="WrappedElement"/></panzoom>');
$scope.panZoomElementId = "panZoom1";
$compile(element)($scope);
var handler = jasmine.createSpy('success');
PanZoomService.getAPI('panZoom1').then(handler);
$scope.$digest();
expect(handler).toHaveBeenCalled();
});
it('should publish and unpublish its API', function () {
var _this = this;
var element = angular.element('<div ng-if="includeDirective"><panzoom id="PanZoomElementId" config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom></div>');
$compile(element)($scope);
$scope.includeDirective = true;
$scope.$digest();
var handler = jasmine.createSpy('success');
PanZoomService.getAPI('PanZoomElementId').then(handler);
$scope.$digest();
expect(handler).toHaveBeenCalled();
$scope.includeDirective = false;
$scope.$digest();
PanZoomService.getAPI('PanZoomElementId').then(function (api) {
_this.fail(Error('Failed to unregister API'));
});
});
});
| cyrixmorten/angular-pan-zoom | test/unit/PanZoomSpec.js | JavaScript | mit | 8,427 |
var express = require('express');
var user = require('../model/user');
var jsonReturn = require('../common/jsonReturn');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
user.getUsers(function(err, rows, fields){
res.render('users', { users : rows } );
})
});
router.post('/getUsers', function (req, res, next) {
if(req.body.username){
user.getUsers(function(err, rows, fields){
res.json(jsonReturn({ users : rows } ));
})
}
});
module.exports = router;
| Justinidlerz/react-and-express | controller/users.js | JavaScript | mit | 535 |
import { createAction } from 'redux-actions';
import { APP_LAYOUT_CHANGE, APP_LAYOUT_INIT } from './constants';
// 选中菜单列表项
const appLayoutInit = createAction(APP_LAYOUT_INIT);
export const onAppLayoutInit = (key) => {
return (dispatch) => {
dispatch(appLayoutInit(key));
};
};
const appLayoutChange = createAction(APP_LAYOUT_CHANGE);
export const onAppLayoutChange = (key) => {
return (dispatch) => {
dispatch(appLayoutChange(key));
};
};
| dunwu/react-app | codes/src/view/general/setting/redux/actions.js | JavaScript | mit | 471 |
// Init express server
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server = require('http').Server(app);
server.listen(3000);
console.log("started listenning on port 3000");
// Subscribe to lexa's router stream and update the LED accordingly
// var onoff = require('onoff');
// var Gpio = onoff.Gpio;
// var led = new Gpio(18, 'out');
var sio = require('socket.io-client');
var socket = sio.connect('http://lexa.tuscale.ro');
// socket.on('message', function(msg) {
// console.log('Got a new message from the router:', msg);
// var jMsg = JSON.parse(msg);
// var newLedState = jMsg.led;
// led.writeSync(newLedState);
// });
// Init firebase
var firebase = require('firebase');
var io = require('socket.io')(server);
var firebase_app = firebase.initializeApp({
apiKey: "AIzaSyB3ZvJDuZ2HD-UppgPvY2by-GI0KnessXw",
authDomain: "rlexa-9f1ca.firebaseapp.com",
databaseURL: "https://rlexa-9f1ca.firebaseio.com",
projectId: "rlexa-9f1ca",
storageBucket: "rlexa-9f1ca.appspot.com",
messagingSenderId: "161670508523"
});
var db = firebase.database();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Init NFC serial link
// var SerialPort = require('serialport');
// SerialPort.list(function (err, ports) {
// ports.forEach(function (port) {
// console.log(port.comName);
// });
// });
// var port = new SerialPort('/dev/ttyACM0', {
// baudRate: 9600,
// parser: SerialPort.parsers.readline("\r\n")
// });
// port.on('open', function () {
// console.log('open');
// });
// // Monitor NFC activity
// port.on('data', function (data) {
// var tagID = data.split(' ').join('');
// console.log(data.split(' '));
// tagID = tagID.substring(0, tagID.length - 1);
// console.log(tagID + " scanned ...");
// db.ref("card/" + tagID).once("value", function(cardOwnerSnap) {
// var cardOwnerName = cardOwnerSnap.child('name').val();
// if (cardOwnerName) {
// db.ref('authed').set(cardOwnerName);
// }
// });
// // Notify our web-clients that a tag was scanned
// io.sockets.emit('idscanned', { cardid: tagID });
// });
io.on('connection', function (socket) {
console.log('Web client connected.');
});
// Define web-facing endpoints for managing the users
app.post('/add_user', function (req, res) {
var currentUser = { name: req.body.name, led: req.body.led, id: req.body.id };
var updates = {};
updates['card/' + currentUser.id] = {
name: currentUser.name,
led: currentUser.led
};
updates['users/' + currentUser.name] = currentUser;
return firebase.database().ref().update(updates);
});
app.get('/get_users', function (req, res) {
firebase.database().ref().once('value', function (snap) {
var dataUsers = snap.child("users");
res.send(dataUsers);
});
});
app.get('/get_authed', function (req, res) {
db.ref().once('value', function (snap) {
var isUserLogged = snap.child("authed/Mike").val();
console.log(isUserLogged);
if (isUserLogged) {
var userData = snap.child("users/Mike/led")
console.log(parseInt(userData.val()));
}
})
var name = "BLAH";
name = name.toLowerCase();
name = name.charAt(0).toUpperCase() + name.slice(1);
res.send(name);
});
// Monitor process termination and do cleanups
// process.on('SIGINT', function () {
// led.writeSync(0);
// led.unexport();
// process.exit();
// });
// db.ref('authed').once('value', function (snap) {
// var lastScannedTagOwner = snap.val();
// if (lastScannedTagOwner) {
// // Valid tag present
// request({
// url: 'http://lexa.tuscale.ro/publish',
// method: 'POST',
// json: { led: (stateName === "on" ? 1 : 0) }
// },
// function (error, response, body) {
// if (error) {
// return console.error('upload failed:', error);
// }
// // Delete scanned tag and notify user of successfull op
// db.ref('authed').remove();
// that.emit(':tell', 'Hi ' + lastScannedTagOwner + '! Turning ' + stateName + ' the LED!');
// console.log('Upload successful! Server responded with:', body)
// }
// );
// } else {
// that.emit(':tell', 'Please scan your tag and try again.');
// }
// }); | JaxonDvl/lexa-piduino | serverlocal.js | JavaScript | mit | 4,714 |
// fetch() polyfill for making API calls.
import 'whatwg-fetch';
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
import objectAssign from 'object-assign';
Object.assign = objectAssign;
| ZachMayer35/Radioscope | API/tests/config/polyfills.js | JavaScript | mit | 261 |
!function e(n,r,t){function o(a,u){if(!r[a]){if(!n[a]){var c="function"==typeof require&&require;if(!u&&c)return c(a,!0);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}var f=r[a]={exports:{}};n[a][0].call(f.exports,function(e){var r=n[a][1][e];return o(r?r:e)},f,f.exports,e,n,r,t)}return r[a].exports}for(var i="function"==typeof require&&require,a=0;a<t.length;a++)o(t[a]);return o}({1:[function(e,n,r){!function(e,n,r,t,o,i,a){e.GoogleAnalyticsObject=o,e[o]=e[o]||function(){(e[o].q=e[o].q||[]).push(arguments)},e[o].l=1*new Date,i=n.createElement(r),a=n.getElementsByTagName(r)[0],i.async=1,i.src=t,a.parentNode.insertBefore(i,a)}(window,document,"script","//www.google-analytics.com/analytics.js","ga"),ga("create","UA-67843411-1","auto"),ga("send","pageview")},{}]},{},[1]); | jer-keel/jkeeler-net-static | public/js/ga.js | JavaScript | mit | 799 |
// getPostsParameters gives an object containing the appropriate find and options arguments for the subscriptions's Posts.find()
getPostsParameters = function (terms) {
var maxLimit = 200;
// console.log(terms)
// note: using jquery's extend() with "deep" parameter set to true instead of shallow _.extend()
// see: http://api.jquery.com/jQuery.extend/
// initialize parameters by extending baseParameters object, to avoid passing it by reference
var parameters = deepExtend(true, {}, viewParameters.baseParameters);
// if view is not defined, default to "top"
var view = !!terms.view ? dashToCamel(terms.view) : 'top';
// get query parameters according to current view
if (typeof viewParameters[view] !== 'undefined')
parameters = deepExtend(true, parameters, viewParameters[view](terms));
// extend sort to sort posts by _id to break ties
deepExtend(true, parameters, {options: {sort: {_id: -1}}});
// if a limit was provided with the terms, add it too (note: limit=0 means "no limit")
if (typeof terms.limit !== 'undefined')
_.extend(parameters.options, {limit: parseInt(terms.limit)});
// limit to "maxLimit" posts at most when limit is undefined, equal to 0, or superior to maxLimit
if(!parameters.options.limit || parameters.options.limit == 0 || parameters.options.limit > maxLimit) {
parameters.options.limit = maxLimit;
}
// hide future scheduled posts unless "showFuture" is set to true or postedAt is already defined
if (!parameters.showFuture && !parameters.find.postedAt)
parameters.find.postedAt = {$lte: new Date()};
// console.log(parameters);
return parameters;
};
getUsersParameters = function(filterBy, sortBy, limit) {
var find = {},
sort = {createdAt: -1};
switch(filterBy){
case 'invited':
// consider admins as invited
find = {$or: [{isInvited: true}, adminMongoQuery]};
break;
case 'uninvited':
find = {$and: [{isInvited: false}, notAdminMongoQuery]};
break;
case 'admin':
find = adminMongoQuery;
break;
}
switch(sortBy){
case 'username':
sort = {username: 1};
break;
case 'karma':
sort = {karma: -1};
break;
case 'postCount':
sort = {postCount: -1};
break;
case 'commentCount':
sort = {commentCount: -1};
case 'invitedCount':
sort = {invitedCount: -1};
}
return {
find: find,
options: {sort: sort, limit: limit}
};
};
| haribabuthilakar/fh | lib/parameters.js | JavaScript | mit | 2,548 |
// ==UserScript==
// @name Kiss Simple Infobox hider
// @description Hides the infobox on kissanime.com, kisscartoon.me and kissasian.com player sites
// @include https://kissanime.ru/Anime/*/*
// @include https://kimcartoon.to/Cartoon/*/*
// @include https://kissasian.sh/Drama/*/*
// @author Playacem
// @updateURL https://raw.githubusercontent.com/Playacem/KissScripts/master/kiss-simple-infobox-hider/kiss-simple-infobox-hider.user.js
// @downloadURL https://raw.githubusercontent.com/Playacem/KissScripts/master/kiss-simple-infobox-hider/kiss-simple-infobox-hider.user.js
// @require https://code.jquery.com/jquery-latest.js
// @grant none
// @run-at document-end
// @version 0.0.11
// ==/UserScript==
// do not change
var JQ = jQuery;
function hideInfobox() {
var selector = JQ('#centerDivVideo') /* the div with the video */
.prev() /*a clear2 div*/
.prev() /*dropdown*/
.prev() /*a clear2 div*/
.prev(); /*the actual div*/
selector.remove();
}
// load after 2 seconds
setTimeout(hideInfobox, 2000);
| Playacem/KissScripts | kiss-simple-infobox-hider/kiss-simple-infobox-hider.user.js | JavaScript | mit | 1,191 |
'use strict';
const fs = require('fs');
const Q = require('q');
const exec = require('child_process').exec;
const searchpaths = ["/bin/xset"];
class XSetDriver {
constructor(props) {
this.name = "Backlight Control";
this.devicePath = "xset";
this.description = "Screensaver control via Xwindows xset command";
this.devices = [];
this.driver = {};
//this.depends = [];
}
probe(props) {
searchpaths.forEach(function(p) {
if(fs.existsSync(p)) {
let stat = fs.lstatSync(p);
if (stat.isFile()) {
console.log("found xset control at "+p);
this.devices.push(new XSetDriver.Channel(this, p, props));
}
}
}.bind(this));
return this.devices.length>0;
}
}
class XSetChannel {
constructor(driver, path, props)
{
this.value = 1;
this.setCommand = path;
this.enabled = true;
this.display = ":0.0";
this.error = 0;
// internal variables
this.lastReset = new Date();
}
enable() {
this.set("on");
}
disable() {
this.set("off");
}
activate() {
this.set("activate");
}
blank() {
this.set("blank");
}
reset() {
this.set("reset");
this.lastReset=new Date();
}
setTimeout(secs) {
this.set(""+secs);
}
set(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" "+this.setCommand+" s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
}.bind(this));
}
}
XSetDriver.Channel = XSetChannel;
module.exports = XSetDriver;
/*
Treadmill.prototype.init_screensaver = function(action)
{
this.screensaver = {
// config/settings
enabled: !simulate,
display: ":0.0",
error: 0,
// internal variables
lastReset: new Date(),
// screensaver functions
enable: function() { this.set("on"); },
disable: function() { this.set("off"); },
activate: function() { this.set("activate"); },
blank: function() { this.set("blank"); },
reset: function() { this.set("reset"); this.lastReset=new Date(); },
timeout: function(secs) { this.set(""+secs); },
// main set() function calls command "xset s <action>"
set: function(action) {
if(!this.enabled) return false;
var ss = this;
exec("DISPLAY="+this.display+" xset s "+action, function(error,stdout, stderr) {
if(error) {
if(ss.error++ >10) {
ss.enabled=false;
}
console.log("xset error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
}
};
if(simulate) return false;
// initialize the screensaver
var ss = this.screensaver;
exec("./screensaver.conf "+this.screensaver.display, function(error,stdout, stderr) {
if(error) {
ss.enabled = false;
console.log("screensaver.conf error "+error);
console.log(stdout);
console.log("errors:");
console.log(stderr);
}
});
this.screensaver.enable();
}
*/ | flyingeinstein/tread-station | nodejs/drivers/output/screensaver/xset.js | JavaScript | mit | 3,736 |
var fs = require("fs");
var longStr = (new Array(10000)).join("welefen");
while(true){
fs.writeFileSync("1.txt", longStr);
} | welefen/node-test | file/a.js | JavaScript | mit | 125 |
/**
* Copyright (c) 2011 Bruno Jouhier <[email protected]>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
"use strict";
var fs = require("fs");
var path = require("path");
var compile = require("./compile");
var registered = false;
var _options = {};
/// !doc
///
/// # streamline/lib/compiler/register
///
/// Streamline `require` handler registration
///
/// * `register.register(options)`
/// Registers `require` handlers for streamline.
/// `options` is a set of default options passed to the `transform` function.
exports.register = function(setoptions) {
if (registered) return;
_options = setoptions || {};
registered = true;
var pModule = require('module').prototype;
var orig = pModule._compile;
pModule._compile = function(content, filename) {
content = compile.transformModule(content, filename, _options);
return orig.call(this, content, filename);
}
};
var dirMode = parseInt('777', 8);
exports.trackModule = function(m, options) {
if (registered) throw new Error("invalid call to require('streamline/module')");
m.filename = m.filename.replace(/\\/g, '/');
var tmp = m.filename.substring(0, m.filename.lastIndexOf('/'));
tmp += '/tmp--' + Math.round(Math.random() * 1e9) + path.extname(m.filename);
//console.error("WARNING: streamline not registered, re-loading module " + m.filename + " as " + tmp);
exports.register({});
fs.writeFileSync(tmp, fs.readFileSync(m.filename, "utf8"), "utf8");
process.on('exit', function() {
try { fs.unlinkSync(tmp); }
catch (ex) {}
})
m.exports = require(tmp);
return false;
}
Object.defineProperty(exports, "options", {
enumerable: true,
get: function() {
return _options;
}
}); | doowb/grunttest | node_modules/azure/node_modules/streamline/lib/compiler/register.js | JavaScript | mit | 2,722 |
/*
* Copyright 2016 Joyent, Inc., All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE
*/
module.exports = {
KeyPair: SDCKeyPair,
LockedKeyPair: SDCLockedKeyPair
};
var mod_assert = require('assert-plus');
var mod_sshpk = require('sshpk');
var mod_util = require('util');
var mod_httpsig = require('http-signature');
var KeyRing = require('./keyring');
function SDCKeyPair(kr, opts) {
mod_assert.object(kr, 'keyring');
mod_assert.ok(kr instanceof KeyRing,
'keyring instanceof KeyRing');
this.skp_kr = kr;
mod_assert.object(opts, 'options');
mod_assert.string(opts.plugin, 'options.plugin');
mod_assert.optionalString(opts.source, 'options.source');
this.plugin = opts.plugin;
this.source = opts.source;
this.comment = '';
if (opts.public !== undefined) {
/*
* We need a Key of v1,3 or later for defaultHashAlgorithm and
* the Signature hashAlgorithm support.
*/
mod_assert.ok(mod_sshpk.Key.isKey(opts.public, [1, 3]),
'options.public must be a sshpk.Key instance');
this.comment = opts.public.comment;
}
this.skp_public = opts.public;
if (opts.private !== undefined) {
mod_assert.ok(mod_sshpk.PrivateKey.isPrivateKey(opts.private),
'options.private must be a sshpk.PrivateKey instance');
}
this.skp_private = opts.private;
}
SDCKeyPair.fromPrivateKey = function (key) {
mod_assert.object(key, 'key');
mod_assert.ok(mod_sshpk.PrivateKey.isPrivateKey(key),
'key is a PrivateKey');
var kr = new KeyRing({ plugins: [] });
var kp = new SDCKeyPair(kr, {
plugin: 'none',
private: key,
public: key.toPublic()
});
return (kp);
};
SDCKeyPair.prototype.canSign = function () {
return (this.skp_private !== undefined);
};
SDCKeyPair.prototype.createRequestSigner = function (opts) {
mod_assert.string(opts.user, 'options.user');
mod_assert.optionalString(opts.subuser, 'options.subuser');
mod_assert.optionalBool(opts.mantaSubUser, 'options.mantaSubUser');
var sign = this.createSign(opts);
var user = opts.user;
if (opts.subuser) {
if (opts.mantaSubUser)
user += '/' + opts.subuser;
else
user += '/users/' + opts.subuser;
}
var keyId = '/' + user + '/keys/' + this.getKeyId();
function rsign(data, cb) {
sign(data, function (err, res) {
if (res)
res.keyId = keyId;
cb(err, res);
});
}
return (mod_httpsig.createSigner({ sign: rsign }));
};
SDCKeyPair.prototype.createSign = function (opts) {
mod_assert.object(opts, 'options');
mod_assert.optionalString(opts.algorithm, 'options.algorithm');
mod_assert.optionalString(opts.keyId, 'options.keyId');
mod_assert.string(opts.user, 'options.user');
mod_assert.optionalString(opts.subuser, 'options.subuser');
mod_assert.optionalBool(opts.mantaSubUser, 'options.mantaSubUser');
if (this.skp_private === undefined) {
throw (new Error('Private key for this key pair is ' +
'unavailable (because, e.g. only a public key was ' +
'found and no matching private half)'));
}
var key = this.skp_private;
var keyId = this.getKeyId();
var alg = opts.algorithm;
var algParts = alg ? alg.toLowerCase().split('-') : [];
if (algParts[0] && algParts[0] !== key.type) {
throw (new Error('Requested algorithm ' + alg + ' is ' +
'not supported with a key of type ' + key.type));
}
var self = this;
var cache = this.skp_kr.getSignatureCache();
function sign(data, cb) {
if (Buffer.isBuffer(data)) {
mod_assert.buffer(data, 'data');
} else {
mod_assert.string(data, 'data');
}
mod_assert.func(cb, 'callback');
var ck = { key: key, data: data };
if (Buffer.isBuffer(data))
ck.data = data.toString('base64');
if (cache.get(ck, cb))
return;
cache.registerPending(ck);
/*
* We can throw in here if the hash algorithm we were told to
* use in 'algorithm' is invalid. Return it as a normal error.
*/
var signer, sig;
try {
signer = self.skp_private.createSign(algParts[1]);
signer.update(data);
sig = signer.sign();
} catch (e) {
cache.put(ck, e);
cb(e);
return;
}
var res = {
algorithm: key.type + '-' + sig.hashAlgorithm,
keyId: keyId,
signature: sig.toString(),
user: opts.user,
subuser: opts.subuser
};
sign.algorithm = res.algorithm;
cache.put(ck, null, res);
cb(null, res);
}
sign.keyId = keyId;
sign.user = opts.user;
sign.subuser = opts.subuser;
sign.getKey = function (cb) {
cb(null, self.skp_private);
};
return (sign);
};
SDCKeyPair.prototype.getKeyId = function () {
return (this.skp_public.fingerprint('md5').toString('hex'));
};
SDCKeyPair.prototype.getPublicKey = function () {
return (this.skp_public);
};
SDCKeyPair.prototype.getPrivateKey = function () {
return (this.skp_private);
};
SDCKeyPair.prototype.isLocked = function () {
return (false);
};
SDCKeyPair.prototype.unlock = function (passphrase) {
throw (new Error('Keypair is not locked'));
};
function SDCLockedKeyPair(kr, opts) {
SDCKeyPair.call(this, kr, opts);
mod_assert.buffer(opts.privateData, 'options.privateData');
this.lkp_privateData = opts.privateData;
mod_assert.string(opts.privateFormat, 'options.privateFormat');
this.lkp_privateFormat = opts.privateFormat;
this.lkp_locked = true;
}
mod_util.inherits(SDCLockedKeyPair, SDCKeyPair);
SDCLockedKeyPair.prototype.createSign = function (opts) {
if (this.lkp_locked) {
throw (new Error('SSH private key ' +
this.getPublicKey().comment +
' is locked (encrypted/password-protected). It must be ' +
'unlocked before use.'));
}
return (SDCKeyPair.prototype.createSign.call(this, opts));
};
SDCLockedKeyPair.prototype.createRequestSigner = function (opts) {
if (this.lkp_locked) {
throw (new Error('SSH private key ' +
this.getPublicKey().comment +
' is locked (encrypted/password-protected). It must be ' +
'unlocked before use.'));
}
return (SDCKeyPair.prototype.createRequestSigner.call(this, opts));
};
SDCLockedKeyPair.prototype.canSign = function () {
return (true);
};
SDCLockedKeyPair.prototype.getPrivateKey = function () {
if (this.lkp_locked) {
throw (new Error('SSH private key ' +
this.getPublicKey().comment +
' is locked (encrypted/password-protected). It must be ' +
'unlocked before use.'));
}
return (this.skp_private);
};
SDCLockedKeyPair.prototype.isLocked = function () {
return (this.lkp_locked);
};
SDCLockedKeyPair.prototype.unlock = function (passphrase) {
mod_assert.ok(this.lkp_locked);
this.skp_private = mod_sshpk.parsePrivateKey(this.lkp_privateData,
this.lkp_privateFormat, { passphrase: passphrase });
mod_assert.ok(this.skp_public.fingerprint('sha512').matches(
this.skp_private));
this.lkp_locked = false;
};
| joyent/node-smartdc-auth | lib/keypair.js | JavaScript | mit | 7,717 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DropdownMenuItemType;
(function (DropdownMenuItemType) {
DropdownMenuItemType[DropdownMenuItemType["Normal"] = 0] = "Normal";
DropdownMenuItemType[DropdownMenuItemType["Divider"] = 1] = "Divider";
DropdownMenuItemType[DropdownMenuItemType["Header"] = 2] = "Header";
})(DropdownMenuItemType = exports.DropdownMenuItemType || (exports.DropdownMenuItemType = {}));
//# sourceMappingURL=Dropdown.Props.js.map
| SpatialMap/SpatialMapDev | node_modules/office-ui-fabric-react/lib/components/Dropdown/Dropdown.Props.js | JavaScript | mit | 499 |
/**
* Export exceptions
* @type {Object}
*/
module.exports = {
Schema: require('./Schema'),
Value: require('./Value')
}
| specla/validator | lib/exceptions/index.js | JavaScript | mit | 127 |
// flow-typed signature: da1b0a6922881fd3985864661b7297ce
// flow-typed version: <<STUB>>/babel-eslint_v^10.0.3/flow_v0.113.0
/**
* This is an autogenerated libdef stub for:
*
* 'babel-eslint'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'babel-eslint' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'babel-eslint/lib/analyze-scope' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/babylon-to-espree/attachComments' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/babylon-to-espree/convertComments' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/babylon-to-espree/convertTemplateType' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/babylon-to-espree' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/babylon-to-espree/toAST' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/babylon-to-espree/toToken' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/babylon-to-espree/toTokens' {
declare module.exports: any;
}
declare module 'babel-eslint/lib' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/parse-with-scope' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/parse' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/require-from-eslint' {
declare module.exports: any;
}
declare module 'babel-eslint/lib/visitor-keys' {
declare module.exports: any;
}
// Filename aliases
declare module 'babel-eslint/lib/analyze-scope.js' {
declare module.exports: $Exports<'babel-eslint/lib/analyze-scope'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/attachComments.js' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/attachComments'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/convertComments.js' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/convertComments'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/convertTemplateType.js' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/convertTemplateType'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/index' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/index.js' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/toAST.js' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/toAST'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/toToken.js' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/toToken'>;
}
declare module 'babel-eslint/lib/babylon-to-espree/toTokens.js' {
declare module.exports: $Exports<'babel-eslint/lib/babylon-to-espree/toTokens'>;
}
declare module 'babel-eslint/lib/index' {
declare module.exports: $Exports<'babel-eslint/lib'>;
}
declare module 'babel-eslint/lib/index.js' {
declare module.exports: $Exports<'babel-eslint/lib'>;
}
declare module 'babel-eslint/lib/parse-with-scope.js' {
declare module.exports: $Exports<'babel-eslint/lib/parse-with-scope'>;
}
declare module 'babel-eslint/lib/parse.js' {
declare module.exports: $Exports<'babel-eslint/lib/parse'>;
}
declare module 'babel-eslint/lib/require-from-eslint.js' {
declare module.exports: $Exports<'babel-eslint/lib/require-from-eslint'>;
}
declare module 'babel-eslint/lib/visitor-keys.js' {
declare module.exports: $Exports<'babel-eslint/lib/visitor-keys'>;
}
| pCloud/pcloud-sdk-js | flow-typed/npm/babel-eslint_vx.x.x.js | JavaScript | mit | 3,903 |
var express = require('express');
var userRouter = express.Router();
var passport = require('passport');
var Model = require('../models/user');
var authenticate = require('./auth');
/* GET all the users */
exports.getAll = function(req, res, next) {
Model.Users.forge()
.fetch({ columns: ['_id', 'username', 'admin'] })
.then(function(user) {
res.json(user);
}).catch(function(err) {
console.log(err);
});
};
/* GET a user given its id */
exports.getUser = function(req, res, next) {
var userID = req.params.userID;
Model.User.forge({'_id':userID})
.fetch({columns:['_id', 'username', 'admin']})
.then(function (user) {
res.json(user);
});
};
/* PUT update a user given its id */
exports.updateUser = function(req, res, next) {
var userID = req.params.userID;
Model.User.forge({'_id':userID})
.fetch({columns:['_id', 'username', 'admin']})
.then(function (user) {
res.json(user);
});
};
/* GET logout */
exports.signOut = function(req, res){
req.logout();
res.status(200).json({message: 'Login user out'});
};
/* POST login. */
exports.signIn = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
return req.logIn(user, function(err) {
if (err) {
console.log(err);
return res.status(500).json({
error: 'Could not log in user'
});
}
var token = authenticate.getToken(user);
res.status(200).json({
status: 'Login successful',
succes: true,
token: token
});
});
})(req, res, next);
};
/* POST Register. */
exports.signUp = function(req, res, next) {
var userData = req.body;
Model.User.forge({
username: userData.username
}).fetch() //see if user already exists
.then(function(user) {
if (user) {
return res.status(400).json({
title: 'signup',
errorMessage: 'That username already exists'
});
} else {
//User does not existe, lets add it
var signUpUser = Model.User.forge({
username: userData.username,
password: userData.password,
admin: false
});
signUpUser.save()
.then(function(user) {
var result = 'User ' + user.get('username') + ' created.';
return res.status(200).json({
message: result,
user: {
id: user.get('id'),
username: user.get('username'),
}
});
});
}
});
};
| TheKiqGit/TimeTracker | src/server/routes/userController.js | JavaScript | mit | 2,707 |
import Float from 'ember-advanced-form/components/float';
export default Float;
| jakkor/ember-advanced-form | app/components/advanced-form/float.js | JavaScript | mit | 81 |
document.getElementsByTagName('body')[0].style.overflow = 'hidden';
window.scrollTo(70, 95); | nash716/SandanshikiKanpan | src2/inject/scroll.js | JavaScript | mit | 92 |
var url = args.url;
var limit = args.limitl;
var defaultWaitTime = Number(args.wait_time_for_polling)
uuid = executeCommand('urlscan-submit-url-command', {'url': url})[0].Contents;
uri = executeCommand('urlscan-get-result-page', {'uuid': uuid})[0].Contents;
var resStatusCode = 404
var waitedTime = 0
while(resStatusCode == 404 && waitedTime < Number(args.timeout)) {
var resStatusCode = executeCommand('urlscan-poll-uri', {'uri': uri})[0].Contents;
if (resStatusCode == 200) {
break;
}
wait(defaultWaitTime);
waitedTime = waitedTime + defaultWaitTime;
}
if(resStatusCode == 200) {
return executeCommand('urlscan-get-http-transaction-list', {'uuid': uuid, 'url': url, 'limit': limit});
} else {
if(waitedTime >= Number(args.timeout)){
return 'Could not get result from UrlScan, please try to increase the timeout.'
} else {
return 'Could not get result from UrlScan, possible rate-limit issues.'
}
}
| demisto/content | Packs/UrlScan/Scripts/UrlscanGetHttpTransactions/UrlscanGetHttpTransactions.js | JavaScript | mit | 963 |
import User from '../models/user.model';
import Post from '../models/post.model';
import UserPost from '../models/users_posts.model';
import fs from 'fs';
import path from 'path';
/**
* Load user and append to req.
*/
function load(req, res, next, id) {
User.get(id)
.then((user) => {
req.user = user; // eslint-disable-line no-param-reassign
return next();
})
.catch(e => next(e));
}
/**
* Get user
* @returns {User}
*/
function get(req, res) {
req.user.password = "";
var user = JSON.parse(JSON.stringify(req.user));
Post.count({
userId: req.user._id
}).exec()
.then(postCount => {
user.postCount = postCount;
User.count({
following: req.user._id
}).exec()
.then(followedByCount => {
user.followedByCount = followedByCount;
return res.json({
data: user,
result: 0
});
})
})
.catch(err => {
return res.json({
data: err,
result: 1
});
})
}
/**
* Update basic info;firstname lastname profie.bio description title
* @returns {User}
*/
function updateBasicinfo(req, res, next) {
var user = req.user;
user.firstname = req.body.firstname;
user.lastname = req.body.lastname;
user.profile.bio = req.body.profile.bio;
user.profile.title = req.body.profile.title;
user.profile.description = req.body.profile.description;
user.save()
.then(savedUser => res.json({
data: savedUser,
result: 0
}))
.catch(e => next(e));
}
/**
* Update basic info;firstname lastname profie.bio description title
* @returns {User}
*/
function uploadUserimg(req, res, next) {
var user = req.user;
var file = req.files.file;
fs.readFile(file.path, function(err, original_data) {
if (err) {
next(err);
}
// save image in db as base64 encoded - this limits the image size
// to there should be size checks here and in client
var newPath = path.join(__filename, '../../../../public/uploads/avatar/');
fs.writeFile(newPath + user._id + path.extname(file.path), original_data, function(err) {
if (err)
next(err);
console.log("write file" + newPath + user._id + path.extname(file.path));
fs.unlink(file.path, function(err) {
if (err) {
console.log('failed to delete ' + file.path);
} else {
console.log('successfully deleted ' + file.path);
}
});
user.image = '/uploads/avatar/' + user._id + path.extname(file.path);
user.save(function(err) {
if (err) {
next(err);
} else {
res.json({
data: user,
result: 1
});
}
});
});
});
}
/**
* Create new user
* @property {string} req.body.username - The username of user.
* @property {string} req.body.mobileNumber - The mobileNumber of user.
* @returns {User}
*/
function create(req, res, next) {
const user = new User({
username: req.body.username,
mobileNumber: req.body.mobileNumber
});
user.save()
.then(savedUser => res.json(savedUser))
.catch(e => next(e));
}
/**
* Update existing user
* @property {string} req.body.username - The username of user.
* @property {string} req.body.mobileNumber - The mobileNumber of user.
* @returns {User}
*/
function update(req, res, next) {
const user = req.user;
user.username = req.body.username;
user.mobileNumber = req.body.mobileNumber;
user.save()
.then(savedUser => res.json(savedUser))
.catch(e => next(e));
}
/**
* Get user list.
req.params.query : search string
req.params.
* @returns {User[]}
*/
function list(req, res, next) {
var params = req.query;
var condition;
if (params.query == "")
condition = {};
else {
condition = {
$or: [{
"firstname": new RegExp(params.query, 'i')
}, {
"lastname": new RegExp(params.query, 'i')
}]
};
}
User.count(condition).exec()
.then(total => {
if (params.page * params.item_per_page > total) {
params.users = [];
throw {
data: params,
result: 1
};
}
params.total = total;
return User.find(condition)
.sort({
createdAt: -1
})
.skip(params.page * params.item_per_page)
.limit(parseInt(params.item_per_page))
.exec();
})
.then(users => {
params.users = users;
res.json({
data: params,
result: 0
});
})
.catch(err => next(err));
}
/**
* Delete user.
* @returns {User}
*/
function remove(req, res, next) {
const user = req.user;
user.remove()
.then(deletedUser => res.json(deletedUser))
.catch(e => next(e));
}
/**
* get post of ther user
* @returns {User}
*/
function getPosts(req, res, next) {
var user = req.user;
Post.find({
userId: user._id
})
.sort({
createdAt: -1
})
.populate('userId')
.populate({
path: 'comments',
// Get friends of friends - populate the 'friends' array for every friend
populate: {
path: 'author'
}
})
.exec()
.then(posts => {
console.log(posts);
res.json({
data: posts,
result: 0
})
})
.catch(e => next(e));
}
/**
* get post of ther user
* @returns {User}
*/
function addPost(req, res, next) {
var user = req.user;
var post = new Post({
userId: user._id,
title: req.body.title,
content: req.body.content,
});
post.save()
.then(post => {
console.log(post);
res.json({
data: post,
result: 0
})
})
.catch(e => next(e));
}
function followUser(req, res, next) {
var user = req.user;
User.get(req.body.user_follow_to)
.then((user_follow_to) => {
if (user.following.indexOf(user_follow_to._id) == -1)
user.following.push(user_follow_to._id);
user.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
function disconnectUser(req, res, next) {
var user = req.user;
User.get(req.body.user_disconnect_to)
.then(user_disconnect_to => {
var index = user.following.indexOf(user_disconnect_to._id)
if (index > -1)
user.following.splice(index, 1);
user.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
function myFeeds(req, res, next) {
var user = req.user;
Post.find({
userId: {
$in: user.following
}
})
.populate('userId')
.populate({
path: 'comments',
// Get friends of friends - populate the 'friends' array for every friend
populate: {
path: 'author'
}
})
// .populate('likeUsers')
.exec()
.then(feeds => {
res.json({
data: feeds,
result: 0
});
})
.catch(e => next(e));
}
// function allUsers(req, res, next) {
// var user = req.user;
// User.find()
// .sort({ createdAt: -1 })
// .exec()
// .then(users => {
// res.json(users)
// })
// .catch(e => next(e));
// }
//----------------------Like system----------------
function likePost(req, res, next) {
// UserPost.find({
// user: req.current_user,
// post: req.body.post_id
// })
// .exec()
// .then(userpost => {
// if(userpost.length == 0){
// new UserPost({
// user: req.current_user,
// post: req.body.post_id
// }).save().then((userpost)=>{
// res.json({
// result:0,
// data:userpost
// });
// })
// }
// else
// {
// res.json({
// result:0,
// data:"You already like it"
// })
// }
// })
// .catch(e => {
// res.json({
// result: 1,
// data: e
// })
// });
Post.get(req.body.post_id)
.then((post) => {
if (post.likeUsers.indexOf(req.current_user._id) == -1)
post.likeUsers.push(req.current_user._id);
post.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
function dislikePost(req, res, next) {
// UserPost.remove({
// user: req.current_user,
// post: req.body.post_id
// })
// .exec()
// .then(userpost => {
// res.json({
// result:0,
// data:userpost
// })
// })
// .catch(e => {
// res.json({
// result: 1,
// data: e.message
// })
// });
Post.get(req.body.post_id)
.then((post) => {
if (post.likeUsers.indexOf(req.current_user._id) != -1)
post.likeUsers.splice(post.likeUsers.indexOf(req.current_user._id), 1);
post.save()
.then(result => {
res.json({
result: 0,
data: result
});
})
.catch(e => next(e));
})
.catch(e => next(e));
}
export default {
load,
get,
create,
update,
list,
remove,
updateBasicinfo,
uploadUserimg,
getPosts,
addPost,
followUser,
disconnectUser,
myFeeds,
likePost,
dislikePost
}; | kenectin215/kenectin | server/controllers/user.controller.js | JavaScript | mit | 8,464 |
define(function (require) {
require('plugins/timelion/directives/expression_directive');
const module = require('ui/modules').get('kibana/timelion_vis', ['kibana']);
module.controller('TimelionVisParamsController', function ($scope, $rootScope) {
$scope.vis.params.expression = $scope.vis.params.expression || '.es(*)';
$scope.vis.params.interval = $scope.vis.params.interval || '1m';
$scope.search = function () {
$rootScope.$broadcast('courier:searchRefresh');
};
});
});
| istresearch/PulseTheme | kibana/src/core_plugins/timelion/public/vis/timelion_vis_params_controller.js | JavaScript | mit | 507 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Cache Status.
*
* The Initial Developer of the Original Code is
* Jason Purdy.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Thanks to the Fasterfox Extension for some pointers
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
function cs_updated_stat( type, aDeviceInfo, prefs ) {
var current = round_memory_usage( aDeviceInfo.totalSize/1024/1024 );
var max = round_memory_usage( aDeviceInfo.maximumSize/1024/1024 );
var cs_id = 'cachestatus';
var bool_pref_key = 'auto_clear';
var int_pref_key = 'ac';
var clear_directive;
if ( type == 'memory' ) {
cs_id += '-ram-label';
bool_pref_key += '_ram';
int_pref_key += 'r_percent';
clear_directive = 'ram';
// this is some sort of random bug workaround
if ( current > max && current == 4096 ) {
current = 0;
}
} else if ( type == 'disk' ) {
cs_id += '-hd-label';
bool_pref_key += '_disk';
int_pref_key += 'd_percent';
clear_directive = 'disk';
} else {
// offline ... or something else we don't manage
return;
}
/*
dump( 'type: ' + type + ' - aDeviceInfo' + aDeviceInfo );
// do we need to auto-clear?
dump( "evaling if we need to auto_clear...\n" );
dump( bool_pref_key + ": " + prefs.getBoolPref( bool_pref_key ) + " and " +
(( current/max )*100) + " > " +
prefs.getIntPref( int_pref_key ) + "\n" );
dump( "new min level: " + prefs.getIntPref( int_pref_key )*.01*max + " > 10\n" );
*/
/*
This is being disabled for now:
http://code.google.com/p/cachestatus/issues/detail?id=10
*/
/*
if (
prefs.getBoolPref( bool_pref_key ) &&
prefs.getIntPref( int_pref_key )*.01*max > 10 &&
(( current/max )*100) > prefs.getIntPref( int_pref_key )
) {
//dump( "clearing!\n" );
cs_clear_cache( clear_directive, 1 );
current = 0;
}
*/
// Now, update the status bar label...
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
if (win) {
win.document.getElementById(cs_id).setAttribute(
'value', current + " MB / " + max + " MB " );
}
}
function update_cache_status() {
var cache_service = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var prefs = prefService.getBranch("extensions.cachestatus.");
var cache_visitor = {
visitEntry: function(a,b) {},
visitDevice: function( device, aDeviceInfo ) {
cs_updated_stat( device, aDeviceInfo, prefs );
}
}
cache_service.visitEntries( cache_visitor );
}
/*
* This function takes what could be 15.8912576891 and drops it to just
* one decimal place. In a future version, I could have the user say
* how many decimal places...
*/
function round_memory_usage( memory ) {
memory = parseFloat( memory );
memory *= 10;
memory = Math.round(memory)/10;
return memory;
}
// I got the cacheService code from the fasterfox extension
// http://www.xulplanet.com/references/xpcomref/ifaces/nsICacheService.html
function cs_clear_cache( param, noupdate ) {
var cacheService = Components.classes["@mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
if ( param && param == 'ram' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
} else if ( param && param == 'disk' ) {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
} else {
cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
}
if ( ! noupdate ) {
update_cache_status();
}
}
/*
* Grabbed this helpful bit from:
* http://kb.mozillazine.org/On_Page_Load
* http://developer.mozilla.org/en/docs/Code_snippets:On_page_load
*/
var csExtension = {
onPageLoad: function(aEvent) {
update_cache_status();
},
QueryInterface : function (aIID) {
if (aIID.equals(Components.interfaces.nsIObserver) ||
aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference))
return this;
throw Components.results.NS_NOINTERFACE;
},
register: function()
{
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
this._prefs = prefService.getBranch("extensions.cachestatus.");
if ( this._prefs.getBoolPref( 'auto_update' ) ) {
var appcontent = document.getElementById( 'appcontent' );
if ( appcontent )
appcontent.addEventListener( "DOMContentLoaded", this.onPageLoad, true );
}
this._branch = this._prefs;
this._branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
this._branch.addObserver("", this, true);
this._hbox = this.grabHBox();
this.rebuildPresence( this._prefs.getCharPref( 'presence' ) );
this.welcome();
},
welcome: function ()
{
//Do not show welcome page if user has turned it off from Settings.
if (!csExtension._prefs.getBoolPref( 'welcome' )) {
return
}
//Detect Firefox version
var version = "";
try {
version = (navigator.userAgent.match(/Firefox\/([\d\.]*)/) || navigator.userAgent.match(/Thunderbird\/([\d\.]*)/))[1];
} catch (e) {}
function welcome(version) {
if (csExtension._prefs.getCharPref( 'version' ) == version) {
return;
}
//Showing welcome screen
setTimeout(function () {
var newTab = getBrowser().addTab("http://add0n.com/cache-status.html?version=" + version);
getBrowser().selectedTab = newTab;
}, 5000);
csExtension._prefs.setCharPref( 'version', version );
}
//FF < 4.*
var versionComparator = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
.getService(Components.interfaces.nsIVersionComparator)
.compare(version, "4.0");
if (versionComparator < 0) {
var extMan = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
var addon = extMan.getItemForID("[email protected]");
welcome(addon.version);
}
//FF > 4.*
else {
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID("[email protected]", function (addon) {
welcome(addon.version);
});
}
},
grabHBox: function()
{
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var found_hbox;
if (win) {
this._doc = win.document;
found_hbox = win.document.getElementById("cs_presence");
}
//dump( "In grabHBox(): WIN: " + win + " HB: " + found_hbox + "\n" );
return found_hbox;
},
observe: function(aSubject, aTopic, aData)
{
if ( aTopic != 'nsPref:changed' ) return;
// aSubject is the nsIPrefBranch we're observing (after appropriate QI)
// aData is the name of the pref that's been changed (relative to aSubject)
//dump( "pref changed: S: " + aSubject + " T: " + aTopic + " D: " + aData + "\n" );
if ( aData == 'auto_update' ) {
var add_event_handler = this._prefs.getBoolPref( 'auto_update' );
if ( add_event_handler ) {
window.addEventListener( 'load', this.onPageLoad, true );
} else {
window.removeEventListener( 'load', this.onPageLoad, true );
}
} else if ( aData == 'presence' ) {
var presence = this._prefs.getCharPref( 'presence' );
if ( presence == 'original' || presence == 'icons' ) {
this.rebuildPresence( presence );
} else {
dump( "Unknown presence value: " + presence + "\n" );
}
}
},
rebuildPresence: function(presence)
{
// Take the hbox 'cs_presence' and replace it
if ( this._hbox == null ) {
this._hbox = this.grabHBox();
}
var hbox = this._hbox;
var child_node = hbox.firstChild;
while( child_node != null ) {
hbox.removeChild( child_node );
child_node = hbox.firstChild;
}
var popupset = this._doc.getElementById( 'cs_popupset' );
var child_node = popupset.firstChild;
while( child_node != null ) {
popupset.removeChild( child_node );
child_node = popupset.firstChild;
}
var string_bundle = this._doc.getElementById( 'cache-status-strings' );
if ( presence == 'original' ) {
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
var ram_label = this._doc.createElement( 'label' );
ram_label.setAttribute( 'id', 'cachestatus-ram-label' );
ram_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
ram_label.setAttribute(
'tooltiptext', string_bundle.getString( 'ramcache' ) );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
var disk_label = this._doc.createElement( 'label' );
disk_label.setAttribute(
'tooltiptext', string_bundle.getString( 'diskcache' ) );
disk_label.setAttribute( 'id', 'cachestatus-hd-label' );
disk_label.setAttribute(
'value', ': ' + string_bundle.getString( 'nly' ) );
hbox.appendChild( ram_image );
hbox.appendChild( ram_label );
hbox.appendChild( disk_image );
hbox.appendChild( disk_label );
} else if ( presence == 'icons' ) {
var ram_tooltip = this._doc.createElement( 'tooltip' );
ram_tooltip.setAttribute( 'id', 'ram_tooltip' );
ram_tooltip.setAttribute( 'orient', 'horizontal' );
var ram_desc_prefix = this._doc.createElement( 'description' );
ram_desc_prefix.setAttribute( 'id', 'cachestatus-ram-prefix' );
ram_desc_prefix.setAttribute(
'value', string_bundle.getString( 'ramcache' ) + ':' );
ram_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var ram_desc = this._doc.createElement( 'description' );
ram_desc.setAttribute( 'id', 'cachestatus-ram-label' );
ram_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
ram_tooltip.appendChild( ram_desc_prefix );
ram_tooltip.appendChild( ram_desc );
var hd_tooltip = this._doc.createElement( 'tooltip' );
hd_tooltip.setAttribute( 'id', 'hd_tooltip' );
hd_tooltip.setAttribute( 'orient', 'horizontal' );
var hd_desc_prefix = this._doc.createElement( 'description' );
hd_desc_prefix.setAttribute( 'id', 'cachestatus-hd-prefix' );
hd_desc_prefix.setAttribute(
'value', string_bundle.getString( 'diskcache' ) + ':' );
hd_desc_prefix.setAttribute( 'style', 'font-weight: bold;' );
var hd_desc = this._doc.createElement( 'description' );
hd_desc.setAttribute( 'id', 'cachestatus-hd-label' );
hd_desc.setAttribute(
'value', string_bundle.getString( 'nly' ) );
hd_tooltip.appendChild( hd_desc_prefix );
hd_tooltip.appendChild( hd_desc );
popupset.appendChild( ram_tooltip );
popupset.appendChild( hd_tooltip );
hbox.parentNode.insertBefore( popupset, hbox );
var ram_image = this._doc.createElement( 'image' );
ram_image.setAttribute( 'src', 'chrome://cachestatus/skin/ram.png' );
ram_image.setAttribute( 'tooltip', 'ram_tooltip' );
var disk_image = this._doc.createElement( 'image' );
disk_image.setAttribute( 'src', 'chrome://cachestatus/skin/hd.png' );
disk_image.setAttribute( 'tooltip', 'hd_tooltip' );
hbox.appendChild( ram_image );
hbox.appendChild( disk_image );
}
}
}
// I can't just call csExtension.register directly b/c the XUL
// might not be loaded yet.
window.addEventListener( 'load', function() { csExtension.register(); }, false );
| purdy/cachestatus-firefox | chrome/content/cachestatus.js | JavaScript | mit | 15,267 |
(function() {
'use strict';
angular.module('newApp')
.controller('newAppCtrl', newAppCtrl);
function newAppCtrl() {
}
})();
| ekrtf/angular-express-starter | client/index.controller.js | JavaScript | mit | 156 |
let upath = require('upath'),
through2 = require('through2'),
paths = require('../../project.conf.js').paths,
RegexUtil = require('../util/RegexUtil');
module.exports = class StreamReplacer {
constructor(replacements = {}) {
this.replacements = replacements;
}
/**
* Add a transform to the replacer. A transform is a function that takes a vinyl file from the stream as a
* parameter and returns the path to be used as a replacement for that file.
*
* This function is called for each file present in the stream.
*
* @param transformFn(file)
*
* @returns {through2}
*/
push(transformFn) {
let that = this;
return through2.obj(function (file, enc, flush) {
let dir = upath.dirname(upath.relative(paths.src(), file.path)),
ext = upath.extname(file.path),
name = upath.basename(file.path, ext);
that.replacements[transformFn(file)] =
new RegExp(RegexUtil.escape(upath.join(dir, name + ext)).replace(/ /g, '(?: |%20)'), 'g');
this.push(file);
flush();
});
}
/**
* Search and replace all files in the stream with values according to the transforms configured via `push()`.
*
* @returns {through2}
*/
replace() {
let that = this;
return through2.obj(function (file, enc, flush) {
Object.keys(that.replacements).forEach((replacement) => {
file.contents = new Buffer(String(file.contents).replace(that.replacements[replacement], replacement));
});
this.push(file);
flush();
});
}
};
| tniswong/web-build | build/support/stream/StreamReplacer.js | JavaScript | mit | 1,719 |
/**
* WebCLGLVertexFragmentProgram Object
* @class
* @constructor
*/
WebCLGLVertexFragmentProgram = function(gl, vertexSource, vertexHeader, fragmentSource, fragmentHeader) {
this.gl = gl;
var highPrecisionSupport = this.gl.getShaderPrecisionFormat(this.gl.FRAGMENT_SHADER, this.gl.HIGH_FLOAT);
this.precision = (highPrecisionSupport.precision != 0) ? 'precision highp float;\n\nprecision highp int;\n\n' : 'precision lowp float;\n\nprecision lowp int;\n\n';
this.utils = new WebCLGLUtils();
this.vertexSource;
this.fragmentSource;
this.in_vertex_values = [];
this.in_fragment_values = [];
this.vertexAttributes = []; // {location,value}
this.vertexUniforms = []; // {location,value}
this.fragmentSamplers = []; // {location,value}
this.fragmentUniforms = []; // {location,value}
if(vertexSource != undefined) this.setVertexSource(vertexSource, vertexHeader);
if(fragmentSource != undefined) this.setFragmentSource(fragmentSource, fragmentHeader);
};
/**
* Update the vertex source
* @type Void
* @param {String} vertexSource
* @param {String} vertexHeader
*/
WebCLGLVertexFragmentProgram.prototype.setVertexSource = function(vertexSource, vertexHeader) {
this.vertexHead =(vertexHeader!=undefined)?vertexHeader:'';
this.in_vertex_values = [];//{value,type,name,idPointer}
// value: argument value
// type: 'buffer_float4_fromKernel'(4 packet pointer4), 'buffer_float_fromKernel'(1 packet pointer4), 'buffer_float4'(1 pointer4), 'buffer_float'(1 pointer1)
// name: argument name
// idPointer to: this.vertexAttributes or this.vertexUniforms (according to type)
var argumentsSource = vertexSource.split(')')[0].split('(')[1].split(','); // "float* A", "float* B", "float C", "float4* D"
//console.log(argumentsSource);
for(var n = 0, f = argumentsSource.length; n < f; n++) {
if(argumentsSource[n].match(/\*kernel/gm) != null) {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float4_fromKernel',
name:argumentsSource[n].split('*kernel')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float_fromKernel',
name:argumentsSource[n].split('*kernel')[1].trim()};
}
} else if(argumentsSource[n].match(/\*/gm) != null) {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float4',
name:argumentsSource[n].split('*')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float',
name:argumentsSource[n].split('*')[1].trim()};
}
} else {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'float4',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'float',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/mat4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'mat4',
name:argumentsSource[n].split(' ')[1].trim()};
}
}
}
//console.log(this.in_vertex_values);
//console.log('original source: '+vertexSource);
this.vertexSource = vertexSource.replace(/\r\n/gi, '').replace(/\r/gi, '').replace(/\n/gi, '');
this.vertexSource = this.vertexSource.replace(/^\w* \w*\([\w\s\*,]*\) {/gi, '').replace(/}(\s|\t)*$/gi, '');
//console.log('minified source: '+this.vertexSource);
this.vertexSource = this.parseVertexSource(this.vertexSource);
if(this.fragmentSource != undefined) this.compileVertexFragmentSource();
};
/** @private **/
WebCLGLVertexFragmentProgram.prototype.parseVertexSource = function(source) {
//console.log(source);
for(var n = 0, f = this.in_vertex_values.length; n < f; n++) { // for each in_vertex_values (in argument)
var regexp = new RegExp(this.in_vertex_values[n].name+'\\[\\w*\\]',"gm");
var varMatches = source.match(regexp);// "Search current "in_vertex_values.name[xxx]" in source and store in array varMatches
//console.log(varMatches);
if(varMatches != null) {
for(var nB = 0, fB = varMatches.length; nB < fB; nB++) { // for each varMatches ("A[x]", "A[x]")
var regexpNativeGL = new RegExp('```(\s|\t)*gl.*'+varMatches[nB]+'.*```[^```(\s|\t)*gl]',"gm");
var regexpNativeGLMatches = source.match(regexpNativeGL);
if(regexpNativeGLMatches == null) {
var name = varMatches[nB].split('[')[0];
var vari = varMatches[nB].split('[')[1].split(']')[0];
var regexp = new RegExp(name+'\\['+vari.trim()+'\\]',"gm");
if(this.in_vertex_values[n].type == 'buffer_float4_fromKernel')
source = source.replace(regexp, 'buffer_float4_fromKernel_data('+name+'0,'+name+'1,'+name+'2,'+name+'3)');
if(this.in_vertex_values[n].type == 'buffer_float_fromKernel')
source = source.replace(regexp, 'buffer_float_fromKernel_data('+name+'0)');
if(this.in_vertex_values[n].type == 'buffer_float4')
source = source.replace(regexp, name);
if(this.in_vertex_values[n].type == 'buffer_float')
source = source.replace(regexp, name);
}
}
}
}
source = source.replace(/```(\s|\t)*gl/gi, "").replace(/```/gi, "");
//console.log('%c translated source:'+source, "background-color:#000;color:#FFF");
return source;
};
/**
* Update the fragment source
* @type Void
* @param {String} fragmentSource
* @param {String} fragmentHeader
*/
WebCLGLVertexFragmentProgram.prototype.setFragmentSource = function(fragmentSource, fragmentHeader) {
this.fragmentHead =(fragmentHeader!=undefined)?fragmentHeader:'';
this.in_fragment_values = [];//{value,type,name,idPointer}
// value: argument value
// type: 'buffer_float4'(RGBA channels), 'buffer_float'(Red channel)
// name: argument name
// idPointer to: this.fragmentSamplers or this.fragmentUniforms (according to type)
var argumentsSource = fragmentSource.split(')')[0].split('(')[1].split(','); // "float* A", "float* B", "float C", "float4* D"
//console.log(argumentsSource);
for(var n = 0, f = argumentsSource.length; n < f; n++) {
if(argumentsSource[n].match(/\*/gm) != null) {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'buffer_float4',
name:argumentsSource[n].split('*')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'buffer_float',
name:argumentsSource[n].split('*')[1].trim()};
}
} else {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'float4',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'float',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/mat4/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'mat4',
name:argumentsSource[n].split(' ')[1].trim()};
}
}
}
//console.log(this.in_fragment_values);
//console.log('original source: '+source);
this.fragmentSource = fragmentSource.replace(/\r\n/gi, '').replace(/\r/gi, '').replace(/\n/gi, '');
this.fragmentSource = this.fragmentSource.replace(/^\w* \w*\([\w\s\*,]*\) {/gi, '').replace(/}(\s|\t)*$/gi, '');
//console.log('minified source: '+this.fragmentSource);
this.fragmentSource = this.parseFragmentSource(this.fragmentSource);
if(this.vertexSource != undefined) this.compileVertexFragmentSource();
};
/** @private **/
WebCLGLVertexFragmentProgram.prototype.parseFragmentSource = function(source) {
//console.log(source);
for(var n = 0, f = this.in_fragment_values.length; n < f; n++) { // for each in_fragment_values (in argument)
var regexp = new RegExp(this.in_fragment_values[n].name+'\\[\\w*\\]',"gm");
var varMatches = source.match(regexp);// "Search current "in_fragment_values.name[xxx]" in source and store in array varMatches
//console.log(varMatches);
if(varMatches != null) {
for(var nB = 0, fB = varMatches.length; nB < fB; nB++) { // for each varMatches ("A[x]", "A[x]")
var regexpNativeGL = new RegExp('```(\s|\t)*gl.*'+varMatches[nB]+'.*```[^```(\s|\t)*gl]',"gm");
var regexpNativeGLMatches = source.match(regexpNativeGL);
if(regexpNativeGLMatches == null) {
var name = varMatches[nB].split('[')[0];
var vari = varMatches[nB].split('[')[1].split(']')[0];
var regexp = new RegExp(name+'\\['+vari.trim()+'\\]',"gm");
if(this.in_fragment_values[n].type == 'buffer_float4')
source = source.replace(regexp, 'buffer_float4_data('+name+','+vari+')');
if(this.in_fragment_values[n].type == 'buffer_float')
source = source.replace(regexp, 'buffer_float_data('+name+','+vari+')');
}
}
}
}
source = source.replace(/```(\s|\t)*gl/gi, "").replace(/```/gi, "");
//console.log('%c translated source:'+source, "background-color:#000;color:#FFF");
return source;
};
/** @private **/
WebCLGLVertexFragmentProgram.prototype.compileVertexFragmentSource = function() {
lines_vertex_attrs = (function() {
str = '';
for(var n = 0, f = this.in_vertex_values.length; n < f; n++) {
if(this.in_vertex_values[n].type == 'buffer_float4_fromKernel') {
str += 'attribute vec4 '+this.in_vertex_values[n].name+'0;\n';
str += 'attribute vec4 '+this.in_vertex_values[n].name+'1;\n';
str += 'attribute vec4 '+this.in_vertex_values[n].name+'2;\n';
str += 'attribute vec4 '+this.in_vertex_values[n].name+'3;\n';
} else if(this.in_vertex_values[n].type == 'buffer_float_fromKernel') {
str += 'attribute vec4 '+this.in_vertex_values[n].name+'0;\n';
} else if(this.in_vertex_values[n].type == 'buffer_float4') {
str += 'attribute vec4 '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'buffer_float') {
str += 'attribute float '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'float') {
str += 'uniform float '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'float4') {
str += 'uniform vec4 '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'mat4') {
str += 'uniform mat4 '+this.in_vertex_values[n].name+';\n';
}
}
return str;
}).bind(this);
lines_fragment_attrs = (function() {
str = '';
for(var n = 0, f = this.in_fragment_values.length; n < f; n++) {
if(this.in_fragment_values[n].type == 'buffer_float4' || this.in_fragment_values[n].type == 'buffer_float') {
str += 'uniform sampler2D '+this.in_fragment_values[n].name+';\n';
} else if(this.in_fragment_values[n].type == 'float') {
str += 'uniform float '+this.in_fragment_values[n].name+';\n';
} else if(this.in_fragment_values[n].type == 'float4') {
str += 'uniform vec4 '+this.in_fragment_values[n].name+';\n';
} else if(this.in_fragment_values[n].type == 'mat4') {
str += 'uniform mat4 '+this.in_fragment_values[n].name+';\n';
}
}
return str;
}).bind(this);
var sourceVertex = this.precision+
'uniform float uOffset;\n'+
lines_vertex_attrs()+
this.utils.unpackGLSLFunctionString()+
'vec4 buffer_float4_fromKernel_data(vec4 arg0, vec4 arg1, vec4 arg2, vec4 arg3) {\n'+
'float argX = (unpack(arg0)*(uOffset*2.0))-uOffset;\n'+
'float argY = (unpack(arg1)*(uOffset*2.0))-uOffset;\n'+
'float argZ = (unpack(arg2)*(uOffset*2.0))-uOffset;\n'+
'float argW = (unpack(arg3)*(uOffset*2.0))-uOffset;\n'+
'return vec4(argX, argY, argZ, argW);\n'+
'}\n'+
'float buffer_float_fromKernel_data(vec4 arg0) {\n'+
'float argX = (unpack(arg0)*(uOffset*2.0))-uOffset;\n'+
'return argX;\n'+
'}\n'+
'vec2 get_global_id() {\n'+
'return vec2(0.0, 0.0);\n'+
'}\n'+
this.vertexHead+
'void main(void) {\n'+
this.vertexSource+
'}\n';
//console.log(sourceVertex);
var sourceFragment = this.precision+
lines_fragment_attrs()+
'vec4 buffer_float4_data(sampler2D arg, vec2 coord) {\n'+
'vec4 textureColor = texture2D(arg, coord);\n'+
'return textureColor;\n'+
'}\n'+
'float buffer_float_data(sampler2D arg, vec2 coord) {\n'+
'vec4 textureColor = texture2D(arg, coord);\n'+
'return textureColor.x;\n'+
'}\n'+
'vec2 get_global_id() {\n'+
'return vec2(0.0, 0.0);\n'+
'}\n'+
this.fragmentHead+
'void main(void) {\n'+
this.fragmentSource+
'}\n';
//console.log(sourceFragment);
this.vertexFragmentProgram = this.gl.createProgram();
this.utils.createShader(this.gl, "WEBCLGL VERTEX FRAGMENT PROGRAM", sourceVertex, sourceFragment, this.vertexFragmentProgram);
this.vertexAttributes = []; // {location,value}
this.vertexUniforms = []; // {location,value}
this.fragmentSamplers = []; // {location,value}
this.fragmentUniforms = []; // {location,value}
this.uOffset = this.gl.getUniformLocation(this.vertexFragmentProgram, "uOffset");
// vertexAttributes & vertexUniforms
for(var n = 0, f = this.in_vertex_values.length; n < f; n++) {
if( this.in_vertex_values[n].type == 'buffer_float4_fromKernel') {
this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"0"),
this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"1"),
this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"2"),
this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"3")],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1;
} else if(this.in_vertex_values[n].type == 'buffer_float_fromKernel') {
this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"0")],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1;
} else if(this.in_vertex_values[n].type == 'buffer_float4' || this.in_vertex_values[n].type == 'buffer_float') {
this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name)],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1;
} else if(this.in_vertex_values[n].type == 'float' || this.in_vertex_values[n].type == 'float4' || this.in_vertex_values[n].type == 'mat4') {
this.vertexUniforms.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name)],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexUniforms.length-1;
}
}
// fragmentSamplers & fragmentUniforms
for(var n = 0, f = this.in_fragment_values.length; n < f; n++) {
if(this.in_fragment_values[n].type == 'buffer_float4' || this.in_fragment_values[n].type == 'buffer_float') {
this.fragmentSamplers.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_fragment_values[n].name)],
value:this.in_fragment_values[n].value,
type: this.in_fragment_values[n].type});
this.in_fragment_values[n].idPointer = this.fragmentSamplers.length-1;
} else if(this.in_fragment_values[n].type == 'float' || this.in_fragment_values[n].type == 'float4' || this.in_fragment_values[n].type == 'mat4') {
this.fragmentUniforms.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_fragment_values[n].name)],
value:this.in_fragment_values[n].value,
type: this.in_fragment_values[n].type});
this.in_fragment_values[n].idPointer = this.fragmentUniforms.length-1;
}
}
return true;
};
/**
* Bind float, mat4 or a WebCLGLBuffer to a vertex argument
* @type Void
* @param {Int|String} argument Id of argument or name of this
* @param {Float|Int|WebCLGLBuffer} data
*/
WebCLGLVertexFragmentProgram.prototype.setVertexArg = function(argument, data) {
if(data == undefined) alert("Error: setVertexArg("+argument+", undefined)");
var numArg;
if(typeof argument != "string") {
numArg = argument;
} else {
for(var n=0, fn = this.in_vertex_values.length; n < fn; n++) {
if(this.in_vertex_values[n].name == argument) {
numArg = n;
break;
}
}
}
if(this.in_vertex_values[numArg] == undefined) {
console.log("argument "+argument+" not exist in this vertex program");
return;
}
this.in_vertex_values[numArg].value = data;
if( this.in_vertex_values[numArg].type == 'buffer_float4_fromKernel' ||
this.in_vertex_values[numArg].type == 'buffer_float_fromKernel' ||
this.in_vertex_values[numArg].type == 'buffer_float4' ||
this.in_vertex_values[numArg].type == 'buffer_float') {
this.vertexAttributes[this.in_vertex_values[numArg].idPointer].value = this.in_vertex_values[numArg].value;
} else if(this.in_vertex_values[numArg].type == 'float' || this.in_vertex_values[numArg].type == 'float4' || this.in_vertex_values[numArg].type == 'mat4') {
this.vertexUniforms[this.in_vertex_values[numArg].idPointer].value = this.in_vertex_values[numArg].value;
}
};
/**
* Bind float or a WebCLGLBuffer to a fragment argument
* @type Void
* @param {Int|String} argument Id of argument or name of this
* @param {Float|Int|WebCLGLBuffer} data
*/
WebCLGLVertexFragmentProgram.prototype.setFragmentArg = function(argument, data) {
if(data == undefined) alert("Error: setFragmentArg("+argument+", undefined)");
var numArg;
if(typeof argument != "string") {
numArg = argument;
} else {
for(var n=0, fn = this.in_fragment_values.length; n < fn; n++) {
if(this.in_fragment_values[n].name == argument) {
numArg = n;
break;
}
}
}
if(this.in_fragment_values[numArg] == undefined) {
console.log("argument "+argument+" not exist in this fragment program");
return;
}
this.in_fragment_values[numArg].value = data;
if(this.in_fragment_values[numArg].type == 'buffer_float4' || this.in_fragment_values[numArg].type == 'buffer_float') {
this.fragmentSamplers[this.in_fragment_values[numArg].idPointer].value = this.in_fragment_values[numArg].value;
} else if(this.in_fragment_values[numArg].type == 'float' || this.in_fragment_values[numArg].type == 'float4' || this.in_fragment_values[numArg].type == 'mat4') {
this.fragmentUniforms[this.in_fragment_values[numArg].idPointer].value = this.in_fragment_values[numArg].value;
}
};
| stormcolor/stormenginec | StormEngineC/WebCLGLVertexFragmentProgram.class.js | JavaScript | mit | 19,084 |
"use strict";
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
interval: 200,
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: false,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
node: true,
es5: true,
strict: true,
globalstrict: true
},
files: {
src: ['Gruntfile.js', 'package.json', 'lib/*.js', 'lib/controllers/**/*.js', 'lib/models/**/*.js', 'lib/utils/**/*.js', 'demo/*.js']
}
},
watch: {
files: ['<%= jshint.files.src %>'],
tasks: ['default']
}
});
// npm tasks
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Default task.
grunt.registerTask('default', ['jshint']);
};
| ahultgren/presspress | Gruntfile.js | JavaScript | mit | 943 |
//borrowed from stefanocudini bootstrap-list-filter
(function($) {
$.fn.btsListFilterContacts = function(inputEl, options) {
var searchlist = this,
searchlist$ = $(this),
inputEl$ = $(inputEl),
items$ = searchlist$,
callData,
callReq; //last callData execution
function tmpl(str, data) {
return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
return data[key] || '';
});
}
function debouncer(func, timeout) {
var timeoutID;
timeout = timeout || 300;
return function () {
var scope = this , args = arguments;
clearTimeout( timeoutID );
timeoutID = setTimeout( function () {
func.apply( scope , Array.prototype.slice.call( args ) );
}, timeout);
};
}
options = $.extend({
delay: 300,
minLength: 1,
initial: true,
eventKey: 'keyup',
resetOnBlur: true,
sourceData: null,
sourceTmpl: '<a class="list-group-item" href="#"><tr><h3><span>{title}</span></h3></tr></a>',
sourceNode: function(data) {
return tmpl(options.sourceTmpl, data);
},
emptyNode: function(data) {
return '<a class="list-group-item well" href="#"><span>No Results</span></a>';
},
itemEl: '.list-group-item',
itemChild: null,
itemFilter: function(item, val) {
//val = val.replace(new RegExp("^[.]$|[\[\]|()*]",'g'),'');
//val = val.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
val = val && val.replace(new RegExp("[({[^.$*+?\\\]})]","g"),'');
var text = $.trim($(item).text()),
i = options.initial ? '^' : '',
regSearch = new RegExp(i + val,'i');
return regSearch.test( text );
}
}, options);
inputEl$.on(options.eventKey, debouncer(function(e) {
var val = $(this).val();
console.log(val);
if(options.itemEl)
items$ = searchlist$.find(options.itemEl);
if(options.itemChild)
items$ = items$.find(options.itemChild);
var contains = items$.filter(function(){
return options.itemFilter.call(searchlist, this, val);
}),
containsNot = items$.not(contains);
if (options.itemChild){
contains = contains.parents(options.itemEl);
containsNot = containsNot.parents(options.itemEl).hide();
}
if(val!=='' && val.length >= options.minLength)
{
contains.show();
containsNot.hide();
if($.type(options.sourceData)==='function')
{
contains.hide();
containsNot.hide();
if(callReq)
{
if($.isFunction(callReq.abort))
callReq.abort();
else if($.isFunction(callReq.stop))
callReq.stop();
}
callReq = options.sourceData.call(searchlist, val, function(data) {
callReq = null;
contains.hide();
containsNot.hide();
searchlist$.find('.bts-dynamic-item').remove();
if(!data || data.length===0)
$( options.emptyNode.call(searchlist) ).addClass('bts-dynamic-item').appendTo(searchlist$);
else
for(var i in data)
$( options.sourceNode.call(searchlist, data[i]) ).addClass('bts-dynamic-item').appendTo(searchlist$);
});
} else if(contains.length===0) {
$( options.emptyNode.call(searchlist) ).addClass('bts-dynamic-item').appendTo(searchlist$);
}
}
else
{
contains.show();
containsNot.show();
searchlist$.find('.bts-dynamic-item').remove();
}
}, options.delay));
if(options.resetOnBlur)
inputEl$.on('blur', function(e) {
$(this).val('').trigger(options.eventKey);
});
return searchlist$;
};
})(jQuery); | navroopsingh/HepBProject | app/assets/javascripts/bootstrap-list-filter-contacts.js | JavaScript | mit | 3,485 |
/*!
* jquery.initialize. An basic element initializer plugin for jQuery.
*
* Copyright (c) 2014 Barış Güler
* http://hwclass.github.io
*
* Licensed under MIT
* http://www.opensource.org/licenses/mit-license.php
*
* http://docs.jquery.com/Plugins/Authoring
* jQuery authoring guidelines
*
* Launch : July 2014
* Version : 0.1.0
* Released: July 29th, 2014
*
*
* makes an element initialize for defined events with their names
*/
(function ($) {
$.fn.initialize = function (options) {
var currentElement = $(this),
opts = options;
var getSize = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var setEvents = function () {
for (var countForEventsObj = 0, len = getSize(opts.events); countForEventsObj < len; countForEventsObj++) {
$(this).on(opts.events[countForEventsObj].name, opts.events[countForEventsObj].funcBody)
}
}
if (opts.init) {
setEvents();
}
return this;
}
})(jQuery); | hwclass/jquery.initialize | jquery.initialize-0.1.0.js | JavaScript | mit | 1,101 |
/**
* utility library
*/
var basicAuth = require('basic-auth');
var fs = require('fs');
/**
* Simple basic auth middleware for use with Express 4.x.
*
* @example
* app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
*
* @param {string} username Expected username
* @param {string} password Expected password
* @returns {function} Express 4 middleware requiring the given credentials
*/
exports.basicAuth = function(username, password) {
return function(req, res, next) {
var user = basicAuth(req);
if (!user || user.name !== username || user.pass !== password) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
}
next();
};
};
exports.cpuTemp = function() {
var cputemp = Math.round(((parseFloat(fs.readFileSync("/sys/class/thermal/thermal_zone0/temp"))/1000) * (9/5) + 32)*100)/100;
return cputemp;
};
exports.w1Temp = function(serial) {
var temp;
var re=/t=(\d+)/;
try {
var text=fs.readFileSync('/sys/bus/w1/devices/' + serial + '/w1_slave','utf8');
if (typeof(text) != "undefined") {
if (text.indexOf("YES") > -1) {
var temptext=text.match(re);
if (typeof(temptext) != "undefined") {
temp = Math.round(((parseFloat(temptext[1])/1000) * (9/5) + 32)*100)/100;
}
}
}
} catch (e) {
console.log(e);
}
return temp;
};
| scwissel/garagepi | utils.js | JavaScript | mit | 1,421 |
version https://git-lfs.github.com/spec/v1
oid sha256:5f5740cfcc24e2a730f7ea590ae0dc07d66d256fd183c46facf3fdfeb0bd69d2
size 3654
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.16.0/io-queue/io-queue.js | JavaScript | mit | 129 |
version https://git-lfs.github.com/spec/v1
oid sha256:467bccdb74ef62e6611ba27f338a0ba0c49ba9a90ef1facb394c14de676318cf
size 1150464
| yogeshsaroya/new-cdnjs | ajax/libs/vis/3.12.0/vis.js | JavaScript | mit | 132 |
version https://git-lfs.github.com/spec/v1
oid sha256:4f8b1998d2048d6a6cabacdfb3689eba7c9cb669d6f81dbbd18156bdb0dbe18f
size 1880
| yogeshsaroya/new-cdnjs | ajax/libs/uikit/2.5.0/js/addons/form-password.js | JavaScript | mit | 129 |
import React from 'react'
import { FormControl } from 'react-bootstrap'
import './@FilterListInput.css'
const FilterListInput = ({onFilter, searchValue}) => {
let handleFilter = e => {
onFilter(e.target.value)
}
return (<FormControl className='FilterListInput' type='text' defaultValue={searchValue} placeholder='Search within this list...' onChange={handleFilter.bind(this)} />)
}
export default FilterListInput
| DataSF/open-data-explorer | src/components/FilterListInput/index.js | JavaScript | mit | 425 |
/*!
* ear-pipe
* Pipe audio streams to your ears
* Dan Motzenbecker <[email protected]>
* MIT Licensed
*/
"use strict";
var spawn = require('child_process').spawn,
util = require('util'),
Duplex = require('stream').Duplex,
apply = function(obj, method, args) {
return obj[method].apply(obj, args);
}
var EarPipe = function(type, bits, transcode) {
var params;
if (!(this instanceof EarPipe)) {
return new EarPipe(type, bits, transcode);
}
Duplex.apply(this);
params = ['-q', '-b', bits || 16, '-t', type || 'mp3', '-'];
if (transcode) {
this.process = spawn('sox',
params.concat(['-t', typeof transcode === 'string' ? transcode : 'wav', '-']));
} else {
this.process = spawn('play', params);
}
}
util.inherits(EarPipe, Duplex);
EarPipe.prototype._read = function() {
return apply(this.process.stdout, 'read', arguments);
}
EarPipe.prototype._write = function() {
return apply(this.process.stdin, 'write', arguments);
}
EarPipe.prototype.pipe = function() {
return apply(this.process.stdout, 'pipe', arguments);
}
EarPipe.prototype.end = function() {
return apply(this.process.stdin, 'end', arguments);
}
EarPipe.prototype.kill = function() {
return apply(this.process, 'kill', arguments);
}
module.exports = EarPipe;
| dmotz/ear-pipe | index.js | JavaScript | mit | 1,304 |
/**
* @description - The purpose of this model is to lookup various Drinking activities for a user
*/
var baseModel = require('./base');
var Drink;
Drink = baseModel.Model.extend({
tableName: 'drink'
});
module.exports = baseModel.model('Drink', Drink); | salimkapadia/dating-with-node-api | database/models/drink.js | JavaScript | mit | 260 |
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module',
ecmaFeatures: {
'jsx': true
},
},
globals: {
enz: true,
xhr_calls: true,
},
plugins: [
'react'
],
extends: 'react-app',
rules: {
'semi': [2, 'never'],
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 2,
// allow debugger during development
'no-debugger': 2,
'comma-danglcd e': 0,
'camelcase': 0,
'no-alert': 2,
'space-before-function-paren': 2,
'react/jsx-uses-react': 2,
'react/jsx-uses-vars': 2,
}
}
| tutorcruncher/socket-frontend | .eslintrc.js | JavaScript | mit | 653 |
define(['jquery'], function ($) {
if (!Array.prototype.reduce) {
/**
* Array.prototype.reduce polyfill
*
* @param {Function} callback
* @param {Value} [initialValue]
* @return {Value}
*
* @see http://goo.gl/WNriQD
*/
Array.prototype.reduce = function (callback) {
var t = Object(this),
len = t.length >>> 0,
k = 0,
value;
if (arguments.length === 2) {
value = arguments[1];
} else {
while (k < len && !(k in t)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value');
}
value = t[k++];
}
for (; k < len; k++) {
if (k in t) {
value = callback(value, t[k], k, t);
}
}
return value;
};
}
if ('function' !== typeof Array.prototype.filter) {
/**
* Array.prototype.filter polyfill
*
* @param {Function} func
* @return {Array}
*
* @see http://goo.gl/T1KFnq
*/
Array.prototype.filter = function (func) {
var t = Object(this),
len = t.length >>> 0;
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (func.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
var isSupportAmd = typeof define === 'function' && define.amd;
/**
* @class core.agent
*
* Object which check platform and agent
*
* @singleton
* @alternateClassName agent
*/
var agent = {
/** @property {Boolean} [isMac=false] true if this agent is Mac */
isMac: navigator.appVersion.indexOf('Mac') > -1,
/** @property {Boolean} [isMSIE=false] true if this agent is a Internet Explorer */
isMSIE: navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1,
/** @property {Boolean} [isFF=false] true if this agent is a Firefox */
isFF: navigator.userAgent.indexOf('Firefox') > -1,
/** @property {String} jqueryVersion current jQuery version string */
jqueryVersion: parseFloat($.fn.jquery),
isSupportAmd: isSupportAmd,
isW3CRangeSupport: !!document.createRange
};
return agent;
}); | czajkowski/sunnynote | src/js/core/agent.js | JavaScript | mit | 2,766 |
ml.module('three.scenes.Fog')
.requires('three.Three',
'three.core.Color')
.defines(function(){
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.Fog = function ( hex, near, far ) {
this.color = new THREE.Color( hex );
this.near = ( near !== undefined ) ? near : 1;
this.far = ( far !== undefined ) ? far : 1000;
};
}); | zfedoran/modulite-three.js | example/js/threejs/src/scenes/Fog.js | JavaScript | mit | 390 |
/**
* @file Generate ico image files.
* @memberof module:ci/tasks
* @function icoTask
* @param grunt
* @param {object} config - Task configuration.
* @param {function} callback - Callback when done.
*
*/
"use strict";
var ico = require('../../lib/commands/ico');
module.exports = function (grunt, config, callback) {
ico(config.src, config.dest, {}, function (err) {
if (!err) {
grunt.log.writeln('ICO file created: %s', config.dest);
callback(err);
}
});
}; | itkoren/fur | ci/tasks/ico_task.js | JavaScript | mit | 517 |
'use strict';
const path = require('path')
const webpack = require('webpack')
const pkg = require('./package.json')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackNotifierPlugin = require('webpack-notifier')
var paths = {
dist: path.join(__dirname, 'dist'),
src: path.join(__dirname, 'src')
}
const baseAppEntries = [
'./src/index.jsx'
];
const devAppEntries = [
'webpack-dev-server/client',
'webpack/hot/only-dev-server'
];
const appEntries = baseAppEntries
.concat(process.env.NODE_ENV === 'development' ? devAppEntries : []);
const basePlugins = [
new webpack.DefinePlugin({
__DEV__: process.env.NODE_ENV !== 'production',
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.optimize.CommonsChunkPlugin('vendor', '[name].[hash].js'),
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body'
})
];
const devPlugins = [
new webpack.NoErrorsPlugin(),
new WebpackNotifierPlugin({ title: pkg.name })
];
const prodPlugins = [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
];
const plugins = basePlugins
.concat(process.env.NODE_ENV === 'production' ? prodPlugins : [])
.concat(process.env.NODE_ENV === 'development' ? devPlugins : []);
module.exports = {
entry: {
app: appEntries,
vendor: [
'es5-shim',
'es6-shim',
'es6-promise',
'react',
'react-dom',
'react-redux',
'redux',
'redux-thunk'
]
},
output: {
path: paths.dist,
filename: '[name].[hash].js',
publicPath: '/',
sourceMapFilename: '[name].[hash].js.map',
chunkFilename: '[id].chunk.js'
},
devtool: 'eval-source-map',
resolve: {
extensions: ['', '.jsx', '.js', '.css']
},
plugins: plugins,
// devServer: {
// historyApiFallback: { index: '/' },
// proxy: proxy(),
// },
module: {
preLoaders: [
{
test: /\.js$/,
loader: "eslint",
exclude: /node_modules/
}
],
loaders: [{
test: /\.(jsx|js)?$/,
loader: 'react-hot!babel',
include: paths.src,
exclude: /(\.test\.js$)/
}, {
test: /\.css$/,
loaders: ['style', 'css?modules&localIdentName=[local]---[hash:base64:5]', 'postcss'],
include: paths.src
}, {
test: /\.html$/,
loader: 'raw',
exclude: /node_modules/
}
]
},
postcss: function (webpack) {
return [
require("postcss-import")({ addDependencyTo: webpack }),
require("postcss-url")(),
require("postcss-custom-properties")(),
require("postcss-nesting")(),
require("postcss-cssnext")(),
require("postcss-browser-reporter")(),
require("postcss-reporter")()
]
}
};
| shprink/react-redux-webpack-todo | webpack.config.js | JavaScript | mit | 3,162 |
var EcommerceProductsEdit = function () {
var handleImages = function() {
// see http://www.plupload.com/
var uploader = new plupload.Uploader({
runtimes : 'html5,html4',
browse_button : document.getElementById('tab_images_uploader_pickfiles'), // you can pass in id...
container: document.getElementById('tab_images_uploader_container'), // ... or DOM Element itsel
url : "assets/ajax/product-images.php",
filters : {
max_file_size : '10mb',
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
]
},
multipart_params: {'oper': "addproductimages"},
// Flash settings
flash_swf_url : 'assets/global/plugins/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url : 'assets/global/plugins/plupload/js/Moxie.xap',
init: {
PostInit: function() {
$('#tab_images_uploader_filelist').html("");
$('#tab_images_uploader_uploadfiles').click(function() {
uploader.start();
return false;
});
$('#tab_images_uploader_filelist').on('click', '.added-files .remove', function(){
uploader.removeFile($(this).parent('.added-files').attr("id"));
$(this).parent('.added-files').remove();
});
},
BeforeUpload: function(up, file) {
},
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
$('#tab_images_uploader_filelist').append('<div class="alert col-md-6 col-sm-12 alert-warning added-files" id="uploaded_file_' + file.id + '">' + file.name + '(' + plupload.formatSize(file.size) + ') <span class="status label label-info"></span> <a href="javascript:;" style="margin-top:0px" class="remove pull-right btn btn-xs red"><i class="fa fa-times"></i> </a></div>');
});
},
UploadProgress: function(up, file) {
$('#uploaded_file_' + file.id + ' > .status').html(file.percent + '%');
},
FileUploaded: function(up, file, response) {
var response = $.parseJSON(response.response);
if (response.error && response.error == 'no') {
var $uplaod_path = "../images/products/";
var newfile = response.newfilename.trim(); // uploaded file's unique name. Here you can collect uploaded file names and submit an jax request to your server side script to process the uploaded files and update the images tabke
if(newfile != ""){
$image_names = $("#image-names").val();
$img_lists = new Array();
$img_lists.push(newfile);
if($image_names != ""){
$img_lists = $image_names.split("::::");
$img_lists.push(newfile);
}
$("#image-names").val($img_lists.join("::::"));
$('#uploaded_file_' + file.id + ' > .status').removeClass("label-info").addClass("label-success").html('<i class="fa fa-check"></i> Done'); // set successfull upload
var imgContaint = '<div class="col-md-3 product-image-div"><div class=mt-overlay-1><div class=item-image><img alt="'+newfile+'"src="'+$uplaod_path+newfile+'"></div><div class=mt-overlay><ul class=mt-info><li><a class="btn btn-outline green" href="'+$uplaod_path+newfile+'"><i class=icon-magnifier></i></a><li><a class="btn btn-outline btn-product-image-delete red" href=javascript:; data-image="'+newfile+'"><i class="fa fa-trash-o"></i></a></ul></div></div></div>';
$('#Product-iamge-list').append(imgContaint);
}
} else {
$('#uploaded_file_' + file.id + ' > .status').removeClass("label-info").addClass("label-danger").html('<i class="fa fa-warning"></i> Failed'); // set failed upload
Metronic.alert({type: 'danger', message: response.msg, closeInSeconds: 10, icon: 'warning'});
}
},
Error: function(up, err) {
Metronic.alert({type: 'danger', message: err.message, closeInSeconds: 10, icon: 'warning'});
}
}
});
uploader.init();
// delete images();
//varient image handing
var optgroupContainer = $("#optiongroup-containner");
optgroupContainer.on("click", ".option-img-upload", function(e){
e.preventDefault();
$(this).closest('.mt-overlay-1').find(".option-img-upload-input").trigger("click");
});
optgroupContainer.on("change", ".option-img-upload-input", function(e){
e.preventDefault();
var $fileInput = $(this);
var fileInputImageContainer = $(this).closest('.mt-overlay-1');
var el = $fileInput.closest(".portlet").children(".portlet-body");
var $oper = 'saveoptionimage';
//over initialization
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
var formData = new FormData();
formData.append('oper', $oper);
formData.append('file', $fileInput[0].files[0]);
$.ajax({
url: "assets/ajax/ajax1.php",
data: formData,
method: "post",
contentType: false,
processData: false,
dataType: 'json',
success : function(response){
if(response.error == "no"){
var d = new Date();
fileInputImageContainer.find("img").attr('src', "../images/products/"+response.filename+"?"+d.getTime());
fileInputImageContainer.find('input[name^="product-option-img"]').val(response.filename);
$fileInput.val('');
}else{
Metronic.alert({type: 'danger', message: response.msg, closeInSeconds: 10, icon: 'warning'});
}
}
});
Metronic.unblockUI(el);
});
}
var initComponents = function(){
var summerEditer = $('#product-description');
summerEditer.summernote({
height: 150, // set editor height
minHeight: 100, // set minimum height of editor
maxHeight: 300, // set maximum height of editor
placeholder: 'Product Description here...',
toolbar: [
['style', ['bold', 'italic', 'underline', 'clear']],
['font', ['superscript', 'subscript']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']]
]
});
$('.note-editable').on('blur', function() {
if($(summerEditer.summernote('code')).text().length > 20){
$('.summernote-error').hide();
}else{
$('.summernote-error').show();
}
});
$.fn.select2.defaults.set("theme", "bootstrap");
$.fn.select2.defaults.set("id", function(object){ return object.text; });
$.fn.select2.defaults.set("tags", true);
/*$.fn.select2.defaults.set("createTag", function (params) { return { id: params.term, text: params.term, newOption: true}});
$.fn.select2.defaults.set("createSearchChoice", function(term, data){
if ( $(data).filter( function() {
return term.localeCompare(this.text)===0; //even if the this.text is undefined it works
}).length===0) {
if(confirm("Are you do you want to add item.")){
return {id:term, text:term};}
}
}) */
// non casesensetive matcher....
$.fn.select2.defaults.set("matcher", function(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// `params.term` should be the term that is used for searching
// `data.text` is the text that is displayed for the data object
if (data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) {
return data;
}
// Return `null` if the term should not be displayed
return null;
});
// non casesensitive tags creater
$.fn.select2.defaults.set("createTag", function(params) {
var term = $.trim(params.term);
if(term === "") { return null; }
var optionsMatch = false;
this.$element.find("option").each(function() {
// if(this.value.toLowerCase().indexOf(term.toLowerCase()) > -1) { // for caompare values
if($(this).text().toLowerCase().indexOf(term.toLowerCase()) > -1) { // for caompare option text
optionsMatch = true;
}
});
if(optionsMatch) {
return null;
}
return {id: term, text: term, tag:true};
});
$('#product-category').select2({placeholder:"Select Category"});
$('#product-brand').select2({placeholder:"Select Manufacturer"});
$("#product-collection").select2().on("select2:select", function(e){
if(e.params.data.tag == true){
$this = $(this);
var el = $this.closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post("assets/ajax/ajax1.php", {"oper": "saverandomcollection", "collection-name": $.trim(e.params.data.text)}, function(data){
Metronic.unblockUI(el);
if(data.error == "no"){
$('<option value="' + e.params.data.id + '">' + e.params.data.text + '</option>').appendTo($this);
}
}, "json");
}
});
$("#product-tags").select2();
var removeArrayItem = function (array, item){
for(var i in array){
if(array[i]==item){
array.splice(i,1);
break;
}
}
}
$("#Product-iamge-list").on("click", ".btn-product-image-delete", function(){
var $this = $(this);
if(confirm("Are you sure you want to remove image")){
var $image_container = $this.closest(".product-image-div");
var $img_name = $this.data("image");
var el = $(this).closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post( "assets/ajax/product-images.php", {'product-image':$img_name, 'oper':'deleteproductimages'},function(data){
data = jQuery.parseJSON(data);
if(data.error =="no"){
$image_container.fadeOut(300, function(){ $(this).remove();});
var $image_names = $("#image-names").val();
var $img_lists = new Array();
if($image_names != ""){
$img_lists = $image_names.split("::::");
removeArrayItem($img_lists, $img_name);
}
$("#image-names").val($img_lists.join("::::"));
}
Metronic.unblockUI(el);
});
}
});
// product attribuets
var addCustomAttrVal = function(){
$('select[name^="product-attributes-value"]').select2().on("select2:select", function(e){
$this = $(this);
$attribute_id = $.trim($this.data("attribute"));
if(e.params.data.tag == true && $attribute_id > 0){
var el = $this.closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post("assets/ajax/ajax1.php", {"oper": "savenewattributevalue", "attribute-value": $.trim(e.params.data.text), "attribute-id":$attribute_id}, function(data){
Metronic.unblockUI(el);
if(data.error == "no"){
$('<option value="' + e.params.data.id + '">' + e.params.data.text + '</option>').appendTo($this);
}
}, "json");
}
});
}
$("#product-category").on('change', function(){
$(".categoey-name-span").html($(this).find(":selected").html());
});
$(".categoey-name-span").html($("#product-category").find(":selected").html());
$("#btn-attribute-load").on("click", function(e){
e.preventDefault();
var filled_field = false;
$('input[name^="product-attributes-value"]').each(function() {
if($.trim($(this).val())){
filled_field = true;
return false;
}
});
var Confirm = true;
if(filled_field) Confirm = confirm("Previous specification data will erased. Are you sure want to reload Specification data.");
if(Confirm){
var el = $(this).closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post( "assets/ajax/ajax1.php", {'category-id':$("#product-category").val(), 'oper':'getattributebycategory'},function(data){
data = $.parseJSON(data);
if(data.error =="no"){
var $_html = "";
if(!$.isEmptyObject(data.attributeCollection)){
$i = 0;
$.each(data.attributeCollection, function(index, attributeGroup){
$_html += '<tr><td colspan="2" class="text-danger text-center"><strong>' + attributeGroup.name + '</strong></td></tr>';
$.each(attributeGroup.attributes, function(indexJ, attribute){
$_html += '<tr><td class="text-right"><label class="control-label input-sm">'+attribute.text +' : </label></td><input type="hidden" name="product-attributes-id['+$i+']" value="' + attribute.id + '"/><td>'
if(attribute.isfilter > 0){
$_html += '<select data-attribute="' + attribute.id + '" style="width:100%;" name="product-attributes-value['+$i+']" class="form-control input-sm">';
var filterArray = attribute.filters.split(",");
$.each(filterArray, function(index, filter){
$_html += '<option value = "'+filter+'">'+filter+'</option>';
});
$_html += "</select>";
}else{
$_html += '<input type="type" name="product-attributes-value['+$i+']" class="form-control input-sm">';
}
$_html += '</td></tr>';
$i++;
});
});
}else{
$_html = '<tr><td colspan="2" class="text-center">No Attributes Found. </td></tr>';
}
$("#attribute-list-table tbody").html($_html);
addCustomAttrVal();
}
Metronic.unblockUI(el);
});
}
});
addCustomAttrVal();
$("img", "#Product-iamge-list").error(function() {
$this = $(this);
$this.error = null;
$this.attr("src", "http://placehold.it/400?text=image")
});
$('[data-toggle="tooltip"]').tooltip();
// product varients
var optiongroupMaster = $("#optiongroupmaster").html();
var optgroupContainer = $("#optiongroup-containner");
var createCombinations = function($elements){
var CombinationArray = {};
var $i = 0;
$elements.each(function(index, element){
var SelectedOptGgroup = $(element).select2("data");
if(SelectedOptGgroup.length > 0){
var temp_array = {};
$.each(SelectedOptGgroup, function(index, data){
temp_array[index] = {text:data.text, id:data.id};
});
CombinationArray[$i++] = temp_array;
}
});
var $totalCombinations = {};
var i=0, k=0;
var combinations = [];
$.each(CombinationArray, function(index1, varients){
if(i== 0){
//combinations = varients;
$.each(varients, function(index, varient){
combinations.push(varient);
});
}else{
k = 0;
tempCombination = [];
$.each(combinations, function(index2, combination){
$.each(varients, function(index3, varient){
tempCombination[k] = [];
if(i == 1){
tempCombination[k].push(combination);
}else{
$.each(combination, function(index4, subCombination){
tempCombination[k].push(subCombination);
});
}
tempCombination[k].push(varient);
k++;
});
});
combinations = tempCombination;
}
i++;
});
return combinations;
}
var loadCombination = function(){
var $combinations = createCombinations($(".product-options-select2", optgroupContainer));
var $_html = "";
$.each($combinations, function(index, combination){
$_html += '<tr><td class="text-center">';
var combination_id = [];
if(Array.isArray(combination)){
combination_length = combination.length;
$.each(combination, function(index1, varient){
$_html += '<label class="label label-sm label-success lh2"><strong>'+varient.text+'</strong></label>';
combination_id.push(varient.id);
if(index1+1 < combination_length) $_html += " X ";
});
}else{
$_html += '<label class="label label-sm label-success lh2"><strong>'+combination.text+'</strong></label>';
combination_id.push(combination.id);
}
var comb_id_text = combination_id.join("-")
$_html += '<input type="hidden" name="combination-id[]" value="'+comb_id_text+'"></td><td><input type="text" name="combination-qty['+comb_id_text+']" placeholder="Quantity" class="form-control input-sm"></td><td><input type="text" name="combination-price['+comb_id_text+']" placeholder="Price" class="form-control input-sm"></td><!---<td><button type="button" class="btn btn-sm red btn-combination-delete">Delete</button></td>---></tr>';
});
$("tbody", "#verient-form-table").html($_html);
}
var has_img_html = '';
var insertImageDiv = function(id, text){
return '<div class="col-md-3 col-sm-6 text-center" id="selected-option-'+id+'" ><div class="mt-overlay-1"><div class="item-image"><img src="http://placehold.it/400?text='+text+'"></div><div class="mt-overlay"><ul class="mt-info"><li><input type="file" class="option-img-upload-input display-hide"><input type="hidden" name="product-option-img['+id+']"><a class="btn green btn-outline" href="javascript:;"><i class="icon-magnifier"></i></a></li><li><a class="btn yellow btn-outline option-img-upload" href="javascript:;"><i class="fa fa-upload"></i></a></li></ul></div></div><div class="bg-blue label-full">'+text+'</div></div>';
}
$(".product-options-select2", optgroupContainer).select2({tags : false});
$("#add_attrbut_btn").on("click", function(){
optgroupContainer.append(optiongroupMaster);
var otgrouplength = optgroupContainer.find(".optiongroups").length - 1;
var lastOptgroup = optgroupContainer.find(".optiongroups:last");
lastOptgroup.find(".product-options-select2:last").select2({tags: false})
.on("change", function(e) {
$this = $(this);
e.preventDefault();
loadCombination();
})
.on("select2:select", function(e){
$this = $(this);
if($this.closest(".optiongroups").find('.product-optgroup-select option:selected').data("type") == "image")
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").append(insertImageDiv(e.params.data.id, e.params.data.text));
})
.on("select2:unselect", function(e){
$this = $(this);
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").find("#selected-option-"+e.params.data.id).remove();
})
});
optgroupContainer.find(".product-options-select2").select2()
.on("change", function(e) {
e.preventDefault();
loadCombination();
})
.on("select2:select", function(e){
$this = $(this);
if($this.closest(".optiongroups").find('.product-optgroup-select option:selected').data("type") == "image")
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").append(insertImageDiv(e.params.data.id, e.params.data.text));
})
.on("select2:unselect", function(e){
$this = $(this);
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").find("#selected-option-"+e.params.data.id).remove();
});
optgroupContainer.on('click', ".optiongroup-delete-btn" , function(){
$(this).closest(".optiongroups").fadeOut(300, function(){ $(this).remove(); loadCombination();});
});
optgroupContainer.on("change", '.product-optgroup-select', function(){
var $this = $(this);
$found = false;
optgroupContainer.find(".product-optgroup-select").each(function(index, optgroup_select){
if($this.val() == $(optgroup_select).val() && !$this.is($(optgroup_select))){
$found = true;
return;
}
});
if($found){
Metronic.alert({type: 'danger', message: "This varient is already selected", closeInSeconds: 4, icon: 'warning'});
$this.val("").trigger("change");
return;
}
var optionGroupSelect = $this.closest(".optiongroups").find('.product-options-select2');
optionGroupSelect.select2("val", "");
if($.trim($this.val()) > 0){
$.post("assets/ajax/ajax1.php", {"option-group-id": $this.val(), "oper": "getoptionbyoptiongroup"}, function(data){
data = $.parseJSON(data);
if(data.error == "no"){
var $_html = "";
$.each(data.options, function(index, option){
$_html += '<option value="'+option.id+'">'+option.text+'</option>';
});
optionGroupSelect.html($_html);
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").html("");
}
});
}
if($this.find("option:selected").data("type") == "image"){
$this.closest(".optiongroups").find(".optgroup-image-btn").removeClass("display-hide");
$this.closest(".optiongroups").find(".optgroup-image-div").collapse("show");
}else{
$this.closest(".optiongroups").find(".optgroup-image-btn").addClass("display-hide");
$this.closest(".optiongroups").find(".optgroup-image-div").collapse("hide");
}
});
$("#verient-form-table tbody").on("click", ".btn-combination-delete",function(){
$(this).closest("tr").fadeOut(300, function(){ $(this).remove()});
});
optgroupContainer.on("click", ".optgroup-image-btn",function(e){
e.preventDefault();
$(this).closest(".optiongroups").find(".optgroup-image-div").collapse("toggle");
});
}
var handleForms = function() {
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
var product_form_validater = $("#product-form").validate();
$("#tab_images_uploader_pickfiles").on('click', function(){
$(".alert-product-image").hide();
});
$("#product-form").on('submit', function(e){
e.preventDefault();
$(".alert-product-image").hide();
if(product_form_validater.valid() === true){
$this = $(this);
var el = $this.closest(".portlet").children(".portlet-body");
image_vals = $("#image-names").val().trim();
$productDescription = $('#product-description').summernote('code');
if($($productDescription).text().length < 20){ // summernote validation....
$('.summernote-error').show();
$('#product-description').summernote('focus');
return false;
Metronic.unblockUI(el);
}
if(image_vals == "" || image_vals.indexOf(".") < 5){ // image valiadation
$(".alert-product-image").fadeIn("300").show();
var $target = $('html,body');
$target.animate({scrollTop: $target.height()}, 1000);
return false;
Metronic.unblockUI(el);
}
var $data = $this.serializeArray(); // convert form to array
$data.push({name: "product-description", value: $productDescription});
var optionGroups = $(".optiongroups", "#optiongroup-containner");
if(optionGroups.length > 0){
optionGroups.each(function(index, optiongroup){
$data.push({name: "product-optgroup["+index+"]", value: $(optiongroup).find(".product-optgroup-select").val()});
$data.push({name: "product-opttype["+index+"]", value: $(optiongroup).find(".product-optgroup-select option:selected").data("type")});
$data.push({name: "product-options["+index+"]", value: $(optiongroup).find(".product-options-select2").select2("val")});
});
}
//Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post( "assets/ajax/ajax1.php", $data, function(data){
data = jQuery.parseJSON(data);
if(data.error =="no"){
var ClickBtnVal = $("[type=submit][clicked=true]", $this).data("value");
if(ClickBtnVal == "save-exit"){
location.href="products.php?Saved=Successfully";
}else{
Metronic.alert({type: 'success', message: data.msg, closeInSeconds: 5, icon: 'check'});
}
}else{
Metronic.alert({type: 'danger', message: data.msg, closeInSeconds: 5, icon: 'warning'});
}
Metronic.unblockUI(el);
});
}
});
$("form button[type=submit], form input[type=submit]").click(function() {
$("button[type=submit], input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
}
return {
//main function to initiate the module
init: function () {
handleImages();
initComponents();
handleForms();
}
};
}(); | webstruction/eCommerce | assets/admin/pages/scripts/products-edit.js | JavaScript | mit | 24,442 |
var dotBeautify = require('../index.js');
var fs = require('fs');
var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;
var setup = 'function start (resp)\
{\
resp.writeHead(200, {"Content-Type": "text/html"\
});\
fs.readFile(filename, "utf8", function(err, data) {\
if (err) throw err;\
resp.write(data);resp.end ();});\
}';
describe('dotbeautify', function() {
before(function() {
fs.writeFileSync(__dirname + '/data/badFormat.js', setup, 'utf8');
});
it('Beautify the horribly formatted code without a config', function() {
dotBeautify.beautify([__dirname + '/data/']);
var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8');
var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8');
if(properFormat == badFormat) {
return true;
}
});
it('Beautify the horribly formatted code with a given config', function() {
dotBeautify.beautify([__dirname + '/data/'], { indent_size: 8 });
var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8');
var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8');
if(properFormat == badFormat) {
return true;
}
});
it('Should throw an error upon not passing any directories in', function() {
expect(function() {
dotBeautify.beautify([],{});
}).to.throw(Error);
});
});
| bearjaws/dotbeautify | test/index.spec.js | JavaScript | mit | 1,510 |
function Block() {
this.isAttacked = false;
this.hasShip = false;
this.shipType = "NONE";
this.attackable = true;
this.shipSize = 0;
this.direction = "no"
}
function Ship(x,y,direction,size){
this.x = x;
this.y = y;
this.direction = direction;
this.size = size;
this.win = false;
}
var bKimage = document.getElementById("OL");
function GameMap(x, y, scale,ctx) {
this.x = x;
this.y = y;
this.ctx =ctx;
this.scale = scale;
this.length = scale / 11;
this.mapGrid = new Array(10);
this.mapX = this.x + this.length;
this.mapY = this.y + this.length;
this.ships = [];
this.adjustScale = function(num){
this.scale = num;
this.length = this.scale / 11;
this.mapX = this.x + this.length;
this.mapY = this.y + this.length;
}
//ship info
this.sinkList = new Array(5);
for(var i = 0 ; i < 5 ; i++)
this.sinkList[i]= false;
this.win = function(){
for(var i = 0 ; i < 10 ; i++){
for(var j = 0 ;j < 10 ; j++){
if(this.mapGrid[j][i].hasShip && !this.mapGrid[j][i].isAttacked){
return false;
}
}
}
return true;
}
this.updateSink = function (){
var count = [0,0,0,0,0];
for(var i = 0 ;i < 10 ; i++){
for(var j = 0 ;j < 10 ; j++){
if(this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){
if(this.mapGrid[j][i].shipType == AIRCRAFT_CARRIER)
count[AIRCRAFT_CARRIER]++;
if(this.mapGrid[j][i].shipType == BATTLESHIP)
count[BATTLESHIP]++;
if(this.mapGrid[j][i].shipType == CRUISER)
count[CRUISER]++;
if(this.mapGrid[j][i].shipType == SUBMARINE)
count[SUBMARINE]++;
if(this.mapGrid[j][i].shipType == DESTROYER)
count[DESTROYER]++;
}
}
}
for(var i = 0 ;i < 5 ; i++){
if(count[AIRCRAFT_CARRIER]==5){
this.sinkList[AIRCRAFT_CARRIER]=true;
this.updataAttackable(AIRCRAFT_CARRIER);
}
if(count[BATTLESHIP]==4){
this.sinkList[BATTLESHIP]=true;
this.updataAttackable(BATTLESHIP);
}
if(count[CRUISER]==3){
this.sinkList[CRUISER]=true;
this.updataAttackable(CRUISER);
}
if(count[SUBMARINE]==3){
this.sinkList[SUBMARINE]=true;
this.updataAttackable(SUBMARINE);
}
if(count[DESTROYER]==2){
this.sinkList[DESTROYER]=true;
this.updataAttackable(DESTROYER);
}
}
//console.log(count);
}
this.updataAttackable = function(type){
for(var b = 0 ;b < 10 ; b++){
for(var a = 0 ;a < 10 ; a++){
if(this.mapGrid[a][b].shipType == type){
if(this.inIndex(a-1,b) && !this.hasShip(a-1,b) && !this.mapGrid[a-1][b].isAttacked)
this.mapGrid[a-1][b].attackable = false;
if(this.inIndex(a+1,b) && !this.hasShip(a+1,b) && !this.mapGrid[a+1][b].isAttacked)
this.mapGrid[a+1][b].attackable = false;
if(this.inIndex(a-1,b+1) && !this.hasShip(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked)
this.mapGrid[a-1][b+1].attackable = false;
if(this.inIndex(a+1,b+1) && !this.hasShip(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked)
this.mapGrid[a+1][b+1].attackable = false;
if(this.inIndex(a-1,b-1) && !this.hasShip(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked)
this.mapGrid[a-1][b-1].attackable = false;
if(this.inIndex(a+1,b-1) && !this.hasShip(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked)
this.mapGrid[a+1][b-1].attackable = false;
if(this.inIndex(a,b+1) && !this.hasShip(a,b+1) && !this.mapGrid[a][b+1].isAttacked)
this.mapGrid[a][b+1].attackable = false;
if(this.inIndex(a,b-1) && !this.hasShip(a,b-1) && !this.mapGrid[a][b-1].isAttacked)
this.mapGrid[a][b-1].attackable = false;
}
}
}
}
this.inIndex = function(a,b){
if(a < 0 || a > 9 || b < 0 || b >9)
return false;
return true;
}
this.resetMap = function() {
for (var i = 0; i < 10; i++) {
this.mapGrid[i] = new Array(10);
}
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
this.mapGrid[i][j] = new Block();
}
}
}
this.imgBG = document.getElementById("LB");
this.drawMap = function() {
this.ctx.font = "" + this.length + "px airborne";
this.ctx.fillStyle = "rgba(221,221,255,0.6)";
this.ctx.drawImage(this.imgBG,10,10,450,450,this.x + this.length, this.y + this.length, this.scale - this.length, this.scale - this.length);
this.ctx.fillRect(this.x + this.length, this.y + this.length, this.scale - this.length, this.scale - this.length);
this.ctx.strokeRect(this.x, this.y, this.scale, this.scale);
this.ctx.fillStyle = "#ddddff";
for (var i = 1; i <= 10; i++) {
this.ctx.moveTo(this.x + i * this.length, this.y);
this.ctx.lineTo(this.x + i * this.length, this.y + this.scale);
this.ctx.stroke();
this.ctx.fillText(i, this.x + i * this.length + this.length / 20, this.y + this.length - this.length / 10);
this.ctx.strokeText(i, this.x + i * this.length + this.length / 20, this.y + this.length - this.length / 10);
}
for (var i = 1; i <= 10; i++) {
this.ctx.moveTo(this.x, this.y + i * this.length);
this.ctx.lineTo(this.x + this.scale, this.y + i * this.length);
this.ctx.stroke();
this.ctx.fillText(String.fromCharCode(64 + i), this.x + this.length / 10, this.y + (i + 1) * this.length - this.length / 10);
this.ctx.strokeText(String.fromCharCode(64 + i), this.x + this.length / 10, this.y + (i + 1) * this.length - this.length / 10);
}
}
this.drawMark = function(shipOption){
for(var i = 0 ;i < 10 ; i++){
for(var j = 0 ;j < 10 ; j++){
if(shipOption && this.mapGrid[j][i].hasShip && !this.mapGrid[j][i].isAttacked ){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawShip(a,b);
}
if(this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawHit(a,b);
}
if(!this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawWave(a,b);
}
if(!this.mapGrid[j][i].attackable && hintSys){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawHint(a,b);
}
}
}
}
this.shipAttacked=function(a,b){
if(a>this.mapX && a<this.mapX+10*this.length && b>this.mapY && b<this.mapY+this.length*10){
a=a-this.mapX;
b=b-this.mapY;
a=Math.floor(a/this.length);
b=Math.floor(b/this.length);
if(!this.mapGrid[a][b].attackable || this.mapGrid[a][b].isAttacked){
return true;
}
this.mapGrid[a][b].isAttacked = true;
console.log(a + ", " + b);
this.drawMark();
this.updateSink();
if(this.mapGrid[a][b].hasShip == true){
shipHit();
if(this.inIndex(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked){
this.mapGrid[a+1][b+1].attackable = false;
}
if(this.inIndex(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked){
this.mapGrid[a+1][b-1].attackable = false;
}
if(this.inIndex(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked){
this.mapGrid[a-1][b+1].attackable = false;
}
if(this.inIndex(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked){
this.mapGrid[a-1][b-1].attackable = false;
}
this.drawMark();
return true;
}
else{
missedHit();
return false;
}
}
return true;
}
this.aiAttack = function(a,b){
console.log(a + ", " + b);
if(!this.mapGrid[a][b].attackable || this.mapGrid[a][b].isAttacked){
return true;
}
this.mapGrid[a][b].isAttacked = true;
this.drawMark();
this.updateSink();
if(this.mapGrid[a][b].hasShip == true){
if(this.inIndex(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked){
this.mapGrid[a+1][b+1].attackable = false;
}
if(this.inIndex(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked){
this.mapGrid[a+1][b-1].attackable = false;
}
if(this.inIndex(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked){
this.mapGrid[a-1][b+1].attackable = false;
}
if(this.inIndex(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked){
this.mapGrid[a-1][b-1].attackable = false;
}
this.drawMark();
return true;
}
else{
return false;
}
return true;
}
this.drawShip = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "blue";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.drawHit = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "red";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.drawWave = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "Grey";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.drawHint = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "#DDDDDD";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.hasShip = function(a,b) {
//if out of map , means no ship in there;
if(a < 0 || a > 9 || b < 0 || b >9)
return false;
return this.mapGrid[a][b].hasShip;
}
//check surrounding
this.checkSurrounding = function(a,b){
if(this.hasShip(a-1,b))
return false;
if(this.hasShip(a+1,b))
return false;
if(this.hasShip(a-1,b+1))
return false;
if(this.hasShip(a+1,b+1))
return false;
if(this.hasShip(a-1,b-1))
return false;
if(this.hasShip(a+1,b-1))
return false;
if(this.hasShip(a,b+1))
return false;
if(this.hasShip(a,b-1))
return false;
return true;
}
this.isPlaceable = function(a,b,direction,length){
//check this position
if(this.hasShip(a,b))
return false;
if(!this.checkSurrounding(a,b)){
return false;
}
if(direction == HORIZONTAL){
for(var i = 1 ; i < length ; i++){
if(a + length - 1 > 9){
return false
}
if(this.hasShip(a+i,b) || !this.checkSurrounding(a+i,b))
return false;
}
}
else{
for(var i = 1 ; i < length ; i++){
if(b + length - 1 > 9){
return false
}
if(this.hasShip(a,b+i) || !this.checkSurrounding(a,b+i))
return false;
}
}
return true;
}
this.randomPlacment = function(){
var direction;
var x;
var y;
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}
while(!this.isPlaceable(x,y,direction,5));
this.placeShip(x,y,AIRCRAFT_CARRIER,direction,5);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,4));
this.placeShip(x,y,BATTLESHIP,direction,4);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,3));
this.placeShip(x,y,CRUISER,direction,3);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,3));
this.placeShip(x,y,SUBMARINE,direction,3);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,2));
this.placeShip(x,y,DESTROYER,direction,2);
}
this. placeShip = function(x,y,name,direction,size){
if(direction == HORIZONTAL){
for(var i = 0 ; i< size ; i++){
this.mapGrid[x+i][y].hasShip = true;
this.mapGrid[x+i][y].shipType = name;
this.mapGrid[x+i][y].shipSize = size;
this.mapGrid[x+i][y].direction = direction;
}
}
else{
for(var i = 0 ; i< size ; i++){
this.mapGrid[x][y+i].hasShip = true;
this.mapGrid[x][y+i].shipType = name;
this.mapGrid[x][y+i].shipSize = size;
this.mapGrid[x][y+i].direction = direction;
}
}
}
}
| MAGKILLER/magkiller.github.io | Demo/battleship/mapObject.js | JavaScript | mit | 14,779 |
import Ember from 'ember';
export default Ember.Component.extend({
colorMap: {
running: 'green',
waiting: 'orange',
terminated: 'red'
},
getStatusByName(name) {
let retval = null;
Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => {
if (name === containerStatus.name) {
retval = containerStatus;
return;
}
});
return retval;
},
items: Ember.computed('containers', 'containerStatuses', function() {
let items = [];
this.get('containers').map((container) => {
let status = this.getStatusByName(container.name);
let state = Object.keys(status.state)[0],
stateLabel = state.capitalize(),
stateColor = this.colorMap[state],
readyLabel = status.ready ? 'Ready' : 'Not ready',
readyColor = status.ready ? 'green': 'orange';
items.push({ container, status, stateLabel, stateColor, readyLabel, readyColor });
});
return items;
})
});
| holandes22/kube-admin | app/components/pod-containers/component.js | JavaScript | mit | 987 |
define(function() {
var TramoView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#tramo-tmpl').html()),
events: {},
initialize: function() {},
render: function(index) {
$(this.el).html(this.template(this.model.toJSON()))
.addClass((index % 2 === 0) ? 'row1' : 'row2');
return this;
}
});
return TramoView;
});
| tapichu/highway-maps | project/media/js/views/TramoView.js | JavaScript | mit | 436 |
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'ts', 'tsx'],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.tsx?$': 'ts-jest'
},
transformIgnorePatterns: ['/node_modules/'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: ['jest-serializer-vue'],
testMatch: ['**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'],
testURL: 'http://localhost/',
watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'],
globals: {
'ts-jest': {
babelConfig: true
}
}
}
| vue-styleguidist/vue-styleguidist | examples/vuecli3-class-pug-ts/jest.config.js | JavaScript | mit | 655 |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.bitcoin = {
messagePrefix: '\x18Bitcoin Signed Message:\n',
bech32: 'bc',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4,
},
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80,
};
exports.regtest = {
messagePrefix: '\x18Bitcoin Signed Message:\n',
bech32: 'bcrt',
bip32: {
public: 0x043587cf,
private: 0x04358394,
},
pubKeyHash: 0x6f,
scriptHash: 0xc4,
wif: 0xef,
};
exports.testnet = {
messagePrefix: '\x18Bitcoin Signed Message:\n',
bech32: 'tb',
bip32: {
public: 0x043587cf,
private: 0x04358394,
},
pubKeyHash: 0x6f,
scriptHash: 0xc4,
wif: 0xef,
};
| visvirial/bitcoinjs-lib | src/networks.js | JavaScript | mit | 700 |
import React from 'react';
import PropTypes from 'prop-types';
import './index.css';
const TemplateWrapper = ({children}) => <div>{children()}</div>;
TemplateWrapper.propTypes = {
children: PropTypes.func,
};
export default TemplateWrapper;
| jwngr/jwn.gr | src/layouts/index.js | JavaScript | mit | 247 |
'use strict';
describe('Purchases E2E Tests:', function () {
describe('Test purchases page', function () {
it('Should report missing credentials', function () {
browser.get('http://localhost:3000/purchases');
expect(element.all(by.repeater('purchase in purchases')).count()).toEqual(0);
});
});
});
| bakmar/piwi | modules/purchases/tests/e2e/purchases.e2e.tests.js | JavaScript | mit | 324 |
(function(){
function render (context, points) {
console.log ('render called');
var angle = 0,
center = new Point3D (400,400,400);
return function () {
context.clearRect(0,0,800,600);
if (points.length < 1000) {
points.push (randomPoint());
}
if (angle > 360) {angle = 0;}
points.map (
function (pt) {
return pt.subtract (center);
}
).map (
function (pt) {
return y_rotate(pt, angle);
}
)/*.map (
function (pt) {
return x_rotate(pt, angle);
}
)//.map (
function (pt) {
return z_rotate(pt,angle);
}
)/**/.map (
function (pt) {
return project (pt,700);
}
).map (
function (pt) {
return {
x: pt['x'] + center.x,
y: pt['y'] + center.y,
scale: pt['scale']
}
}
).forEach (
function (pt) {
if (pt.scale < 0) {return;}
context.fillStyle = 'rgba(255,255,255,' + pt.scale + ')';
context.beginPath();
context.arc(pt.x, pt.y, 4*pt.scale, 0, Math.PI * 2, true);
context.closePath();
context.fill();
}
);
angle = angle + 1;
}
}
function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomPoint () {
return new Point3D (
randomInt (-100,900),
randomInt (-100,900),
randomInt (-100,900),
1,
randomInt (1,10)
);
}
function init() {
console.log ('inited');
var viewport = document.getElementById('viewport'),
context = viewport.getContext ('2d'),
points = [];
context.strokeStyle = '#aaa';
context.lineWidth = 1;
setInterval (render (context, points), 50);
}
document.body.onload = init;
}()); | davepkennedy/js-canvas | 3d-starfield/terrain.js | JavaScript | mit | 2,403 |
version https://git-lfs.github.com/spec/v1
oid sha256:59e6f2fa6c70c504d839d897c45f9a84348faf82342a31fb5818b1deb13861fa
size 294301
| yogeshsaroya/new-cdnjs | ajax/libs/handsontable/0.14.1/handsontable.full.min.js | JavaScript | mit | 131 |
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('coffee').del()
.then(function () {
// Inserts seed entries
return knex('coffee').insert([
{
id: 1,
name: 'Three Africas',
producer_id: 1,
flavor_profile: 'Fruity, radiant, creamy',
varieties: 'Heirloom',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
},
{
id: 2,
name: 'Ethiopia Bulga',
producer_id: 2,
flavor_profile: 'Cotton Candy, Strawberry, Sugar, Tangerine',
varieties: 'Heirloom',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
},
{
id: 3,
name: 'Columbia Andino',
producer_id: 2,
flavor_profile: 'Butterscotch Citrus',
varieties: 'Bourbon, Caturra, Typica',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
},
{
id: 4,
name: 'Colombia Popayán Fall Harvest',
producer_id: 1,
flavor_profile: 'Baking spice, red apple, nougat',
varieties: '',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
}])
.then(() => {
return knex.raw("SELECT setval('coffee_id_seq', (SELECT MAX(id) FROM coffee));");
});
});
};
| Jitters-API/jitters | db/seeds/development/04_coffee.js | JavaScript | mit | 1,738 |
'use strict';
var express = require('express'),
router = express.Router(),
Post = require('../models/post');
module.exports = function (app) {
app.use('/', router);
};
router.get('/', function (req, res, next) {
var posts = [new Post({
"title": "dummy posty"
}), new Post()];
res.render('index', {
title: 'Brian Mitchell',
active: {active_home: true},
posts: posts
});
});
| bman4789/brianm.me | app/controllers/home.js | JavaScript | mit | 406 |
"use strict";
const express = require('express');
const router = express.Router();
const quoteCtrl = require('../controllers/quote.js');
//returns an array of stocks that potentially match the query string
//no result will return an empty string
router.get('/quote/:quote', quoteCtrl.quote);
module.exports = router; | AJPcodes/stocks | routes/quote.js | JavaScript | mit | 319 |
var Blasticator = function() {
var init = function() {
registerSettings();
};
var showDialogue = function() {
new ModalDialogue({
message:'This will destroy EVERYTHING. FOREVER.',
buttons:[{
label:'Keep my data',
role:'secondary',
autoClose:true
},{
label:'BURN IT ALL',
role:'primary',
autoClose:true,
callback:function() {
App.persister.clear();
window.location.reload(true);
}
}]
});
};
var registerSettings = function() {
App.settings.register([{
section:'Data',
label:'Clear data',
type:'button',
iconClass:'fa-trash',
callback:showDialogue
}]);
};
init();
};
| elliottmina/chronos | docroot/modules/Blasticator/Blasticator.js | JavaScript | mit | 742 |
(function ()
{
window.AgidoMockups = window.AgidoMockups || {};
AgidoMockups.icons = AgidoMockups.icons || {};
AgidoMockups.icons.underline = new Kinetic.Group({name: "underlineIcon", width: 18, height: 20});
AgidoMockups.icons.underline.add(new Kinetic.Text({text: "U", fill: '#000', fontSize: 20, fontStyle: 'normal'}));
AgidoMockups.icons.underline.add(new Kinetic.Line({
points: [1, 19, 13, 19],
stroke: '#000',
strokeWidth: 1
}));
})(); | it-crowd/agido-mockups | src/icons/underline.icon.js | JavaScript | mit | 489 |
(function() {
var myPromise = new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((pos) => {
resolve(pos);
})
});
function parsePosition(pos) {
return {
lat: pos.coords.latitude,
lon: pos.coords.longitude
}
}
function displayMap(pos) {
let img = document.getElementById('theImg');
img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + pos.lat + "," + pos.lon + "&zoom=13&size=500x500&sensor=false";
}
myPromise
.then(parsePosition)
.then(console.log)
}()); | iliyaST/TelerikAcademy | JavaScript-Applications/01. Promises and asynchronous programming/homework/01. GeoLocations/GeoLocation.js | JavaScript | mit | 626 |
module.exports = function(grunt) {
grunt.initConfig({
// package.json is shared by all examples
pkg: grunt.file.readJSON('../../package.json'),
// Uglify the file at `src/foo.js` and output the result to `dist/foo.min.js`
//
// It's likely that this task is preceded by a `grunt-contrib-concat` task
// to create a single file which is then uglified.
uglify: {
options: {},
dist: {
files: {
'dist/foo.min.js': 'src/foo.js' // destination: source
}
}
}
});
// Load libraries used
grunt.loadNpmTasks('grunt-contrib-uglify');
// Define tasks
grunt.registerTask('default', ['uglify']);
}; | searaig/grunt-cookbook | examples/06.grunt-contrib-uglify/Gruntfile.js | JavaScript | mit | 677 |
'use strict';
angular.module('adsApp').controller('AdminTownsController', ['$scope', '$rootScope', 'catalog', 'config', 'notify',
function ($scope, $rootScope, catalog, config, notify) {
$rootScope.pageTitle = 'Towns';
var usersConfig = config.users;
var townsParams = {
startPage: usersConfig.startPage,
pageSize: usersConfig.pageSize
};
$scope.getTowns = function () {
$rootScope.loading = true;
catalog.get('admin/towns', townsParams).then(function (towns) {
$scope.towns = towns;
}, function (error) {
notify.message('Users filed to load!', error);
}).finally(function () {
$rootScope.loading = false;
});
};
$scope.getTowns();
}
]); | unbelt/Ads-Manager | app/controllers/admin/towns/AdminTownsController.js | JavaScript | mit | 838 |
/**
* @providesModule Case
*/
const DOM = require('DOM');
var Case = (function () {
/**
* A Case is a test against an element.
*/
function Case (attributes) {
return new Case.fn.init(attributes);
}
// Prototype object of the Case.
Case.fn = Case.prototype = {
constructor: Case,
init: function (attributes) {
this.listeners = {};
this.timeout = null;
this.attributes = attributes || {};
var that = this;
// Dispatch a resolve event if the case is initiated with a status.
if (this.attributes.status) {
// Delay the status dispatch to the next execution cycle so that the
// Case will register listeners in this execution cycle first.
setTimeout(function () {
that.resolve();
}, 0);
}
// Set up a time out for this case to resolve within.
else {
this.attributes.status = 'untested';
this.timeout = setTimeout(function () {
that.giveup();
}, 350);
}
return this;
},
// Details of the Case.
attributes: null,
get: function (attr) {
return this.attributes[attr];
},
set: function (attr, value) {
var isStatusChanged = false;
// Allow an object of attributes to be passed in.
if (typeof attr === 'object') {
for (var prop in attr) {
if (attr.hasOwnProperty(prop)) {
if (prop === 'status') {
isStatusChanged = true;
}
this.attributes[prop] = attr[prop];
}
}
}
// Assign a single attribute value.
else {
if (attr === 'status') {
isStatusChanged = true;
}
this.attributes[attr] = value;
}
if (isStatusChanged) {
this.resolve();
}
return this;
},
/**
* A test that determines if a case has one of a set of statuses.
*
* @return boolean
* A bit that indicates if the case has one of the supplied statuses.
*/
hasStatus: function (statuses) {
// This is a rought test of arrayness.
if (typeof statuses !== 'object') {
statuses = [statuses];
}
var status = this.get('status');
for (var i = 0, il = statuses.length; i < il; ++i) {
if (statuses[i] === status) {
return true;
}
}
return false;
},
/**
* Dispatches the resolve event; clears the timeout fallback event.
*/
resolve: function () {
clearTimeout(this.timeout);
var el = this.attributes.element;
var outerEl;
// Get a selector and HTML if an element is provided.
if (el && el.nodeType && el.nodeType === 1) {
// Allow a test to provide a selector. Programmatically find one if none
// is provided.
this.attributes.selector = this.defineUniqueSelector(el);
// Get a serialized HTML representation of the element the raised the error
// if the Test did not provide it.
if (!this.attributes.html) {
this.attributes.html = '';
// If the element is either the <html> or <body> elements,
// just report that. Otherwise we might be returning the entire page
// as a string.
if (el.nodeName === 'HTML' || el.nodeName === 'BODY') {
this.attributes.html = '<' + el.nodeName + '>';
}
// Get the parent node in order to get the innerHTML for the selected
// element. Trim wrapping whitespace, remove linebreaks and spaces.
else if (typeof el.outerHTML === 'string') {
outerEl = el.outerHTML.trim().replace(/(\r\n|\n|\r)/gm, '').replace(/>\s+</g, '><');
// Guard against insanely long elements.
// @todo, make this length configurable eventually.
if (outerEl.length > 200) {
outerEl = outerEl.substr(0, 200) + '... [truncated]';
}
this.attributes.html = outerEl;
}
}
}
this.dispatch('resolve', this);
},
/**
* Abandons the Case if it not resolved within the timeout period.
*/
giveup: function () {
clearTimeout(this.timeout);
// @todo, the set method should really have a 'silent' option.
this.attributes.status = 'untested';
this.dispatch('timeout', this);
},
// @todo, make this a set of methods that all classes extend.
listenTo: function (dispatcher, eventName, handler) {
handler = handler.bind(this);
dispatcher.registerListener.call(dispatcher, eventName, handler);
},
registerListener: function (eventName, handler) {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push(handler);
},
dispatch: function (eventName) {
if (this.listeners[eventName] && this.listeners[eventName].length) {
var eventArgs = [].slice.call(arguments);
this.listeners[eventName].forEach(function (handler) {
// Pass any additional arguments from the event dispatcher to the
// handler function.
handler.apply(null, eventArgs);
});
}
},
/**
* Creates a page-unique selector for the selected DOM element.
*
* @param {jQuery} element
* An element in a jQuery wrapper.
*
* @return {string}
* A unique selector for this element.
*/
defineUniqueSelector: function (element) {
/**
* Indicates whether the selector string represents a unique DOM element.
*
* @param {string} selector
* A string selector that can be used to query a DOM element.
*
* @return Boolean
* Whether or not the selector string represents a unique DOM element.
*/
function isUniquePath (selector) {
return DOM.scry(selector).length === 1;
}
/**
* Creates a selector from the element's id attribute.
*
* Temporary IDs created by the module that contain "visitorActions" are excluded.
*
* @param {HTMLElement} element
*
* @return {string}
* An id selector or an empty string.
*/
function applyID (element) {
var selector = '';
var id = element.id || '';
if (id.length > 0) {
selector = '#' + id;
}
return selector;
}
/**
* Creates a selector from classes on the element.
*
* Classes with known functional components like the word 'active' are
* excluded because these often denote state, not identity.
*
* @param {HTMLElement} element
*
* @return {string}
* A selector of classes or an empty string.
*/
function applyClasses (element) {
var selector = '';
// Try to make a selector from the element's classes.
var classes = element.className || '';
if (classes.length > 0) {
classes = classes.split(/\s+/);
// Filter out classes that might represent state.
classes = reject(classes, function (cl) {
return (/active|enabled|disabled|first|last|only|collapsed|open|clearfix|processed/).test(cl);
});
if (classes.length > 0) {
return '.' + classes.join('.');
}
}
return selector;
}
/**
* Finds attributes on the element and creates a selector from them.
*
* @param {HTMLElement} element
*
* @return {string}
* A selector of attributes or an empty string.
*/
function applyAttributes (element) {
var selector = '';
// Whitelisted attributes to include in a selector to disambiguate it.
var attributes = ['href', 'type', 'title', 'alt'];
var value;
if (typeof element === 'undefined' ||
typeof element.attributes === 'undefined' ||
element.attributes === null) {
return selector;
}
// Try to make a selector from the element's classes.
for (var i = 0, len = attributes.length; i < len; i++) {
value = element.attributes[attributes[i]] && element.attributes[attributes[i]].value;
if (value) {
selector += '[' + attributes[i] + '="' + value + '"]';
}
}
return selector;
}
/**
* Creates a unique selector using id, classes and attributes.
*
* It is possible that the selector will not be unique if there is no
* unique description using only ids, classes and attributes of an
* element that exist on the page already. If uniqueness cannot be
* determined and is required, you will need to add a unique identifier
* to the element through theming development.
*
* @param {HTMLElement} element
*
* @return {string}
* A unique selector for the element.
*/
function generateSelector (element) {
var selector = '';
var scopeSelector = '';
var pseudoUnique = false;
var firstPass = true;
do {
scopeSelector = '';
// Try to apply an ID.
if ((scopeSelector = applyID(element)).length > 0) {
selector = scopeSelector + ' ' + selector;
// Assume that a selector with an ID in the string is unique.
break;
}
// Try to apply classes.
if (!pseudoUnique && (scopeSelector = applyClasses(element)).length > 0) {
// If the classes don't create a unique path, tack them on and
// continue.
selector = scopeSelector + ' ' + selector;
// If the classes do create a unique path, mark this selector as
// pseudo unique. We will keep attempting to find an ID to really
// guarantee uniqueness.
if (isUniquePath(selector)) {
pseudoUnique = true;
}
}
// Process the original element.
if (firstPass) {
// Try to add attributes.
if ((scopeSelector = applyAttributes(element)).length > 0) {
// Do not include a space because the attributes qualify the
// element. Append classes if they exist.
selector = scopeSelector + selector;
}
// Add the element nodeName.
selector = element.nodeName.toLowerCase() + selector;
// The original element has been processed.
firstPass = false;
}
// Try the parent element to apply some scope.
element = element.parentNode;
} while (element && element.nodeType === 1 && element.nodeName !== 'BODY' && element.nodeName !== 'HTML');
return selector.trim();
}
/**
* Helper function to filter items from a list that pass the comparator
* test.
*
* @param {Array} list
* @param {function} comparator
* A function that return a boolean. True means the list item will be
* discarded from the list.
* @return array
* A list of items the excludes items that passed the comparator test.
*/
function reject (list, comparator) {
var keepers = [];
for (var i = 0, il = list.length; i < il; i++) {
if (!comparator.call(null, list[i])) {
keepers.push(list[i]);
}
}
return keepers;
}
return element && generateSelector(element);
},
push: [].push,
sort: [].sort,
concat: [].concat,
splice: [].splice
};
// Give the init function the Case prototype.
Case.fn.init.prototype = Case.fn;
return Case;
}());
module.exports = Case;
| quailjs/quail-core | src/core/Case.js | JavaScript | mit | 11,829 |
/*!
* Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0)
* Copyright 2013-2017 Start Bootstrap
* Purchase a license to use this theme at (https://wrapbootstrap.com)
*/
/*!
* Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0)
* Copyright 2013-2017 Start Bootstrap
* Purchase a license to use this theme at (https://wrapbootstrap.com)
*/
// Load WOW.js on non-touch devices
var isPhoneDevice = "ontouchstart" in document.documentElement;
$(document).ready(function() {
if (isPhoneDevice) {
//mobile
} else {
//desktop
// Initialize WOW.js
wow = new WOW({
offset: 50
})
wow.init();
}
});
(function($) {
"use strict"; // Start of use strict
// Collapse the navbar when page is scrolled
$(window).scroll(function() {
if ($("#mainNav").offset().top > 100) {
$("#mainNav").addClass("navbar-shrink");
} else {
$("#mainNav").removeClass("navbar-shrink");
}
});
// Activate scrollspy to add active class to navbar items on scroll
$('body').scrollspy({
target: '#mainNav',
offset: 68
});
// Smooth Scrolling: Smooth scrolls to an ID on the current page
// To use this feature, add a link on your page that links to an ID, and add the .page-scroll class to the link itself. See the docs for more details.
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 68)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Closes responsive menu when a link is clicked
$('.navbar-collapse>ul>li>a, .navbar-brand').click(function() {
$('.navbar-collapse').collapse('hide');
});
// Activates floating label headings for the contact form
$("body").on("input propertychange", ".floating-label-form-group", function(e) {
$(this).toggleClass("floating-label-form-group-with-value", !!$(e.target).val());
}).on("focus", ".floating-label-form-group", function() {
$(this).addClass("floating-label-form-group-with-focus");
}).on("blur", ".floating-label-form-group", function() {
$(this).removeClass("floating-label-form-group-with-focus");
});
// Owl Carousel Settings
$(".team-carousel").owlCarousel({
items: 3,
navigation: true,
pagination: false,
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
});
$(".portfolio-carousel").owlCarousel({
singleItem: true,
navigation: true,
pagination: false,
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
autoHeight: true,
mouseDrag: false,
touchDrag: false,
transitionStyle: "fadeUp"
});
$(".testimonials-carousel, .mockup-carousel").owlCarousel({
singleItem: true,
navigation: true,
pagination: true,
autoHeight: true,
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
transitionStyle: "backSlide"
});
$(".portfolio-gallery").owlCarousel({
items: 3,
});
// Magnific Popup jQuery Lightbox Gallery Settings
$('.gallery-link').magnificPopup({
type: 'image',
gallery: {
enabled: true
},
image: {
titleSrc: 'title'
}
});
// Magnific Popup Settings
$('.mix').magnificPopup({
type: 'image',
image: {
titleSrc: 'title'
}
});
// Vide - Video Background Settings
$('header.video').vide({
mp4: "mp4/camera.mp4",
poster: "img/agency/backgrounds/bg-mobile-fallback.jpg"
}, {
posterType: 'jpg'
});
})(jQuery); // End of use strict | EricRibeiro/DonactionTIS | donaction-enterprise/scripts/source/agency/vitality.js | JavaScript | mit | 4,078 |
import pagination from '@admin/store/modules/paginationStore'
import {HTTP} from '@shared/config/api'
const state = {
clientList: []
}
const getters = {
getClientList: state => state.clientList
}
const mutations = {
set(state, {type, value}) {
state[type] = value
},
delete(state, {id}) {
state.clientList = state.clientList.filter(w => w.Id !== id)
},
deleteMultiple(state, {ids}) {
state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1)
},
update(state, {client}) {
let index = state.clientList.findIndex(w => w.Id === client.Id)
if (index !== -1) {
state.clientList[index].Title = client.Title
state.clientList[index].Email = client.Email
state.clientList[index].Phone = client.Phone
state.clientList[index].Note = client.Note
}
}
}
const actions = {
getClients({commit, dispatch, getters}) {
HTTP.get('api/Client', {params: getters.getParams})
.then((response) => {
commit('set', {
type: 'clientList',
value: response.data.Items
})
dispatch('setTotalItems', response.data.Total)
})
.catch((error) => {
window.console.error(error)
})
},
createClient({dispatch}, client) {
HTTP.post('api/Client', client)
.then(() => {
dispatch('getClients')
})
.catch((error) => {
window.console.error(error)
})
},
updateClient({commit}, client) {
HTTP.patch('api/Client', client)
.then(() => {
commit('update', {client: client})
})
.catch((error) => {
window.console.error(error)
})
},
deleteClient({commit, dispatch}, client) {
HTTP.delete('api/Client', client)
.then(() => {
commit('delete', {id: client.params.id})
dispatch('addToTotalItems', -1)
})
.catch((error) => {
window.console.error(error)
})
},
deleteMultipleClient({commit, dispatch}, clients) {
HTTP.delete('api/Client', clients)
.then(() => {
commit('deleteMultiple', {ids: clients.params.ids})
dispatch('addToTotalItems', -clients.params.ids.length)
})
.catch((error) => {
window.console.error(error)
})
}
}
export default {
namespaced: true,
state,
mutations,
actions,
getters,
modules: {
Pagination: pagination()
}
}
| mt89vein/mvc5-vuejs | Vue/src/admin/store/modules/clientListStore.js | JavaScript | mit | 2,609 |
import "cutaway"
import { assert, report } from "tapeless"
import createPlayer from "./main.js"
const { ok, notOk, equal } = assert
try {
createPlayer()
} catch (e) {
ok
.describe("will throw sans video input")
.test(e, e.message)
}
const source = document.createElement("video")
source.src = ""
const { play, stop } = createPlayer(source)
equal
.describe("play")
.test(typeof play, "function")
notOk
.describe("playing")
.test(play())
equal
.describe("stop")
.test(typeof stop, "function")
ok
.describe("paused", "will operate")
.test(stop())
report()
| thewhodidthis/playah | test.js | JavaScript | mit | 591 |
class dximagetransform_microsoft_maskfilter {
constructor() {
// Variant Color () {get} {set}
this.Color = undefined;
}
}
module.exports = dximagetransform_microsoft_maskfilter;
| mrpapercut/wscript | testfiles/COMobjects/JSclasses/DXImageTransform.Microsoft.MaskFilter.js | JavaScript | mit | 206 |
/**
* Calculates the radius of the Hill Sphere,
* for a body with mass `m1`
* @param {Number} m1 Mass of the lighter body
* @param {Number} m2 Mass of the heavier body
* @param {Number} a Semi-major axis
* @param {Number} e Eccentricity
* @return {Number} Hill Sphere radius
*/
function hillSphere( m1, m2, a, e ) {
return a * ( 1 - e ) * Math.pow(
( m1 / ( 3 * m2 ) ), 1/3
)
}
module.exports = hillSphere
| jhermsmeier/node-hill-sphere | lib/hill-sphere.js | JavaScript | mit | 432 |
var httpRequester = (function() {
var makeHttpRequest = function(url, type, data) {
var deferred = $.Deferred();
$.ajax({
url: url,
type: type,
contentType: 'application/json',
data: data,
success: function(resultData) {
deferred.resolve(resultData);
},
error: function(error) {
deferred.reject(error);
}
});
return deferred;
};
var sendRequest = function(url, type, data) {
return makeHttpRequest(url, type, data);
};
return {
sendRequest: sendRequest
};
}()); | Vali0/WBTA | public/js/httpRequester.js | JavaScript | mit | 664 |
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosCopy extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon>
<g>
<path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path>
</g>
</g>
</g>;
} return <IconBase>
<g>
<polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon>
<g>
<path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path>
</g>
</g>
</IconBase>;
}
};IosCopy.defaultProps = {bare: false} | fbfeix/react-icons | src/icons/IosCopy.js | JavaScript | mit | 693 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import _ from 'lodash';
import User from './User';
import Loading from '../../components/Icon/Loading';
import './InterestingPeople.less';
import steemAPI from '../../steemAPI';
class InterestingPeopleWithAPI extends Component {
static propTypes = {
authenticatedUser: PropTypes.shape({
name: PropTypes.string,
}),
followingList: PropTypes.arrayOf(PropTypes.string),
};
static defaultProps = {
authenticatedUser: {
name: '',
},
followingList: [],
};
state = {
users: [],
loading: true,
noUsers: false,
};
componentWillMount() {
const authenticatedUsername = this.props.authenticatedUser.name;
const usernameValidator = window.location.pathname.match(/@(.*)/);
const username = usernameValidator ? usernameValidator[1] : authenticatedUsername;
this.getBlogAuthors(username);
}
getBlogAuthors = (username = '') =>
steemAPI
.getBlogAuthorsAsync(username)
.then((result) => {
const followers = this.props.followingList;
const users = _.sortBy(result, user => user[1])
.reverse()
.filter(user => !followers.includes(user[0]))
.slice(0, 5)
.map(user => ({ name: user[0] }));
if (users.length > 0) {
this.setState({
users,
loading: false,
noUsers: false,
});
} else {
this.setState({
noUsers: true,
});
}
})
.catch(() => {
this.setState({
noUsers: true,
});
});
render() {
const { users, loading, noUsers } = this.state;
if (noUsers) {
return <div />;
}
if (loading) {
return <Loading />;
}
return (
<div className="InterestingPeople">
<div className="InterestingPeople__container">
<h4 className="InterestingPeople__title">
<i className="iconfont icon-group InterestingPeople__icon" />
{' '}
<FormattedMessage id="interesting_people" defaultMessage="Interesting People" />
</h4>
<div className="InterestingPeople__divider" />
{users && users.map(user => <User key={user.name} user={user} />)}
<h4 className="InterestingPeople__more">
<Link to={'/latest-comments'}>
<FormattedMessage id="discover_more_people" defaultMessage="Discover More People" />
</Link>
</h4>
</div>
</div>
);
}
}
export default InterestingPeopleWithAPI;
| ryanbaer/busy | src/components/Sidebar/InterestingPeopleWithAPI.js | JavaScript | mit | 2,712 |
var pagerun = require('pagerun');
// set for debug
// pagerun.modulesRoot = '../';
pagerun.mode = 'test';
// pagerun.loadNpmPlugin('httpresponse');
pagerun.loadNpmPlugin('httpsummary');
pagerun.loadNpmPlugin('httperror');
pagerun.loadNpmPlugin('htmlhint');
pagerun.loadNpmPlugin('jserror');
pagerun.loadNpmPlugin('pagesummary');
pagerun.loadNpmPlugin('jsunit');
// pagerun.loadNpmPlugin('jscoverage');
process.on('message', function(config) {
pagerun.setConfig(config);
pagerun.run(function(result){
process.send(result);
process.exit(0);
});
}); | yaniswang/pageRun-sampleProject | pagerun.js | JavaScript | mit | 580 |
'use strict';
$(function() {
$.material.init();
$('#libraries').btsListFilter('#searcher', {
itemChild: 'h3',
resetOnBlur: false
});
$('#searcher').focus();
});
| jerone/PackageSize | public/js/script.js | JavaScript | mit | 171 |
/**
* Copyright 2016 aixigo AG
* Released under the MIT license.
* http://laxarjs.org/license
*/
/**
* Allows to instantiate a mock implementations of {@link AxStorage}, compatible to the "axStorage" injection.
*
* @module widget_services_storage_mock
*/
import { create as createGlobalStorageMock } from './storage_mock';
/**
* Creates a mock for the `axStorage` injection of a widget.
*
* @return {AxStorageMock}
* a mock of `axStorage` that can be spied and/or mocked with additional items
*/
export function create() {
const globalStorageMock = createGlobalStorageMock();
const namespace = 'mock';
const local = globalStorageMock.getLocalStorage( namespace );
const session = globalStorageMock.getSessionStorage( namespace );
/**
* The AxStorageMock provides the same API as AxStorage, with the additional property
* {@link #mockBackends} to inspect and/or simulate mock values in the storage backend.
*
* @name AxStorageMock
* @constructor
* @extends AxStorage
*/
return {
local,
session,
/**
* Provides access to the backing stores for `local` and `session` storage.
*
* Contains `local` and `session` store properties. The stores are plain objects whose properties
* reflect any setItem/removeItem operations. When properties are set on a store, they are observed
* by `getItem` calls on the corresponding axStorage API.
*
* @memberof AxStorageMock
*/
mockBackends: {
local: globalStorageMock.mockBackends.local[ namespace ].store,
session: globalStorageMock.mockBackends.session[ namespace ].store
}
};
}
| LaxarJS/laxar | lib/testing/widget_services_storage_mock.js | JavaScript | mit | 1,690 |
import {appendHtml, combine} from './../util';
const ELEMENT_NAMES = {
frameName: 'text-frame',
messageName: 'text-message',
indicatorName: 'text-indicator'
};
let createElements = (container, names) => {
const elements = '\
<div class="text-frame" id="' + names.frameName + '">\
<span class="text-message" id="' + names.messageName + '"></span>\
<span id="' + names.indicatorName + '">▼</span>\
</div>';
appendHtml(container, elements);
}
export default class TextOutput {
constructor(parent, engine) {
let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames);
if (!engine.overrides.useCustomElements) {
createElements(parent, elementNames);
}
this._textMessages = [];
this.engine = engine;
this.textMessageFrame = document.getElementById(elementNames.frameName);
this.textMessage = document.getElementById(elementNames.messageName);
this.textIndicator = document.getElementById(elementNames.indicatorName)
this.textMessageFrame.onclick = () => engine.drawMessages();
engine.clearText = combine(engine.clearText, this.clearText.bind(this));
engine.displayText = combine(engine.displayText, this.displayText.bind(this));
engine.drawMessages = combine(engine.drawMessages, this.drawMessages.bind(this));
engine.actionExecutor.registerAction("text", (options, engine, player, callback) => {
engine.displayText(options.text.split("\n"));
}, false, true);
}
clearText () {
this._textMessages = [];
this.textMessageFrame.classList.remove("in");
this.textMessage.innerHTML = "";
this.textIndicator.classList.remove("in");
this.engine.unpause();
}
displayText (text) {
this._textMessages = this._textMessages.concat(text);
}
drawMessages () {
if (this._textMessages.length > 0) {
this.engine.pause();
const text = this._textMessages.splice(0, 1)[0];
this.textMessage.innerHTML = text;
if (!("in" in this.textMessageFrame.classList)) {
this.textMessageFrame.classList.add("in");
}
if (this._textMessages.length >= 1) {
this.textIndicator.classList.add("in");
} else {
this.textIndicator.classList.remove("in");
}
} else {
this.clearText();
}
}
}
| Parnswir/tie | src/extensions/TextOutput.js | JavaScript | mit | 2,308 |
//= require sencha_touch/sencha-touch
//= require_directory ./sencha_touch/app
//= require_tree ./sencha_touch/app/models
//= require_tree ./sencha_touch/app/stores
//= require_tree ./sencha_touch/app/controllers
//= require_tree ./sencha_touch/app/views
| AlexanderFlatscher/bakk1todo | app/assets/javascripts/sencha_touch.js | JavaScript | mit | 261 |
;(function() {
function ToerismeApp(id, parentContainer) {
this.API_URL = 'https://datatank.stad.gent/4/toerisme/visitgentevents.json';
this.id = id;
this.parentContainer = parentContainer;
this.loadData = function() {
var that = this;
var xhr = new XMLHttpRequest();
xhr.open('get', this.API_URL, true);
xhr.responseType = 'json';
xhr.onload = function() {
if(xhr.status == 200) {
var data = (!xhr.responseType)?JSON.parse(xhr.response):xhr.response;
var id = 1;
var tempStr = '';
for(i=0; i<20; i++) {
var title = data[i].title;
var contact = data[i].contact[0];
//var website = contact.website[0];
//var weburl = website.url;
var images = data[i].images[0];
var language = data[i].language;
var website = '';
if(contact.website){
website = contact.website[0].url;
//console.log(website);
}
if(language == 'nl'){
tempStr += '<div class="row row_events">';
tempStr += '<a href="http://' + website +'" target="_blank";>';
tempStr += '<div class="col-xs-6"><div class="div_image" style="background: url(' + images +') no-repeat center ;background-size:cover;"></div></div>';
tempStr += '<div class="col-xs-6"><h4>' + title + '</h4>';
tempStr += '<p>Adres: ' + contact.street + ' nr ' + contact.number + '<br> Stad: ' + contact.city +'</p>';
tempStr += '</div>'; /* einde adres */
tempStr += '</a>';
tempStr += '<a class="link_heart" id="myDIV'+[i]+'" alt="Add to favorites" title="Add to favorites" onclick="myFunction('+[i]+')" ><span class="glyphicon glyphicon-heart-empty"></span></a>';
tempStr += '</div>';/* einde row */
}else{};
}
that.parentContainer.innerHTML = tempStr;
} else {
console.log('xhr.status');
}
}
xhr.onerror = function() {
console.log('Error');
}
xhr.send();
};
this.updateUI = function() {
};
this.toString = function() {
return `ToerismeApp with id: ${this.id}`;
};
};
var ww1 = new ToerismeApp(1, document.querySelector('.sidebar'));
ww1.loadData();
console.log(ww1.toString());
})();
function myFunction(id){
document.getElementById("myDIV"+id).classList.toggle("link_heart-select");
}
| dwievane/dwievane.github.io | js/events.js | JavaScript | mit | 2,650 |
module.exports = "module-one-A-model";
| sekko27/node-wire-helper | tests/loader/module-one/lib/domain/models/A.js | JavaScript | mit | 39 |
$(function () {
'use strict';
const notificationType = {
success: 'Success',
error: 'Error',
info: 'Info'
},
notificationTypeClass = {
success: 'toast-success',
info: 'toast-info',
error: 'toast-error'
};
function initSignalR() {
let connection = $.connection,
hub = connection.notificationHub;
hub.client.toast = (message, dellay, type) => {
console.log('CALLEEEEEEEEEEEED')
if (type === notificationType.success) {
Materialize.toast(message, dellay, notificationTypeClass.success)
} else if (type === notificationType.info) {
Materialize.toast(message, dellay, notificationTypeClass.info)
} else {
Materialize.toast(message, dellay, notificationTypeClass.error)
}
};
connection.hub.start().done(() => hub.server.init());
}
initSignalR();
}()); | SuchTeam-NoJoro-MuchSad/Doge-News | DogeNews/Src/Web/DogeNews.Web/Scripts/Common/notificator.js | JavaScript | mit | 1,006 |
/**
* Ensures that the callback pattern is followed properly
* with an Error object (or undefined or null) in the first position.
*/
'use strict'
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
/**
* Determine if a node has a possiblity to be an Error object
* @param {ASTNode} node ASTNode to check
* @returns {boolean} True if there is a chance it contains an Error obj
*/
function couldBeError (node) {
let exprs
switch (node.type) {
case 'Identifier':
case 'CallExpression':
case 'NewExpression':
case 'MemberExpression':
case 'TaggedTemplateExpression':
case 'YieldExpression':
return true // possibly an error object.
case 'AssignmentExpression':
return couldBeError(node.right)
case 'SequenceExpression':
exprs = node.expressions
return exprs.length !== 0 && couldBeError(exprs[exprs.length - 1])
case 'LogicalExpression':
return couldBeError(node.left) || couldBeError(node.right)
case 'ConditionalExpression':
return couldBeError(node.consequent) || couldBeError(node.alternate)
default:
return node.value === null
}
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
type: 'suggestion',
docs: {
url: 'https://github.com/standard/eslint-plugin-standard#rules-explanations'
}
},
create: function (context) {
const callbackNames = context.options[0] || ['callback', 'cb']
function isCallback (name) {
return callbackNames.indexOf(name) > -1
}
return {
CallExpression: function (node) {
const errorArg = node.arguments[0]
const calleeName = node.callee.name
if (errorArg && !couldBeError(errorArg) && isCallback(calleeName)) {
context.report(node, 'Unexpected literal in error position of callback.')
}
}
}
}
}
| xjamundx/eslint-plugin-standard | rules/no-callback-literal.js | JavaScript | mit | 2,134 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The Date.prototype.getMinutes property "length" has { ReadOnly,
DontDelete, DontEnum } attributes
es5id: 15.9.5.20_A3_T1
description: Checking ReadOnly attribute
---*/
x = Date.prototype.getMinutes.length;
Date.prototype.getMinutes.length = 1;
if (Date.prototype.getMinutes.length !== x) {
$ERROR('#1: The Date.prototype.getMinutes.length has the attribute ReadOnly');
}
| PiotrDabkowski/Js2Py | tests/test_cases/built-ins/Date/prototype/getMinutes/S15.9.5.20_A3_T1.js | JavaScript | mit | 529 |
module.exports = function(sails) {
var Agenda = require('agenda'),
util = require('util'),
_ = require('lodash'),
os = require("os"),
agenda = new Agenda()
agenda.sails = sails;
var stopServer = function() {
agenda.stop(function() {
console.log("agenda stopped");
});
};
sails.on("lower", stopServer);
sails.on("lowering", stopServer);
// return hook
return {
// expose agenda in sails.hooks.jobs.agenda
jobs: agenda,
// Defaults config
defaults: {
jobs: {
"globalJobsObjectName": "Jobs",
"jobsDirectory": "api/jobs",
"db": {
"address" : "localhost:27017/jobs",
"collection" : "agendaJobs"
},
"name": os.hostname() + '-' + process.pid,
"processEvery": "1 minutes",
"maxConcurrency": 20,
"defaultConcurrency": 5,
"defaultLockLifetime": 10000,
}
},
// Runs automatically when the hook initializes
initialize: function (cb) {
var hook = this
, config = sails.config.jobs
// init agenda
agenda
.database(config.db.address, config.db.collection)
.name(config.name)
.processEvery(config.processEvery)
.maxConcurrency(config.maxConcurrency)
.defaultConcurrency(config.defaultConcurrency)
.defaultLockLifetime(config.defaultLockLifetime)
global[config.globalJobsObjectName] = agenda;
// Enable jobs using coffeescript
try {
require('coffee-script/register');
} catch(e0) {
try {
var path = require('path');
var appPath = sails.config.appPath || process.cwd();
require(path.join(appPath, 'node_modules/coffee-script/register'));
} catch(e1) {
sails.log.verbose('Please run `npm install coffee-script` to use coffescript (skipping for now)');
}
}
// Find all jobs
var jobs = require('include-all')({
dirname : sails.config.appPath + '/' + config.jobsDirectory,
filter : /(.+Job).(?:js|coffee)$/,
excludeDirs : /^\.(git|svn)$/,
optional : true
});
// init jobs
hook.initJobs(jobs);
// Lets wait on some of the sails core hooks to
// finish loading before we load our hook
// that talks about cats.
var eventsToWaitFor = [];
if (sails.hooks.orm)
eventsToWaitFor.push('hook:orm:loaded');
if (sails.hooks.pubsub)
eventsToWaitFor.push('hook:pubsub:loaded');
sails.after(eventsToWaitFor, function(){
// if (jobs.length > 0) {
// start agenda
agenda.start();
sails.log.verbose("sails jobs started")
// }
// Now we will return the callback and our hook
// will be usable.
return cb();
});
},
/**
* Function that initialize jobs
*/
initJobs: function(jobs, namespace) {
var hook = this
if (!namespace) namespace = "jobs";
sails.log.verbose("looking for job in " + namespace + "... ")
_.forEach(jobs, function(job, name){
if (typeof job === 'function') {
var log = ""
, _job = job(agenda)
, _dn = namespace + "." + name
, _name = _job.name || _dn.substr(_dn.indexOf('.') +1);
if (_job.disabled) {
log += "-> Disabled Job '" + _name + "' found in '" + namespace + "." + name + "'.";
} else {
var options = (typeof _job.options === 'object')?_job.options:{}
, freq = typeof _job.frequency == 'undefined'?sails.config.jobs.processEvery:_job.frequency
, error = false;
if (typeof _job.run === "function")
agenda.define(_name, options, _job.run);
log += "-> Job '" + _name + "' found in '" + namespace + "." + name + "', defined in agenda";
if (typeof freq === 'string') {
freq = freq.trim().toLowerCase();
if (freq.indexOf('every') == 0) {
var interval = freq.substr(6).trim();
agenda.every(interval, _name, _job.data);
log += " and will run " + freq;
} else if (freq.indexOf('schedule') == 0) {
var when = freq.substr(9).trim();
agenda.schedule(when, _name, _job.data);
log += " and scheduled " + when;
} else if (freq === 'now') {
agenda.now(_name, _job.data);
log += " and started";
} else {
error = true;
log += " but frequency is not supported";
}
}
}
log += ".";
if (error) sails.log.error(log);
else sails.log.verbose(log);
} else {
hook.initJobs(job, namespace + "." + name);
}
})
}
}
};
| ptphats/sails-hook-jobs | index.js | JavaScript | mit | 4,966 |
export class NewForm {
update() {
}
}
| sergemazille/gextion | src/AppBundle/Resources/js/New/NewForm.js | JavaScript | mit | 48 |
var grunt = require('grunt');
var fs = require('fs');
var gruntTextReplace = require('../lib/grunt-match-replace');
var replace = function (settings) {
return gruntTextReplace.replace(settings);
};
exports.textReplace = {
'Test error handling': {
setUp: function (done) {
grunt.file.copy('test/text_files/test.txt', 'test/temp/testA.txt');
grunt.file.copy('test/text_files/test.txt', 'test/temp/testB.txt');
done();
},
tearDown: function (done) {
fs.unlinkSync('test/temp/testA.txt');
fs.unlinkSync('test/temp/testB.txt');
fs.rmdirSync('test/temp');
done();
},
'Test no destination found': function (test) {
var warnCountBefore = grunt.fail.warncount;
replace({
src: 'test/temp/testA.txt',
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
replace({
src: 'test/temp/testA.txt',
overwrite: true,
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
replace({
src: 'test/temp/testA.txt',
dest: 'test/temp/',
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
test.done();
},
'Test no replacements found': function (test) {
var warnCountBefore = grunt.fail.warncount;
replace({
src: 'test/temp/testA.txt',
dest: 'test/temp/'
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
replace({
src: 'test/temp/testA.txt',
dest: 'test/temp/',
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
test.done();
},
'Test overwrite failure': function (test) {
var warnCountBefore = grunt.fail.warncount;
replace({
src: 'test/temp/testA.txt',
dest: 'test/temp/',
overwrite: true,
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
replace({
src: 'test/temp/*',
overwrite: true,
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
replace({
src: 'test/temp/testA.txt',
overwrite: true,
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
test.done();
},
'Test destination error': function (test) {
var warnCountBefore = grunt.fail.warncount;
replace({
src: 'test/temp/*',
dest: 'test/temp',
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 1);
replace({
src: 'test/temp/*',
dest: 'test/temp/testA.txt',
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 2);
replace({
src: 'test/temp/testA.txt',
dest: 'test/temp/testB.txt',
replacements: [{ from: 'Hello', to: 'Good bye' }]
});
test.equal(grunt.fail.warncount - warnCountBefore, 2);
test.done();
}
}
};
| ebsco/grunt-translations | test/text-replace-error-tests.js | JavaScript | mit | 3,366 |
var sourceFolder = 'src',
destFolder = 'public',
configFolder = 'config';
module.exports = {
folders: {
source: sourceFolder,
dest: destFolder
},
files: {
scripts: [
`${sourceFolder}/js/utils.js`,
`${sourceFolder}/js/sprites/weapon.js`,
`${sourceFolder}/js/sprites/hook.js`,
`${sourceFolder}/js/sprites/enemy.js`,
`${sourceFolder}/js/sprites/**/*.js`,
`${sourceFolder}/js/map.js`,
`${sourceFolder}/js/ui/**/*.js`,
`${sourceFolder}/js/states/**/*.js`,
`${sourceFolder}/js/**/*.js`
],
templates: `${sourceFolder}/templates/**/*.html`,
libs: [
'node_modules/phaser/dist/phaser.js',
'node_modules/stats.js/build/stats.min.js'
],
styles: `${sourceFolder}/styles/**/*.css`,
images: `${sourceFolder}/images/**/*.*`,
sounds: `${sourceFolder}/sounds/**/*.*`,
json: `${sourceFolder}/json/**/*.*`,
fonts: `${sourceFolder}/fonts/**/*.*`,
cname: `${configFolder}/CNAME`
},
scripts: {
destFolder: `${destFolder}/js`,
outFile: 'index.js'
},
libs: {
destFolder: `${destFolder}/js`,
outFile: 'libs.js'
},
styles: {
destFolder: `${destFolder}/css`,
outFile: 'index.css'
},
images: {
destFolder: `${destFolder}/images`
},
sounds: {
destFolder: `${destFolder}/sounds`
},
json: {
destFolder: `${destFolder}/json`
},
fonts: {
destFolder: `${destFolder}/fonts`
},
server: {
root: destFolder,
livereload: true
}
};
| themadknights/wellofeternity | config/gulp.config.js | JavaScript | mit | 1,714 |
module.exports = {
server: {
host: '0.0.0.0',
port: 3000
},
database: {
host: '158.85.190.240',
port: 27017,
db: 'hackathon',
username: 'administrator',
password: 'hunenokGaribaldi9'
}
}; | esmoreit-hack/hackathon | src/server/config.js | JavaScript | mit | 259 |
Subsets and Splits