text
stringlengths 2
6.14k
|
|---|
'use strict';
// Load the application's configuration
const config = require('../server/config');
const url = config.express_host + '/api';
// Required modules
const async = require('async');
const colors = require('colors');
const request = require('request');
// Counter for the Measurements
let counter = 1;
// Read the arguments from the command line or set them to the default values
const interval = process.argv[2] || 2000;
const thingName = process.argv[3] || 'Demo';
const thingLocLat = process.argv[4] || 51.964113;
const thingLocLng = process.argv[5] || 7.624862;
// REST API authentication token
let token;
console.log('\n////////////////////////////////////////////////////////////\n');
console.log(' STARTING DEMONSTRATION...'.cyan);
console.log('\n////////////////////////////////////////////////////////////\n');
async.waterfall([
// Create a new User
function(callback) {
console.log(' Creating a new', 'User...\n'.cyan);
const userJson = {
email: 'demo#' + Math.random().toFixed() + '@example.com',
password: 'demoPass'
};
// Post the new User
request.post({
headers: {'content-type': 'application/json'},
url: url + '/users',
json: userJson
}, function(error, response, body) {
if (!error) {
console.log(' New User', 'created.'.green);
token = body.token;
} else {
console.log(' New User creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, body._id);
});
},
// Create a new Thing
function(userId, callback) {
console.log(' Creating a new', 'Thing...\n'.cyan);
const thingJson = {
name: thingName,
loc: {
coordinates: [ thingLocLat, thingLocLng ]
},
userId: userId,
waterbodyId: '5752d2d7e5d703480187e0d9',
token: token
};
// Post the new Thing
request.post({
headers: {'content-type': 'application/json'},
url: url + '/things',
json: thingJson
}, function(error, response, body) {
if (!error) {
console.log(' New Thing', 'created.'.green);
} else {
console.log(' New Thing creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, body._id);
});
},
// Create a new Feature
function(thingId, callback) {
console.log(' Creating a new', 'Feature...\n'.cyan);
const featureJson = {
name: 'demoFeature',
unit: 'foo',
token: token
};
// Post the new Feature
request.post({
headers: {'content-type': 'application/json'},
url: url + '/features',
json: featureJson
}, function(error, response, body) {
if (!error) {
console.log(' New Feature', 'created'.green);
} else {
console.log(' New Feature creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, thingId, body._id);
});
},
// Create a new Sensor
function(thingId, featureId, callback) {
console.log(' Creating a new', 'Sensor...\n'.cyan);
const sensorJson = {
name: 'demoSensor',
interval: interval,
refLevel: 2,
warnLevel: 6,
riskLevel: 8,
thingId: thingId,
featureId: featureId,
token: token
};
// Post the new Sensor
request.post({
headers: {'content-type': 'application/json'},
url: url + '/sensors',
json: sensorJson
}, function(error, response, body) {
if (!error) {
console.log(' New Sensor', 'created.'.green);
} else {
console.log(' New Sensor creation', 'failed'.red);
}
console.log('\n------------------------------------------------------------\n');
callback(error, body._id);
});
},
// Create new Measurements in an interval
function(sensorId, callback) {
console.log(' Finished demo setup. Measuring now...'.cyan);
console.log('\n------------------------------------------------------------\n');
let value = 4;
setInterval(function() {
console.log(' Creating a new', 'Measurement...\n'.cyan);
// Calculate the Measurement's value as a random number with respect to its previous value
if (value < 1 || Math.random() > 0.5) {
value += Math.random();
} else {
value -= Math.random();
}
value = parseFloat(value.toFixed(2));
let measurementJson = {
date: Date.now(),
value: value,
sensorId: sensorId,
token: token
};
// Post the new Measurement
request.post({
headers: {'content-type': 'application/json'},
url: url + '/measurements',
json: measurementJson
}, function(error, response, body) {
if (!error) {
console.log(' New Measurement', ('#' + counter).cyan, 'created.'.green, '\nValue:', body.value.cyan);
counter++;
} else {
console.log(' New Measurement creation', 'failed'.red);
callback(error);
}
console.log('\n------------------------------------------------------------\n');
});
}, interval);
}
], function(err, result) {
if (err) {
console.log(err);
}
});
|
import React from 'react'
import {HOC, Link} from 'cerebral-view-react'
import PageProgress from '../PageProgress'
// View
class AutoReload extends React.Component {
constructor (props) {
super(props)
this.state = {
secondsElapsed: 0
}
this.onInterval = this.onInterval.bind(this)
}
componentWillMount () {
this.intervals = []
}
componentWillUnmount () {
this.intervals.forEach(clearInterval)
}
componentDidMount () {
this.setInterval(this.onInterval, 1000)
}
setInterval () {
this.intervals.push(setInterval.apply(null, arguments))
}
onInterval () {
let secondsElapsed = 0
if (this.props.isEnabled) {
secondsElapsed = this.state.secondsElapsed + 1
if (secondsElapsed >= this.props.triggerAfterSeconds) {
this.trigger()
secondsElapsed = 0
}
}
if (secondsElapsed !== this.state.secondsElapsed) {
this.setState({
secondsElapsed: secondsElapsed
})
}
}
trigger () {
this.props.triggers.map((trigger) => trigger())
}
triggerNow (e) {
if (e) {
e.preventDefault()
}
if (this.props.isEnabled) {
if (this.state.secondsElapsed > 0) {
this.trigger()
this.setState({
secondsElapsed: 0
})
}
}
}
render () {
const signals = this.props.signals
const progress = {
isEnabled: this.props.isEnabled,
elapsed: this.state.secondsElapsed,
total: this.props.triggerAfterSeconds
}
return (
<div>
<PageProgress {...progress} />
<hr />
<pre>
BastardAutoloaderFromHell<br />
=========================<br />
[{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br />
isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br />
triggerAfterSeconds: {this.props.triggerAfterSeconds}<br />
numberOfTriggers: {this.props.triggers.length}<br />
secondsElapsed: {this.state.secondsElapsed}<br />
secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br />
-------------------------<br />
<Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br />
--<br />
<Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br />
--<br />
<Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br />
-------------------------<br />
<a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br />
-------------------------<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br />
--<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br />
--<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br />
--<br />
<Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br />
====<br />
<i>designed by pbit</i>
</pre>
</div>
)
}
}
// Model
AutoReload.propTypes = {
isEnabled: React.PropTypes.bool,
triggerAfterSeconds: React.PropTypes.number,
signals: React.PropTypes.object,
triggers: React.PropTypes.array
}
AutoReload.defaultProps = {
triggers: []
}
// Binding
const StatefullAutoReload = HOC(AutoReload, {
isEnabled: ['app', 'reload', 'isEnabled'],
triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds']
})
// API
export default StatefullAutoReload
|
/* Client-side router settings */
Router.configure({
layoutTemplate:"layout",
notFoundTemplate:"page_not_found",
loadingTemplate:"loading"
});
Router.route("/", {
name:"home",
template:"home"
});
Router.route("/profile", {
name:"profile",
template:"profile"
});
Router.route("/admin", {
name:"admin",
template:"admin"
});
Router.route("/user/:_id", {
name:"user",
template:"user",
data: function(){
return Meteor.users.findOne({_id: this.params._id});
}
});
|
//Change class of "Home" and "About"
function setActive() {
document.getElementById("about").className += "active"
document.getElementById("home").setAttribute('class','no')
}
|
export const ADD_COCKTAIL = 'ADD_COCKTAIL';
export const LOAD_COCKTAILS = 'LOAD_COCKTAILS';
export const ADD_SPIRIT = 'ADD_SPIRIT';
export const REMOVE_SPIRIT = 'REMOVE_SPIRIT';
export const UPDATE_HUE = 'UPDATE_HUE';
|
// animating the scroll effect
$('.screenshots').on('click', function(e){
e.preventDefault();
$("html, body").animate({ scrollTop: "950px", duration: 500 });
});
|
'use strict';
var path = require('path');
module.exports = path.join.bind(path, __dirname, '..');
|
"use strict";
var http_1 = require("@angular/http");
var AppSettings = (function () {
function AppSettings() {
}
Object.defineProperty(AppSettings, "API_OPTIONS", {
get: function () {
var headers = new http_1.Headers({ 'Content-Type': 'application/json' }), options = new http_1.RequestOptions({ headers: headers });
return options;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AppSettings, "API_URL", {
get: function () {
var devMode = true, prodPath = "http://cristi.red:8080/api", apiSecured = false, apiHost = "localhost", apiPort = "8080/api";
return (devMode) ? ("http" + ((apiSecured) ? "s" : "") + "://" + apiHost + ":" + apiPort) : prodPath;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AppSettings, "SOCKETG_URL", {
get: function () {
var devMode = true, prodPath = "http://cristi.red:8080/gs-guide-websocket", local = "http://localhost:8080/gs-guide-websocket";
return (devMode) ? local : prodPath;
},
enumerable: true,
configurable: true
});
return AppSettings;
}());
exports.AppSettings = AppSettings;
//# sourceMappingURL=app.settings.js.map
|
const fs = require('fs')
const path = require('path')
const {generateBabelEnvLoader, getConfig} = require('./common')
const buildCache = {}
module.exports = (params) => {
const baseConfig = getConfig(params)
const config = Object.assign({}, baseConfig)
config.outputPath = path.join(__dirname, '../dist-' + config.app)
return {
entry: config.sourcePath + '/tools/initdb.js',
context: config.sourcePath,
target: 'node',
output: {
path: config.outputPath,
filename: 'initdb.js'
},
stats: {
colors: true,
reasons: true,
chunks: false
},
cache: buildCache,
module: {
rules: [generateBabelEnvLoader({node: 'current'}, config)]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: baseConfig.aliases
},
devServer: {
contentBase: config.sourcePath
}
}
}
|
'use strict';
var page = 'projects';
module.exports = {
renderPage: function(req, res) {
if (!req.user) {
res.redirect('/login');
} else {
res.render(page, {
helpers: {
activeClass: function(section) {
if (section === 'projects') {
return 'active';
} else {
return '';
}
}
},
user: req.user ? req.user.toJSON() : null
});
}
}
}
|
Search = function(data, input, result) {
this.data = data;
this.$input = $(input);
this.$result = $(result);
this.$current = null;
this.$view = this.$result.parent();
this.searcher = new Searcher(data.index);
this.init();
};
Search.prototype = $.extend({}, Navigation, new function() {
var suid = 1;
this.init = function() {
var _this = this;
var observer = function(e) {
switch(e.originalEvent.keyCode) {
case 38: // Event.KEY_UP
case 40: // Event.KEY_DOWN
return;
}
_this.search(_this.$input[0].value);
};
this.$input.keyup(observer);
this.$input.click(observer); // mac's clear field
this.searcher.ready(function(results, isLast) {
_this.addResults(results, isLast);
});
this.initNavigation();
this.setNavigationActive(false);
};
this.search = function(value, selectFirstMatch) {
value = jQuery.trim(value).toLowerCase();
if (value) {
this.setNavigationActive(true);
} else {
this.setNavigationActive(false);
}
if (value == '') {
this.lastQuery = value;
this.$result.empty();
this.$result.attr('aria-expanded', 'false');
this.setNavigationActive(false);
} else if (value != this.lastQuery) {
this.lastQuery = value;
this.$result.attr('aria-busy', 'true');
this.$result.attr('aria-expanded', 'true');
this.firstRun = true;
this.searcher.find(value);
}
};
this.addResults = function(results, isLast) {
var target = this.$result.get(0);
if (this.firstRun && (results.length > 0 || isLast)) {
this.$current = null;
this.$result.empty();
}
for (var i=0, l = results.length; i < l; i++) {
var item = this.renderItem.call(this, results[i]);
item.setAttribute('id', 'search-result-' + target.childElementCount);
target.appendChild(item);
}
if (this.firstRun && results.length > 0) {
this.firstRun = false;
this.$current = $(target.firstChild);
this.$current.addClass('search-selected');
}
if (jQuery.browser.msie) this.$element[0].className += '';
if (isLast) this.$result.attr('aria-busy', 'false');
};
this.move = function(isDown) {
if (!this.$current) return;
var $next = this.$current[isDown ? 'next' : 'prev']();
if ($next.length) {
this.$current.removeClass('search-selected');
$next.addClass('search-selected');
this.$input.attr('aria-activedescendant', $next.attr('id'));
this.scrollIntoView($next[0], this.$view[0]);
this.$current = $next;
this.$input.val($next[0].firstChild.firstChild.text);
this.$input.select();
}
return true;
};
this.hlt = function(html) {
return this.escapeHTML(html).
replace(/\u0001/g, '<em>').
replace(/\u0002/g, '</em>');
};
this.escapeHTML = function(html) {
return html.replace(/[&<>]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
});
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:505b4ccd47ed9526d0238c6f2d03a343ce476abc1c4aa79a9f22cabcbd0a3c16
size 12575
|
'use strict';
//Ghost service used for communicating with the ghost api
angular.module('ghost').factory('Ghost', ['$http', 'localStorageService',
function($http, localStorageService) {
return {
login: function() {
return $http.get('api/ghost/login').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
data.authenticator = 'simple-auth-authenticator:oauth2-password-grant';
data.expires_at = data.expires_in + Date.now();
localStorageService.set('ghost-cms:session',data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('ghost login failure');
});
}
};
}
]).factory('GhostPosts', ['$http',
function($http) {
return {
read: function(options) {
return $http.get('api/ghost/posts/slug/' + options.slug).
success(function(data, status, headers, config) {
//console.log(data);
return data;
});
},
query: function(options) {
return $http.get('api/ghost/posts/tag/' + options.tag).
success(function(data, status, headers, config) {
//console.log(data);
return data;
});
}
};
}
]);
|
//config file for bae
if(sumeru.BAE_VERSION){
sumeru.config.database({
dbname : '',
user: '',//bae 3.0 required
password: ''//bae 3.0 required
});
sumeru.config({
site_url : '' //with tailing slash
});
}
|
///<reference src="js/tempus-dominus"/>
/*global $ */
tempusDominus.jQueryInterface = function (option, argument) {
if (this.length === 1) {
return tempusDominus.jQueryHandleThis(this, option, argument);
}
// "this" is jquery here
return this.each(function () {
tempusDominus.jQueryHandleThis(this, option, argument);
});
};
tempusDominus.jQueryHandleThis = function (me, option, argument) {
let data = $(me).data(tempusDominus.Namespace.dataKey);
if (typeof option === 'object') {
$.extend({}, tempusDominus.DefaultOptions, option);
}
if (!data) {
data = new tempusDominus.TempusDominus($(me)[0], option);
$(me).data(tempusDominus.Namespace.dataKey, data);
}
if (typeof option === 'string') {
if (data[option] === undefined) {
throw new Error(`No method named "${option}"`);
}
if (argument === undefined) {
return data[option]();
} else {
if (option === 'date') {
data.isDateUpdateThroughDateOptionFromClientCode = true;
}
const ret = data[option](argument);
data.isDateUpdateThroughDateOptionFromClientCode = false;
return ret;
}
}
};
tempusDominus.getSelectorFromElement = function ($element) {
let selector = $element.data('target'),
$selector;
if (!selector) {
selector = $element.attr('href') || '';
selector = /^#[a-z]/i.test(selector) ? selector : null;
}
$selector = $(selector);
if ($selector.length === 0) {
return $element;
}
if (!$selector.data(tempusDominus.Namespace.dataKey)) {
$.extend({}, $selector.data(), $(this).data());
}
return $selector;
};
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$(document)
.on(
`click${tempusDominus.Namespace.events.key}.data-api`,
`[data-toggle="${tempusDominus.Namespace.dataKey}"]`,
function () {
const $originalTarget = $(this),
$target = tempusDominus.getSelectorFromElement($originalTarget),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (
config._options.allowInputToggle &&
$originalTarget.is('input[data-toggle="datetimepicker"]')
) {
return;
}
tempusDominus.jQueryInterface.call($target, 'toggle');
}
)
.on(
tempusDominus.Namespace.events.change,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0 || event.isInit) {
return;
}
tempusDominus.jQueryInterface.call($target, '_change', event);
}
)
.on(
tempusDominus.Namespace.events.blur,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (config._options.debug || window.debug) {
return;
}
tempusDominus.jQueryInterface.call($target, 'hide', event);
}
)
/*.on(tempusDominus.Namespace.Events.keydown, `.${tempusDominus.Namespace.NAME}-input`, function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0) {
return;
}
tempusDominus.jQueryInterface.call($target, '_keydown', event);
})
.on(tempusDominus.Namespace.Events.keyup, `.${tempusDominus.Namespace.NAME}-input`, function (event) {
const $target = tempusDominus.getSelectorFromElement($(this));
if ($target.length === 0) {
return;
}
tempusDominus.jQueryInterface.call($target, '_keyup', event);
})*/
.on(
tempusDominus.Namespace.events.focus,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.getSelectorFromElement($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (!config._options.allowInputToggle) {
return;
}
tempusDominus.jQueryInterface.call($target, 'show', event);
}
);
const name = 'tempusDominus';
$.fn[name] = tempusDominus.jQueryInterface;
$.fn[name].Constructor = tempusDominus.TempusDominus;
$.fn[name].noConflict = function () {
$.fn[name] = $.fn[name];
return tempusDominus.jQueryInterface;
};
|
import Telescope from 'meteor/nova:lib';
import Posts from "meteor/nova:posts";
import Comments from "meteor/nova:comments";
import Users from 'meteor/nova:users';
serveAPI = function(terms){
var posts = [];
var parameters = Posts.parameters.get(terms);
const postsCursor = Posts.find(parameters.selector, parameters.options);
postsCursor.forEach(function(post) {
var url = Posts.getLink(post);
var postOutput = {
title: post.title,
headline: post.title, // for backwards compatibility
author: post.author,
date: post.postedAt,
url: url,
pageUrl: Posts.getPageUrl(post, true),
guid: post._id
};
if(post.body)
postOutput.body = post.body;
if(post.url)
postOutput.domain = Telescope.utils.getDomain(url);
if (post.thumbnailUrl) {
postOutput.thumbnailUrl = Telescope.utils.addHttp(post.thumbnailUrl);
}
var twitterName = Users.getTwitterNameById(post.userId);
if(twitterName)
postOutput.twitterName = twitterName;
var comments = [];
Comments.find({postId: post._id}, {sort: {postedAt: -1}, limit: 50}).forEach(function(comment) {
var commentProperties = {
body: comment.body,
author: comment.author,
date: comment.postedAt,
guid: comment._id,
parentCommentId: comment.parentCommentId
};
comments.push(commentProperties);
});
var commentsToDelete = [];
comments.forEach(function(comment, index) {
if (comment.parentCommentId) {
var parent = comments.filter(function(obj) {
return obj.guid === comment.parentCommentId;
})[0];
if (parent) {
parent.replies = parent.replies || [];
parent.replies.push(JSON.parse(JSON.stringify(comment)));
commentsToDelete.push(index);
}
}
});
commentsToDelete.reverse().forEach(function(index) {
comments.splice(index,1);
});
postOutput.comments = comments;
posts.push(postOutput);
});
return JSON.stringify(posts);
};
|
import React from 'react';
import Helmet from 'react-helmet';
import { Route } from '../../core/router';
import { Model as Waste } from '../../entities/Waste';
import { Deferred } from '../../util/utils';
import NavLink from '../../components/NavLink';
import Progress from 'react-progress-2';
import { PageHeader, Row, Col, Panel, Label } from 'react-bootstrap';
import radio from 'backbone.radio';
const router = radio.channel('router');
export default class WasteShowRoute extends Route {
breadcrumb({ params }) {
const dfd = new Deferred;
const waste = new Waste({ fid: params.wfid });
waste.forSubjectParam(params.fid);
waste.fetch({ success: m => dfd.resolve(m.get('title')) });
return dfd.promise;
}
fetch({ params }) {
this.companyFid = params.fid;
this.waste = new Waste({ fid: params.wfid });
this.waste.forSubjectParam(params.fid).expandParam('subtype');
return this.waste.fetch();
}
render() {
const waste = this.waste.toJSON();
return (
<div>
<Helmet title={waste.title} />
<PageHeader>{waste.title}</PageHeader>
<Row>
<Col md={12}>
<ul className="nav menu-nav-pills">
<li>
<NavLink
to={`/companies/${this.companyFid}/waste/${waste.fid}/edit`}
>
<i className="fa fa-pencil-square-o" /> Редактировать
</NavLink>
</li>
<li>
<a
href="javascript:;"
onClick={() => {
Progress.show();
this.waste.destroy({
success: () => {
Progress.hide();
router.request('navigate', `companies/${this.companyFid}`);
},
});
}}
>
<i className="fa fa-ban" aria-hidden="true" /> Удалить
</a>
</li>
</ul>
</Col>
</Row>
<Row>
<Col md={12}>
<Panel>
<h4><Label>Название</Label>{' '}
{waste.title}
</h4>
<h4><Label>Вид отходов</Label>{' '}
<NavLink to={`/waste-types/${waste.subtype.fid}`}>{waste.subtype.title}</NavLink>
</h4>
<h4><Label>Количество</Label>{' '}
{waste.amount} т
</h4>
</Panel>
</Col>
</Row>
</div>
);
}
}
|
var basePaths = {
src: 'public/',
dest: 'public.dist/',
bower: 'bower_components/'
};
var paths = {
images: {
src: basePaths.src + 'images/',
dest: basePaths.dest + 'images/min/'
},
scripts: {
src: basePaths.src + 'scripts/',
dest: basePaths.dest + 'scripts/min/'
},
styles: {
src: basePaths.src + 'styles/',
dest: basePaths.dest + 'styles/min/'
},
sprite: {
src: basePaths.src + 'sprite/*'
}
};
var appFiles = {
styles: paths.styles.src + '**/*.scss',
scripts: [paths.scripts.src + 'scripts.js']
};
var vendorFiles = {
styles: '',
scripts: ''
};
var spriteConfig = {
imgName: 'sprite.png',
cssName: '_sprite.scss',
imgPath: paths.images.dest.replace('public', '') + 'sprite.png'
};
// let the magic begin
var gulp = require('gulp');
var es = require('event-stream');
var gutil = require('gulp-util');
var autoprefixer = require('gulp-autoprefixer');
var plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/
});
// allows gulp --dev to be run for a more verbose output
var isProduction = true;
var sassStyle = 'compressed';
var sourceMap = false;
if (gutil.env.dev === true) {
sassStyle = 'expanded';
sourceMap = true;
isProduction = false;
}
var changeEvent = function(evt) {
gutil.log('File', gutil.colors.cyan(evt.path.replace(new RegExp('/.*(?=/' + basePaths.src + ')/'), '')), 'was', gutil.colors.magenta(evt.type));
};
gulp.task('css', function() {
var sassFiles = gulp.src(appFiles.styles)
/*
.pipe(plugins.rubySass({
style: sassStyle, sourcemap: sourceMap, precision: 2
}))
*/
.pipe(plugins.sass())
.on('error', function(err) {
new gutil.PluginError('CSS', err, {showStack: true});
});
return es.concat(gulp.src(vendorFiles.styles), sassFiles)
.pipe(plugins.concat('style.min.css'))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4', 'Firefox >= 4'))
/*
.pipe(isProduction ? plugins.combineMediaQueries({
log: true
}) : gutil.noop())
*/
.pipe(isProduction ? plugins.cssmin() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.styles.dest))
;
});
gulp.task('scripts', function() {
gulp.src(vendorFiles.scripts.concat(appFiles.scripts))
.pipe(plugins.concat('app.js'))
.pipe(isProduction ? plugins.uglify() : gutil.noop())
.pipe(plugins.size())
.pipe(gulp.dest(paths.scripts.dest))
;
});
// sprite generator
gulp.task('sprite', function() {
var spriteData = gulp.src(paths.sprite.src).pipe(plugins.spritesmith({
imgName: spriteConfig.imgName,
cssName: spriteConfig.cssName,
imgPath: spriteConfig.imgPath,
cssOpts: {
functions: false
},
cssVarMap: function (sprite) {
sprite.name = 'sprite-' + sprite.name;
}
}));
spriteData.img.pipe(gulp.dest(paths.images.dest));
spriteData.css.pipe(gulp.dest(paths.styles.src));
});
gulp.task('watch', ['sprite', 'css', 'scripts'], function() {
gulp.watch(appFiles.styles, ['css']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.scripts.src + '*.js', ['scripts']).on('change', function(evt) {
changeEvent(evt);
});
gulp.watch(paths.sprite.src, ['sprite']).on('change', function(evt) {
changeEvent(evt);
});
});
gulp.task('default', ['css', 'scripts']);
|
var fs = require('fs');
var mysql = require('mysql');
var qs = require('querystring');
var express = require('express');
var config = JSON.parse(fs.readFileSync(__dirname+'/config.json', 'UTF-8'));
// -----------------------------------------------------------------------------
// Keep a persistant connection to the database (reconnect after an error or disconnect)
// -----------------------------------------------------------------------------
if (typeof config.databaseConnection == 'undefined' || typeof config.databaseConnection.retryMinTimeout == 'undefined')
config.databaseConnection = {retryMinTimeout: 2000, retryMaxTimeout: 60000};
var connection, retryTimeout = config.databaseConnection.retryMinTimeout;
function persistantConnection(){
connection = mysql.createConnection(config.database);
connection.connect(
function (err){
if (err){
console.log('Error connecting to database: '+err.code);
setTimeout(persistantConnection, retryTimeout);
console.log('Retrying in '+(retryTimeout / 1000)+' seconds');
if (retryTimeout < config.databaseConnection.retryMaxTimeout)
retryTimeout += 1000;
}
else{
retryTimeout = config.databaseConnection.retryMinTimeout;
console.log('Connected to database');
}
});
connection.on('error',
function (err){
console.log('Database error: '+err.code);
if (err.code === 'PROTOCOL_CONNECTION_LOST')
persistantConnection();
});
}
//persistantConnection();
var app = express();
// -----------------------------------------------------------------------------
// Deliver the base template of SPA
// -----------------------------------------------------------------------------
app.get('/', function (req, res){
res.send(loadTemplatePart('base.html', req));
});
app.get('/images/:id', function (req, res){
res.send(dataStore.images);
});
// -----------------------------------------------------------------------------
// Deliver static assets
// -----------------------------------------------------------------------------
app.use('/static/', express.static('static'));
// ==================================================
// Below this point are URIs that are accesible from outside, in REST API calls
// ==================================================
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// -----------------------------------------------------------------------------
// API Endpoint to receive data
// -----------------------------------------------------------------------------
var dataStore = {};
app.post('/api/put', function (req, res){
// Needs to authenticate the RPi module
//
handlePost(req, function(data){
//console.log(data);
for (var i = 0; i < 4; i++){
//var img = Buffer.from(, 'base64');
fs.writeFile('./static/images/'+data.id+'/'+i+'.png',
'data:image/png;base64,'+data.images[i],
function(err){
if (err)
console.log(err);
}
);
}
//
//dataStore[data.id] = data;
dataStore = data;
res.send('ok');
});
});
app.listen(config.listenPort, function (){
console.log('RainCatcher server is listening on port '+config.listenPort);
});
// --------------------------------------------------------------------------
// Handler for multipart POST request/response body
function handlePost(req, callback){
var body = '';
req.on('data', function (data){
body += data;
if (body.length > 1e8)
req.connection.destroy();
});
req.on('end', function (data){
var post = body;
try{
post = JSON.parse(post);
}
catch(e){
try{
post = qs.parse(post);
}
catch(e){}
}
callback(post);
});
}
function loadTemplatePart(template, req){
try{
return fs.readFileSync('./templates/'+template, 'utf8');
}
catch(e){
return '<h2>Page Not Found</h2>';
}
}
Date.prototype.sqlFormatted = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]);
};
function isset(obj){
return typeof obj != 'undefined';
}
|
import SuccessPage from '../index';
import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';
describe('<SuccessPage />', () => {
});
|
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'lib/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
//Testing libraries
//'@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
//'@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
//'@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
//'@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
//'@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
//'@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
//'@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
//'@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
|
/**
* Created by Tomas Kulhanek on 1/16/17.
*/
//import {HttpClient} from 'aurelia-http-client';
import {ProjectApi} from "../components/projectapi";
import {Vfstorage} from '../components/vfstorage';
//import {bindable} from 'aurelia-framework';
export class Modulecontrol{
// @bindable classin = "w3-card-4 w3-sand w3-padding w3-margin w3-round";
constructor () {
this.client=new HttpClient();
this.url=window.location.href;
this.baseurl=Vfstorage.getBaseUrl()
this.enabled=false;
this.client.configure(config=> {
config.withHeader('Accept', 'application/json');
config.withHeader('Content-Type', 'application/json');
});
}
attached(){
//console.log("attached() url:"+this.url);
this.client.get(this.baseurl+this.url)
.then(response => this.okcallback(response))
.catch(error => this.failcallback(error))
}
okcallback(response){
//console.log("okcallback()");
var res= JSON.parse(response.response);
//console.log(res.enabled);
this.enabled= res.enabled;
}
failcallback(error){
this.enabled=false;
console.log('Sorry, error when connecting backend web service at '+this.url+' error:'+error.response+" status:"+error.statusText);
}
enable(){
this.client.post(this.baseurl+this.url)
.then(response => this.okcallback(response))
.catch(error => this.failcallback(error))
}
}
|
/* eslint-disable no-undef,no-unused-expressions */
const request = require('supertest')
const expect = require('chai').expect
const app = require('../../bin/www')
const fixtures = require('../data/fixtures')
describe('/api/mappings', () => {
beforeEach(() => {
this.Sample = require('../../models').Sample
this.Instrument = require('../../models').Instrument
this.InstrumentMapping = require('../../models').InstrumentMapping
this.ValidationError = require('../../models').sequelize.ValidationError
expect(this.Sample).to.exist
expect(this.Instrument).to.exist
expect(this.InstrumentMapping).to.exist
expect(this.ValidationError).to.exist
return require('../../models').sequelize
.sync({force: true, logging: false})
.then(() => {
console.log('db synced')
return this.Sample
.bulkCreate(fixtures.samples)
})
.then(samples => {
this.samples = samples
return this.Instrument
.bulkCreate(fixtures.instruments)
})
.then(instruments => {
return this.InstrumentMapping.bulkCreate(fixtures.instrumentMappings)
})
.then(() => console.log('Fixtures loaded'))
})
it('should return 200 on GET /api/instruments/:instrumentId/mappings', () => {
return request(app)
.get('/api/instruments/a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45/mappings')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then((res) => {
expect(res.body, 'body should be an array').to.be.an('array')
expect(res.body, 'body should contain 2 items').to.have.lengthOf(2)
expect(res.body[0], 'item 0 should be an object').to.be.an('object')
})
})
it('should return 201 on POST /api/instruments/:instrumentId/mappings', () => {
return request(app)
.post('/api/instruments/a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45/mappings')
.send({
lowerRank: 55,
upperRank: 56,
referenceRank: 55,
sampleId: '636f247a-dc88-4b52-b8e8-78448b5e5790'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(201)
.then(res => {
expect(res.body, 'body should be an object')
expect(res.body.lowerRank, 'lowerRank should equal 55').to.equal(55)
expect(res.body.upperRank, 'upperRank should equal 56').to.equal(56)
expect(res.body.referenceRank, 'referenceRank should equal 55').to.equal(55)
expect(res.body.sampleId).to.equal('636f247a-dc88-4b52-b8e8-78448b5e5790', 'sampleId should equal 636f247a-dc88-4b52-b8e8-78448b5e5790')
expect(res.body.instrumentId).to.equal('a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45', 'instrumentId should equal a35c6ac4-53f7-49b7-82e3-7a0aba5c2c45')
})
})
it('should return 200 GET /api/mappings/:id', () => {
return request(app)
.get('/api/mappings/1bcab515-ed82-4449-aec9-16a6142b0d15')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then((res) => {
expect(res.body, 'body should be an object').to.be.an('object')
expect(res.body.id, 'id should equal 1bcab515-ed82-4449-aec9-16a6142b0d15').to.equal('1bcab515-ed82-4449-aec9-16a6142b0d15')
})
})
it('should return 200 on PUT /api/mappings/:id', () => {
return request(app)
.put('/api/mappings/712fda5f-3ff5-4e23-8949-320a96e0d565')
.send({
lowerRank: 45,
upperRank: 46,
referenceRank: 45,
sampleId: '0f1ed577-955a-494d-868c-cf4dc5c3c892'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then(res => {
expect(res.body.lowerRank, 'lowerRank should equal 45').to.equal(45)
expect(res.body.upperRank, 'upperRank should equal 46').to.equal(46)
expect(res.body.referenceRank, 'referenceRank should equal 45').to.equal(45)
expect(res.body.sampleId).to.equal('0f1ed577-955a-494d-868c-cf4dc5c3c892', 'sampleId should equal 0f1ed577-955a-494d-868c-cf4dc5c3c892')
})
})
it('should return 404 on PUT /api/mappings/:id when id is unknown', () => {
return request(app)
.put('/api/mappings/bb459a9e-0d2c-4da1-b538-88ea43d30f8c')
.send({
sampleId: '0f1ed577-955a-494d-868c-cf4dc5c3c892'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(404)
.then((res) => {
expect(res.body, 'body should be a object').to.be.an('object')
expect(res.body).to.include({
msg: 'Failed to retrieve instrument mapping n°bb459a9e-0d2c-4da1-b538-88ea43d30f8c',
name: 'DatabaseError'
})
})
})
it('should return 204 on DELETE /api/mappings/:id', () => {
return request(app)
.delete('/api/mappings/712fda5f-3ff5-4e23-8949-320a96e0d565')
.expect(204)
.then((res) => {
expect(res.body, 'body should be empty').to.be.empty
})
})
it('should return 404 on DELETE /api/mappings/:id when id is unknown', () => {
return request(app)
.delete('/api/mappings/bb459a9e-0d2c-4da1-b538-88ea43d30f8c')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(404)
.then((res) => {
expect(res.body, 'body should be a object').to.be.an('object')
expect(res.body).to.include({
msg: 'Failed to retrieve instrument mapping n°bb459a9e-0d2c-4da1-b538-88ea43d30f8c',
name: 'DatabaseError'
})
})
})
})
|
/**
* @license Highcharts JS v9.0.1 (2021-02-16)
* @module highcharts/modules/dependency-wheel
* @requires highcharts
* @requires highcharts/modules/sankey
*
* Dependency wheel module
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/DependencyWheel/DependencyWheelSeries.js';
|
'use strict';
/* global angular */
(function() {
var aDashboard = angular.module('aDashboard');
aDashboard.controller('ADashboardController', function( $scope, $rootScope, tradelistFactory, $timeout) {
$scope.subState = $scope.$parent;
$scope.accountValue;
$scope.avgWin;
$scope.avgLoss;
$scope.avgTradeSize;
$scope.$on('tradeActionUpdated', function(event, args) {
var tradelist = args.tradelist;
calculateValue( tradelist );
$scope.avgWin = calculateAvgWin( tradelist ).avg;
$scope.winCount = calculateAvgWin( tradelist ).count;
$scope.avgLoss = calculateAvgLoss( tradelist ).avg;
$scope.lossCount = calculateAvgLoss( tradelist ).count;
calculateAvgTradeSize( tradelist );
});
var getTradelist = function() {
tradelistFactory.getTradelist()
.then(function(tradelist) {
});
};
getTradelist();
function calculateValue( tradelist ){
var sum = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue ){
sum += Number(entry.tradeValue);
}
});
$scope.accountValue = sum;
};
function calculateAvgWin( tradelist ){
var sum = 0;
var count = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue > 0 ){
++count;
sum += Number(entry.tradeValue);
}
});
return {avg: (sum / count).toFixed(2), count: count};
};
function calculateAvgLoss( tradelist ){
var sum = 0;
var count = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue < 0 ){
++count
sum += Number(entry.tradeValue);
}
});
console.log('sum: ', sum);
return {avg: (sum / count).toFixed(2), count: count};
};
function calculateAvgTradeSize( tradelist ){
var actionCount = 0;
var sum = 0;
tradelist.forEach(function(entry) {
var actions = entry.actions;
actions.forEach(function(action) {
if( action.price && action.quantity ){
++actionCount;
sum = sum + (Math.abs(action.price * action.quantity));
}
});
});
if( actionCount == 0 ){
actionCount = 1;
}
$scope.avgTradeSize = (sum / actionCount).toFixed(2);
};
});
})();
|
'use strict';
// MODULES //
var isArrayLike = require( 'validate.io-array-like' ),
isTypedArrayLike = require( 'validate.io-typed-array-like' ),
deepSet = require( 'utils-deep-set' ).factory,
deepGet = require( 'utils-deep-get' ).factory;
// FUNCTIONS
var POW = require( './number.js' );
// POWER //
/**
* FUNCTION: power( arr, y, path[, sep] )
* Computes an element-wise power or each element and deep sets the input array.
*
* @param {Array} arr - input array
* @param {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Number} y - either an array of equal length or a scalar
* @param {String} path - key path used when deep getting and setting
* @param {String} [sep] - key path separator
* @returns {Array} input array
*/
function power( x, y, path, sep ) {
var len = x.length,
opts = {},
dget,
dset,
v, i;
if ( arguments.length > 3 ) {
opts.sep = sep;
}
if ( len ) {
dget = deepGet( path, opts );
dset = deepSet( path, opts );
if ( isTypedArrayLike( y ) ) {
for ( i = 0; i < len; i++ ) {
v = dget( x[ i ] );
if ( typeof v === 'number' ) {
dset( x[ i ], POW( v, y[ i ] ) );
} else {
dset( x[ i ], NaN );
}
}
} else if ( isArrayLike( y ) ) {
for ( i = 0; i < len; i++ ) {
v = dget( x[ i ] );
if ( typeof v === 'number' && typeof y[ i ] === 'number' ) {
dset( x[ i ], POW( v, y[ i ] ) );
} else {
dset( x[ i ], NaN );
}
}
} else {
if ( typeof y === 'number' ) {
for ( i = 0; i < len; i++ ) {
v = dget( x[ i ] );
if ( typeof v === 'number' ) {
dset( x[ i ], POW( v, y ) );
} else {
dset( x[ i ], NaN );
}
}
} else {
for ( i = 0; i < len; i++ ) {
dset( x[ i ], NaN );
}
}
}
}
return x;
} // end FUNCTION power()
// EXPORTS //
module.exports = power;
|
'use strict';
function getReferenceMatrix (matrix, direction) {
return matrix.unflatten().rows.sort((r1, r2) => {
return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1);
});
}
function simpleSort (matrix, direction) {
const referenceMatrix = getReferenceMatrix(matrix, direction);
return matrix.clone({
axes: [
Object.assign({}, matrix.axes[0], {values: referenceMatrix.map(r => r[0])})
],
data: referenceMatrix.map(r => r[1])
});
}
function complexSort () {//matrix, direction, strategy, dimension) {
// const referenceMatrix = getReferenceMatrix(matrix.reduce(strategy, dimension), direction);
}
module.exports.ascending = function (strategy, dimension) {
if (this.dimension === 1) {
return simpleSort(this, 'asc');
} else if (this.dimension === 2) {
throw new Error('Cannot sort tables of dimension greater than 1. It\'s on the todo list though!');
return complexSort(this, 'asc', strategy, dimension);
} else {
throw new Error('Cannot sort tables of dimesnion greater than 2');
}
}
module.exports.descending = function (strategy, dimension) {
if (this.dimension === 1) {
return simpleSort(this, 'desc');
} else if (this.dimension === 2) {
throw new Error('Cannot sort tables of dimension greater than 1. It\'s on the todo list though!');
return complexSort(this, 'desc', strategy, dimension);
} else {
throw new Error('Cannot sort tables of dimesnion greater than 2');
}
}
function getReferenceMatrix (matrix, direction) {
return matrix.unflatten().rows.sort((r1, r2) => {
return (r1[1] > r2[1] ? 1 : r1[1] < r2[1] ? -1 : 0) * (direction === 'desc' ? -1 : 1);
});
}
function simpleSort (matrix, direction) {
const referenceMatrix = getReferenceMatrix(matrix, direction);
return matrix.clone({
axes: [
Object.assign({}, matrix.axes[0], {values: referenceMatrix.map(r => r[0])})
],
data: referenceMatrix.map(r => r[1])
});
}
module.exports.property = function (prop) {
const order = [].slice.call(arguments, 1);
const dimension = this.getAxis(prop);
if (dimension === -1) {
throw new Error(`Attempting to do a custom sort on the property ${prop}, which doesn't exist`);
}
const originalValues = this.axes.find(a => a.property === prop).values;
// this makes it easier to put the not found items last as the order
// will go n = first, n-1 = second, ... , 0 = last, -1 = not found
// we simply exchange 1 and -1 in the function below :o
order.reverse();
const orderedValues = originalValues.slice().sort((v1, v2) => {
const i1 = order.indexOf(v1);
const i2 = order.indexOf(v2);
return i1 > i2 ? -1 : i1 < i2 ? 1 : 0;
});
const mapper = originalValues.map(v => orderedValues.indexOf(v))
const newAxes = this.axes.slice();
newAxes[dimension] = Object.assign({}, this.axes[dimension], {
values: orderedValues
});
return this.clone({
axes: newAxes,
data: Object.keys(this.data).reduce((obj, k) => {
const coords = k.split(',');
coords[dimension] = mapper[coords[dimension]];
obj[coords.join(',')] = this.data[k];
return obj;
}, {})
});
}
|
import watch from 'gulp-watch';
import browserSync from 'browser-sync';
import path from 'path';
/**
* Gulp task to watch files
* @return {function} Function task
*/
export default function watchFilesTask() {
const config = this.config;
const runSequence = require('run-sequence').use(this.gulp);
return () => {
if (config.entryHTML) {
watch(
path.join(
config.basePath,
config.browsersync.server.baseDir,
config.entryHTML
),
() => {
runSequence('build', browserSync.reload);
}
);
}
if (config.postcss) {
watch(path.join(config.sourcePath, '**/*.{css,scss,less}'), () => {
runSequence('postcss');
});
}
if (config.customWatch) {
if (typeof config.customWatch === 'function') {
config.customWatch(config, watch, browserSync);
} else {
watch(config.customWatch, () => {
runSequence('build', browserSync.reload);
});
}
}
};
}
|
// load package date-util
require('../libs/sugar-date')
module.exports = (pluginContext) => {
return {
respondsTo: (query) => {
return true
},
search: (query = '', env = {}) => {
// check if timestamp given
let isTimestamp = !isNaN(parseFloat(query)) && isFinite(query);
// default settings
let outputFormat = env['outputFormat'] || '{full}';
let timestampUnit = 'seconds';
// override timestamp unit
if (env['timestampUnit'] && env['timestampUnit'] == 'milliseconds') {
timestampUnit = 'milliseconds';
}
// check if string or timestamp is given
if (!isTimestamp) {
// handle timestamp unit
if (timestampUnit == 'seconds') {
// timestamp in seconds
outputFormat = '{X}';
} else {
// timestamp in milliseconds
outputFormat = '{x}';
}
} else {
// parse query
query = parseFloat(query);
// convert given timestamp in seconds to milliseconds
if (timestampUnit == 'seconds') {
query *= 1000;
}
}
// create Sugar Date
var sugarDate = Sugar.Date.create(query);
// check if valid date
if (!Sugar.Date.isValid(sugarDate)) {
return Promise.reject();
}
// set result value
const value = Sugar.Date.format(sugarDate, outputFormat);
// set result subtitle
const subtitle = `Select to copy ` + (isTimestamp ? `the formatted date` : `the timestamp in ${timestampUnit}`) + `.`;
// return results
return new Promise((resolve, reject) => {
resolve([
{
id: 'zazu-utime',
icon: 'fa-clock-o',
title: value,
subtitle: subtitle,
value: value,
}
])
})
}
}
}
|
'use strict';
describe('Directive: cssCode', function () {
// load the directive's module and view
beforeEach(module('googleWebfontsHelperApp'));
beforeEach(module('app/cssCode/cssCode.html'));
var element, scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<css-code></css-code>');
element = $compile(element)(scope);
scope.$apply();
expect(element.text()).toBe('this is the cssCode directive');
}));
});
|
var assert = require('assert');
var keys = require("cmd/common/keys/user.js");
var userKeysNock = require('test/fixtures/user/fixture_user_keys');
module.exports = {
setUp : function(cb){
return cb();
},
'list keys' : function(cb){
keys({ _ : ['list'] }, function(err, list){
assert.equal(err, null, err);
assert.ok(list);
assert.equal(list.list.length, 1);
return cb();
});
},
'create keys' : function(cb){
keys({ _ : ['add'] }, function(err){
assert.ok(!err, err);
keys({ _ : ['add', 'UserKey'] }, function(err, key){
assert.equal(err, null, err);
assert.ok(key.apiKey);
assert.ok(key.apiKey.label);
assert.ok(key.apiKey.key);
return cb();
});
});
},
'revoke keys' : function(cb){
keys.skipPrompt = true;
keys({ _ : ['delete'] }, function(err){
assert.ok(err);
keys({ _ : ['delete', 'UserKey'] }, function(err, key){
assert.equal(err, null, err);
assert.ok(key.apiKey);
assert.ok(key.apiKey.label);
assert.ok(key.apiKey.key);
return cb();
});
});
},
'update keys' : function (cb) {
keys.skipPrompt = true;
keys({ _ : ['update'] }, function(err){
assert.ok(err);
keys({ _ : ['update', 'UserKey', 'UserKey-Updated'] }, function(err, key){
assert.ok(!err, err);
assert.ok(key.apiKey);
assert.ok(key.apiKey.label);
assert.equal('UserKey-Updated', key.apiKey.label);
keys({ _ : ['update', '1239jncjjcd'] }, function(err){
assert.ok(err);
return cb();
});
});
});
},
'target keys' : function(cb){
var key_val = "pviryBwt22iZ0iInufMYBuVV";
keys({ _ : ['target', 'UserKey'] }, function(err, r){
assert.equal(err, null, err);
assert.equal(r, key_val);
keys({ _ : ['target'] }, function(err, r){
assert.equal(err, null);
assert.equal(r, key_val);
return cb();
});
});
},
tearDown : function(cb){
userKeysNock.done();
return cb();
}
};
|
module.exports = {
audioFilter: require('./audioFilter'),
destination: require('./destination'),
filename: require('./filename'),
multer: require('./multer')
}
|
import * as types from 'constants/ActionTypes'
import jsCookie from 'js-cookie'
import history from 'history'
export const setUser = (user) => (dispatch) => {
dispatch({
type: types.SET_USER,
payload: { ...user }
})
}
|
var scp;
var cal_color;
$(document).ready(function(){
scp = angular.element('.main').scope();
$("#div_point").toggle();
//Set default values
cal_color = defaults.cal_color;
//Setup plugins
$("#cal_color").spectrum({
preferredFormat: "hex",
showInput: true,
color: cal_color,
change: setColor,
showButtons: false
});
//Show modal
$('.reveal-modal').css('max-height', $('html').height() - 110 + 'px');
$('#config_modal').reveal();
});
// Reset max-height after window resize
$(window).resize(function() {
$('.reveal-modal').css('max-height', $('html').height() - 110 + 'px');
});
function setColor(color){
//Color picker callback
if(this.id === "cal_color") cal_color = color;
}
function setup(){
//Setup environment before start
$('body').css("background-color", cal_color);
//Update model
$('#cal_color').trigger('input');
//Animate description and target
setTimeout(function() {
$("#div_text" ).fadeOut( "slow", function() {
$( "#div_point" ).fadeIn( "slow", startCalibration);
});
}, 2000);
}
function closeCallback(){
//Configuration modal close callback
$(".main").css("cursor","none");
setup();
}
function calibrationFinished(){
$(".main").css("cursor","pointer");
$("#text").html("Calibration completed");
$( "#div_point" ).fadeOut( "slow", function(){
$("#div_text" ).fadeIn( "slow", function() {
setTimeout(function() {
window.history.back();
}, 2500);
});
});
}
function startCalibration(){
scp.makeRequest();
}
|
/**
* @license Highstock JS v8.0.3 (2020-03-06)
* @module highcharts/indicators/wma
* @requires highcharts
* @requires highcharts/modules/stock
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Kacper Madej
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../indicators/wma.src.js';
|
jsonp({"cep":"89874000","cidade":"Maravilha","uf":"SC","estado":"Santa Catarina"});
|
jsonp({"cep":"63880000","cidade":"Domingos da Costa","uf":"CE","estado":"Cear\u00e1"});
|
import {CHANGE_PAGE_ID} from 'actions'
const initialState = null
export default function(state = initialState, action = {}) {
switch (action.type) {
case CHANGE_PAGE_ID:
return action.payload
default:
return state
}
}
|
'use strict';
var packager = require('electron-packager');
var options = {
'arch': 'ia32',
'platform': 'win32',
'dir': './',
'app-copyright': 'Paulo Galdo',
'app-version': '2.2.5',
'asar': true,
'icon': './app.ico',
'name': 'TierraDesktop',
'out': './releases',
'overwrite': true,
'prune': true,
'version': '1.4.13',
'version-string': {
'CompanyName': 'Paulo Galdo',
'FileDescription': 'Tierra de colores', /*This is what display windows on task manager, shortcut and process*/
'OriginalFilename': 'TierraDesktop',
'ProductName': 'Tierra de colores',
'InternalName': 'TierraDesktop'
}
};
packager(options, function done_callback(err, appPaths) {
console.log("Error: ", err);
console.log("appPaths: ", appPaths);
});
|
'use strict';
var _index = require('/Users/markmiro/proj/ui-experiments/node_modules/babel-preset-react-hmre/node_modules/redbox-react/lib/index.js');
var _index2 = _interopRequireDefault(_index);
var _index3 = require('/Users/markmiro/proj/ui-experiments/node_modules/babel-preset-react-hmre/node_modules/react-transform-catch-errors/lib/index.js');
var _index4 = _interopRequireDefault(_index3);
var _react2 = require('react');
var _react3 = _interopRequireDefault(_react2);
var _index5 = require('/Users/markmiro/proj/ui-experiments/node_modules/babel-preset-react-hmre/node_modules/react-transform-hmr/lib/index.js');
var _index6 = _interopRequireDefault(_index5);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Row = undefined;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _components = {
Row: {
displayName: 'Row'
}
};
var _UsersMarkmiroProjUiExperimentsNode_modulesBabelPresetReactHmreNode_modulesReactTransformHmrLibIndexJs2 = (0, _index6.default)({
filename: 'src/modules/Row.js',
components: _components,
locals: [module],
imports: [_react3.default]
});
var _UsersMarkmiroProjUiExperimentsNode_modulesBabelPresetReactHmreNode_modulesReactTransformCatchErrorsLibIndexJs2 = (0, _index4.default)({
filename: 'src/modules/Row.js',
components: _components,
locals: [],
imports: [_react3.default, _index2.default]
});
function _wrapComponent(id) {
return function (Component) {
return _UsersMarkmiroProjUiExperimentsNode_modulesBabelPresetReactHmreNode_modulesReactTransformHmrLibIndexJs2(_UsersMarkmiroProjUiExperimentsNode_modulesBabelPresetReactHmreNode_modulesReactTransformCatchErrorsLibIndexJs2(Component, id), id);
};
}
var Row = exports.Row = _wrapComponent('Row')(function (_React$Component) {
_inherits(Row, _React$Component);
function Row() {
_classCallCheck(this, Row);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Row).apply(this, arguments));
}
_createClass(Row, [{
key: 'render',
value: function render() {
return _react3.default.createElement(
'div',
null,
this.props.children.map(function (child, i) {
return _react3.default.createElement(
'div',
{ key: i, style: { width: '50%', display: 'inline-block' } },
child
);
})
);
}
}]);
return Row;
}(_react3.default.Component));
|
jsonp({"cep":"78335000","cidade":"Colniza","uf":"MT","estado":"Mato Grosso"});
|
$(document).ready( function () {
// Add return on top button
$('body').append('<div id="returnOnTop" title="Retour en haut"> </div>');
// On button click, let's scroll up to top
$('#returnOnTop').click( function() {
$('html,body').animate({scrollTop: 0}, 'slow');
});
});
$(window).scroll(function() {
// If on top fade the bouton out, else fade it in
if ( $(window).scrollTop() == 0 )
$('#returnOnTop').fadeOut();
else
$('#returnOnTop').fadeIn();
});
|
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const {ipcMain} = require('electron')
const {dialog} = require('electron')
const {Menu} = require('electron')
import {enableLiveReload} from 'electron-compile'
const path = require('path')
const url = require('url')
const fs = require('fs')
enableLiveReload()
//Window Creation
var windowArray = []
exports.windowCount = 0
function createWindow () {
// Create the new browser window.
windowArray.push( new BrowserWindow({width: 800, height: 600}) )
exports.windowCount = windowArray.length
var newWindow = windowArray[exports.windowCount-1]
// windowArray[windowCount-1].maximize()
// and load the index.html of the app.
newWindow.loadURL(url.format({
pathname: path.join(__dirname, 'html/index.html'),
protocol: 'file:',
slashes: true
}))
// Emitted when the window is closed.
newWindow.on('closed', function () {
newWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
// app.on('activate', function () {
// // On OS X it's common to re-create a window in the app when the
// // dock icon is clicked and there are no other windows open.
// if (mainWindow === null) {
// createWindow()
// }
// })
//Menus
var template = [
{
label: 'File',
submenu: [
{label: 'New Project'},
{label: 'Open Project'},
{label: 'Import File'},
{type: 'separator'},
{label: 'Save'},
{label: 'Save As'},
{label: 'Settings'}
]
},
{
label: 'Edit',
submenu: [
{role: 'undo'},
{role: 'redo'},
{type: 'separator'},
{role: 'cut'},
{role: 'copy'},
{role: 'paste'},
{role: 'delete'},
{role: 'selectall'}
]
},
{
label: 'Window',
submenu: [
{label: 'New Window', click: createWindow},
{role: 'minimize'},
{type: 'separator'},
{role: 'toggledevtools'},
{role: 'close'}
]
},
]
var mainMenu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(mainMenu)
//File Functions
function importFile (event) {
dialog.showOpenDialog({properties: ['openFile', 'multiSelections']}, (filePaths) => {
console.log(filePaths)
event.sender.send('importer', filePaths)
})
}
//IPC Functions
ipcMain.on('window-manager', (event, arg) => {
console.log(arg)
if (arg == "New Window") { //Create new window
createWindow()
}
})
ipcMain.on('file-manager', (event, arg) => {
console.log(arg)
if (arg == "Import Files") {
importFile(event)
}
})
|
// npm
var chalk = require('chalk')
// local
var Copper = require('../copper')
var copper = new Copper
var util = require('../util')
module.exports = function (config, wallet, keys, args) {
var abort = false
var name
if (args._.length > 0) {
name = args._.join(' ')
}
var key = copper.newKey()
console.log(' pub:', chalk.green(key.pub))
console.log('priv:', chalk.blue(key.priv))
var wkey = {pub: key.pub, priv: key.priv, date: new Date()}
if (name) {
var keynames = wallet.keys.map(function (k) {return k.name})
if (keynames.indexOf(name) > -1) {
console.log('abort!', chalk.red('key named', name, 'already exists'))
abort = true
} else {
wkey.name = name
console.log('name:', JSON.stringify(wkey.name))
}
}
if (!abort) {
wallet.keys.push(wkey)
util.saveJSON(config.wallet.file, wallet)
}
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _lib = require('../../lib');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className;
var classes = (0, _classnames2.default)((0, _lib.useKeyOnly)(active, 'active'), 'title', className);
var rest = (0, _lib.getUnhandledProps)(AccordionTitle, this.props);
var ElementType = (0, _lib.getElementType)(AccordionTitle, this.props);
return _react2.default.createElement(
ElementType,
(0, _extends3.default)({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
}]);
return AccordionTitle;
}(_react.Component);
AccordionTitle.displayName = 'AccordionTitle';
AccordionTitle._meta = {
name: 'AccordionTitle',
type: _lib.META.TYPES.MODULE,
parent: 'Accordion'
};
exports.default = AccordionTitle;
process.env.NODE_ENV !== "production" ? AccordionTitle.propTypes = {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Whether or not the title is in the open state. */
active: _react.PropTypes.bool,
/** Primary content. */
children: _react.PropTypes.node,
/** Additional classes. */
className: _react.PropTypes.string,
/**
* Called on blur.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: _react.PropTypes.func
} : void 0;
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'onClick'];
|
var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
parent: 'phaser-example',
scene: {
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var graphics;
var pointerRect;
var rectangles;
function create ()
{
graphics = this.add.graphics({ lineStyle: { color: 0x0000aa }, fillStyle: { color: 0x0000aa, alpha: 0.5 } });
pointerRect = new Phaser.Geom.Rectangle(0, 0, 80, 60);
rectangles = [];
for(var x = 0; x < 10; x++)
{
rectangles[x] = [];
for(var y = 0; y < 10; y++)
{
rectangles[x][y] = new Phaser.Geom.Rectangle(x * 80, y * 60, 80, 60);
}
}
this.input.on('pointermove', function (pointer) {
var x = Math.floor(pointer.x / 80);
var y = Math.floor(pointer.y / 60);
pointerRect.setPosition(x * 80, y * 60);
Phaser.Geom.Rectangle.CopyFrom(pointerRect, rectangles[x][y]);
});
}
function update ()
{
graphics.clear();
graphics.fillRectShape(pointerRect);
for(var x = 0; x < 10; x++)
{
for(var y = 0; y < 10; y++)
{
var rect = rectangles[x][y];
if(rect.width > 10)
{
rect.width *= 0.95;
rect.height *= 0.95;
}
graphics.strokeRectShape(rect);
}
}
}
|
var config = {
type: Phaser.WEBGL,
parent: 'phaser-example',
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload() {
this.load.image('bunny', 'assets/sprites/bunny.png');
}
function create() {
var parent = this.add.image(0, 0, 'bunny');
var child = this.add.image(100, 100, 'bunny');
parent.alpha = 0.5;
}
|
requirejs(['bmotion.config'], function() {
requirejs(['bms.integrated.root'], function() {});
});
|
var page = require('webpage').create();
var url;
if (phantom.args) {
url = phantom.args[0];
} else {
url = require('system').args[1];
}
page.onConsoleMessage = function (message) {
console.log(message);
};
function exit(code) {
setTimeout(function(){ phantom.exit(code); }, 0);
phantom.onError = function(){};
}
console.log("Loading URL: " + url);
page.open(url, function (status) {
if (status != "success") {
console.log('Failed to open ' + url);
phantom.exit(1);
}
console.log("Running test.");
var result = page.evaluate(function() {
return chess_game.test_runner.runner();
});
if (result != 0) {
console.log("*** Test failed! ***");
exit(1);
}
else {
console.log("Test succeeded.");
exit(0);
}
});
|
// Compiled by ClojureScript 1.9.946 {}
goog.provide('eckersdorf.window.db');
goog.require('cljs.core');
goog.require('re_frame.core');
eckersdorf.window.db.window_state = new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword("window","height","window/height",1310154766),(0),new cljs.core.Keyword("window","width","window/width",-1138776901),(0)], null);
//# sourceMappingURL=db.js.map?rel=1510703504091
|
/**
* Created by Paul on 24/01/2015.
*/
var install_url = $("#install_url").val();
$("#updateCase").click(function () {
var case_id = $('#case_id').val();
var case_priority = $('#case_priority').val();
var case_status = $('#case_status').val();
var case_type = $('#case_type').val();
var assignedTo = $('#assignedTo').val();
var case_subject = $('#case_subject').val();
var case_description = $('#case_description').val();
var case_resolution = $('#case_resolution').val();
$.ajax({
url: install_url + '/web/front.php/tickets/update_case_ajax',
type: 'POST',
data: "id=" + case_id + "&case_priority=" + case_priority +
"&case_status=" + case_status + "&case_type=" + case_type + "&assignedTo=" + assignedTo + "&case_subject=" + case_subject
+ "&case_description=" + case_description + "&case_resolution=" + case_resolution,
dataType: 'json',
success: function (data) {
if (data.error == "no") {
toastr.options = {
"closeButton": true,
"showDuration": 3
};
toastr['success']('MyCRM', "Case updated");
} else {
toastr.options = {
"closeButton": true,
"showDuration": 3
};
toastr['error']('MyCRM', "Error while updating case");
}
},
error: function (data) {
toastr.options = {
"closeButton": true,
"showDuration": 3
};
toastr['error']('MyCRM', "Error while updating case : " + data);
}
});
});
|
/**
Copyright 2011 Red Hat, Inc.
This software is licensed to you under the GNU General Public
License as published by the Free Software Foundation; either version
2 of the License (GPLv2) or (at your option) any later version.
There is NO WARRANTY for this software, express or implied,
including the implied warranties of MERCHANTABILITY,
NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
have received a copy of GPLv2 along with this software; if not, see
http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*/
KT.panel.list.registerPage('gpg_keys', {
create : 'new_gpg_key',
extra_create_data : function(){
return { 'gpg_key[name]' : $('#gpg_key_name').val() };
}
});
$(document).ready(function(){
$('#upload_gpg_key').live('click', function(event){
KT.gpg_key.upload();
});
$('#upload_new_gpg_key').live('submit', function(e){
e.preventDefault();
KT.gpg_key.upload();
});
$('#update_upload_gpg_key').live('click', function(event){
KT.gpg_key.upload_update();
});
$('#gpg_key_content').live('input keyup paste', function(){
if( $(this).val() !== '' ){
$('#gpg_key_content_upload').attr('disabled', 'disabled');
$('#upload_gpg_key').attr('disabled', 'disabled');
$('#clear_gpg_key').removeAttr('disabled');
} else {
$('#gpg_key_content_upload').removeAttr('disabled');
$('#upload_gpg_key').removeAttr('disabled');
$('#clear_gpg_key').attr('disabled', 'disabled');
}
});
$('#gpg_key_content_upload').live('change', function(){
if( $(this).val() !== '' ){
$('#gpg_key_content').attr('disabled', 'disabled');
$('#save_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
} else {
$('#gpg_key_content').removeAttr('disabled');
$('#save_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
}
});
$('#clear_upload_gpg_key').live('click', function(){
$('#gpg_key_content_upload').val('');
$('#gpg_key_content').removeAttr('disabled');
$('#save_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_gpg_key').attr('disabled', 'disabled');
});
$('#clear_gpg_key').live('click', function(){
$('#gpg_key_content').val('');
$('#gpg_key_content_upload').removeAttr('disabled');
$('#upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_gpg_key').attr('disabled', 'disabled');
});
$('#gpg_key_content_upload_update').live('change', function(){
if( $(this).val() !== '' ){
$('#update_upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
} else {
$('#update_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
}
});
$('#clear_upload_gpg_key').live('click', function(){
$('#update_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#gpg_key_content_upload_update').val('');
});
});
KT.gpg_key = (function($){
var self = this,
get_buttons = function(){
return {
'gpg_key_save' : $('#save_gpg_key'),
'gpg_key_upload': $('#upload_gpg_key')
}
},
enable_buttons = function(){
var buttons = get_buttons();
buttons.gpg_key_save.removeAttr('disabled');
buttons.gpg_key_upload.removeAttr('disabled');
},
disable_buttons = function(){
var buttons = get_buttons();
buttons.gpg_key_save.attr('disabled', 'disabled');
buttons.gpg_key_upload.attr('disabled', 'disabled');
};
self.upload = function(){
var submit_data = { 'gpg_key[name]' : $('#gpg_key_name').val() };
disable_buttons();
$('#upload_new_gpg_key').ajaxSubmit({
url : KT.routes['gpg_keys_path'](),
type : 'POST',
data : submit_data,
iframe : true,
success : function(data, status, xhr){
var parsed_data = $(data);
if( parsed_data.get(0).tagName === 'PRE' ){
notices.displayNotice('error', parsed_data.html());
} else {
KT.panel.list.createSuccess(data);
}
enable_buttons();
},
error : function(){
enable_buttons();
notices.checkNotices();
}
});
};
self.upload_update = function(){
$('#update_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#upload_gpg_key').ajaxSubmit({
url : $(this).data('url'),
type : 'POST',
iframe : true,
success : function(data, status, xhr){
if( !data.match(/notices/) ){
$('#gpg_key_content').html(data);
$('#upload_gpg_key').val('');
}
notices.checkNotices();
$('#update_upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
},
error : function(){
$('#update_upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
notices.checkNotices();
}
});
};
return self;
})(jQuery);
|
function isPrime(n) {
if (n === 2) {
return true;
}
if (n % 2 === 0 || n === 1) {
return false;
}
for (var i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i === 0) {
return false;
}
}
return true;
}
function nthPrimeNumber(n) {
if (n <= 0) {
throw new Error('Must be an integer >= 1');
}
var numPrime = 1;
var i = 1;
if (n === 1) {
return 2;
}
while (numPrime < n) {
i += 2;
if (isPrime(i)) {
numPrime++;
}
}
return i;
}
console.log(nthPrimeNumber(10001));
|
/*
* Copyright (C) 2008-2010 Surevine Limited.
*
* Although intended for deployment and use alongside Alfresco this module should
* be considered 'Not a Contribution' as defined in Alfresco'sstandard contribution agreement, see
* http://www.alfresco.org/resource/AlfrescoContributionAgreementv2.pdf
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// Get the change password url
model.changePasswordUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_change_password.txt');
//Get the security label header
model.securityLabelHeaderNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/security_label.txt');
//Get the help url
model.helpLinkNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_help.txt');
model.launchChatUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Chat Dashlet/url_launch_chat.txt');
//Get the logo node
model.appLogoNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/app_logo');
model.surevineLinkUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Footer/url_surevine_link.txt');
cache.neverCache=false;
cache.isPublic=false;
cache.maxAge=36000; //10 hours
cache.mustRevalidate=false;
cache.ETag = 100;
|
/*
YUI 3.7.3 (build 5687)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('dom-class', function(Y) {
var addClass, hasClass, removeClass;
Y.mix(Y.DOM, {
/**
* Determines whether a DOM element has the given className.
* @method hasClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the given class.
*/
hasClass: function(node, className) {
var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
return re.test(node.className);
},
/**
* Adds a class name to a given DOM element.
* @method addClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to add to the class attribute
*/
addClass: function(node, className) {
if (!Y.DOM.hasClass(node, className)) { // skip if already present
node.className = Y.Lang.trim([node.className, className].join(' '));
}
},
/**
* Removes a class name from a given element.
* @method removeClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to remove from the class attribute
*/
removeClass: function(node, className) {
if (className && hasClass(node, className)) {
node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' +
className + '(?:\\s+|$)'), ' '));
if ( hasClass(node, className) ) { // in case of multiple adjacent
removeClass(node, className);
}
}
},
/**
* Replace a class with another class for a given element.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
*/
replaceClass: function(node, oldC, newC) {
//Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node');
removeClass(node, oldC); // remove first in case oldC === newC
addClass(node, newC);
},
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} className the class name to be toggled
* @param {Boolean} addClass optional boolean to indicate whether class
* should be added or removed regardless of current state
*/
toggleClass: function(node, className, force) {
var add = (force !== undefined) ? force :
!(hasClass(node, className));
if (add) {
addClass(node, className);
} else {
removeClass(node, className);
}
}
});
hasClass = Y.DOM.hasClass;
removeClass = Y.DOM.removeClass;
addClass = Y.DOM.addClass;
}, '3.7.3' ,{requires:['dom-core']});
|
var options={}; options.login=true;
LoginRadius_SocialLogin.util.ready(function ()
{ $ui = LoginRadius_SocialLogin.lr_login_settings;
$ui.interfacesize = Drupal.settings.lrsociallogin.interfacesize;
$ui.lrinterfacebackground=Drupal.settings.lrsociallogin.lrinterfacebackground;
$ui.noofcolumns= Drupal.settings.lrsociallogin.noofcolumns;
$ui.apikey = Drupal.settings.lrsociallogin.apikey;
$ui.is_access_token=true;
$ui.callback=Drupal.settings.lrsociallogin.location;
$ui.lrinterfacecontainer ="interfacecontainerdiv"; LoginRadius_SocialLogin.init(options); });
LoginRadiusSDK.setLoginCallback(function () {
var token = LoginRadiusSDK.getToken();
var form = document.createElement('form');
form.action = Drupal.settings.lrsociallogin.location;
form.method = 'POST';
var hiddenToken = document.createElement('input');
hiddenToken.type = 'hidden';
hiddenToken.value = token;
hiddenToken.name = 'token';
form.appendChild(hiddenToken);
document.body.appendChild(form);
form.submit();
});
|
module.exports = function(grunt) {
require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
copy: {
main: {
expand: true,
cwd: "src/",
src: ["**", "!css/**/*.scss", "!css/**/*.less"],
dest: "dist/"
}
},
less: {
options: {
paths: ["src/css"]
},
src: {
expand: true,
cwd: "src/css",
src: "*.less",
ext: ".css",
dest: "src/css"
}
},
sass: {
dist:{
options:{
style: 'expanded', // values: nested, expanded, compact, compressed
noCache: true
},
files:[{
expand: true,
cwd: "src/css",
src: ["*.scss"],
dest: "src/css",
ext: ".css"
}]
}
},
watch: {
options: {
nospawn: true,
livereload: true
},
less: {
files: ["src/css/**/*.less"],
tasks: ["less"]
},
sass: {
files: ["src/css/**/*.scss"],
tasks: ["sass"]
},
copy: {
files: ["src/**"],
tasks: ["copy:main"]
}
}
});
grunt.registerTask("default", ["watch"]);
};
|
var SPHERE = {
getSphereVertex: function (radius, res) { // Se obtienen los vértices, normales y coordenadas de textura
var vertexData = [], alpha, beta, x, y, z, u, v;
for (var i = 0; i <= res; i++) { // Se recorren las latitudes
alpha = i * Math.PI / res; // Ángulo latitud
for (var j = 0; j <= res; j++) { // Se recorren las longitudes
beta = j * 2 * Math.PI / res; // Ángulo longitud
// Cálculo de x, y, z para vértices y normales
x = Math.cos(beta) * Math.sin(alpha);
y = Math.cos(alpha);
z = Math.sin(beta) * Math.sin(alpha);
// Cálculo de u, v para las coordenadas de textura
u = 1 - (j / res);
v = 1 - (i / res);
// Vértices
vertexData.push(radius * x);
vertexData.push(radius * y);
vertexData.push(radius * z);
// Normales
vertexData.push(x);
vertexData.push(y);
vertexData.push(z);
// Coordenadas de textura
vertexData.push(u);
vertexData.push(v);
}
}
return vertexData;
},
getShereFaces: function (res) { // Se obtienen los índices para crear las caras
var indexData = [], first, second;
for (var i = 0; i < res; i++) { // Se recorren las latitudes
for (var j = 0; j < res; j++) { // Se recorren las longitudes
// Cálculo de las esquinas superior e inferior izquierda
first = (i * (res + 1)) + j;
second = first + res + 1;
// Cara par
indexData.push(first); // Esquina superior izquierda
indexData.push(second); // Esquina inferior izquierda
indexData.push(first + 1); // Esquina superior derecha
// Cara impar
indexData.push(second); // Esquina inferior izquierda
indexData.push(second + 1); // Esquina inferior derecha
indexData.push(first + 1); // Esquina superior derecha
}
}
return indexData;
}
};
|
/**
* Copyright (C) SiteSupra SIA, Riga, Latvia, 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
YUI.add('itemmanager.itemlist-uploader', function (Y) {
//Invoke strict mode
"use strict";
//Shortcut
var Manager = Supra.Manager,
Action = Manager.PageContent;
/*
* Editable content
*/
function ItemListUploader (config) {
ItemListUploader.superclass.constructor.apply(this, arguments);
}
ItemListUploader.NAME = 'itemmanager-itemlist-uploader';
ItemListUploader.NS = 'uploader';
ItemListUploader.ATTRS = {};
Y.extend(ItemListUploader, Y.Plugin.Base, {
/**
* Supra.Uploader instance
* @type {Object}
* @private
*/
uploader: null,
/**
* File uploader ids to item ids
* @type {Object}
* @private
*/
ids: null,
/**
*
*/
initializer: function () {
var itemlist = this.get('host'),
container = itemlist.get('contentElement');
this.ids = {};
this.listeners = [];
this.listeners.push(itemlist.after('contentElementChange', this.reattachListeners, this));
if (container) {
this.reattachListeners();
}
},
destructor: function () {
this.resetAll();
// Listeners
var listeners = this.listeners,
i = 0,
ii = listeners.length;
for (; i < ii; i++) listeners[i].detach();
this.listeners = null;
},
/**
* Attach drag and drop listeners
*/
reattachListeners: function () {
var itemlist = this.get('host'),
container = itemlist.get('contentElement'),
//doc = null,
target = null;
if (this.uploader) {
this.uploader.destroy();
this.uploader = null;
}
if (!container) {
return false;
}
//Create uploader
target = itemlist.get('iframe').one('.supra-itemmanager-wrapper');
this.uploader = new Supra.Uploader({
'dropTarget': target,
'allowBrowse': false,
'allowMultiple': true,
'accept': 'image/*',
'requestUri': Supra.Url.generate('media_library_upload'),
'uploadFolderId': itemlist.get('host').options.imageUploadFolder
});
this.uploader.on('file:upload', this.onFileUploadStart, this);
this.uploader.on('file:complete', this.onFileUploadEnd, this);
this.uploader.on('file:error', this.onFileUploadError, this);
},
/**
* Reset all iframe content bindings, etc.
*/
resetAll: function () {
var uploader = this.uploader;
if (uploader) {
uploader.destroy(true);
this.uploader = null;
}
},
/* ------------------------ FILE UPLOAD ------------------------ */
/**
* Handle file upload start
*/
onFileUploadStart: function (e) {
var data = e.details[0],
itemlist = this.get('host'),
item = null;
// Prevent item from being opened for editing
itemlist.initializing = true;
item = itemlist.addItem({'title': e.title.replace(/\..+$/, '')});
itemlist.initializing = false;
this.ids[e.id] = item.__suid;
},
/**
* Handle file upload end
*/
onFileUploadEnd: function (e) {
var data = e.details[0],
itemlist = this.get('host'),
itemdrop = itemlist.drop;
if (e.old_id in this.ids) {
itemdrop.updateItemInCollection(data, this.ids[e.old_id]);
delete(this.ids[e.old_id]);
} else {
itemdrop.addItemToCollection(data);
}
},
/**
* Handle file upload error
*/
onFileUploadError: function (e) {
var itemlist = this.get('host');
itemlist.removeItem(this.ids[e.id]);
delete(this.ids[e.id]);
}
});
Supra.ItemManagerItemListUploader = ItemListUploader;
//Since this widget has Supra namespace, it doesn't need to be bound to each YUI instance
//Make sure this constructor function is called only once
delete(this.fn); this.fn = function () {};
}, YUI.version, {requires: ['plugin', 'supra.uploader']});
|
var iconhead={
title:"Icon Heading Shortcode",
id :'oscitas-form-iconhead',
pluginName: 'iconhead',
setRowColors:false
};
(function() {
_create_tinyMCE_options(iconhead,800);
})();
function create_oscitas_iconhead(pluginObj){
if(jQuery(pluginObj.hashId).length){
jQuery(pluginObj.hashId).remove();
}
// creates a form to be displayed everytime the button is clicked
// you should achieve this using AJAX instead of direct html code like this
var iconhead_fa='';
/*if(ebs.ebs_fa_inclusion==1){
iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>';
}*/
iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>';
// creates a form to be displayed everytime the button is clicked
// you should achieve this using AJAX instead of direct html code like this
var form = jQuery('<div id="'+pluginObj.id+'" class="oscitas-container" title="'+pluginObj.title+'"><table id="gallery-table" class="form-table">\
<tr>\
<th><label for="oscitas-heading-icon">Select Icon:</label></th>\
<td><div id="click_icon_list" class="oscitas-icon-div"><span id="osc_show_icon"></span><span class="show-drop"></span></div><input type="hidden" id="oscitas-iconhead-icon" value=""><input type="hidden" id="oscitas-iconhead-icontype" value="">\
<div id="osc_show_iconlist" class="oscitas-icon" style="display:none;width:100%"><h4>Glyphicons</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsicons+'</ul>'+iconhead_fa+'</div>\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-iconcolor">Icon Color:</label></th>\
<td><input type="text" name="label" id="oscitas-iconhead-iconcolor" class="color" value="" /><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-headingtype">Heading Type:</label></th>\
<td><select name="oscitas-iconhead-headingtype" id="oscitas-iconhead-headingtype">\
<option value="h1">H1</option>\
<option value="h2">H2</option>\
<option value="h3">H3</option>\
<option value="h4">H4</option>\
<option value="h5">H5</option>\
<option value="h6">H6</option>\
</select><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-heading">Heading:</label></th>\
<td><input type="text" name="oscitas-iconhead-heading" id="oscitas-iconhead-heading" value="Heading"/><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-class">Custom Class:</label></th>\
<td><input type="text" name="line" id="oscitas-iconhead-class" value=""/><br />\
</td>\
</tr>\
</table>\
<p class="submit">\
<input type="button" id="oscitas-iconhead-submit" class="button-primary" value="Insert Icon Heading" name="submit" />\
</p>\
</div>');
var table = form.find('table');
jQuery('.glyphicon').css('display','inline');
form.appendTo('body').hide();
form.find('.color').wpColorPicker();
table.find('#click_icon_list').click(function(){
if(!jQuery(this).hasClass('osc_icon_showing')){
jQuery(this).addClass('osc_icon_showing')
table.find('#osc_show_iconlist').show();
} else{
jQuery(this).removeClass('osc_icon_showing')
table.find('#osc_show_iconlist').hide();
}
});
table.find('.oscitas-heading-icon li').click(function(){
var val=jQuery(this).attr('data-value');
var type=jQuery(this).attr('type');
table.find('.oscitas-heading-icon li').removeClass('osc_icon_selected');
jQuery(this).addClass('osc_icon_selected');
table.find('#click_icon_list').removeClass('osc_icon_showing');
table.find('#osc_show_iconlist').hide();
table.find('#osc_show_icon').removeClass().addClass(type).addClass(val);
table.find('#oscitas-iconhead-icon').val(val);
table.find('#oscitas-iconhead-icontype').val(type);
});
// // handles the click event of the submit button
form.find('#oscitas-iconhead-submit').click(function() {
// defines the options and their default values
// again, this is not the most elegant way to do this
// but well, this gets the job done nonetheless
var type=jQuery('#oscitas-iconhead-headingtype').val();
var cusclass='',style='';
if(table.find('#oscitas-iconhead-icon').val()!=''){
style=' style="' + table.find('#oscitas-iconhead-icon').val()+'"' ;
}
if(table.find('#oscitas-iconhead-icontype').val()!=''){
style+=' icontype="' + table.find('#oscitas-iconhead-icontype').val()+'"' ;
}
if(table.find('#oscitas-iconhead-iconcolor').val()!=''){
cusclass+= ' color="'+table.find('#oscitas-iconhead-iconcolor').val()+'"';
}
if(table.find('#oscitas-iconhead-class').val()!=''){
cusclass+= ' class="'+table.find('#oscitas-iconhead-class').val()+'"';
}
var shortcode = '[iconheading type="'+type+'"';
shortcode += style+cusclass ;
shortcode += ']'+table.find('#oscitas-iconhead-heading').val()+'[/iconheading]' ;
// inserts the shortcode into the active editor
tinyMCE.activeEditor.execCommand('mceInsertContent',0 , shortcode);
// closes Dialoguebox
close_dialogue(pluginObj.hashId);
});
}
|
$('#section').on('click', '[id$="Empty"]', function(event) {
event.preventDefault();
var match = /(.+)Empty/.exec($(event.target).closest('.unwell').attr('id'));
var id = match[1];
var emptyId = match[0];
$('#'+id).trigger('addrow');
$('#'+emptyId).addClass('hidden');
return false;
});
$('#section').on('submit', 'form[name="formItem"]', function(e) {
e.preventDefault();
var form = $(this),
btn = form.find('.btn-primary'),
valid = isFormValid(form);
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
if($(e).val() == "Select an option"){
valid = false;
showPermanentError(form, "Please select a valid action.");
}
});
if (valid) {
btn.button('loading');
resetAlert($('#section'));
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize()
}).always(function() {
btn.button('reset');
}).done(function(data, textStatus, jqXHR) {
showSuccess(form, "Saved");
window.location.hash = "#config/portal_module/"+form.find('input[name="id"]').val()+"/read"
}).fail(function(jqXHR) {
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(form, status_msg);
});
}
});
$('#section').on('click', '.delete-portal-module', function(e){
e.preventDefault();
var button = $(e.target);
button.button('loading');
$.ajax({
type: 'GET',
url: button.attr('href'),
}).always(function() {
}).done(function(data, textStatus, jqXHR) {
showSuccess(button.closest('.table'), "Deleted");
button.closest('tr').remove();
}).fail(function(jqXHR) {
button.button('reset');
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(button.closest('.table'), status_msg);
});
return false;
});
$('#section').on('click', '.expand', function(e){
e.preventDefault();
$(e.target).hide(function(){
$($(e.target).attr('data-expand')).slideDown();
});
return false;
});
$('#section').on('change', '#actions select[name$=".type"]', function(event) {
var type_input = $(event.currentTarget);
updateActionMatchInput(type_input,false);
});
$('#section').on('click', '#actionsContainer a[href="#add"]', function(event) {
setTimeout(initActionMatchInput, 3000);
});
function initActionMatchInput() {
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
updateActionMatchInput($(e),true);
});
}
function updateActionMatchInput(type_input, keep) {
var match_input = type_input.next();
var type_value = type_input.val();
var match_input_template_id = '#' + type_value + "_action_match";
var match_input_template = $(match_input_template_id);
if ( match_input_template.length == 0 ) {
match_input_template = $('#default_action_match');
}
if ( match_input_template.length ) {
changeInputFromTemplate(match_input, match_input_template, keep);
if (type_value == "switch") {
type_input.next().typeahead({
source: searchSwitchesGenerator($('#section h2')),
minLength: 2,
items: 11,
matcher: function(item) { return true; }
});
}
}
}
|
jQuery(function($){
$.supersized({
//Functionality
slideshow : 1, //Slideshow on/off
autoplay : 1, //Slideshow starts playing automatically
start_slide : 1, //Start slide (0 is random)
slide_interval : 4000, //Length between transitions
slideshow_interval : 4000, //Length between transitions
transition : 1, //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 500, //Speed of transition
new_window : 1, //Image links open in new window/tab
pause_hover : 0, //Pause slideshow on hover
keyboard_nav : 1, //Keyboard navigation on/off
performance : 1, //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
image_protect : 1, //Disables image dragging and right click with Javascript
image_path : 'img/', //Default image path
//Size & Position
min_width : 0, //Min width allowed (in pixels)
min_height : 0, //Min height allowed (in pixels)
vertical_center : 1, //Vertically center background
horizontal_center : 1, //Horizontally center background
fit_portrait : 1, //Portrait images will not exceed browser height
fit_landscape : 0, //Landscape images will not exceed browser width
//Components
navigation : 1, //Slideshow controls on/off
thumbnail_navigation : 1, //Thumbnail navigation
slide_counter : 1, //Display slide numbers
slide_captions : 1, //Slide caption (Pull from "title" in slides array)
slides : (function(){
var ret = new Array();
for(var i in supersizedImgs){
ret.push({image: supersizedImgs[i]});
}
return ret;
})()
});
});
|
define(function () {
return {
customerAccount: ['CustomerAccountService', function (CustomerAccountService) {
return CustomerAccountService.getCurrent();
}]
};
});
|
'use strict';
angular.module('sbAdminApp')
.controller('CustomerListCtrl', function ($scope, $http, $rootScope, $stateParams, $location) {
$scope.page = {itemsPerPage: 20};
$scope.iForm = {pageSize : $scope.page.itemsPerPage};
$scope.showLevel = true;
if ($stateParams.searchFounder == 1) {
$scope.searchFounder = true;
}
$scope.level = $stateParams.level;
if ($stateParams.page) {
$scope.iForm.page = parseInt($stateParams.page);
}
$http.get("/org/customer/level-enumeration")
.success(function (data) {
$scope.levels = data;
});
$http.get("/org/customer/status-enumeration")
.success(function (data) {
$scope.statuses = data;
});
$http({
url: "/org/team/all",
method: "GET"
})
.success(function (data) {
$scope.teams = data;
});
$http({
url: "/org/customer/list",
method: "GET",
params: $scope.iForm
})
.success(function (data) {
$scope.items = data.content;
$scope.page.totalItems = data.total;
$scope.page.currentPage = data.page + 1;
});
$scope.pageChanged = function() {
$scope.iForm.page = $scope.page.currentPage - 1;
$location.search($scope.iForm);
}
$scope.search = function () {
$scope.iForm.page = 0;
$location.search($scope.iForm);
}
});
|
(function() {
tinymce.PluginManager.requireLangPack('kotofey_shortcodes');
tinymce.create('tinymce.plugins.kotofey_shortcodes', {
init : function(ed, url) {
ed.addCommand('mcekotofey_shortcodes', function() {
ed.windowManager.open({
file : url + '/interface.php',
width : 290 + ed.getLang('kotofey_shortcodes.delta_width', 0),
height : 150 + ed.getLang('kotofey_shortcodes.delta_height', 0),
inline : 1
}, {
plugin_url : url
});
});
ed.addButton('kotofey_shortcodes', {
title : 'Click to add a shortcode',
cmd : 'mcekotofey_shortcodes',
image : url + '/shortcode_button.png'
});
ed.onNodeChange.add(function(ed, cm, n) {
cm.setActive('kotofey_shortcodes', n.nodeName == 'IMG');
});
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : 'kotofey_shortcodes',
author : 'kotofey',
authorurl : 'http://themeforest.net/user/kotofey',
infourl : 'http://themeforest.net/user/kotofey',
version : "1.0"
};
}
});
tinymce.PluginManager.add('kotofey_shortcodes', tinymce.plugins.kotofey_shortcodes);
})();
|
const fs = require('fs');
const util = require('../../util');
// test equality
function equal(a, b, options) {
if (a === b) {
return options.fn(this);
}
return options.inverse(this);
}
// great than
function gt(a, b, options) {
if (a >= b) {
return options.fn(this);
}
return options.inverse(this);
}
// between
function between(a, b, c, options) {
if (a >= b && a <= c) {
return options.fn(this);
}
return options.inverse(this);
}
// less than
function lt(a, b, options) {
if (a < b) {
return options.fn(this);
}
return options.inverse(this);
}
function ignoreNan(val, symbol) {
const isNumber = (val >= 0 || val < 0);
return isNumber ? `${util.roundDecimal(val, 2)} ${symbol}` : '';
}
// test inequality
function inequal(a, b, options) {
if (a !== b) {
return options.fn(this);
}
return options.inverse(this);
}
// test File Exit
function fileExist(a, b, options) {
try {
fs.statSync(`${a}${b}`);
return options.fn(this);
} catch (err) {
return options.inverse(this);
}
}
exports.equal = equal;
exports.gt = gt;
exports.lt = lt;
exports.between = between;
exports.ignoreNan = ignoreNan;
exports.inequal = inequal;
exports.fileExist = fileExist;
|
'use strict';
/*@ngInject*/
function repoItemClassifierFilter() {
return function(node) {
if (node.type) {
return 'uib-repository__item--movable';
} else {
return 'uib-repository__group';
}
};
}
module.exports = repoItemClassifierFilter;
|
/**
* App Control
*
* Central controller attached to the top level <html>
* element
*/
"use strict";
( function ( angular, app ) {
// get user profile data
app.controller( "AppCtrl", [ '$rootScope', '$scope', '$state', 'UserService',
function ( $rootScope, $scope, $state, UserService ) {
//
// bodyClass definitions
//
// in a larger project this would be abstracted to allow for multiple
// classes to easily be added or removed
//
// current state
$rootScope.$on( '$stateChangeStart',
function ( event, toState, toParams, fromState, fromParams ) {
var currentState = toState.name.replace( '.', '-' );
$scope.bodyClass = 'state-' + currentState;
}
);
/**
* Format Avatar
*/
$scope.currentUserAvatar = function ( src, size ) {
return UserService.getCurrentUserAvatar( size );
};
}
] );
} )( angular, SimplySocial );
|
'use strict';
/**
* @ngdoc function
* @name quickNewsApp.controller:CbcCtrl
* @description
* # CbcCtrl
* Controller of the quickNewsApp
*/
angular.module('quickNewsApp')
.controller('CbcCtrl', function ($scope, $http) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.postLimit = 10;
$scope.showMorePosts = function() {
$scope.postLimit += 5;
};
$scope.isSet = function(checkTab) {
return this.tab === checkTab;
};
$scope.setTab = function(activeTab) {
this.tab = activeTab;
$scope.postLimit = 10;
$scope.getFeed(activeTab);
};
$scope.getActiveTab = function() {
return this.tab;
};
$scope.getFeed = function(category) {
/*jshint unused: false */
$scope.loading = true;
var url = '//quicknews.amanuppal.ca:5000/cbc?url=' + category;
$http.get(url)
.success(function(data, status, headers, config) {
$scope.entries = data.items;
console.log($scope.entries);
$scope.numEntries = Object.keys($scope.entries).length;
$scope.loading = false;
})
.error(function(data, status, headers, config) {
console.log('Error loading feed: ' + url + ', status: ' + status);
});
};
});
|
module.exports = {
dist: {
options: {
plugin_slug: 'simple-user-adding',
svn_user: 'wearerequired',
build_dir: 'release/svn/',
assets_dir: 'assets/'
}
}
};
|
/**
* The routes worker process
*
* This worker process gets the app routes by running the application dynamically
* on the server, then stores the publicly exposed routes in an intermediate format
* (just the url paths) in Redis.
* From there, the paths are used by the live app for serving /sitemap.xml and /robots.txt requests.
* The paths are also used by downstream worker processes (snapshots) to produce the site's html snapshots
* for _escaped_fragment_ requests.
*
* Run this worker anytime the app menu has changed and needs to be refreshed.
*
* PATH and NODE_ENV have to set in the environment before running this.
* PATH has to include phantomjs bin
*/
var phantom = require("node-phantom");
var urlm = require("url");
var redis = require("../../../helpers/redis");
var configLib = require("../../../config");
var config = configLib.create();
// Write the appRoutes to Redis
function writeAppRoutes(appRoutes) {
// remove pattern routes, and prepend /
appRoutes = appRoutes.filter(function(appRoute) {
return !/[*\(\:]/.test(appRoute);
}).map(function(appRoute) {
return "/"+appRoute;
});
if (appRoutes.length > 0) {
var redisClient = redis.client();
redisClient.set(config.keys.routes, appRoutes, function(err) {
if (err) {
console.error("failed to store the routes for "+config.keys.routes);
} else {
console.log("successfully stored "+appRoutes.length+" routes in "+config.keys.routes);
}
redisClient.quit();
});
} else {
console.error("no routes found for "+config.app.hostname);
}
}
// Start up phantom, wait for the page, get the appRoutes
function routes(urlPath, timeout) {
var url = urlm.format({
protocol: "http",
hostname: config.app.hostname,
port: config.app.port || 80,
pathname: urlPath
});
phantom.create(function(err, ph) {
return ph.createPage(function(err, page) {
return page.open(url, function(err, status) {
if (status !== "success") {
console.error("Unable to load page " + url);
ph.exit();
} else {
setTimeout(function() {
return page.evaluate(function() {
return window.wpspa.appRoutes;
}, function(err, result) {
if (err) {
console.error("failed to get appRoutes");
} else {
writeAppRoutes(Object.keys(result));
}
ph.exit();
});
}, timeout);
}
});
});
});
}
module.exports = {
routes: routes
};
|
jQuery('#bootstrapslider').carousel({
interval: bootstrapslider_script_vars.interval,
pause: bootstrapslider_script_vars.pause,
wrap: bootstrapslider_script_vars.wrap
});
|
/**
* Setup (required for Joomla! 3)
*/
if(typeof(akeeba) == 'undefined') {
var akeeba = {};
}
if(typeof(akeeba.jQuery) == 'undefined') {
akeeba.jQuery = jQuery.noConflict();
}
akeeba.jQuery(document).ready(function($){
function atsAssignmentClick()
{
var parent = akeeba.jQuery(this).parent('td');
var id = akeeba.jQuery(this).parents('td').find('input.ticket_id').val();
var hide = ['.loading img', '.loading .icon-warning-sign'];
var show = ['.loading .icon-ok'];
var assign_to = 0;
if(akeeba.jQuery(this).hasClass('assignme'))
{
assign_to = akeeba.jQuery('#user').val();
}
else if(akeeba.jQuery(this).parent('.assignto'))
{
assign_to = akeeba.jQuery(this).parent().find('input.assignto').val();
}
if(this.hasClass('unassign')){
hide.push('.unassign');
show.push('.assignme');
}
else{
hide.push('.assignme');
show.push('.unassign');
}
var structure = {
_rootElement: this,
type: "POST",
dataType: 'json',
url : ATS_ROOT_URL + 'index.php?option=com_ats&view=ticket&format=json&' + akeeba.jQuery('#token').attr('name') + '=1',
data: {
'task' : 'assign',
'id' : id,
'assigned_to' : assign_to
},
beforeSend: function() {
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.css('display','inline').find('i').css('display', 'none');
wait.find('img').css('display', 'inline-block');
},
success: function(responseJSON)
{
var assigned = akeeba.jQuery(this._rootElement).parents('td').find('.assigned_to');
var unassign = akeeba.jQuery(this._rootElement).hasClass('unassign');
if(responseJSON.result == true){
assigned.html(responseJSON.assigned);
unassign ? assigned.removeClass('badge-info') : assigned.addClass('badge-info');
for (var i = 0; i < hide.length; i++)
{
var elementDefinition = hide[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'none');
}
for (var i = 0; i < show.length; i++)
{
var elementDefinition = show[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'inline-block');
}
}
else
{
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.find('.icon-ok,img').css('display', 'none');
wait.find('.icon-warning-sign').show('fast');
}
}
};
akeeba.jQuery.ajax( structure );
}
akeeba.jQuery('.unassign a').click(atsAssignmentClick);
akeeba.jQuery('.assignme a').click(atsAssignmentClick);
akeeba.jQuery('.assignto li a').click(atsAssignmentClick);
akeeba.jQuery('.select-status li a').click(function(){
var image = akeeba.jQuery(this).parent().find('img');
var self = this;
akeeba.jQuery.ajax(ATS_ROOT_URL + 'index.php?option=com_ats&view=tickets&task=ajax_set_status&format=json&'+jQuery('#token').attr('name')+'=1',{
type : 'POST',
dataType : 'json',
data : {
'id' : akeeba.jQuery(this).parents('tr').find('.ats_ticket_id').val(),
'status' : akeeba.jQuery(this).data('status')
},
beforeSend : function(){
image.show();
},
success : function(responseJSON){
image.hide();
if(responseJSON.err){
alert(responseJSON.err);
}
else{
var label = akeeba.jQuery(self).parents('td').find('span[class*="label-"]');
label.attr('class', 'ats-status label pull-right ' + responseJSON.ats_class).html(responseJSON.msg);
}
}
})
})
});
|
/**
* Created by LPAC006013 on 23/11/14.
*/
/*
* wiring Super fish to menu
*/
var sfvar = jQuery('div.menu');
var phoneSize = 600;
jQuery(document).ready(function($) {
//if screen size is bigger than phone's screen (Tablet,Desktop)
if($(document).width() >= phoneSize) {
// enable superfish
sfvar.superfish({
delay: 500,
speed: 'slow'
});
jQuery("#menu-main-menu").addClass('clear');
var containerheight = jQuery("#menu-main-menu").height();
jQuery("#menu-main-menu").children().css("height",containerheight);
}
$(window).resize(function() {
if($(document).width() >= phoneSize && !sfvar.hasClass('sf-js-enabled')) {
sfvar.superfish({
delay: 500,
speed: 'slow'
});
}
// phoneSize, disable superfish
else if($(document).width() < phoneSize) {
sfvar.superfish('destroy');
}
});
});
|
var express = require('express');
var path = require('path');
var tilestrata = require('tilestrata');
var disk = require('tilestrata-disk');
var mapnik = require('tilestrata-mapnik');
var dependency = require('tilestrata-dependency');
var strata = tilestrata();
var app = express();
// define layers
strata.layer('hillshade')
.route('shade.png')
.use(disk.cache({dir: './tiles/shade/'}))
.use(mapnik({
pathname: './styles/hillshade.xml',
tileSize: 256,
scale: 1
}));
strata.layer('dem')
.route('dem.png')
.use(disk.cache({dir: './tiles/dem/'}))
.use(mapnik({
pathname: './styles/dem.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim1')
.route('sim1.png')
.use(disk.cache({dir: './tiles/sim1/'}))
.use(mapnik({
pathname: './styles/sim1.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim2')
.route('sim2.png')
.use(disk.cache({dir: './tiles/sim2/'}))
.use(mapnik({
pathname: './styles/sim2.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim3')
.route('sim3.png')
.use(disk.cache({dir: './tiles/sim3/'}))
.use(mapnik({
pathname: './styles/sim3.xml',
tileSize: 256,
scale: 1
}));
strata.layer('slope')
.route('slope.png')
.use(disk.cache({dir: './tiles/slope/'}))
.use(mapnik({
pathname: './styles/slope.xml',
tileSize: 256,
scale: 1
}));
var staticPath = path.resolve(__dirname, './public/');
app.use(express.static(staticPath));
app.use(tilestrata.middleware({
server: strata,
prefix: ''
}));
app.listen(8080, function() {
console.log('Express server running on port 8080.');
});
|
var express = require('express'),
Weapon = require('../models/Weapon'),
router = express.Router();
// HOMEPAGE
router.get('/', function(req, res) {
res.render('index', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'Hello Word!'
});
});
// WEAPON
router.get('/weapon', function(req, res) {
var schema = {};
Weapon.schema.eachPath(function (pathname, schemaType) {
schema[pathname] = schemaType.instance;
});
res.render('weapon', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'This is a form.',
schema: schema
});
});
module.exports = router;
|
Package.describe({
summary: "Next bike list package"
});
Package.on_use(function (api) {
api.use(['nb','underscore', 'templating', 'nb-autocomplete', 'nb-markers', 'nb-infowindow', 'nb-directions', 'nb-geocoder', 'nb-markerlabel', 'nb-citypicker'], ['client']);
api.add_files(['list.html', 'list.js'], ['client']);
});
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Mecab = require('mecab-async');
var mecab = new Mecab();
var MarkovChain = function () {
function MarkovChain(text) {
_classCallCheck(this, MarkovChain);
this.text = text;
this.result = null;
this.dictionary = {};
this.output = 'output';
}
_createClass(MarkovChain, [{
key: 'start',
value: function start(sentence, callback) {
this.parse(sentence, callback);
}
}, {
key: 'parse',
value: function parse(sentence, callback) {
var _this = this;
mecab.parse(this.text, function (err, result) {
_this.dictionary = _this.makeDic(result);
_this.makeSentence(_this.dictionary, sentence);
callback(_this.output);
});
}
}, {
key: 'makeDic',
value: function makeDic(items) {
var tmp = ['@'];
var dic = {};
for (var i in items) {
var t = items[i];
var word = t[0];
word = word.replace(/\s*/, '');
if (word == '' || word == 'EOS') continue;
tmp.push(word);
if (tmp.length < 3) continue;
if (tmp.length > 3) tmp.splice(0, 1);
this.setWord3(dic, tmp);
if (word == '。') {
tmp = ['@'];
continue;
}
}
return dic;
}
}, {
key: 'setWord3',
value: function setWord3(p, s3) {
var w1 = s3[0];
var w2 = s3[1];
var w3 = s3[2];
if (p[w1] == undefined) p[w1] = {};
if (p[w1][w2] == undefined) p[w1][w2] = {};
if (p[w1][w2][w3] == undefined) p[w1][w2][w3] = 0;
p[w1][w2][w3]++;
}
}, {
key: 'makeSentence',
value: function makeSentence(dic, sentence) {
for (var i = 0; i < sentence; i++) {
var ret = [];
var top = dic['@'];
if (!top) continue;
var w1 = this.choiceWord(top);
var w2 = this.choiceWord(top[w1]);
ret.push(w1);
ret.push(w2);
for (;;) {
var w3 = this.choiceWord(dic[w1][w2]);
ret.push(w3);
if (w3 == '。') break;
w1 = w2, w2 = w3;
}
this.output = ret.join('');
return this.output;
}
}
}, {
key: 'objKeys',
value: function objKeys(obj) {
var r = [];
for (var i in obj) {
r.push(i);
}
return r;
}
}, {
key: 'choiceWord',
value: function choiceWord(obj) {
var ks = this.objKeys(obj);
var i = this.rnd(ks.length);
return ks[i];
}
}, {
key: 'rnd',
value: function rnd(num) {
return Math.floor(Math.random() * num);
}
}]);
return MarkovChain;
}();
module.exports = MarkovChain;
|
/**************************************************
* Funkcje związane z geolokalizacją GPS
**************************************************/
WMB.Comment = {
/**
* Funkcja dodająca nowy komentarz do zgłoszenia
*
* @method onAddSubmit
*/
onAddSubmit: function(marker_id) {
if (WMB.User.isLoggedIn()) {
if ($('#add-comment-form')[0].checkValidity()) {
var post_data = new FormData();
post_data.append('user_id', parseInt(getCookie('user_id')));
post_data.append('marker_id', parseInt(marker_id));
post_data.append('comment', $('#comment').val());
$.ajax({
url: REST_API_URL + 'comment',
beforeSend: function(request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'POST',
cache: false,
processData: false,
contentType: false,
data: post_data,
success: function(s) {
$('#add-comment-modal').modal('hide');
bootbox.alert('Pomyślnie dodaną komentarz.', function() {
location.reload();
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#add-comment-modal').modal('hide');
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message);
}
});
}
} else {
bootbox.alert('Aby móc dodawać komentarze musisz być zalogowany.');
}
},
onEditClick: function(id) {
// Pobranie danych o komentarzu
$.ajax({
url: REST_API_URL + 'comment/id/' + id,
type: 'GET',
success: function(data) {
// Wstawienie danych do formularza
$('#comment_id').val(id);
$('#comment').val(data.comment);
$('#edit-comment-modal').modal('show');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
},
onEditSubmit: function() {
if ($('#edit-comment-form')[0].checkValidity()) {
var comment_data = new FormData(),
comment_id = parseInt($('#comment_id').val()),
comment = $('#comment').val();
comment_data.append('comment', comment);
$.ajax({
url: REST_API_URL + 'comment/id/' + comment_id + '/edit',
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'POST',
cache: false,
processData: false,
contentType: false,
data: comment_data,
success: function(s) {
$('#edit-comment-modal').modal('hide');
bootbox.alert('Pomyślnie zedytowano komentarz.', function() {
window.location.href = WEBSITE_URL + 'comments';
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message);
}
});
}
},
onDeleteClick: function(id) {
$.ajax({
url: REST_API_URL + 'comment/id/' + id,
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'DELETE',
cache: false,
processData: false,
contentType: false,
success: function(data) {
$('#edit-comment-modal').modal('hide');
bootbox.alert('Pomyślnie usunięto komentarz.', function() {
location.reload();
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
},
/**
* Funkcja służąca do zmiany statusu komentarza
*
* @method changeStatus
* @param {Integer} id Identyfikator komentarza
* @param {Integer} status_id Identyfikator statusu
*/
changeStatus: function(id, status_id) {
if (WMB.User.isLoggedIn()) {
$.ajax({
url: REST_API_URL + 'comment/id/' + id + '/status/' + status_id,
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'PUT',
cache: false,
processData: false,
contentType: false,
success: function(data) {
if (status_id == 0) {
bootbox.alert('Pomyślnie zgłoszono nadużycie w komentarzu.', function() {
location.reload();
});
} else {
bootbox.alert('Pomyślnie zmieniono status komentarza na ' + comment_statuses[status_id] + '.', function() {
location.reload();
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
} else {
bootbox.alert('Aby zgłosić nadużycie musisz być zalogowany/a.');
}
},
/**
* Funkcja pobierająca wszystkie komentarze dla danego zgłoszenia
*
* @method getAll
* @param {Integer} marker_id Identyfikator zgłoszenia
*/
getAll: function(marker_id) {
$.ajax({
url: REST_API_URL + 'comment/marker/' + marker_id,
type: 'GET',
cache: false,
dataType: 'json',
success: function(data) {
$.each(data.comments, function(i) {
if (data.comments[i].status_id != 0 && data.comments[i].user_id == parseInt(getCookie('user_id'))) {
$('#marker-comment-list').append(
'<tr>' +
'<td>' + data.comments[i].login + '</td>' +
'<td>' + data.comments[i].date + '</td>' +
'<td>' + data.comments[i].comment + '</td>' +
'<td>brak</td>' +
'</tr>');
} else if (data.comments[i].status_id != 0) {
$('#marker-comment-list').append(
'<tr>' +
'<td>' + data.comments[i].login + '</td>' +
'<td>' + data.comments[i].date + '</td>' +
'<td>' + data.comments[i].comment + '</td>' +
'<td><a href="#" onclick="WMB.Comment.changeStatus(' + data.comments[i].comment_id + ', 0)">Zgłoś nadużycie</a></td>' +
'</tr>');
}
});
}
});
}
}
|
define(function(require) {
var Model = require("web/common/model");
var SpsrModel = Model.extend({
idAttribute: "recordId",
defaults: {
name: "SDI1",
kzck: 0,
ydsd: 0,
srjkxh: 0,
ld: 123,
dbd: 124,
bhd: 125,
sppy: 126,
czpy: 127
},
urls: {
"create": "spsr.psp",
"update": "spsr.psp",
"delete": "spsr.psp",
"read": "spsr.psp"
}
});
return SpsrModel;
});
|
var express = require('express'),
formidable = require('formidable'),
imgur = require('imgur'),
fs = require('fs'),
url = require('url'),
bodyParser = require('body-parser'),
router = express.Router(),
uuid = require('node-uuid'),
db = require('../lib/database'),
tools = require('../lib/functions');
var connection = db.connectdb();
router.post('/upload', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked'
});
var id = tools.makeid();
var owner = uuid.v1();
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form.uploadDir = 'tmp/';
form.on('field', function(field, value) {
fields.push(value);
});
form.on('file', function(field, file) {
files.push(file);
});
form.on('end', function() {
res.end('http://' + req.headers.host + '/' + id);
if (fields[0]) {
owner = fields[0];
}
files.forEach(function(file) {
imgur.uploadFile(file.path)
.then(function(json) {
fs.unlink(file.path);
connection.query("INSERT INTO `imgsnap`.`images` (`id`, `direct`, `timestamp`, `delete`, `owner`) VALUES ('" + connection.escape(id).replace(/'/g, '') + "', '" + connection.escape(json.data.link).replace(/'/g, '') + "', '" + connection.escape(json.data.datetime) + "', '" + connection.escape(json.data.deletehash).replace(/'/g, '') + "', '" + connection.escape(owner).replace(/'/g, '') + "')");
})
.catch(function(err) {
fs.unlink(file.path);
console.log(err);
});
});
});
form.parse(req);
});
router.get('/image/:id', function(req, res) {
var id = req.params.id;
connection.query('SELECT * FROM images WHERE id = ' + connection.escape(id), function(err, row, fields) {
if (!row[0]) {
res.json({
status: false
});
} else {
res.json({
status: true,
direct: row[0].direct,
timestamp: row[0].timestamp
});
}
});
});
router.get('/check', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked'
});
res.end('Server Online');
});
module.exports = router;
|
/*
Copyright: © 2011 Thomas Stein, CodeLounge.de
<mailto:info@codelounge.de> <http://www.codelounge.de/>
Released under the terms of the GNU General Public License.
You should have received a copy of the GNU General Public License,
along with this software. In the main directory, see: licence.txt
If not, see: <http://www.gnu.org/licenses/>.
*/
/*
* MBP - Mobile boilerplate helper functions
*/
(function(document){
window.MBP = window.MBP || {};
// Fix for iPhone viewport scale bug
// http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]');
MBP.ua = navigator.userAgent;
MBP.scaleFix = function () {
if (MBP.viewportmeta && /iPhone|iPad/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) {
MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
document.addEventListener("gesturestart", MBP.gestureStart, false);
}
};
MBP.gestureStart = function () {
MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
};
// Hide URL Bar for iOS
// http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/
MBP.hideUrlBar = function () {
/iPhone/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () {
window.scrollTo(0, 1);
}, 1000),
/iPad/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () {
window.scrollTo(0, 1);
}, 1000);
};
});
jQuery( function() {
$("a.facebox").fancybox();
//$("a.fancybox").prettyPhoto({
// social_tools: false
//});
jQuery('.entenlogo').click(function() {
$('.entenlogo').hide();
});
var current_url = $(location).attr('href');
//console.log($(location).attr('href'));
jQuery('body').bind( 'taphold', function( e ) {
//$('#next_post_link').attr('refresh');
//$('#previous_post_link').attr('refresh');
$('#page').page('refresh');
var next_url = $('#next_post_link').attr('href');
var previous_url = $('#previous_post_link').attr('href');
console.log(next_url + ' --- ' + previous_url);
e.stopImmediatePropagation();
return false;
} );
jQuery('body').bind( 'swipeleft', function( e ) {
var next_url = $('.ui-page-active #next_post_link').attr('href');
var previous_url = $('.ui-page-active #previous_post_link').attr('href');
console.log("Swiped Left: " + next_url + ' --- ' + previous_url);
if (undefined != previous_url) {
//$.mobile.changePage( previous_url,"slide", true);
$.mobile.changePage( previous_url, {
transition: "slide",
reverse: false,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
} );
jQuery('body').bind( 'swiperight', function( e ) {
var next_url = $('.ui-page-active #next_post_link').attr('href');
var previous_url = $('.ui-page-active #previous_post_link').attr('href');
console.log("Swiped Right: " + next_url + ' --- ' + previous_url);
if (undefined != next_url) {
//$.mobile.changePage( next_url, "slide", true);
$.mobile.changePage( next_url, {
transition: "slide",
reverse: true,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
} );
} );
|
/**
* card_view = new BaristaCardView({el: $("target_selector",
url:"",
title:"",
subtitle:"",
fg_color: "#1b9e77",
image:"",
span_class: "col-lg-12"});
*
* A Backbone View that displays a card of information wrapped in link
* The view is meant to be a top level entry point to other pages
* basic use:
card_view = new BaristaCardView();
* optional arguments:
* @param {string} url the link to navigate to if the card is clicked, defaults to ""
* @param {string} title the title of the card. defaults to "title"
* @param {string} subtitle the subtitle of the card. defaults to "subtitle"
* @param {string} image the link to an image to show as the cards main content. defaults to ""
* @param {string} fg_color the hex color code to use as the foreground color of the view, defaults to
* #1b9e77
* @param {string} span_class a bootstrap span class to size the width of the view, defaults to
* "col-lg-12"
*/
Barista.Views.BaristaCardView = Backbone.View.extend({
/**
* give the view a name to be used throughout the View's functions when it needs to know what its class
* name is
* @type {String}
*/
name: "BaristaCardView",
/**
* supply a base model for the view
* Overide this if you need to use it for dynamic content
* @type {Backbone}
*/
model: new Backbone.Model(),
/**
* overide the view's default initialize method in order to catch options and render a custom template
*/
initialize: function(){
// set up color options. default if not specified
this.fg_color = (this.options.fg_color !== undefined) ? this.options.fg_color : "#1b9e77";
// set up the span size
this.span_class = (this.options.span_class !== undefined) ? this.options.span_class : "col-lg-12";
// set up the url
this.url = (this.options.url !== undefined) ? this.options.url : "";
// set up the title
this.title = (this.options.title !== undefined) ? this.options.title : "Title";
// set up the subtitle
this.subtitle = (this.options.subtitle !== undefined) ? this.options.subtitle : "subtitle";
// set up the image
this.image = (this.options.image !== undefined) ? this.options.image : "";
// bind render to model changes
this.listenTo(this.model,'change', this.update);
// compile the default template for the view
this.compile_template();
},
/**
* use Handlebars to compile the template for the view
*/
compile_template: function(){
var self = this;
this.div_string = 'barista_view' + new Date().getTime();;
this.$el.append(BaristaTemplates.CMapCard({div_string: this.div_string,
span_class: this.span_class,
url: this.url,
title: this.title,
subtitle: this.subtitle,
image: this.image,
fg_color: this.fg_color}));
}
});
|
'use strict';
app.controller('orderController', ['$scope', '$rootScope', 'toastrService', 'orderService',
function ($scope, $rootScope, toastrService, orderService) {
$scope.paging = 1;
$scope.disabledMore = false;
$scope.data = [];
$scope.getOrders = function () {
orderService.get($scope.paging).then(function (data) {
if (data.length > 0) {
$scope.data.push.apply($scope.data, data);
} else {
$scope.disabledMore = true;
}
});
}
$scope.more = function () {
$scope.paging++;
$scope.getOrders();
};
$scope.refresh = function () {
$scope.paging = 1;
$scope.data = [];
$scope.getOrders();
};
$scope.getOrders();
$scope.openOrder = function (item, $index) {
$scope.order = item;
$scope.order.$index = $index;
$('#modal-order').modal({
backdrop: true
});
};
}
]);
|
/*
* Flocking Debugging Unit Generators
* http://github.com/colinbdclark/flocking
*
* Copyright 2011-2014, Colin Clark
* Dual licensed under the MIT and GPL Version 2 licenses.
*/
/*global require*/
/*jshint white: false, newcap: true, regexp: true, browser: true,
forin: false, nomen: true, bitwise: false, maxerr: 100,
indent: 4, plusplus: false, curly: true, eqeqeq: true,
freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true,
unused: true, strict: true, asi: false, boss: false, evil: false, expr: false,
funcscope: false*/
var fluid = fluid || require("infusion"),
flock = fluid.registerNamespace("flock");
(function () {
"use strict";
// TODO: Unit tests.
flock.ugen.print = function (input, output, options) {
var that = flock.ugen(input, output, options);
that.gen = function (numSamps) {
var inputs = that.inputs,
out = that.output,
m = that.model,
label = m.label,
chan = inputs.channel,
// Basic multichannel support. This should be inproved
// by factoring the multichannel input code out of flock.ugen.out.
source = chan ? inputs.source.output[chan.output[0]] : inputs.source.output,
trig = inputs.trigger.output[0],
freq = inputs.freq.output[0],
i,
j,
val;
if (trig > 0.0 && m.prevTrig <= 0.0) {
fluid.log(fluid.logLevel.IMPORTANT, label + source);
}
if (m.freq !== freq) {
m.sampInterval = Math.round(m.sampleRate / freq);
m.freq = freq;
m.counter = m.sampInterval;
}
for (i = 0, j = 0 ; i < numSamps; i++, j += m.strides.source) {
if (m.counter >= m.sampInterval) {
fluid.log(fluid.logLevel.IMPORTANT, label + source[j]);
m.counter = 0;
}
m.counter++;
out[i] = val = source[i];
}
m.value = m.unscaledValue = val;
};
that.init = function () {
var o = that.options;
that.model.label = o.label ? o.label + ": " : "";
that.onInputChanged();
};
that.init();
return that;
};
flock.ugenDefaults("flock.ugen.print", {
rate: "audio",
inputs: {
source: null,
trigger: 0.0,
freq: 1.0
},
ugenOptions: {
model: {
unscaledValue: 0.0,
value: 0.0,
counter: 0
},
strideInputs: ["source"]
}
});
}());
|
import { createSelector } from '@automattic/state-utils';
import { filter, orderBy } from 'lodash';
import 'calypso/state/comments/init';
function filterCommentsByStatus( comments, status ) {
return 'all' === status
? filter(
comments,
( comment ) => 'approved' === comment.status || 'unapproved' === comment.status
)
: filter( comments, ( comment ) => status === comment.status );
}
/**
* Returns list of loaded comments for a given site, filtered by status
*
* @param {object} state Redux state
* @param {number} siteId Site for whose comments to find
* @param {string} [status] Status to filter comments
* @param {string} [order=asc] Order in which to sort filtered comments
* @returns {Array<object>} Available comments for site, filtered by status
*/
export const getSiteComments = createSelector(
( state, siteId, status, order = 'asc' ) => {
const comments = state.comments.items ?? {};
const parsedComments = Object.keys( comments )
.filter( ( key ) => parseInt( key.split( '-', 1 ), 10 ) === siteId )
.reduce( ( list, key ) => [ ...list, ...comments[ key ] ], [] );
return status
? orderBy( filterCommentsByStatus( parsedComments, status ), 'date', order )
: orderBy( parsedComments, 'date', order );
},
( state ) => [ state.comments.items ]
);
|
(function(customer_id) {
tinymce.create('tinymce.plugins.ItStream_AttachToPost', {
customer_id: customer_id,
init : function(editor, plugin_url) {
editor.addButton('player_scheduling', {
title : 'Embed ItStream Player',
cmd : 'itm_scheduling',
image : plugin_url + '/scheduling.gif'
});
// Register a new TinyMCE command
editor.addCommand('itm_scheduling', this.render_attach_to_post_interface, {
editor: editor,
plugin: editor.plugins.ItStream_AttachToPost
});
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : 'ItStream Scheduling Button',
author : 'It-Marketing',
authorurl : 'http://www.itmarketingsrl.it/',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example',
version : "0.1"
};
},
wm_close_event: function() {
// Restore scrolling for the main content window when the attach to post interface is closed
jQuery('html,body').css('overflow', 'auto');
tinyMCE.activeEditor.selection.select(tinyMCE.activeEditor.dom.select('p')[0]);
tinyMCE.activeEditor.selection.collapse(0);
},
render_attach_to_post_interface: function() {
var attach_to_post_url = itstream_ajax.attach_to_post;
if (typeof(customer_id) != 'undefined') {
attach_to_post_url += "?id=" + itstream_ajax.customer_id;
}
var win = window;
while (win.parent != null && win.parent != win) {
win = win.parent;
}
win = jQuery(win);
var winWidth = win.width();
var winHeight = win.height();
var popupWidth = 680;
var popupHeight = 560;
var minWidth = 320;
var minHeight = 200;
var maxWidth = winWidth - (winWidth * 0.05);
var maxHeight = winHeight - (winHeight * 0.05);
if (maxWidth < minWidth) { maxWidth = winWidth - 10; }
if (maxHeight < minHeight) { maxHeight = winHeight - 10; }
if (popupWidth > maxWidth) { popupWidth = maxWidth; }
if (popupHeight > maxHeight) { popupHeight = maxHeight; }
// Open a window
this.editor.windowManager.open({
url: attach_to_post_url,
id: 'its_attach_to_post_dialog',
width: popupWidth,
height: popupHeight,
title: 'ItStream - Embed Player',
inline: 1
/*buttons: [{
text: 'Close',
onclick: 'close'
}]*/
});
// Ensure that the window cannot be scrolled - XXX actually allow scrolling in the main window and disable it for the inner-windows/frames/elements as to create a single scrollbar
jQuery('html,body').css('overflow', 'hidden');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-y', 'auto');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-x', 'hidden');
}
});
// Register plugin
tinymce.PluginManager.add( 'itstream', tinymce.plugins.ItStream_AttachToPost );
})(itstream_ajax.customer_id);
|
jQuery(function($) {
///////////////////////////////////////////////////////////////////
///// META BOXES JS
///////////////////////////////////////////////////////////////////
jQuery('.repeatable-add').live('click', function() {
var field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);
var fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');
field.find('input.regular-text, textarea, select').val('');
field.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
field.insertAfter(fieldLocation, jQuery(this).closest('td'));
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount > 1 ) {
jQuery('.repeatable-remove').css('display','inline');
}
return false;
});
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
jQuery('.repeatable-remove').live('click', function() {
jQuery(this).parent().remove();
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
return false;
});
jQuery('.custom_repeatable').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.sort'
});
// the upload image button, saves the id and outputs a preview of the image
var imageFrame;
$('.rg-bb_upload_image_button').live('click', function(event) {
event.preventDefault();
var options, attachment;
$self = $(event.target);
$div = $self.closest('div.rg-bb_image');
// if the frame already exists, open it
if ( imageFrame ) {
imageFrame.open();
return;
}
// set our settings
imageFrame = wp.media({
title: 'Choose Image',
multiple: true,
library: {
type: 'image'
},
button: {
text: 'Use This Image'
}
});
// set up our select handler
imageFrame.on( 'select', function() {
selection = imageFrame.state().get('selection');
if ( ! selection )
return;
// loop through the selected files
selection.each( function( attachment ) {
console.log(attachment);
var src = attachment.attributes.sizes.full.url;
var id = attachment.id;
$div.find('.rg-bb_preview_image').attr('src', src);
$div.find('.rg-bb_upload_image').val(id);
} );
});
// open the frame
imageFrame.open();
});
// the remove image link, removes the image id from the hidden field and replaces the image preview
$('.rg-bb_clear_image_button').live('click', function() {
var defaultImage = $(this).parent().siblings('.rg-bb_default_image').text();
$(this).parent().siblings('.rg-bb_upload_image').val('');
$(this).parent().siblings('.rg-bb_preview_image').attr('src', defaultImage);
return false;
});
// function to create an array of input values
function ids(inputs) {
var a = [];
for (var i = 0; i < inputs.length; i++) {
a.push(inputs[i].val);
}
//$("span").text(a.join(" "));
}
// repeatable fields
$('.toggle').on("click", function() {
console.log($(this).parent().siblings().toggleClass('closed'));
});
$('.meta_box_repeatable_add').live('click', function(e) {
e.preventDefault();
// clone
var row = $(this).closest('.meta_box_repeatable').find('tbody tr:last-child');
var clone = row.clone();
var defaultImage = clone.find('.meta_box_default_image').text();
clone.find('select.chosen').removeAttr('style', '').removeAttr('id', '').removeClass('chzn-done').data('chosen', null).next().remove();
// clone.find('input.regular-text, textarea, select').val('');
clone.find('.meta_box_preview_image').attr('src', defaultImage).removeClass('loaded');
clone.find('input[type=checkbox], input[type=radio]').attr('checked', false);
row.after(clone);
// increment name and id
clone.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
var arr = [];
$('input.repeatable_id:text').each(function(){ arr.push($(this).val()); });
clone.find('input.repeatable_id')
.val(Number(Math.max.apply( Math, arr )) + 1);
if (!!$.prototype.chosen) {
clone.find('select.chosen')
.chosen({allow_single_deselect: true});
}
});
$('.meta_box_repeatable_remove').live('click', function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
$('.meta_box_repeatable tbody').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.hndle'
});
// post_drop_sort
$('.sort_list').sortable({
connectWith: '.sort_list',
opacity: 0.6,
revert: true,
cursor: 'move',
cancel: '.post_drop_sort_area_name',
items: 'li:not(.post_drop_sort_area_name)',
update: function(event, ui) {
var result = $(this).sortable('toArray');
var thisID = $(this).attr('id');
$('.store-' + thisID).val(result)
}
});
$('.sort_list').disableSelection();
// turn select boxes into something magical
if (!!$.prototype.chosen)
$('.chosen').chosen({ allow_single_deselect: true });
});
|
/* JavaScript User Interface Library -- Common datatypes for user elements
* Copyright 2010 Jaakko-Heikki Heusala <jhh@jhh.me>
* $Id: common.js 415 2010-10-15 05:00:51Z jheusala $
*/
/** Simple message box constructor
* @params type The message type: error, notice, info or success
* @params msg Message
*/
function UIMessage(type, msg) {
var undefined;
if(this instanceof arguments.callee) {
if(type === undefined) throw TypeError("type undefined");
if(msg === undefined) {
msg = type;
type = undefined;
}
this.type = type || "info";
this.msg = ""+msg;
} else {
return new UIMessage(type, msg);
}
}
/** Get the message as a string */
UIMessage.prototype.toString = function() {
return this.type + ": " + this.msg;
}
/** Convert to JSON using JSONObject extension */
UIMessage.prototype.toJSON = function() {
return new JSONObject("UIMessage", this.type + ":" + this.msg );
};
/* Setup reviver for JSONObject */
JSONObject.revivers.UIMessage = function(value) {
var parts = (""+value).split(":");
return new UIMessage(parts.shift(), parts.join(":"));
};
/* EOF */
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
( function($) {
} )( jQuery );
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
|
'use strict';
angular.module('eshttp')
.filter('unixtostr', function() {
return function(str){
var dt;
dt = Date.create(str * 1000).format('{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}');
if (dt == "Invalid Date") {
return 'N/A';
} else {
return dt;
}
};
});
|
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colordialog', 'en-gb', {
clear: 'Clear',
highlight: 'Highlight',
options: 'Colour Options',
selected: 'Selected Colour',
title: 'Select colour'
} );
|
import Backbone from 'backbone';
export default class Router extends Backbone.Router {
get routes() {
return {
'(/)': 'home',
'login': 'login',
'access_token=*token': 'token',
'activity': 'activity',
'swim': 'swim',
'sleep': 'sleep',
'about': 'about',
'privacy': 'privacy'
};
}
}
|
var wocs_loading_first_time = true;//simply flag var
jQuery(function () {
if (woocs_drop_down_view == 'chosen') {
try {
if (jQuery("select.woocommerce-currency-switcher").length) {
jQuery("select.woocommerce-currency-switcher").chosen({
disable_search_threshold: 10
});
jQuery.each(jQuery('.woocommerce-currency-switcher-form .chosen-container'), function (index, obj) {
jQuery(obj).css({'width': jQuery(this).prev('select').data('width')});
});
}
} catch (e) {
console.log(e);
}
}
if (woocs_drop_down_view == 'ddslick') {
try {
jQuery.each(jQuery('select.woocommerce-currency-switcher'), function (index, obj) {
var width = jQuery(obj).data('width');
var flag_position = jQuery(obj).data('flag-position');
jQuery(obj).ddslick({
//data: ddData,
width: width,
imagePosition: flag_position,
selectText: "Select currency",
//background:'#ff0000',
onSelected: function (data) {
if (!wocs_loading_first_time) {
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').find('input[name="woocommerce-currency-switcher"]').eq(0).val(data.selectedData.value);
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').submit();
}
}
});
});
} catch (e) {
console.log(e);
}
}
//for flags view instead of drop-down
jQuery('.woocs_flag_view_item').click(function () {
if (jQuery(this).hasClass('woocs_flag_view_item_current')) {
return false;
}
//***
if (woocs_is_get_empty) {
window.location = window.location.href + '?currency=' + jQuery(this).data('currency');
} else {
var l = window.location.href;
l = l.replace(/(\?currency=[a-zA-Z]+)/g, '?');
l = l.replace(/(¤cy=[a-zA-Z]+)/g, '');
window.location = l + '¤cy=' + jQuery(this).data('currency');
}
return false;
});
wocs_loading_first_time = false;
});
|
var elixir = require('laravel-elixir');
var gulp = require("gulp");
require('laravel-elixir-wiredep');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
var bowerDir = "public/vendor/";
var lessPaths = [
bowerDir + "bootstrap/less/"
]
var templatePaths = [
"resources/assets/js/app/components/*/*.html",
];
elixir.extend("templates", function(src, base, dest) {
gulp.task("templates", function () {
// the base option sets the relative root for the set of files,
// preserving the folder structure
gulp.src(src, {base: base})
.pipe(gulp.dest(dest));
});
// Watch each glob in src
for (idx in src){
var glob = src[idx];
this.registerWatcher("templates", glob);
}
return this.queueTask("templates");
});
elixir(function(mix) {
// Complile LESS into CSS
mix.less("main.less", "public/css/", {paths: lessPaths});
// Inject dependencies into layout (except bootstrap css, since that is compiled into main css)
mix.wiredep({src: "master.blade.php"}, {exclude: "vendor/bootstrap/dist/css/bootstrap.css"});
// Combine app js into one file
mix.scriptsIn("resources/assets/js/", "public/js/main.js");
// Copy angular templates to public folder
mix.templates(templatePaths, "resources/assets/js/app/components/", "public");
});
|
define(["require", "exports"], function (require, exports) {
"use strict";
exports.ZaOverviewPanelController = ZaOverviewPanelController;
});
|
function playAudioVisualize(track) {
var bars = 50;
var waveResolution = 128;
var style = "bars"; //set default style upon loading here
var audio = new Audio();
var canvas, source, context, analyser, fFrequencyData, barX, barWidth, barHeight, red, green, blue, ctx;
audio.controls = true;
audio.src = track;
audio.loop = false;
audio.autoplay = false;
window.addEventListener("load", initPlayer, false);
function initPlayer() {
document.getElementById('audio-container').appendChild(audio);
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById('audio-display');
canvas.addEventListener("click", toggleStyle);
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
drawFrames();
function toggleStyle() {
style = (style === "wave" ? "bars" : "wave");
}
}
var k = 0; //keep track of total number of frames drawn
function drawFrames() {
window.requestAnimationFrame(drawFrames);
analyser.fftsize = 128;
fFrequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fFrequencyData);
ctx.clearRect(0,0,canvas.width,canvas.height);
numBarsBars = 16;
//calculate average frequency for color
var total = 0;
for(var j = 0; j < fFrequencyData.length; j++) {
total += fFrequencyData[j];
}
var avg = total / fFrequencyData.length;
avg = avg / 1.2;
//bar style visual representation
function drawBars(numBars) {
for(var i = 0; i < numBars; i++) {
barX = i * (canvas.width / numBars);
barWidth = (canvas.width / numBars - 1);
barHeight = -(fFrequencyData[i] / 2);
//reduce frequency of color changing to avoid flickering
if(k % 15 === 0) {
getColors();
k = 0;
}
ctx.fillStyle = 'rgb('+red+','+green+','+blue+')';
ctx.fillRect(barX, canvas.height, barWidth, barHeight);
}
}
//waveform visualization
function drawWave(resolution, lineWidth) {
ctx.beginPath();
ctx.lineWidth = lineWidth;
var barX, barY;
for(var i = 0; i < resolution; i++) {
barX = i * (Math.ceil(canvas.width / resolution));
barY = -(fFrequencyData[i] / 2);
getColors();
k = 0;
ctx.strokeStyle = 'rgb('+red+','+green+','+blue+')';
ctx.lineTo(barX, barY + canvas.height );
ctx.stroke();
}
}
function getColors() {
//can edit these values to get overall different coloration!!
red = Math.round(Math.sin(avg/29.0 + 6.1) * 127 + 128);
green = Math.round(Math.sin(avg/42.0 - 7.4) * 127 + 128);
blue = Math.round(Math.sin(avg/34.0 - 3.8) * 127 + 128);
}
if(style === "wave") {
drawWave(waveResolution, 2);
}
if(style === "bars") {
drawBars(bars);
}
k++;
}
}
|
/*global chrome */
// Check if the feature is enable
let promise = new Promise(function (resolve) {
chrome.storage.sync.get({
isEdEnable: true
}, function (items) {
if (items.isEdEnable === true) {
resolve();
}
});
});
promise.then(function () {
/*global removeIfExist */
/*eslint no-undef: "error"*/
removeIfExist(".blockheader");
removeIfExist(".blockcontent .upload-infos");
removeIfExist(".blockfooter");
});
|
PUMP_SELECTOR.CoordSlicer = function( parameters ) {
var image = parameters.image;
var coord = parameters.coord;
var name = parameters.name;
var obj = {};
if( image === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Cannot slice image, image missing.");
return undefined;
}else if (coord === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Warn: No coordinate data given. Returning image.");
return obj[name] = obj;
}else{
var coords = coord.split("\n");
coords.clean("");
for(var i=0;i<coords.length;i++) {
var coordinate = coords[i].split(" ");
obj[coordinate[0]] = PUMP_SELECTOR.CropImage(image,coordinate[1],coordinate[2],coordinate[3],coordinate[4]);
}
return obj;
}
};
|
/**
* Created by inwebo on 05/02/15.
*/
alert('local');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.