text
stringlengths 2
6.14k
|
|---|
const ReadAtTimeDetails_Schema = {
name: "ReadAtTimeDetails",
baseType: "HistoryReadDetails",
fields: [
{ name: "reqTimes", isArray: true, fieldType: "DateTime" },
{ name: "useSimpleBounds", fieldType: "Boolean" }
]
};
export {ReadAtTimeDetails_Schema};
|
var searchData=
[
['paint',['paint',['../class_abstract_symbol.html#abe3fb701b78186e024810def5fdb3194',1,'AbstractSymbol::paint()'],['../class_circle.html#a907d31f610a206b32ec8e930f0355222',1,'Circle::paint()'],['../class_cross.html#a9e929101acd72cdd0f8250666a678689',1,'Cross::paint()']]],
['paintline',['paintLine',['../class_abstract_board.html#a8041c3f8a6f35b1b549dcbeb7dca636c',1,'AbstractBoard']]]
];
|
'use strict';
if (typeof Symbol === 'function') {
module.exports = Symbol;
}
else {
module.exports = function (name) {
return name;
};
}
|
import parse from 'date-fns/parse';
export function attendClassFromCache(object, classId) {
let attendedClass = object.attendedClasses[classId];
if (!attendedClass) {
console.warn(`attendedClass ${classId} not in cache`);
return null;
}
return Object.assign({}, attendedClass);
}
export function unattendClassFromCache(object, classId) {
let unattendedClass = object.unattendedClasses[classId];
unattendedClass.date = parse(unattendedClass.date);
if (!unattendedClass) {
console.warn(`unattendedClass ${classId} not in cache`);
return null;
}
return Object.assign({}, unattendedClass);
}
export function activitiesFromCache(object, activityId) {
let activity = object.activities[activityId];
if (!activity) {
console.warn(`activity ${activityId} not in cache`);
return null;
}
return Object.assign({}, activity);
}
export function faqFromCache(object, faqId) {
let faq = object.faqs[faqId];
if (!faq) {
console.warn(`faq ${faqId} not in cache`);
return null;
}
return Object.assign({}, faq);
}
export function feedBackFromCache(object, feedbackId) {
let feedback = object.feedbacks[feedbackId];
if (!feedback) {
console.warn(`feedback ${feedbackId} not in cache`);
return null;
}
return Object.assign({}, feedback);
}
export function referralFromCache(object, referralId) {
let referral = object.referrals[referralId];
if (!referral) {
console.warn(`referral ${referralId} not in cache`);
return null;
}
return Object.assign({}, referral);
}
export function sponsorFromCache(object, sponsorId) {
let sponsor = object.sponsors[sponsorId];
if (!sponsor) {
console.warn(`sponsor ${sponsorId} not in cache`);
return null;
}
return Object.assign({}, sponsor);
}
export function appointmentFromCache(object, appointmentId) {
let appointment = object.appointments[appointmentId];
if (!appointment) {
console.warn(`appointment ${appointmentId} not in cache`);
return null;
}
return Object.assign({}, appointment);
}
export function packedSelectablesFromCache(object) {
let packed = object.selectableClasses;
if (!packed) {
console.warn(`selectableClasses not in cache`);
return null;
}
return Object.assign({}, packed);
}
export function fileFromCache(object, fileId) {
let file = object.files[fileId];
if (!file) {
console.warn(`file ${fileId} not in cache`);
return null;
}
return file;
}
|
import EventsEmitter from '../../utils/EventsEmitter';
export default class SidebarInfoPanel extends EventsEmitter {
constructor() {
super();
this.attributeList = null;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
async initialize(infoPanelAttributeList) {
this.attributeList = infoPanelAttributeList;
}
}
function guid(format = 'xxxxxxxxxx') {
let d = new Date().getTime();
let guid = format.replace(/[xy]/g, (c) => {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return guid;
}
|
'use strict';
/**
* Serverless Module: Lambda Handler
* - Your lambda functions should be a thin wrapper around your own separate
* modules, to keep your code testable, reusable and AWS independent
* - 'serverless-helpers-js' module is required for Serverless ENV var support. Hopefully, AWS will add ENV support to Lambda soon :)
*/
// Require Logic
var lib = require('../../lib');
// Lambda Handler
module.exports.handler = function(event, context) {
lib.multiCreate(event, function(error, response) {
return context.done(error, response);
});
};
|
'use strict';
//Dia lists service used to communicate Dia lists REST endpoints
angular.module('dia-lists').factory('DiaLists', ['$resource',
function($resource) {
return $resource('dia-lists/:diaListId', { diaListId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
/**
* @license Highcharts JS v9.2.1 (2021-08-19)
* @module highcharts/modules/sonification
* @requires highcharts
*
* Sonification module
*
* (c) 2012-2021 Øystein Moseng
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Extensions/Sonification/Sonification.js';
|
import axios from 'axios';
export default function getTargetAxios(axiosParam) {
if (axiosParam && axiosParam.create) {
// axiosParam is the global axios instance.
return axiosParam.create();
} else if (typeof axiosParam === 'function' && axiosParam.get) {
// axiosParam is already an instance of axios.
return axiosParam;
} else {
// axiosParam is either null or a config object.
return axios.create(axiosParam);
}
}
|
import appRootDir from 'app-root-dir';
import {unlinkSync, readFileSync} from 'fs';
import path from 'path';
import Pleeb from '../src/index';
const contractPath = path.join(appRootDir.get(), './__tests__/app/api_contract.json');
const contractFixturePath = path.join(appRootDir.get(), './__tests__/app/api_contract.fixture.json');
describe('Builder', () => {
beforeEach(async (done) => {
await Pleeb.build({
src: `./__tests__/app/__mocks__/**/*.mock.js`,
dest: `./__tests__/app`,
});
done();
});
afterEach(() => {
unlinkSync(contractPath);
});
it('generates the same number of routes', () => {
var apiContractFixture = JSON.parse(readFileSync(contractFixturePath, 'utf8'));
var fileContents = require(contractPath);
expect(fileContents.length).toEqual(apiContractFixture.length);
});
it('generates a valid contract', () => {
var apiContractFixture = JSON.parse(readFileSync(contractFixturePath, 'utf8'));
var fileContents = require(contractPath);
expect(fileContents).toEqual(apiContractFixture);
});
});
|
var notifications = {
// color:'info','success','warning','danger'
show: function (message, from, align, color) {
$.notify({
icon: "ti-user",
message: message
}, {
type: color,
timer: 1000,
placement: {
from: from,
align: align
}
});
}
};
|
export const ABOVE = 'above';
export const INSIDE = 'inside';
export const BELOW = 'below';
export const INVISIBLE = 'invisible';
|
rio.Application.require("components/box");
rio.components.DependenciesList = rio.Component.create(rio.components.Box, "DependenciesList", {
methods: {
buildHtml: function() {
var html = rio.Tag.pre("loading...", { className: "scripts" });
if (Prototype.Browser.IE) {
html.setStyle({ height: "500px" });
}
return html;
},
setContent: function(content) {
this.html().update(content);
}
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:3b12024520f51f2f2d65ba628051e5b45f56011ec011d7b937e26b72b36a3ab5
size 7320
|
import React from 'react';
import { connect } from 'react-redux';
import LazyLoad from 'react-lazyload';
import MobileDetect from 'mobile-detect';
import { getUserAgent } from '../../modules/UserAgent/UserAgentReducer';
import Loading from './Loading';
export function getStyles() {
const styles = {
img: {
visibility: 'visible',
opacity: 1,
transition: 'visibility 0s linear 0s,opacity .4s 0s',
},
};
return styles;
}
class Img extends React.PureComponent {
static defaultProps = {
style: {},
src: '',
alt: '',
size: 60,
userAgent: '',
};
renderImg = () => {
const { style, src, alt, userAgent, size, dispatch, ...other } = this.props;
const styles = getStyles();
const finalStyle = Object.assign({}, styles.img, style);
return <img style={finalStyle} src={src} alt={alt} {...other} />;
};
render() {
const { size, userAgent } = this.props;
const mobileDetect = new MobileDetect(userAgent);
if (mobileDetect.is('bot')) {
return this.renderImg();
} else {
const placeholder = <Loading size={size} />;
return (
<LazyLoad
height={size}
once={true}
debounce={false}
throttle={300}
offset={30}
placeholder={placeholder}
>
{this.renderImg()}
</LazyLoad>
);
}
}
}
function mapStateToProps(store) {
return { userAgent: getUserAgent(store) };
}
export default connect(mapStateToProps)(Img);
const ImgWithoutConnect = Img;
export { ImgWithoutConnect };
|
exports.createElement = require('./create-element')
exports.dom = require('./dom')
|
'use strict';
const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var extend = require('util')._extend;
var Q = require("q");
var request = require("request");
//
function schedSessions(schedRequest){
var deferred = Q.defer();
var options = new prepRequest(schedRequest);
request(options,function(err,response,body){
if (err) {
console.error(err);
}
// .then(() =>
// pg.defaults.ssl = true;
// pg.connect(process.env.DATABASE_URL, function(err, client, done){
// client.query('insert into conversation (smoochid, received, usermessage, role, message_id, sourcetype, receivedtime, responsemessage, responsetype, responsetime) values ($1,$2, $3, $4, $5,$6, $7, $8, $9, $10);',
// [msgLog.smoochId, msgLog.received, msgLog.usermessage, msgLog.role, msgLog.message_id, msgLog.sourcetype, msgLog.receivedtime, msgLog.responsemessage, msgLog.responsetype, msgLog.responsetime],
// function(err,result) {
// done();
// if (err) {
// console.error(err);
// deferred.reject(err);
// }
// else {
console.log('=== body: ',body);
// deferred.resolve(result);
// }
// })
//}))
deferred.resolve(body);
});
return deferred.promise;
}
function prepRequest(schedRequest){
switch(schedRequest){
case "SessionCount":
var options = {
"method" : "POST",
"url" : "https://agile2016.sched.org/api/session/count",
"qs" : {
"api_key" : process.env.SCHED_TOKEN
},
"headers" : {
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
}
};
break;
case "SessionList":
var options = {
"method" : "POST",
"url" : "https://agile2016.sched.org/api/session/export",
"qs" : {
"api_key" : process.env.SCHED_TOKEN,
"format" : "json",
"fields" : "active, name, event_start, event_end, venue, id, speakers",
"strip_html" : "Y"
},
"headers" : {
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
}
};
break;
default:
var options = '';
}
return options;
}
exports.schedSessions = schedSessions;
|
'use strict';
/**
* @type {EmmetOutputProfile}
*/
export default {
indent: '\t',
tagCase: '',
attributeCase: '',
attributeQuotes: 'double',
format: true,
formatSkip: ['html'],
formatForce: ['body'],
inlineBreak: 3,
compactBooleanAttributes: false,
booleanAttributes: ['contenteditable', 'seamless', 'async', 'autofocus',
'autoplay', 'checked', 'controls', 'defer', 'disabled', 'formnovalidate',
'hidden', 'ismap', 'loop', 'multiple', 'muted', 'novalidate', 'readonly',
'required', 'reversed', 'selected', 'typemustmatch'],
selfClosingStyle: 'html',
inlineElements: ['a', 'abbr', 'acronym', 'applet', 'b', 'basefont', 'bdo',
'big', 'br', 'button', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i',
'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'map', 'object', 'q',
's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup',
'textarea', 'tt', 'u', 'var']
};
|
var videoPlayers = [];
function initVideoPlayer(stream) {
var videoPlayer = document.createElement('video');
videoPlayer.muted = !enableTabCaptureAPI;
videoPlayer.volume = !!enableTabCaptureAPI;
videoPlayer.src = URL.createObjectURL(stream);
videoPlayer.play();
videoPlayers.push(videoPlayer);
}
|
module.exports = {
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*-test.(ts|js)'],
testEnvironment: 'node',
};
|
/**
* @module dommodule
* @author Vyacheslav Aristov <vv.aristov@gmail.com>
* @license MIT
* @see https://www.w3.org/TR/dom
* @see https://dom.spec.whatwg.org
*/
export * from './AttrAssembler'
export * from './CharacterDataAssembler'
export * from './ChildNodeAssembler'
export * from './CommentAssembler'
export * from './DocumentAssembler'
export * from './DocumentFragmentAssembler'
export * from './DocumentTypeAssembler'
export * from './ElementAssembler'
export * from './EventTargetAssembler'
export * from './NodeAssembler'
export * from './ParentNodeAssembler'
export * from './TextAssembler'
|
const globWatcher = require('glob-watcher');
/**
* Spacedoc parsing and building class.
* @private
*/
class Spacedoc {
/**
* Create a new Spacedoc parser.
*/
constructor() {
/**
* Spacedoc instance settings.
* @type ConfigOptions
*/
this.options = {};
/**
* Adapters to use to parse documentation data.
* @type Object.<String, AdapterDefinition>
*/
this.adapters = {};
/**
* List of parsed pages.
* @type PageData[]
*/
this.tree = [];
/**
* Theme class instance. Used to render pages.
* @type ?Theme
*/
this.theme = null;
}
}
Spacedoc.prototype.addAdapter = require('./lib/add-adapter');
Spacedoc.prototype.build = require('./lib/build');
Spacedoc.prototype.buildSearch = require('./lib/build-search');
Spacedoc.prototype.config = require('./lib/config');
Spacedoc.prototype.init = require('./lib/init');
Spacedoc.prototype.parse = require('./lib/parse');
Spacedoc.prototype.parseDocs = require('./lib/parse-docs');
/**
* Exported Spacedoc instance.
* @private
* @type Spacedoc
*/
const sd = new Spacedoc();
/**
* Run the Spacedoc parser and build pages.
* @name Spacedoc
* @param {Object} [options] - Build options.
* @param {Boolean} [options.watch = false] - Watch pages for changes and re-compile.
* @param {Function} cb - If watching, callback to run whenever files change.
* @returns {(Promise|Function)} If the `input` option was set in `Spacedoc.config()`, a Promise will be returned. Otherwise, a stream transform function will be returned.
*/
module.exports = ({watch = false}, cb = () => {}) => {
if (watch && sd.options.input) {
globWatcher(sd.options.input, {ignoreInitial: false}, () => {
return sd.init().then(() => {
cb(null);
}).catch(err => {
cb(err);
});
});
} else {
return sd.init();
}
};
/**
* Configure Spacedoc.
* @name Spacedoc.config
* @param {(ConfigOptions|String)} [opts={}] - Plugin options, or a path to a YML config file with options.
*/
module.exports.config = sd.config.bind(sd);
/**
* Build static assets for a Spacedoc site, including CSS and JavaScript.
* @name Spacedoc.build
* @param {Object} [options] - Build options.
* @param {Boolean} [options.watch=false] - Watch files for changes and re-build assets.
* @returns {Promise} Promise which resolves when the build process finishes, or rejects when there's an error. If the `watch` option is enabled, the Promise will not resolve.
*/
module.exports.build = ({watch = false}) => {
if (watch) {
return sd.theme.buildAndWatch();
}
return sd.theme.build();
};
/**
* Generate a search file from the pages and doclets in the site.
* @name Spacedoc.buildSearch
* @param {string} outFile - Path to write to.
* @returns {Promise} Promise which resolves when the search file has been written to disk.
*/
module.exports.buildSearch = sd.buildSearch.bind(sd);
/**
* List of pages that have been processed.
* @name Spacedoc.tree
* @type PageData[]
*/
Object.defineProperty(module.exports, 'tree', {
get: () => sd.tree
});
// Direct reference to instance (mostly for debugging)
module.exports._instance = sd;
// Standalone class
module.exports.Spacedoc = Spacedoc;
|
'use strict';
module.exports = {
src: {
js: {
files: [ './demo/index.js', './src/*/js/**/*.js', '!./src/*/js/**/spec/**/*.js' ],
main: './demo/index.js'
},
css: {
index: './src/*/css/index.scss',
files: './src/*/css/**/*.scss'
}
},
dist: {
dir: './demo',
js: {
dir: './demo',
bundleName: 'demo.bundle.js'
},
css: {
dir: './demo',
bundleName: 'demo.index.css'
}
},
test: {
files: './src/*/js/**/spec/**/*.spec.js',
bundle: {
dir: './dist',
name: 'tests.js'
},
runtime: './test/phantomjs-extensions.js',
runnerConfig: './karma.conf.js'
}
}
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/**
* Contact address.
* @constructor
* @param {DOMString} id unique identifier, should only be set by native code
* @param formatted // NOTE: not a W3C standard
* @param streetAddress
* @param locality
* @param region
* @param postalCode
* @param country
*/
const ContactAddress = function (pref, type, formatted, streetAddress, locality, region, postalCode, country) {
this.id = null;
this.pref = (typeof pref != 'undefined' ? pref : false);
this.type = type || null;
this.formatted = formatted || null;
this.streetAddress = streetAddress || null;
this.locality = locality || null;
this.region = region || null;
this.postalCode = postalCode || null;
this.country = country || null;
};
module.exports = ContactAddress;
|
/**
* Created by Deepak Sisodiya on 08/03/15.
*/
var app = angular.module("myApp", ['ui.router', 'ngSanitize']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/inbox');
$stateProvider
.state('inbox', {
url : '/inbox',
templateUrl : './src/view/inbox.html',
controller : 'inboxController'
})
.state('inbox/email/:id', {
url : '/inbox/email/:id',
templateUrl : './src/view/email.html',
controller : 'emailController'
})
});
|
import React from 'react'
import { withStyles } from '@material-ui/core/styles'
import Item from './Item'
const styles = theme => ({
padding: {
padding: theme.spacing.unit
}
})
function Group (props) {
const { classes } = props
const { items } = props
return (
<section className={classes.padding}>
{
items.map(({ title, description }, index) => (<Item key={index} title={title} description={description} />))
}
</section>
)
}
export default withStyles(styles)(Group)
|
/* @flow */
import React, { Component } from 'react';
import {
AppState,
StyleSheet,
StatusBar,
View,
} from 'react-native';
import AppNavigator from './navigator';
export default class App extends Component {
componentDidMount() {
AppState.addEventListener('change', this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
}
handleAppStateChange(currentAppState) {
if (currentAppState === 'active') { // active, background, inactive
// TODO: Notification 같은 정보를 가져옴 !
}
}
render() {
return <AppNavigator />;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
|
/**
* Theme: Adminox Admin Template
* Author: Coderthemes
* Module/App: Justgage
*/
document.addEventListener("DOMContentLoaded", function(event) {
var g1, g2, g3, g4, g5, g6, g7, g8;
var g1 = new JustGage({
id: "g1",
value: getRandomInt(0, 100),
min: 0,
max: 100,
title: "Custom Width",
label: "miles traveled",
gaugeWidthScale: 0.2
});
var g2 = new JustGage({
id: "g2",
value: getRandomInt(0, 100),
min: 0,
max: 100,
title: "Custom Shadow",
label: "",
shadowOpacity: 1,
shadowSize: 10,
shadowVerticalOffset: 5
});
var g3 = new JustGage({
id: "g3",
value: getRandomInt(0, 100),
min: 0,
max: 100,
title: "Custom Colors",
label: "",
levelColors: [
"#00fff6",
"#ff00fc",
"#1200ff"
]
});
var g4 = new JustGage({
id: "g4",
value: getRandomInt(0, 100),
min: 0,
max: 100,
title: "Hide Labels",
hideMinMax: true
});
var g5 = new JustGage({
id: "g5",
value: getRandomInt(0, 100),
min: 0,
max: 100,
title: "Animation Type",
label: "",
startAnimationTime: 2000,
startAnimationType: ">",
refreshAnimationTime: 1000,
refreshAnimationType: "bounce"
});
var g6 = new JustGage({
id: "g6",
value: getRandomInt(0, 100),
min: 0,
max: 100,
title: "Minimal",
label: "",
hideMinMax: true,
gaugeColor: "#fff",
levelColors: ["#000"],
hideInnerShadow: true,
startAnimationTime: 1,
startAnimationType: "linear",
refreshAnimationTime: 1,
refreshAnimationType: "linear"
});
var g7 = new JustGage({
id: "g7",
value: 72,
min: 0,
max: 100,
donut: true,
gaugeWidthScale: 0.6,
counter: true,
hideInnerShadow: true
});
var g8 = new JustGage({
id: "g8",
value : 72.15,
min: 0,
max: 100,
decimals: 2,
gaugeWidthScale: 0.6,
customSectors: [{
color : "#00ff00",
lo : 0,
hi : 50
},{
color : "#ff0000",
lo : 50,
hi : 100
}],
counter: true
});
document.getElementById('g8_refresh').addEventListener('click', function() {
g8.refresh(getRandomInt(0, 100));
});
setInterval(function() {
g1.refresh(getRandomInt(0, 100));
g2.refresh(getRandomInt(0, 100));
g3.refresh(getRandomInt(0, 100));
g4.refresh(getRandomInt(0, 100));
g5.refresh(getRandomInt(0, 100));
g6.refresh(getRandomInt(0, 100));
g7.refresh(getRandomInt(0, 100));
}, 2500);
});
|
var express = require('express');
var crud = require('./crud');
var Product = require('../models/product');
var router = express.Router();
crud.getAll(router, Product, 'products', {
transformQuery: function(query) {
return {
name: query.search
};
}
});
crud.get(router, Product, 'product');
crud.post(router, Product, 'product');
crud.put(router, Product, 'product');
crud.delete(router, Product);
module.exports = router;
|
c['1595']=[['1596',"Properties","topic_000000000000053D_props--.html",1]];
|
import React from 'react';
import E from '../index.js';
/******************************************************************************/
// Define component using a stateless function; this will be wrapped by
// transformStatelessFunctionComponent() and converted to a plain class.
export default function Content (props) {
return <div id='text'>{E.read (props, 'text')}</div>;
}
/******************************************************************************/
|
const knex = require('./knex')
const bcrypt = require('bcrypt')
const saltRounds = 10
function comparePassword (password, hash) {
return bcrypt.compare(password, hash)
}
function addUser (user) {
return bcrypt.hash(user.password, saltRounds)
.then(hash => {
return knex('users')
.insert({
first_name: user.firstName,
last_name: user.lastName,
email: user.email,
phone_number: user.phoneNumber,
hash: hash
}, 'id')
.then(inserted => {
const id = inserted[0]
return id
})
.then(getUserById)
})
}
function getUserByEmail (email) {
return knex('users')
.where('email', email)
.first()
}
function getUserById (id) {
return knex('users')
.select('id', 'first_name', 'last_name', 'email', 'phone_number')
.where('id', id)
.first()
.then(user => {
return {
id: user.id,
firstName: user.first_name,
lastName: user.last_name,
email: user.email,
phoneNumber: user.phone_number
}
})
}
function addFlat (flat) {
return knex('flats')
.insert({
flat_name: flat.flatName
}, 'id')
.then(inserted => {
const id = inserted[0]
return {id}
})
}
function getFlatById (id) {
return knex('flats')
.where('flats.id', id)
.first()
.then(record => {
return {
id: record.id,
flatName: record.flat_name
}
})
.then(flat => {
return getFlatmates(flat.id)
.then(flatmates => {
flat.flatmates = flatmates
return flat
})
})
.then(flat => {
return getJoinRequests(flat.id)
.then(requests => {
flat.requests = requests
return flat
})
})
}
function getFlatsByUserId (userId) {
return knex('tenancies')
.join('users', 'tenancies.user_id', '=', 'users.id')
.join('flats', 'tenancies.flat_id', '=', 'flats.id')
.select('users.id as userId', 'flats.id as flatId', 'flats.flat_name as flatName')
.where('userId', userId)
.then(flatInfos => {
return flatInfos.map(flatInfo => {
return {
id: flatInfo.flatId,
flatName: flatInfo.flatName
}
})
})
}
function getFlatByName (name) {
return knex('flats')
.where('flats.flat_name', name)
.first()
.then(record => {
if (record) {
return {
id: record.id,
flatName: record.flat_name
}
} else {
return null
}
})
}
function addTenancy (userId, flatId) {
return knex('tenancies')
.insert({
user_id: userId,
flat_id: flatId
}, 'id')
}
function getFlatmates (flatId) {
return knex('tenancies')
.join('users', 'tenancies.user_id', '=', 'users.id')
.join('flats', 'tenancies.flat_id', '=', 'flats.id')
.select('flats.id as flatId', 'users.first_name as firstName', 'users.last_name as lastName', 'users.id as userId', 'users.email as email', 'users.phone_number as phoneNumber')
.where('flat_id', flatId)
.then(flatmates => {
return flatmates.map(flatmate => {
return {
id: flatmate.userId,
firstName: flatmate.firstName,
lastName: flatmate.lastName,
email: flatmate.email,
phoneNumber: flatmate.phoneNumber
}
})
})
}
function addJoinRequest (userId, flatId) {
return knex('join-requests')
.insert({
flat_id: flatId,
user_id: userId
})
}
function getJoinRequests (flatId) {
return knex('join-requests')
.join('users', 'join-requests.user_id', '=', 'users.id')
.join('flats', 'join-requests.flat_id', '=', 'flats.id')
.select('join-requests.id as id', 'flats.id as flatId', 'users.first_name as firstName', 'users.last_name as lastName', 'users.id as userId')
.where('flat_id', flatId)
.then(records => {
return records.map(record => {
return {
id: record.id,
user: {
id: record.userId,
firstName: record.firstName,
lastName: record.lastName
}
}
})
})
.then(requests => {
return requests
})
}
function addNote (note) {
return knex('notes')
.insert({
flat_id: note.flat_id,
content: note.content,
author: note.author
})
.then(getNotesByFlatId(note.flat_id))
}
function editNote (note) {
return knex('notes')
.where('id', note.id)
.update({
content: note.content
})
}
function deleteNote (id) {
return knex('notes')
.where('id', id)
.del()
}
function getNotesByFlatId (flatId) {
return knex('notes')
.where('flat_id', flatId)
.then(notes => {
return notes.map(note => {
return {
id: note.id,
content: note.content,
author: note.author
}
})
})
}
module.exports = {
addFlat,
addJoinRequest,
addTenancy,
addUser,
getFlatById,
getFlatsByUserId,
getFlatByName,
getJoinRequests,
getUserById,
getUserByEmail,
comparePassword,
getNotesByFlatId,
addNote,
deleteNote,
editNote
}
|
'use strict';
let AttributeSetter = require('./attribute_setter').AttributeSetter;
class LocalPaymentReversed extends AttributeSetter {
constructor(attributes) {
super(attributes);
}
}
module.exports = {LocalPaymentReversed: LocalPaymentReversed};
|
require('@babel/register')({
ignore: ['node_modules/*']
})
require('@babel/polyfill')
const browserEnv = require('browser-env')
browserEnv()
|
(function () {
angular.module('angular-form-editor')
.directive('feCanvas', Directive);
function Directive($compile, $templateCache, $timeout) {
var CONTROLLER_NAME = '$feCanvasController'
, TEMPLATE_URL = 'angular-form-editor/fe-canvas.tpl.html'
, RESIZE_EVENT = 'resizeFrame'
return {
restrict: 'E',
scope: {
model: "=",
layout: "="
},
template: '<iframe class="fe-canvas"></iframe>',
controller: "FeCanvasCtrl as canvas",
replace: true,
bindToController: true,
transclude: true,
link: function (scope, element, attrs, ctrl, transclude) {
var document = element[0].contentDocument
, head = angular.element(document.head)
, body = angular.element(document.body)
, template = $templateCache.get(TEMPLATE_URL);
transclude(scope, function (clone) {
element.parent().data(CONTROLLER_NAME, ctrl);
element.after(clone);
});
head.append($('<link/>', {
rel: 'stylesheet',
href: '/vendor/angular-form-editor/angular-form-editor.css',
type: 'text/css'
}));
// jqLite.inheritedData does not cross out of iframe,
// this is necessary to maintain the behavior of require
body.data(CONTROLLER_NAME, ctrl);
body.append($compile(template)(scope));
body.addClass('fe-canvas-body');
$timeout(function () {
resizeFrame();
});
scope.$on(RESIZE_EVENT, function () {
$timeout(function () {
resizeFrame();
});
});
function resizeFrame() {
var innerHeight = body.children().get(0).scrollHeight
, outerHeight = element.height();
if (innerHeight > outerHeight) {
element.height(innerHeight);
}
}
}
}
}
})();
|
'use strict';
module.exports = function (config) {
var BaseViewModel = require('../BaseViewModel')(config);
function UserViewModel(user) {
user = user || {};
BaseViewModel.call(this, UserViewModel.schema);
this.id = user.id;
this.username = user.username || '';
this.firstName = user.firstName || '';
this.lastName = user.lastName || '';
this.image = {url: user.image.url || '', isDefault: user.image.isDefault};
this.email = user.email || '';
this.roles = user.roles || [];
this.isLocalUser = !!(user.hashPass && user.salt);
this.token = user.token;
this.expireDate = user.expireDate;
return this;
}
UserViewModel.prototype = BaseViewModel.prototype;
UserViewModel.constructor = UserViewModel;
UserViewModel.schema = {};
return UserViewModel;
};
|
//libs enter
|
// MAIN.js
requirejs.config( {
paths: {
'durandal': '../lib/durandal/js',
'foundation': '../lib/foundation/js/foundation.min',
'jquery': '../lib/jquery/jquery-1.9.1',
'knockout': '../lib/knockout/knockout-3.2.0',
'plugins': '../lib/durandal/js/plugins',
'store': '../lib/store/store.min',
'text': '../lib/require/text',
'transitions': '../lib/durandal/js/transitions',
},
shim: {
'foundation': {
deps: [ 'jquery' ]
}
}
} );
define( function( require ) {
var app = require( 'durandal/app' );
var store = require( 'store' );
var system = require( 'durandal/system' );
var viewLocator = require( 'durandal/viewLocator' )
system.debug( true );
app.title = 'Reportli | Login Sample | Durandal';
app.configurePlugins( {
dialog: true,
http: true,
router: true
} );
// check localStorage support for session tokens
if ( !store.enabled ) {
console.warn( 'LOCAL STORAGE service is not available. Disable "Private Browsing Mode" or upgrade your browser.' );
};
app.start().then( function() {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
//Show the app by setting the root view model for our application with a transition.
app.setRoot( 'viewmodels/shell' );
} );
} );
|
(function($, cornerstone, cornerstoneTools) {
'use strict';
/*
* define the runAnimation boolean as an object
* so that it can be modified by reference
*/
var runAnimation = {
value: false
};
var touchEndEvents = [ 'CornerstoneToolsTouchEnd',
'CornerstoneToolsDragEnd',
'CornerstoneToolsTouchPinch',
'CornerstoneToolsTouchPress',
'CornerstoneToolsTap'
].join(' ');
function animate(lastTime, handle, runAnimation, enabledElement, targetLocation) {
// See http://www.html5canvastutorials.com/advanced/html5-canvas-start-and-stop-an-animation/
if (!runAnimation.value) {
return;
}
// update
var time = (new Date()).getTime();
//var timeDiff = time - lastTime;
// pixels / second
var distanceRemaining = Math.abs(handle.y - targetLocation.y);
var linearDistEachFrame = distanceRemaining / 10;
console.log('distanceRemaining: ' + distanceRemaining);
if (distanceRemaining < 1) {
handle.y = targetLocation.y;
runAnimation.value = false;
return;
}
if (handle.y > targetLocation.y) {
handle.y -= linearDistEachFrame;
} else if (handle.y < targetLocation.y) {
handle.y += linearDistEachFrame;
}
// Update the image
cornerstone.updateImage(enabledElement.element);
// Request a new frame
cornerstone.requestAnimationFrame(function() {
animate(time, handle, runAnimation, enabledElement, targetLocation);
});
}
function touchMoveHandle(touchEventData, toolType, data, handle, doneMovingCallback) {
//console.log('touchMoveHandle');
runAnimation.value = true;
var element = touchEventData.element;
var enabledElement = cornerstone.getEnabledElement(element);
var time = (new Date()).getTime();
// Average pixel width of index finger is 45-57 pixels
// https://www.smashingmagazine.com/2012/02/finger-friendly-design-ideal-mobile-touchscreen-target-sizes/
var fingerDistance = -57;
var aboveFinger = {
x: touchEventData.currentPoints.page.x,
y: touchEventData.currentPoints.page.y + fingerDistance
};
var targetLocation = cornerstone.pageToPixel(element, aboveFinger.x, aboveFinger.y);
function touchDragCallback(e, eventData) {
//console.log('touchMoveHandle touchDragCallback: ' + e.type);
runAnimation.value = false;
if (handle.hasMoved === false) {
handle.hasMoved = true;
}
handle.active = true;
var currentPoints = eventData.currentPoints;
var aboveFinger = {
x: currentPoints.page.x,
y: currentPoints.page.y + fingerDistance
};
targetLocation = cornerstone.pageToPixel(element, aboveFinger.x, aboveFinger.y);
handle.x = targetLocation.x;
handle.y = targetLocation.y;
cornerstone.updateImage(element);
var eventType = 'CornerstoneToolsMeasurementModified';
var modifiedEventData = {
toolType: toolType,
element: element,
measurementData: data
};
$(element).trigger(eventType, modifiedEventData);
}
$(element).on('CornerstoneToolsTouchDrag', touchDragCallback);
function touchEndCallback(e, eventData) {
//console.log('touchMoveHandle touchEndCallback: ' + e.type);
runAnimation.value = false;
handle.active = false;
$(element).off('CornerstoneToolsTouchDrag', touchDragCallback);
$(element).off(touchEndEvents, touchEndCallback);
cornerstone.updateImage(element);
if (e.type === 'CornerstoneToolsTouchPress') {
eventData.handlePressed = data;
handle.x = touchEventData.currentPoints.image.x;
handle.y = touchEventData.currentPoints.image.y;
}
if (typeof doneMovingCallback === 'function') {
doneMovingCallback(e, eventData);
}
}
$(element).on(touchEndEvents, touchEndCallback);
animate(time, handle, runAnimation, enabledElement, targetLocation);
}
// module/private exports
cornerstoneTools.touchMoveHandle = touchMoveHandle;
})($, cornerstone, cornerstoneTools);
|
function initMap() {
var
l,
apiHost = 'localhost:5010';
var map = L.map('map', {
zoom: 6,
minZoom: 6,
maxZoom: 15,
maxBounds: ([[29.5, -127.4], [45.0, -111.1]])
});
// on('load') fires when the map's center and zoom are set for the first time, so this precedes setView().
map.on('load dragend zoomend', function (e) {
var current = {};
current.zoom = map.getZoom();
current.bbox = {
'tuple': map.getBounds().getSouthWest().lng.toFixed(2) + ',' +
map.getBounds().getSouthWest().lat.toFixed(2) + ',' +
map.getBounds().getNorthEast().lng.toFixed(2) + ',' +
map.getBounds().getNorthEast().lat.toFixed(2)
};
console.log(current);
getGeoJson(current);
});
map.setView([37.8922, -119.3335], 6);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
// L.tileLayer('https://a.tiles.mapbox.com/v4/erictheise.k93ep0p9/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZXJpY3RoZWlzZSIsImEiOiJqanBuc3NvIn0.3n-yBu6rKZtkb19T5Bh8GQ', {
attribution: 'Map layer © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
}).addTo(map);
L.control.scale({ position: 'bottomleft' }).addTo(map);
function getGeoJson(current) {
console.log('make ajax huc request.');
var url_hucs;
url_hucs = 'http://' + apiHost + '/huc12sz' + current.zoom + '/?in_bbox=' + current.bbox.tuple;
$.getJSON(url_hucs).done(addTopoData);
function addTopoData(topoData) {
console.log('ajax huc request processing complete.');
console.log(topoData);
if (typeof l !== 'undefined') {
map.removeLayer(l);
l = null;
}
l = new L.TopoJSON();
l.addData(topoData);
l.addTo(map);
l.eachLayer(handleLayer);
}
}
function handleLayer(layer) {
layer.setStyle(style(layer));
layer.on('mouseover mousemove', function(e) {
layer.setStyle({fillOpacity: 0.9});
});
layer.on('mouseout', function(e) {
layer.setStyle(style(layer));
map.closePopup();
});
layer.bindPopup(
'<b>' + layer.feature.properties.first_hu_1 + '</b><br/>' +
'(' + layer.feature.properties.hr_name + ')'
);
}
function style (e) {
return {
stroke: true, color: '#111', weight: 1, opacity: 0.7,
fill: true, fillColor: '#fff', fillOpacity: 0.4 };
}
$('.species-id').on('click', function () {
getHuc12sBySpecies($(this).data('speciesId'), $(this).parents('ul').attr('id'));
});
function getHuc12sBySpecies(speciesId, className) {
console.log('make ajax species request.');
var url_huc12s_by_species = 'http://' + apiHost + '/huc12sbyspecies/' + speciesId + '/';
$.getJSON(url_huc12s_by_species).done(renderHuc12s);
function renderHuc12s(speciesData) {
console.log('ajax huc request processing complete.');
console.log(speciesData.length);
updateSummary(speciesId, speciesData.length);
l.eachLayer(function(layer) {
layer.setStyle(style(layer));
if ($.inArray(layer.feature.id, speciesData) > -1) {
layer.setStyle({fillColor: $('.btn-' + className).css('background-color')});
}
});
}
}
function updateSummary(speciesId, count) {
$('#summary').show();
var
speciesSlug = '',
panelBody = '';
if (typeof species[speciesId].common_name === 'undefined' || !species[speciesId].common_name ) {
speciesSlug = '<a target="_new" href="http://en.wikipedia.org/wiki/' + species[speciesId].scientific_name + '">' + species[speciesId].scientific_name + '</a>';
} else {
speciesSlug = 'The ' + species[speciesId].common_name + ' (<a target="_new" href="http://en.wikipedia.org/wiki/' + species[speciesId].scientific_name + '">' + species[speciesId].scientific_name + '</a>)';
}
if (species[speciesId].alt_scientific_names) {
var
s = species[speciesId].alt_scientific_names,
alternatives = ''
;
switch (s.split(',').length) {
case 1:
speciesSlug += ', also known by the name ' + s + ', ';
break;
case 2:
alternatives = s.substring(0, s.lastIndexOf(',')) + ' and' + s.substring(s.lastIndexOf(',') + 1);
speciesSlug += ', also known by the names ' + alternatives + ', ';
break;
default:
alternatives = s.substring(0, s.lastIndexOf(',')) + ', and' + s.substring(s.lastIndexOf(',') + 1);
speciesSlug += ', also known by the names ' + alternatives + ', ';
break;
}
}
if (count > 0) {
panelBody = ' \
' + speciesSlug + ' \
has been found in ' + count + ' watersheds in California. \
'
} else {
panelBody = ' \
' + speciesSlug + ' \
is a freshwater species in California, but researchers have not yet provided observation information in the sources we reviewed. If you know where this species is found, add the locations to <a href="http://www.inaturalist.org/">iNaturalist.org</a> or another public data repository so it can be included in conservation planning efforts. \
'
}
$('.panel-body').
empty().
append(panelBody);
}
// swap between dropdowns of scientific names and common names.
$('input[name=sci_or_com]').on('change', function () {
if ($(this).data('value') === 'com') {
$('ul.dropdown-menu[id|="sci"]').detach();
$.each($comLists, function (index, $ul) {
$('button.btn-' + $(this).attr('id').replace('com-','') + '.dropdown-toggle').parent().append($(this));
})
} else if ($(this).data('value') === 'sci') {
$('ul.dropdown-menu[id|="com"]').detach();
$.each($sciLists, function (index, $ul) {
$('button.btn-' + $(this).attr('id').replace('sci-','') + '.dropdown-toggle').parent().append($(this));
})
}
})
}
|
'use strict';
const webpack = require('webpack');
const config = require('./webpack.config');
/**
*
*/
config.plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
);
module.exports = config;
|
'use strict';
module.exports = {
env: {
es6: true,
},
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
rules: {
// enforces no braces where they can be omitted
// http://eslint.org/docs/rules/arrow-body-style
// it's optional to have () for arrow functions
'arrow-body-style': ['off', 'always', {
requireReturnForObjectLiteral: false,
}],
// require parens in arrow function arguments
// http://eslint.org/docs/rules/arrow-parens
'arrow-parens': ['off', 'as-needed', {
requireForBlockBody: true,
}],
// require space before/after arrow function's arrow
// http://eslint.org/docs/rules/arrow-spacing
'arrow-spacing': ['error', {before: true, after: true}],
// verify super() callings in constructors
'constructor-super': 'error',
// enforce the spacing around the * in generator functions
// http://eslint.org/docs/rules/generator-star-spacing
'generator-star-spacing': ['error', {before: false, after: true}],
// disallow modifying variables of class declarations
// http://eslint.org/docs/rules/no-class-assign
'no-class-assign': 'error',
// disallow arrow functions where they could be confused with comparisons
// http://eslint.org/docs/rules/no-confusing-arrow
'no-confusing-arrow': ['error', {
allowParens: true,
}],
// disallow modifying variables that are declared using const
'no-const-assign': 'error',
// disallow duplicate class members
// http://eslint.org/docs/rules/no-dupe-class-members
'no-dupe-class-members': 'error',
// disallow importing from the same path more than once
// http://eslint.org/docs/rules/no-duplicate-imports
// replaced by https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
'no-duplicate-imports': 'off',
// disallow symbol constructor
// http://eslint.org/docs/rules/no-new-symbol
'no-new-symbol': 'error',
// disallow specific imports
// http://eslint.org/docs/rules/no-restricted-imports
'no-restricted-imports': 'off',
// disallow to use this/super before super() calling in constructors.
// http://eslint.org/docs/rules/no-this-before-super
'no-this-before-super': 'error',
// disallow useless computed property keys
// http://eslint.org/docs/rules/no-useless-computed-key
'no-useless-computed-key': 'error',
// disallow unnecessary constructor
// http://eslint.org/docs/rules/no-useless-constructor
'no-useless-constructor': 'error',
// disallow renaming import, export, and destructured assignments to the same name
// http://eslint.org/docs/rules/no-useless-rename
'no-useless-rename': ['error', {
ignoreDestructuring: false,
ignoreImport: false,
ignoreExport: false,
}],
// require let or const instead of var
'no-var': 'error',
// require method and property shorthand syntax for object literals
// http://eslint.org/docs/rules/object-shorthand
'object-shorthand': ['off', 'always', {
ignoreConstructors: false,
avoidQuotes: true,
}],
// suggest using arrow functions as callbacks
// this is okay but should not enforce
'prefer-arrow-callback': ['off', {
allowNamedFunctions: false,
allowUnboundThis: true,
}],
// suggest using of const declaration for variables that are never modified after declared
'prefer-const': ['error', {
destructuring: 'any',
ignoreReadBeforeAssign: true,
}],
// Prefer destructuring from arrays and objects
// http://eslint.org/docs/rules/prefer-destructuring
'prefer-destructuring': ['warn', {
array: true,
object: true,
}, {
enforceForRenamedProperties: false,
}],
// disallow parseInt() in favor of binary, octal, and hexadecimal literals
// http://eslint.org/docs/rules/prefer-numeric-literals
'prefer-numeric-literals': 'error',
// suggest using Reflect methods where applicable
// http://eslint.org/docs/rules/prefer-reflect
'prefer-reflect': 'off',
// use rest parameters instead of arguments
// http://eslint.org/docs/rules/prefer-rest-params
'prefer-rest-params': 'error',
// suggest using the spread operator instead of .apply()
// http://eslint.org/docs/rules/prefer-spread
'prefer-spread': 'error',
// suggest using template literals instead of string concatenation
// e.g. '?' + qs.stringify({...}), such case dont need template literals
// http://eslint.org/docs/rules/prefer-template
'prefer-template': 'off',
// disallow generator functions that do not have yield
// koa in some cases dont need to yield
// http://eslint.org/docs/rules/require-yield
'require-yield': 'off',
// enforce spacing between object rest-spread
// http://eslint.org/docs/rules/rest-spread-spacing
'rest-spread-spacing': ['error', 'never'],
// import sorting
// http://eslint.org/docs/rules/sort-imports
'sort-imports': ['off', {
ignoreCase: false,
ignoreMemberSort: false,
memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
}],
// require a Symbol description
// http://eslint.org/docs/rules/symbol-description
'symbol-description': 'error',
// enforce usage of spacing in template strings
// http://eslint.org/docs/rules/template-curly-spacing
'template-curly-spacing': 'error',
// enforce spacing around the * in yield* expressions
// http://eslint.org/docs/rules/yield-star-spacing
'yield-star-spacing': ['error', 'after'],
},
};
|
/**
* @author Rafael Vidaurre
* @module Scraper
* @requires Agent
*/
'use strict';
var _, utils, Agent;
_ = require('lodash');
utils = require('./utils');
Agent = require('./agent');
/**
* @class
*/
function Scraper () {
/**
* Object which contains scraper-wide routine definitions, routines are set via the routine()
* method
*/
this._routines = {};
/**
* Share methods available at scraper-level
* @private
*/
this._shareMethods = {
replace: function (current, next) {
return next;
}
};
/**
* Contains all agents associated with this Scraper
*/
this._agents = {};
// Define the default sharing method
this._shareMethods.default = this._shareMethods.replace;
}
/**
* Creates a new agent
* @param {string} agentId unique agent identifier
* @private
*/
Scraper.prototype.__createAgent = function (agentId) {
this._agents[agentId] = new Agent(agentId);
return this._agents[agentId];
};
/**
* Creates or gets an agent based on the id passed
* @param {string} agentId Id of the agent to retrieve/create
* @returns {Agent} agent to be retrieved/created
*/
Scraper.prototype.agent = function (agentId) {
var thisAgent, agentExists;
if (!agentId || !_.isString(agentId)) {
throw new Error('Agent id must be a non-empty string');
}
agentExists = utils.hasKey(this._agents, agentId);
thisAgent = agentExists ? this._agents[agentId] : this.__createAgent(agentId);
return thisAgent;
};
/**
* Creates a scraper-wide routine which will be available for all agents
* @param {string} routineName name of the routine
* @param {array} array of taskIds which the routine will include
*/
Scraper.prototype.routine = function (routineName, taskIds) {
if (!_.isArray(taskIds)) {
throw new Error('An array of task Ids must be passed to the routine method');
}
if (!_.isString(routineName)) {
throw new Error('Routine name must be a string');
}
this._routines[routineName] = taskIds;
return this;
};
/**
* Adds a new scraper-level share method, it will override framework-level methods
* @params {string} methodName name of the share method
* @params {string} shareFunction
*/
Scraper.prototype.addShareMethod = function (methodName, shareFunction) {
if (!_.isString(methodName)) {
throw new Error('Share method name must be a string');
}
if (!_.isFunction(shareFunction)) {
throw new Error('Share method must be a function');
}
this._shareMethods[methodName] = shareFunction;
};
module.exports = Scraper;
|
/**
* Find the differences between two objects and push to a new object
* (c) 2019 Chris Ferdinandi & Jascha Brinkmann, MIT License, https://gomakethings.com & https://twitter.com/jaschaio
* @param {Object} obj1 The original object
* @param {Object} obj2 The object to compare against it
* @return {Object} An object of differences between the two
*/
cm.diff = function (obj1, obj2) {
// Make sure an object to compare is provided
if (!obj2 || Object.prototype.toString.call(obj2) !== '[object Object]') {
return obj1;
}
//
// Variables
//
var diffs = {};
var key;
//
// Compare our objects
//
// Loop through the first object
for (key in obj1) {
if (obj1.hasOwnProperty(key)) {
cm.diffCompare(diffs, obj1[key], obj2[key], key);
}
}
// Loop through the second object and find missing items
for (key in obj2) {
if (obj2.hasOwnProperty(key)) {
if (!obj1[key] && obj1[key] !== obj2[key] ) {
diffs[key] = obj2[key];
}
}
}
// Return the object of differences
return diffs;
};
/**
* Compare two items and push non-matches to object
* @param {Object} diffs The diffs object
* @param {*} item1 The first item
* @param {*} item2 The second item
* @param {String} key The key in our object
*/
cm.diffCompare = function (diffs, item1, item2, key) {
// Get the object type
var type1 = Object.prototype.toString.call(item1);
var type2 = Object.prototype.toString.call(item2);
// If type2 is undefined it has been removed
if (type2 === '[object Undefined]') {
diffs[key] = null;
return;
}
// If items are different types
if (type1 !== type2) {
diffs[key] = item2;
return;
}
// If an object, compare recursively
if (type1 === '[object Object]') {
var objDiff = cm.diff(item1, item2);
if (Object.keys(objDiff).length > 0) {
diffs[key] = objDiff;
}
return;
}
// If an array, compare
if (type1 === '[object Array]') {
if (!cm.diffArraysMatch(item1, item2)) {
diffs[key] = item2;
}
return;
}
// Else if it's a function, convert to a string and compare
// Otherwise, just compare
if (type1 === '[object Function]') {
if (item1.toString() !== item2.toString()) {
diffs[key] = item2;
}
} else {
if (item1 !== item2 ) {
diffs[key] = item2;
}
}
};
/**
* Check if two arrays are equal
* @param {Array} arr1 The first array
* @param {Array} arr2 The second array
* @return {Boolean} If true, both arrays are equal
*/
cm.diffArraysMatch = function (arr1, arr2) {
// Check if the arrays are the same length
if (arr1.length !== arr2.length) return false;
// Check if all items exist and are in the same order
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
// Otherwise, return true
return true;
};
|
/**
* @file this file is responsible for the persitance disk caching
* it offers helpers to prevent recompilation of the favicons on
* every build
*/
'use strict';
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var pluginVersion = require('../package.json').version;
/**
* Stores the given iconResult together with the control hashes as JSON file
*/
function emitCacheInformationFile (loader, query, cacheFile, fileHash, iconResult) {
if (!query.persistentCache) {
return;
}
loader.emitFile(cacheFile, JSON.stringify({
hash: fileHash,
version: pluginVersion,
optionHash: generateHashForOptions(query),
result: iconResult
}));
}
/**
* Checks if the given cache object is still valid
*/
function isCacheValid (cache, fileHash, query) {
// Verify that the source file is the same
return cache.hash === fileHash &&
// Verify that the options are the same
cache.optionHash === generateHashForOptions(query) &&
// Verify that the favicons version of the cache maches this version
cache.version === pluginVersion;
}
/**
* Try to load the file from the disc cache
*/
function loadIconsFromDiskCache (loader, query, cacheFile, fileHash, callback) {
// Stop if cache is disabled
if (!query.persistentCache) return callback(null);
var resolvedCacheFile = path.resolve(__dirname, loader._compiler.parentCompilation.compiler.outputPath, cacheFile);
fs.exists(resolvedCacheFile, function (exists) {
if (!exists) return callback(null);
fs.readFile(resolvedCacheFile, function (err, content) {
if (err) return callback(err);
var cache;
try {
cache = JSON.parse(content);
// Bail out if the file or the option changed
if (!isCacheValid(cache, fileHash, query)) {
return callback(null);
}
} catch (e) {
return callback(e);
}
callback(null, cache.result);
});
});
}
/**
* Generates a md5 hash for the given options
*/
function generateHashForOptions (options) {
var hash = crypto.createHash('md5');
hash.update(JSON.stringify(options));
return hash.digest('hex');
}
module.exports = {
loadIconsFromDiskCache: loadIconsFromDiskCache,
emitCacheInformationFile: emitCacheInformationFile
};
|
import * as actions from '../actions'
export default function isIncognito(state = false, action) {
switch (action.type) {
case actions.TOGGLE_INCOGNITO:
return action.value
default:
return state
}
}
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['tcy_IN'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%z%c%T%s%b%e%r",
"country_name": "\u0cad\u0cbe\u0cb0\u0ca4",
"country_post": null,
"country_ab2": "IN",
"country_ab3": "IND",
"country_num": 356,
"country_car": "IND",
"country_isbn": null,
"lang_name": "\u0ca4\u0cc1\u0cb3\u0cc1",
"lang_ab": "",
"lang_term": "tcy",
"lang_lib": "tcy"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1yY]",
"noexpr": "^[-0nN]",
"yesstr": null,
"nostr": null
},
"LC_MONETARY": {
"currency_symbol": "\u20b9",
"mon_decimal_point": ".",
"mon_thousands_sep": ",",
"mon_grouping": [
3,
2
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 1,
"p_sep_by_space": 0,
"n_cs_precedes": 1,
"n_sep_by_space": 0,
"p_sign_posn": 1,
"n_sign_posn": 1,
"int_curr_symbol": "INR ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%p%t%f%t%g",
"name_gen": "",
"name_mr": "\u0cb6\u0ccd\u0cb0\u0cc0",
"name_mrs": "\u0cb6\u0ccd\u0cb0\u0cc0\u0cae\u0ca4\u0cbf",
"name_miss": "\u0c95\u0cc1\u0cae\u0cbe\u0cb0\u0cbf",
"name_ms": "\u0c95\u0cc1\u0cae\u0cbe\u0cb0"
},
"LC_NUMERIC": {
"decimal_point": ".",
"thousands_sep": ",",
"grouping": 3
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": [
"+%c ",
0,
0
],
"tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "91"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"\u0c90",
"\u0cb8\u0ccb",
"\u0c85\u0c82",
"\u0cac\u0cc1",
"\u0c97\u0cc1",
"\u0cb6\u0cc1",
"\u0cb6"
],
"day": [
"\u0c90\u0ca5\u0cbe\u0cb0",
"\u0cb8\u0ccb\u0cae\u0cbe\u0cb0",
"\u0c85\u0c82\u0c97\u0cb0\u0cc6",
"\u0cac\u0cc1\u0ca7\u0cbe\u0cb0",
"\u0c97\u0cc1\u0cb0\u0cc1\u0cb5\u0cbe\u0cb0",
"\u0cb6\u0cc1\u0c95\u0ccd\u0cb0\u0cb0",
"\u0cb6\u0ca8\u0cbf\u0cb5\u0cbe\u0cb0"
],
"week": [
7,
19971130,
1
],
"abmon": [
"\u0c9c",
"\u0cab\u0cc6",
"\u0cae\u0cbe",
"\u0c8f",
"\u0cae\u0cc7",
"\u0c9c\u0cc2",
"\u0c9c\u0cc1",
"\u0c86",
"\u0cb8\u0cc6",
"\u0c85",
"\u0ca8",
"\u0ca1\u0cbf"
],
"mon": [
"\u0c9c\u0ca8\u0cb5\u0cb0\u0cbf",
"\u0cab\u0cc6\u0cac\u0ccd\u0cb0\u0cc1\u0cb5\u0cb0\u0cbf",
"\u0cae\u0cbe\u0cb0\u0ccd\u0c9a\u0ccd",
"\u0c8f\u0caa\u0ccd\u0cb0\u0cbf\u0cb2\u0ccd\u200c\u200c",
"\u0cae\u0cc7",
"\u0c9c\u0cc2\u0ca8\u0ccd",
"\u0c9c\u0cc1\u0cb2\u0cc8",
"\u0c86\u0c97\u0cb8\u0ccd\u0c9f\u0ccd",
"\u0cb8\u0cc6\u0caa\u0ccd\u0c9f\u0cc6\u0c82\u0cac\u0cb0\u0ccd\u200c",
"\u0c85\u0c95\u0ccd\u0c9f\u0ccb\u0cac\u0cb0\u0ccd",
"\u0ca8\u0cb5\u0cc6\u0c82\u0cac\u0cb0\u0ccd",
"\u0ca1\u0cbf\u0cb8\u0cc6\u0c82\u0cac\u0cb0\u0ccd"
],
"d_t_fmt": "%A %d %b %Y %I:%M:%S %p %Z",
"d_fmt": "%-d\/\/%-m\/\/%y",
"t_fmt": "%I:%M:%S %p %Z",
"am_pm": [
"\u0c95\u0cbe\u0c82\u0ca1\u0cc6",
"\u0cac\u0caf\u0ccd\u0caf"
],
"t_fmt_ampm": "%I:%M:%S %p %Z",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": null,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
|
/*
*We need to collect some data from the user.
*Please collect the following data. User input from email field
*and name field. User Screen size, Browser information, page title.
* Collect the first 100 mouse coordinates the user makes on the page.
*
*
1. Create a Json that will collect all this data. It’s as simple as a key:value pair.
2. Collect the user input value when they blur on the field
a. Email
b. User name
3. The user screen size, user agent and page title can be collected when
the window loads.
a. window.innerHeight
b. window. innerWidth
c. window. navigator. userAgent
d. document.title
4. Collect the user mouse cords by putting them into an array when the
user moves there mouse on the document. One for the mouseX, and one for
the mouseY. Once the Array has a length of 100 you can stop pushing the
mouse cords into the array.
a. e.clientX
b. e.clientY
c. jsonVariable.ArrayVariable.push(e.clientX) (Do not name your variables this sample)
*/
var userdata = {
"name": '',
"email": '',
"mouseX": [],
"mouseY": [],
"height": '',
"width": '',
"agent": '',
"tittle":''
};
function showResults() {
console.clear();
console.log(userdata);
}
var results = document.getElementById('showResults');
results.addEventListener("click", showResults);
var mail = document.getElementById('email');
var fullname = document.getElementById('fullname');
mail.addEventListener ('blur',saveData);
fullname.addEventListener ('blur',saveData);
function saveData(){
userdata.name = fullname.value;
userdata.email = mail.value;
}
//function saveEmail() {
//serdata.email = mail.value;
//}
function screensize (){
userdata.height = window.innerHeight;
userdata.width = window. innerWidth;
userdata.agent = window. navigator. userAgent;
userdata.tittle = document.title;
}
window.addEventListener ('load', screensize);
function trackMouse(e) {
userdata.mouseX.push(e.clientX);
userdata.mouseY.push(e.clientY);
if ( userdata.mouseX.length > 100 ) {
document.removeEventListener('mousemove', trackMouse);
}
}
document.addEventListener('mousemove', trackMouse);
|
import { createStore as _createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducer from './modules/reducer';
export default function createStore(data) {
const middleware = [ thunk ]
delete data._serverContext
let composeEnhancers = compose;
if (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) {
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
}
const finalCreateStore = composeEnhancers(applyMiddleware(...middleware))(_createStore);
const store = finalCreateStore(reducer, data);
return store;
}
|
'use strict';
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/environment');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compose = require('composable-middleware');
var User = require('../api/user/user.model');
var validateJwt = expressJwt({ secret: config.secrets.session });
/**
* Attaches the user object to the request if authenticated
* Otherwise returns 403
*/
function isAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
// allow access_token to be passed through query parameter as well
if(req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
User.findOne({ id: req.user.id }, function (err, user) {
if (err) return next(err);
if (!user) return res.sendStatus(401);
req.user = user;
next();
});
});
}
/**
* Checks if the user role meets the minimum requirements of the route
*/
function hasRole(roleRequired) {
if (!roleRequired) throw new Error('Required role needs to be set');
return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
if (config.userRoles.indexOf(req.user.role) >= config.userRoles.indexOf(roleRequired)) {
next();
}
else {
res.sendStatus(403);
}
});
}
/**
* Returns a jwt token signed by the app secret
*/
function signToken(id) {
return jwt.sign({ id: id }, config.secrets.session, { expiresInMinutes: 60*5 });
}
/**
* Set token cookie directly for oAuth strategies
*/
function setTokenCookie(req, res) {
if (!req.user) return res.json(404, { message: 'Something went wrong, please try again.'});
var token = signToken(req.user.id, req.user.role);
res.cookie('token', JSON.stringify(token));
res.redirect('/');
}
exports.isAuthenticated = isAuthenticated;
exports.hasRole = hasRole;
exports.signToken = signToken;
exports.setTokenCookie = setTokenCookie;
|
// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Flags: --allow-natives-syntax --use-escape-analysis
// This tests that captured objects materialized through the deoptimizer
// have field descriptors with a representation matching the values that
// have actually been stored in the object.
var values = [ function() { return {}; },
function() { return 23; },
function() { return 4.2; } ];
function constructor(value_track) {
this.x = value_track();
}
function access(value_track, value_break, deopt) {
var o = new constructor(value_track);
o.x = value_break;
deopt.deopt
assertEquals(value_break, o.x);
}
function test(value_track, value_break) {
var deopt = { deopt:false };
// Warm-up field tracking to a certain representation.
access(value_track, value_track(), deopt);
access(value_track, value_track(), deopt);
%OptimizeFunctionOnNextCall(access);
access(value_track, value_track(), deopt);
// Deoptimize on a run with a different representation.
delete deopt.deopt;
access(value_track, value_break(), deopt);
// Clear type feedback of the access function for next run.
%ClearFunctionFeedback(access);
// Also make sure the initial map of the constructor is reset.
constructor.prototype = {};
}
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values.length; j++) {
test(values[i], values[j])
}
}
|
'user strict';
/*
* Maintains results from the simulation between partials/controllers.
*/
module.exports = function($location) {
// results to pass between pages
this.simulationResults = {};
// list of data to maintain
this.periodUnits = 'minutes';
this.totalPeriods = 0;
this.isProbability = false;
this.showProbabilityRm = false;
this.isLinear = true; // default
this.showLinearRm = false;
this.showWorkerRm = false;
this.workerConfigs = [];
this.linearTaskConfigs = [];
this.probabilityArrivalRate = 0;
this.probabilityTaskConfigs = [];
this.setSimulationResults = (data) => {
this.simulationResults = data;
$location.path('/results');
};
this.getSimulationResults = () => {
return this.simulationResults;
};
};
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var RoleSchema = new Schema({
name: { type: String, unique: true, lowercase: true }
});
module.exports = mongoose.model('Role', RoleSchema);
|
class News extends Base {
constructor() {
super();
this.newsSource = [];
this.newsSource.push({key: "20min", name: "20 minutos", url: "http://www.20minutos.com/rss/", icon: "20minutos.png"});
this.newsSource.push({key: "elmundo", name: "El Mundo", url: "http://estaticos.elmundo.es/elmundo/rss/portada.xml", icon: "elmundo.png"});
this.newsSource.push({key: "emt", name: "El Mundo Today", url: "http://www.elmundotoday.com/feed/", icon: "emt.png"});
this.newsSource.push({key: "elpais", name: "El Pais", url: "http://ep00.epimg.net/rss/tags/ultimas_noticias.xml", icon: "elpais.png"});
this.newsSource.push({key: "marca", name: "Marca", url: "http://estaticos.marca.com/rss/portada.xml", icon: "marca.png"});
this.randomNews = [];
this.callRss = 0;
this.currentRss = 0;
this.loopPrint = 0;
this.flagCall = true;
this.maxNewsPerSource = 10;
this.loadNewsSource();
this.updateNews();
}
loadNewsSource() {
let self = this;
$(this.newsSource).each(function(elem){
$("ul#newsList").append("<li><input class='news' type='checkbox' name='news[]' key='"+this.key+"' value='"+this.key+"' /> "+this.name+"</li>");
});
this.getFromStorage('news', function(data){
if(self.isInStorage(data, 'news')) {
$(data.news).each(function(elem){
$("input[key="+this+"]").prop('checked', true);
});
}
});
$("input.news").change(function() {
var n = [];
$("input.news:checked").each(function(){
n.push($(this).val());
});
top.app.factories.news.setInStorage("news", n, function(){
top.app.factories.news.updateNews();
});
});
}
getNews( rss, key, img = null) {
let self = this;
$.get({
url: self.feedURL,
//url: "https://antc-rss-json.herokuapp.com/",
//url: "https://antc-rss-json.herokuapp.com/?rss",
data : {
rss: rss,
}
}).done(function(response){
console.log(rss, response);
var news = [];
self.currentRss++;
if(response != undefined && response != '' && response.items != undefined) {
for(var i = 0; i < response.items.length && i < self.maxNewsPerSource; i++ ) {
var icon = (img == null) ? "<i class='material-icons'>sms_failed</i>" : "<img src='/img/news/"+img+"' />";
var link = "<a href='"+response.items[i].url+"'>"+response.items[i].title+"</a>";
news.push({icon: icon, title: link});
}
}
self.randomNews.push({key: key, news: news});
});
}
processNews(key = null) {
let self = this;
for(var i = 0; i < this.maxNewsPerSource; i++ ) {
$(this.randomNews).each(function(ind){
if(typeof this.news[i] != 'undefined') {
var t = this.news[i];
$(".marquee > p").append(t.icon + t.title);
}
});
}
var duration = 80 * parseInt(this.currentRss);
if(duration > 160) {
duration = 175;
}
$(".marquee > p").css('animation-duration', duration + 's');
}
printNews() {
if(this.currentRss > 0) {
$(".marquee").show();
$(".marquee > p").html('');
}
let self = this;
if(this.currentRss == this.callRss && this.flagCall) {
this.flagCall = false;
this.processNews();
} else if(this.flagCall) {
setTimeout(function() {self.printNews.call(self);}, 500);
}
}
updateNews() {
let self = this;
this.flagCall = true;
this.randomNews = [];
this.callRss = 0;
this.currentRss = 0;
this.loopPrint = 0;
this.getFromStorage('news', function(data){
if(self.isInStorage(data, 'news')) {
$(data.news).each(function(e){
var _k = this;
$(self.newsSource).each(function(elem){
if(this.key == _k) {
self.callRss++;
self.getNews.call(self, this.url, this.key, this.icon);
}
});
});
self.printNews.call(self);
}
});
}
}
|
/**
* Transform a Collection+JSON resource into a hyper+json representation
*
* @param {Object} resource
* @return {Object}
*/
module.exports = function(resource) {
var root = get('collection', resource);
if (!root) throw new Error('Missing root "collection" property');
var hyperObj = {};
mergeItem(hyperObj, root, null, true);
var template = get('data', get('template', root));
if (template) hyperObj.create = {
enctype: 'application/collection+json',
action: hyperObj.href,
method: 'POST',
input: transformInputs(template)
};
hyperObj.collection = get('items', root, []).map(function(item) {
return mergeItem({}, item, template);
});
get('queries', root, []).forEach(function(query) {
var rel = get('rel', query);
if (!rel) return;
var form = hyperObj[rel] = {
method: 'GET',
input: {}
};
Object.keys(query).forEach(function(key) {
if (key === 'rel') return;
if (key === 'href') return form.action = query[key];
if (key === 'data') return form.input = transformInputs(query[key]);
form[key] = query[key];
});
});
return hyperObj;
};
/**
* Merge an item's properties into a document
*
* @param {Object} doc
* @param {Object} item
* @param {Array} template
* @param {Boolean} isRoot
* @return {Object}
*/
function mergeItem(doc, item, template, isRoot) {
var href = doc.href = get('href', item);
get('links', item, []).forEach(function(link) {
var rel = get('rel', link);
if (!rel) return;
var render = get('render', link);
var out = doc[rel] = {};
Object.keys(link).forEach(function(key) {
if (key === 'rel' || key === 'render') return;
if (key === 'href' && render === 'image') return out.src = link[key];
out[key] = link[key];
});
});
get('data', item, []).forEach(function(datum) {
var name = get('name', datum);
if (!name) return;
doc[name] = Object.keys(datum).reduce(function(acc, key) {
if (key === 'name') return acc;
if (key === 'value') acc.data = datum[key];
else acc[key] = datum[key];
return acc;
}, {});
});
if (template) doc.update = {
enctype: 'application/collection+json',
method: 'PUT',
action: href,
input: transformInputs(template, doc)
}
if (!isRoot) doc.delete = {
method: 'DELETE',
action: href
};
return doc;
}
/**
* Transform CJ inputs into hyper rep, filling in any values
*
* @param {Array} inputs
* @param {Object} values
* @return {Object}
*/
function transformInputs(inputs, values) {
var hyperInputs = {};
inputs.forEach(mergeInput.bind(null, hyperInputs, values));
return hyperInputs;
}
/**
* Merge input into inputs
*
* @param {Object} inputs
* @param {Object} values
* @param {Object} input
*/
function mergeInput(inputs, values, input) {
var name = get('name', input);
if (!name) return;
var out = inputs[name] = {};
Object.keys(input).forEach(function(key) {
if (key === 'name') return;
if (!values || key !== 'value') return out[key] = input[key];
var value = values[name];
if (!value || typeof value !== 'object') return out.value = value;
out.value = value.href || value.src || value.data;
});
}
/**
* Gracefully get a value
*
* @param {String} key
* @param {Any} obj
* @param {Any} fallback
* @return {Any}
*/
function get(key, obj, fallback) {
if (!obj) return undefined;
if (obj.hasOwnProperty(key)) return obj[key];
return fallback;
}
|
'use strict';
/* Services */
angular.module('learny.services.feedback', ['ngResource','ngQuill'])
// .factory('Posts', function($resource){
// return $resource("http://localhost:3010/post");
// })
|
exports = module.exports = require('./libs/duoshuo');
|
module.exports = {
extends: ['airbnb-base'],
env: {
browser: true,
},
rules: {
indent: ['error', 4, { SwitchCase: 1 }],
'max-len': ['error', 120],
'import/no-webpack-loader-syntax': 0,
'import/no-unresolved': 0,
'func-names': 0,
'no-underscore-dangle': 0,
'global-require': 0,
'no-param-reassign': 0,
'prefer-rest-params': 0,
'prefer-spread': 0,
'no-plusplus': 0,
'no-bitwise': 0,
'no-continue': 0,
'no-console': 0,
'prefer-destructuring': 0,
'no-prototype-builtins': 0,
'no-restricted-properties': 0,
'no-use-before-define': 0,
'no-loop-func': 0,
},
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:0b131b29be32b112ab61502badd4be2664c53d9a0b26fb605a1e86dd5e4c2c0c
size 4766
|
var jsdom = require("jsdom").jsdom;
global.document = jsdom('<html><body></body></html>');
global.window = global.document.createWindow();
global.navigator = global.window.navigator;
global.ko = require('knockout-client');
global.jQuery = require('jQuery');
require(__dirname + '/../src/ko.sidekick')
|
import React from 'react/addons';
import TimeAgo from 'react-timeago';
import Dialog from '../../components/dialog';
import Avatar from '../../components/avatar';
import Scrollable from './scrollable';
/**
*
*/
export default React.createClass({
mixins: [ React.addons.PureRenderMixin, React.addons.LinkedStateMixin ],
propTypes: {
board: (props) => {
if(!props.board instanceof Board) throw new Error();
},
onDismiss: React.PropTypes.func.isRequired
},
getInitialState() {
return {
}
},
submit(event) {
event.preventDefault();
return this.props.onDismiss();
},
render() {
let board = this.props.board;
let members = board.members.sort(function(x, y) {
return new Date(y.lastSeen) - new Date(x.lastSeen);
});
members = members.sort(function(x, y) {
return (x.isActive === y.isActive)? 0 : x.isActive? -1 : 1;
});
return (
<Dialog className="dialog-board-members"
onDismiss={this.props.onDismiss}>
<section className="dialog-header">
Board members
</section>
<section className="dialog-content">
<section className="dialog-members">
<Scrollable>
<section className="dialog-member-list">
{
members.map(function(member) {
// Sort of dumb fix for user sometimes being a Map
// instead of a Record. Should investigate further...
let user = member.get('user').toJS();
let name = user.username || user.name;
let isActive = member.get('isActive');
let avatarURL = user.avatar;
let userRole = member.get('role');
return (
<div className={isActive ? "member-info-online" : "member-info-offline" }>
<Avatar size={32} name={name}
imageurl={avatarURL}
usertype={userRole}
isOnline={isActive}>
</Avatar>
<div className="user-name" title={name}>
{name}
</div>
{
!isActive ?
(
<div className="user-last-seen">
Seen {React.createElement(TimeAgo, {date: member.get('lastSeen')})}
</div>
) :
null
}
</div>
);
})
}
</section>
</Scrollable>
</section>
<section className="dialog-footer">
<button className="btn-primary" onClick={this.submit}>
Done
</button>
</section>
</section>
</Dialog>
);
}
});
|
var gulp = require('gulp'),
requirejs = require('requirejs'),
htmlmin = require('gulp-htmlmin');
htmlreplace = require('gulp-html-replace');
gulp.task("requirejs", function (done) {
requirejs.optimize({
"baseUrl": 'dev/scripts/lib',
//"generateSourceMaps": true,
"include": [
"../../../vendor/requirejs/require",
],
"name" : '../main',
"optimize": "uglify2",
"out": 'dist/main-build.js',
"paths": {
"jquery" : '../../../vendor/jquery/dist/jquery',
"lodash" : '../../../vendor/lodash/lodash'
},
// for source maps
"preserveLicenseComments": false,
"wrapShim": false
}, function () {
done();
}, done);
});
gulp.task('default', ['requirejs'], function(){
gulp.src('dev/index.htm')
.pipe(htmlreplace({'requirejs': 'main-build.js'}))
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest('dist/'));
});
|
var Parser = {
commands: [],
orders: [],
parse: function(string) {
var command = this.prepare(string, this.orders);
return this.run(command);
},
run: function(command) {
switch (command[0]) {
case 'ls':
command.push('-h');
command.push('--color=auto');
return {
type: 'command',
value: command.shift(),
pars: command
};
case 'xdg-open':
return {
type: 'command',
value: command.shift(),
pars: command
};
case 'exit':
case 'bye':
case 'quit':
return {
type: 'exit',
value: null,
pars: ''
};
default:
return {
type: 'invalid',
value: command,
pars: ''
};
}
},
prepare: function(string, orders) {
var c = null;
for (var i = 0; i < orders.length; i++) {
if (c = this.fit(string, orders[i])) {
return c;
}
}
return string.split(' ');
},
fit: function(string, entry) {
if (entry.request.exec(string)) {
var command = [entry.command];
command.push(string.replace(entry.request, entry.rep));
return command;
}
return null;
}
};
Parser.orders.push({
request: /(abra|abrir|mostre|mostrar) (o |a |os |as |um |uma |uns |umas |)([^ ]*^)/,
rep: '$3',
command: 'xdg-open'
}, {
request: /(pesquise|pesquisar) (pelo|pela|por|o|a|os|as|um|uma|uns|umas|) *(.*)/,
rep: 'http://google.com/search?q=$3',
command: 'xdg-open'
}, {
request: /(abra|abrir|mostre|mostrar|) *(o|a|os|as|um|uma|uns|umas|) *(wiki) (do |da |dos |das |)(.*)/,
rep: 'http://pt.wikipedia.org/wiki/$5',
command: 'xdg-open'
});
module.exports = Parser;
|
import React from 'react';
import configureStore from 'redux-mock-store';
import sinon from 'sinon';
import expect from 'expect';
import thunk from 'redux-thunk';
import { shallow, mount } from 'enzyme';
import RegisterForm from '../components/RegisterForm';
import RegisterContainer from '../components/Register';
import Preloader from '../components/Preloader';
const initialRegisterState = {
register: {
formState: {
username: '',
password: '',
email: ''
},
error: '',
sending: false,
loggedIn: false,
currentlySending: false
}
};
const push = jest.fn();
const history = {
push
};
const match = {
params: 1
};
const FakeErrorMessage = React.createClass({
render: () => <div>Error Message</div>,
});
const FakeRegisterForm = React.createClass({
render: () => <div>Login Form</div>,
});
const FakePreloader = React.createClass({
render: () => <div>Login Form</div>,
});
RegisterForm.__Rewire__('ErrorMessage', FakeErrorMessage);
RegisterContainer.__Rewire__('RegisterForm', FakeRegisterForm);
RegisterContainer.__Rewire__('Preloader', FakePreloader);
// jest.mock('browserMocks');
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('Login Form component', () => {
const data = {
username: 'albert',
password: 'albert',
email: 'albert@gmail.com'
};
const onSubmit = jest.fn();
const dispatch = jest.fn();
it('should have four(4) div html element', () => {
const wrapper = shallow(<RegisterForm
data={data}
error=''
onSubmit={onSubmit}
dispatch={dispatch}
/>);
expect(wrapper.find('div').length).toEqual(4);
});
it('should have one(1) form html element', () => {
const wrapper = shallow(<RegisterForm
data={data}
error=''
onSubmit={onSubmit}
dispatch={dispatch}
/>);
expect(wrapper.find('form').length).toEqual(1);
});
it('should have three(3) input html element', () => {
const wrapper = shallow(<RegisterForm
data={data}
error=''
onSubmit={onSubmit}
dispatch={dispatch}
/>);
expect(wrapper.find('input').length).toEqual(3);
});
it('should have one(1) button html element', () => {
const wrapper = shallow(<RegisterForm
data={data}
error=''
onSubmit={onSubmit}
dispatch={dispatch}
/>);
expect(wrapper.find('button').length).toEqual(1);
});
it('should call onSubmit() when form is submitted', () => {
const preventDefault = jest.fn();
const event = {
preventDefault
};
sinon.stub(document, 'getElementById');
document.getElementById.withArgs('username').returns('');
document.getElementById.withArgs('password').returns('');
document.getElementById.withArgs('email').returns('');
sinon.spy(RegisterForm.prototype, 'onSubmit');
const wrapper = shallow(<RegisterForm
data={data}
error=''
onSubmit={onSubmit}
dispatch={dispatch}
/>);
wrapper.find('form').simulate('submit', event);
expect(RegisterForm.prototype.onSubmit.calledOnce).toEqual(true);
});
it('should have one(1) ErrorMessage component', () => {
const wrapper = shallow(<RegisterForm
data={data}
error='Type Error'
onSubmit={onSubmit}
dispatch={dispatch}
/>);
expect(wrapper.find(FakeErrorMessage).length).toEqual(1);
});
});
describe('Register Containers', () => {
const store = mockStore(initialRegisterState);
it('should have four(4) div html', () => {
const wrapper = mount(<RegisterContainer store={store} history={history} match={match} />);
expect(wrapper.find('div').length).toEqual(4);
});
it('should have one(1) RegisterForm component', () => {
const wrapper = mount(<RegisterContainer store={store} history={history} match={match} />);
expect(wrapper.find(FakeRegisterForm).length).toEqual(1);
});
it('should have one(1) Preloader component', () => {
const errorState = {
register: {
formState: {
username: '',
password: ''
},
error: '',
sending: false,
loggedIn: false,
currentlySending: true
}
};
const errorStore = mockStore(errorState);
const wrapper = mount(<RegisterContainer store={errorStore} history={history} match={match} />);
expect(wrapper.find(FakePreloader).length).toEqual(1);
});
it('should call componentWillReceiveProps once', () => {
const nextProps = {
data: {
register: {
username: 'albert',
password: 'Machine Learning',
email: 'albert',
loggedIn: true
}
}
};
sinon.spy(RegisterContainer.prototype, 'componentWillReceiveProps');
const wrapper = mount(<RegisterContainer store={store} history={history} match={match} />);
const instance = wrapper.instance();
instance.componentWillReceiveProps(nextProps);
expect(RegisterContainer.prototype.componentWillReceiveProps.calledOnce).toEqual(true);
});
});
|
/**
* Created by ceprei2598 on 2016/5/9.
*/
define(['text!../html/CompanyDetailView.html', 'config', 'jquery', 'jquerymobile'], function (CompanyDetailView, config, $) {
var CompanyDetailViewCodeBehind = function (code) {
var self = this;
$(function () {
$("#page-companydetail").html(CompanyDetailView);
$.post(config.baseUrl + config.codeCompanyAppFind, {companyCode: code})
.done(function (json, textStatus, jqXHR) {
var baseId = 'table-company-detail-';
$('#' + baseId + "item").html(json.obj.item);
$('#' + baseId + "itemEasy").html(json.obj.itemEasy);
$('#' + baseId + "item2").html(json.obj.item2);
$('#' + baseId + "code").html(json.obj.code);
$('#' + baseId + "codeCompanyNature").html(json.obj.codeCompanyNature);
$('#' + baseId + "province").html(json.obj.province);
$('#' + baseId + "city").html(json.obj.city);
$('#' + baseId + "location").html(json.obj.location);
$('#' + baseId + "zipCode").html(json.obj.zipCode);
$('#' + baseId + "netAddress").html(json.obj.netAddress);
$('#' + baseId + "OperationDesc").html(json.obj.operationDesc);
if(typeof json.obj.pathCompanyphotos !== "undefined"){
$('#' + baseId + "pathCompanyphotos").attr('src', encodeURI(config.baseGetFileUrl + json.obj.pathCompanyphotos));
}
});
$.mobile.changePage("#page-companydetail");
});
};
return CompanyDetailViewCodeBehind;
});
|
// relevant: https://github.com/jprichardson/node-fs-extra/issues/89
// come up with better file name
var assert = require('assert')
var fs = require('fs')
var path = require('path')
var os = require('os')
var fse = require(process.cwd())
/* global afterEach, beforeEach, describe, it */
describe('copy / gh #89', function () {
var TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy-gh-89')
beforeEach(function (done) {
fse.emptyDir(TEST_DIR, done)
})
afterEach(function (done) {
fse.remove(TEST_DIR, done)
})
it('should...', function (done) {
var A = path.join(TEST_DIR, 'A')
var B = path.join(TEST_DIR, 'B')
fs.mkdirSync(A)
fs.mkdirSync(B)
var one = path.join(A, 'one.txt')
var two = path.join(A, 'two.txt')
var three = path.join(B, 'three.txt')
var four = path.join(B, 'four.txt')
fs.writeFileSync(one, '1')
fs.writeFileSync(two, '2')
fs.writeFileSync(three, '3')
fs.writeFileSync(four, '4')
var C = path.join(TEST_DIR, 'C')
fse.copy(A, C, function (err) {
if (err) return done(err)
fse.copy(B, C, function (err) {
if (err) return done(err)
assert(fs.existsSync(path.join(C, 'one.txt')))
assert(fs.existsSync(path.join(C, 'two.txt')))
assert(fs.existsSync(path.join(C, 'three.txt')))
assert(fs.existsSync(path.join(C, 'four.txt')))
done()
})
})
})
})
|
import crypto from 'crypto';
import assert from 'assert';
import { Serializer, Deserializer } from '../src';
describe('Deserializer', function() {
let serializer,
deserializer;
beforeEach(() => {
serializer = new Serializer();
});
afterEach(() => {
deserializer = null;
});
describe('readBytes()', function() {
let bytes1,
bytes_3_length;
beforeEach(() => {
bytes1 = crypto.randomBytes(8);
bytes_3_length = crypto.randomBytes(3);
});
it('should ignore padding', function() {
serializer.writeBytes(bytes_3_length);
serializer.writeBytes(bytes1);
deserializer = new Deserializer(serializer.getBuffer());
assert.ok(deserializer.readBytes().equals(bytes_3_length));
assert.ok(deserializer.readBytes().equals(bytes1));
assert.equal(deserializer.offset, deserializer.buffer.byteLength);
});
});
describe('readBool()', function() {
it('should throw if unexpected value is give for bools', function() {
const buffer = Buffer.alloc(1);
buffer.writeUInt8(2, 0);
deserializer = new Deserializer(buffer);
assert.throws(function() {
deserializer.readBool();
});
});
});
});
|
var express = require('express')
var serve = require('serve-static')
var https = require('https')
var path = require('path')
var fs = require('fs')
var app = express()
const PORT = 8088
// html/images dirs
var html = path.join(__dirname, 'public', 'index.html')
var public = path.join(__dirname, 'public')
var images = path.join(__dirname, '..', '..', '..', 'public', 'myApps', 'pictures')
// https keys
var options = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./key-cert.pem')
}
app.use(express.static(public))
app.use(express.static(html))
app.use(serve(images))
app.get('*', function (req, res) {
res.sendFile(html)
})
var server = https.createServer(options, app).listen(PORT)
// var udpServer = require('./lib/udp_server');
// var procServer = require('./lib/proc_uptime');
// udpServer.listen(server);
|
import React, {Component, PropTypes} from 'react'
import {Link} from 'react-router'
import classNames from 'classnames'
import {BASE_PATH} from '../constants/common';
import path from 'path';
class Sidebar extends Component {
static propType = {
activeRouteName : PropTypes.string.isRequired,
organizationShortname : PropTypes.string.isRequired,
showMenu : PropTypes.func.isRequired
};
render() {
const {organizationShortname} = this.props;
let classes = classNames({
'list-col column side-menu hidden-print': true
});
const menuList = [
{
name :'Dashboard',
targetLink : path.join(BASE_PATH,organizationShortname+'/'),
className : 'icon-dashboard'
},
{
name :'Senopati',
targetLink : path.join(BASE_PATH,organizationShortname+'/senopati'),
className : 'icon-senopati'
}
];
return (
<section className={classes}>
<nav className="app_tabs">
<ul>
{
menuList.map((menu,index)=> {
return (
<li {...(this.props.activeRouteName.toLowerCase() === menu.name.toLowerCase() ? {className: 'active'} : {})} key={'sidebar-menu-'+index}>
<Link className={menu.className} to={menu.targetLink} onClick={this.props.showMenu}>{menu.name}</Link>
</li>
)
})
}
</ul>
</nav>
</section>
)
}
}
export default Sidebar
|
var defaultReplacement = function(replacement) {
return replacement == '' ? '' : replacement || '-';
};
slugify = function(string, replacement) {
var replacement = defaultReplacement(replacement),
out = '';
if (!_.isString(string)) {
return '';
}
_.forEach(string.split(''), function(ch) {
if (_.has(CHAR_MAP, ch)) {
ch = CHAR_MAP[ch];
}
ch = ch.replace(/[^\w\s$\*\_\+~\.\(\)\-]/g, ''); // allowed
out += ch;
});
out = out.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces
out = out.replace(/[-\s]+/g, replacement); // convert spaces
out.replace("#{replacement}$", ''); // remove trailing separator
return out.toLowerCase();
};
if (Meteor.isClient) {
Template.registerHelper('slugify', function(string, replacement) {
var replacement = defaultReplacement(replacement);
return slugify(string, replacement);
});
}
|
var systemObject = {
run : function() {
this.content($('#navigation ul li a'));
this.pop();
this.runTimer(1);
},
content : function(obj) {
obj.live('click', function(e) {
var thisUrl = $(this).attr('href');
var thisTitle = $(this).attr('title');
systemObject.load(thisUrl);
window.history.pushState(null, thisTitle, thisUrl);
e.preventDefault();
});
},
pop : function() {
window.onpopstate = function() {
systemObject.load(location.pathname);
};
},
load : function(url) {
url = url === '/' ? '/ygwyg' : url;
jQuery.getJSON(url, { ajax : 1 }, function(data) {
jQuery.each(data, function(k, v) {
$('#' + k + ' section').fadeOut(200, function() {
$(this).replaceWith($(v).hide().fadeIn(200));
});
});
});
},
timer : function(n) {
setTimeout(function() {
$('#timer').html(n);
systemObject.runTimer(n);
}, 1000);
},
runTimer : function(n) {
var thisNumber = parseInt(n, 10) + 1;
systemObject.timer(thisNumber);
}
};
$(function() {
systemObject.run();
});
|
import { Helmet } from "react-helmet"
export const onRenderBody = ({
setHeadComponents,
setHtmlAttributes,
setBodyAttributes,
}) => {
const helmet = Helmet.renderStatic()
// These action functions were added partway through the Gatsby 1.x cycle.
if (setHtmlAttributes) {
setHtmlAttributes(helmet.htmlAttributes.toComponent())
}
if (setBodyAttributes) {
setBodyAttributes(helmet.bodyAttributes.toComponent())
}
setHeadComponents([
helmet.title.toComponent(),
helmet.link.toComponent(),
helmet.meta.toComponent(),
helmet.noscript.toComponent(),
helmet.script.toComponent(),
helmet.style.toComponent(),
helmet.base.toComponent(),
])
}
|
import {SF, PLANET_RADIUS} from '../constants.js';
import interactionMesh from './interaction-mesh.js';
export const VELOCITY_LEN_SCALE = SF * 0.05;
const DEF_COLOR = 0x00ff00;
const DEF_EMISSIVE = 0x007700;
const HIGHLIGHT_COLOR = 0xff0000;
const HIGHLIGHT_EMISSIVE = 0xbb3333;
export default class {
constructor() {
let radius = PLANET_RADIUS * SF / 4;
let height = PLANET_RADIUS * SF * 4;
let headRadius = radius * 3;
let headHeight = height / 3;
// Set height to 1, as it will be scaled later (#setProps).
this.arrowGeometry = new THREE.CylinderGeometry(radius, radius, 1, 8);
this.arrowMaterial = new THREE.MeshPhongMaterial({color: DEF_COLOR, emissive: DEF_EMISSIVE});
this.arrowMesh = new THREE.Mesh(this.arrowGeometry, this.arrowMaterial);
this.headGeometry = new THREE.CylinderGeometry(headRadius, 0, headHeight, 16);
this.headMaterial = new THREE.MeshPhongMaterial({color: DEF_COLOR, emissive: DEF_EMISSIVE});
this.headMesh = new THREE.Mesh(this.headGeometry, this.headMaterial);
this.interactionMesh = interactionMesh();
this.headMesh.add(this.interactionMesh);
this.pivot = new THREE.Object3D();
this.pivot.add(this.headMesh);
this.pivot.add(this.arrowMesh);
}
get rootObject() {
return this.pivot;
}
get position() {
return this.pivot.position;
}
setProps(planet) {
this.pivot.rotation.z = Math.atan2(planet.vx, -planet.vy);
let len = Math.sqrt(planet.vx * planet.vx + planet.vy * planet.vy) * VELOCITY_LEN_SCALE;
this.arrowMesh.scale.y = len;
this.arrowMesh.position.y = -len * 0.5;
this.headMesh.position.y = -len;
}
setHighlighted(v) {
this.headMaterial.color.setHex(v ? HIGHLIGHT_COLOR : DEF_COLOR);
this.headMaterial.emissive.setHex(v ? HIGHLIGHT_EMISSIVE : DEF_EMISSIVE);
}
}
|
define("utils", {
//
// Given an object, replaces all string attributes in the object (or deeply nested)
// that match the given regex with the given replacement string.
// Example:
// ( {a : "foo", {b: "foobar"} }, /foo/, "off" ) ==> {a: "off", {b: "offbar"}}
//
replaceStringAttributes : function recursiveReplaceStringAttributes(obj, regex, replaceString) {
_.each(obj, function(value, key) {
if (_.isObject(value)) {
// Recursive call
recursiveReplaceStringAttributes(value, regex, replaceString);
} else if (_.isString(value) && value.match(regex)) {
// Replace the path
obj[key] = value.replace(regex, replaceString);
}
});
},
//
// Replaces URLs for a given collection of assets by providing
// a replacements object that maps the assets' values to new values
//
replaceAssetUrls : function(assets, replacements) {
var _this = this;
_.each(assets, function(url, name) {
if (_.isObject(url)) {
_this.replaceAssetUrls(url, replacements);
} else if (replacements[url]) {
// Replace the asset value with the new mapped value
assets[name] = replacements[url];
}
});
},
// Find all theme attributes with URLs by walking the template object.
// Add a prefix to these URLs
augmentThemeUrls : function(templateObj, themeObj, prefixPath) {
var _this = this;
_.each(templateObj, function(templateValue, templateKey) {
var themeValue = themeObj[templateKey];
if (_.isObject(templateValue)) {
switch (templateValue.type) {
case "image":
themeObj[templateKey] = prefixPath + "/" + themeValue;
break;
case "backgroundImage":
themeObj[templateKey] = prefixPath + "/" + themeValue;
break;
case "font":
themeObj[templateKey].url = prefixPath + "/" + themeValue.url;
break;
case "css":
break;
default:
_this.augmentThemeUrls(templateValue, themeValue, prefixPath);
}
}
});
},
// Set the value of deeply nested attributes
// Example:
// ( {a : {b : {c :10}}}, ["a", "b", "c"], 20 ) ==> {a : {b : {c :20}}}
setByKeyChain : function(target, keychain, value) {
// Handle dot-delimited sting keychains.
if (_.isString(keychain)) keychain = keychain.split(".");
var obj = target;
_.each(keychain, function(key, i) {
if (i == keychain.length - 1) {
obj[key] = value;
} else {
(obj[key]) || (obj[key] = {});
obj = obj[key];
}
});
},
// Gets the value at any depth in a nested object based on the
// path described by the given keychain.
//
// Example: {a : {b : c : "10"}}, "a[b][c]" ==> "10"
//
// Based on https://github.com/documentcloud/underscore-contrib
//
getByKeychain: function getPath (obj, keychain) {
// If we have reached an undefined property
// then stop executing and return undefined
if (obj === undefined) return void 0;
// Handle dot-delimited sting keychains.
if (_.isString(keychain)) keychain = keychain.split(".");
// If the path array has no more elements, we've reached
// the intended property and return its value
if (keychain.length === 0) return obj;
// If we still have elements in the path array and the current
// value is null, stop executing and return undefined
if (obj === null) return void 0;
return getPath(obj[_.first(keychain)], _.rest(keychain));
},
//
// Given the template and theme JSONs, manipulates the target object to
// hold a mapping of {<asset keychain> : <name>}
//
// i.e. {"pages.goods.list.background" : "img/bg.png"}
//
createThemeAssetMap : function createThemeAssetMapRecursive(templateObj, themeObj, target, keychain) {
_.each(templateObj, function(templateValue, templateKey) {
var themeValue = themeObj[templateKey];
// Check that theme value is defined. This is to allow
// Template attributes that a certain theme chooses not to use
if (_.isObject(templateValue) && !_.isUndefined(themeValue)) {
var currentKeychain = keychain + "." + templateKey;
if (_.contains(["image", "backgroundImage", "font"], templateValue.type)) {
currentKeychain = currentKeychain.replace(".", "");
target[currentKeychain] = themeValue;
} else {
createThemeAssetMapRecursive(templateValue, themeValue, target, currentKeychain);
}
}
});
}
});
|
export class KnowhowCtrl {
constructor($scope, $location, $routeParams, $anchorScroll) {
$scope.term = $routeParams.term;
$anchorScroll.yOffset = 0; // always scroll by extra pixels
$location.hash($scope.term);
let images = [
"wall_t13",
"wall_schuko",
"caravan",
"wall_cee",
"cee64",
"auto_type1",
"auto_type2",
"auto_type3",
"auto_chademo",
"auto_ccs",
"tesla-supercharger"
];
$scope.image = [];
for (let i = 0; i < images.length; i++) {
$scope.image[images[i]] = require(`../../images/${images[i]}.jpg`);
}
}
}
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.9.0 (2021-08-26)
*/
(function () {
'use strict';
var global$1 = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global = tinymce.util.Tools.resolve('tinymce.Env');
var getSeparatorHtml = function (editor) {
return editor.getParam('pagebreak_separator', '<!-- pagebreak -->');
};
var shouldSplitBlock = function (editor) {
return editor.getParam('pagebreak_split_block', false);
};
var pageBreakClass = 'mce-pagebreak';
var getPlaceholderHtml = function (shouldSplitBlock) {
var html = '<img src="' + global.transparentSrc + '" class="' + pageBreakClass + '" data-mce-resize="false" data-mce-placeholder />';
return shouldSplitBlock ? '<p>' + html + '</p>' : html;
};
var setup$1 = function (editor) {
var separatorHtml = getSeparatorHtml(editor);
var shouldSplitBlock$1 = function () {
return shouldSplitBlock(editor);
};
var pageBreakSeparatorRegExp = new RegExp(separatorHtml.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function (a) {
return '\\' + a;
}), 'gi');
editor.on('BeforeSetContent', function (e) {
e.content = e.content.replace(pageBreakSeparatorRegExp, getPlaceholderHtml(shouldSplitBlock$1()));
});
editor.on('PreInit', function () {
editor.serializer.addNodeFilter('img', function (nodes) {
var i = nodes.length, node, className;
while (i--) {
node = nodes[i];
className = node.attr('class');
if (className && className.indexOf(pageBreakClass) !== -1) {
var parentNode = node.parent;
if (editor.schema.getBlockElements()[parentNode.name] && shouldSplitBlock$1()) {
parentNode.type = 3;
parentNode.value = separatorHtml;
parentNode.raw = true;
node.remove();
continue;
}
node.type = 3;
node.value = separatorHtml;
node.raw = true;
}
}
});
});
};
var register$1 = function (editor) {
editor.addCommand('mcePageBreak', function () {
editor.insertContent(getPlaceholderHtml(shouldSplitBlock(editor)));
});
};
var setup = function (editor) {
editor.on('ResolveName', function (e) {
if (e.target.nodeName === 'IMG' && editor.dom.hasClass(e.target, pageBreakClass)) {
e.name = 'pagebreak';
}
});
};
var register = function (editor) {
var onAction = function () {
return editor.execCommand('mcePageBreak');
};
editor.ui.registry.addButton('pagebreak', {
icon: 'page-break',
tooltip: 'Page break',
onAction: onAction
});
editor.ui.registry.addMenuItem('pagebreak', {
text: 'Page break',
icon: 'page-break',
onAction: onAction
});
};
function Plugin () {
global$1.add('pagebreak', function (editor) {
register$1(editor);
register(editor);
setup$1(editor);
setup(editor);
});
}
Plugin();
}());
|
/*
* Parse result-specific refract elements.
*
* General structure:
*
* + ParseResult
* + Annotation
*/
import apiDescription from 'minim-api-description';
export function namespace(options) {
const minim = options.base;
const { Element } = minim;
const StringElement = minim.getElementClass('string');
const ArrayElement = minim.getElementClass('array');
/**
* @class ParseResult
*
* @param {Array} content
* @param meta
* @param attributes
*
* @extends ArrayElement
*/
class ParseResult extends ArrayElement {
constructor(...args) {
super(...args);
this.element = 'parseResult';
}
/**
* @name api
* @type Category
* @memberof ParseResult.prototype
*/
get api() {
return this.children.filter(item => item.classes.contains('api')).first;
}
/**
* @name annotations
* @type ArraySlice
* @memberof ParseResult.prototype
*/
get annotations() {
return this.children.filter(item => item.element === 'annotation');
}
/**
* @name warnings
* @type ArraySlice
* @memberof ParseResult.prototype
*/
get warnings() {
return this.children
.filter(item => item.element === 'annotation' && item.classes.contains('warning'));
}
/**
* @name errors
* @type ArraySlice
* @memberof ParseResult.prototype
*/
get errors() {
return this.children
.filter(item => item.element === 'annotation' && item.classes.contains('error'));
}
}
/**
* @class Annotation
*
* @param {string} content
* @param meta
* @param attributes
*
* @extends StringElement
*/
class Annotation extends StringElement {
constructor(...args) {
super(...args);
this.element = 'annotation';
}
get code() {
return this.attributes.get('code');
}
set code(value) {
this.attributes.set('code', value);
}
}
/**
* @class SourceMap
*
* @param {Array} content
* @param meta
* @param attributes
*
* @extends ArrayElement
*/
class SourceMap extends minim.elements.Array {
constructor(...args) {
super(...args);
this.element = 'sourceMap';
}
// Override toValue because until Refract 1.0
// sourceMap is special element that contains array of array
// TODO Remove in next minor release
toValue() {
return this.content.map(value => value.map(element => element.toValue()));
}
}
/**
* @name sourceMapValue
* @type Array
* @memberof Element.prototype
*/
if (!Object.getOwnPropertyNames(Element.prototype).includes('sourceMapValue')) {
Object.defineProperty(Element.prototype, 'sourceMapValue', {
get() {
const sourceMap = this.attributes.get('sourceMap');
if (sourceMap) {
return sourceMap.first.toValue();
}
return undefined;
},
});
}
minim
.use(apiDescription)
.register('parseResult', ParseResult)
.register('annotation', Annotation)
.register('sourceMap', SourceMap);
}
export default { namespace };
|
var remark = require('remark');
var wrap = require('./dist/index.js');
var markdown = 'Hello, world!';
var result = remark().use(wrap, {width: 5}).process(markdown);
// Output:
console.log('md', result.contents);
|
/*!
* Star Rating Italian Translations
*
* This file must be loaded after 'star-rating.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* NOTE: this file must be saved in UTF-8 encoding.
*
* @see http://github.com/kartik-v/bootstrap-star-rating
* @author Kartik Visweswaran <kartikv2@gmail.com>
*/
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery', 'window', 'document'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'), window, document);
} else {
factory(window.jQuery, window, document);
}
}(function ($, window, document, undefined) {
"use strict";
$.fn.ratingLocales['it'] = {
defaultCaption: '{rating} Stelle',
starCaptions: {
0.5: 'Mezza Stella',
1: 'Una Stella',
1.5: 'Una Stella & Mezzo',
2: 'Due Stelle',
2.5: 'Due Stelle & Mezzo',
3: 'Tre Stelle',
3.5: 'Tre Stelle & Mezzo',
4: 'Quattro Stelle',
4.5: 'Quattro Stelle & Mezzo',
5: 'Cinque Stelle'
},
clearButtonTitle: 'Rimuovi',
clearCaption: 'Nessuna valutazione'
};
}));
|
'use strict';
const electron = require('electron');
const childProcess = require('child_process');
const app = electron.app; // Module to control application life.
const Menu = electron.Menu;
const BrowserWindow = electron.BrowserWindow;
const MenuItem = electron.MenuItem;
const Tray = electron.Tray;
const nativeImage = electron.nativeImage;
const UserPreferences = require('./preferences/userPreferences');
const server = require('./server');
const path = require('path');
require('./db');
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
// Global references
let appIcon;
let preferencesWindow;
let playerWindow;
app.on('ready', () => {
let img = nativeImage.createFromPath(process.cwd() + '/images/icon.png');
appIcon = new Tray(img);
let appInterfaceManuItem = new MenuItem({
label: 'Launch Player',
click() {
playerWindow.loadURL(`file://${__dirname}/views/library.html`);
playerWindow.show();
}
});
let item = new MenuItem({
label: 'Launch Web Interface',
click() {
childProcess.exec('open http://localhost:3000');
}
});
playerWindow = new BrowserWindow({ width: 500, height: 600, show: false, resizable: true });
preferencesWindow = new BrowserWindow({ width: 500, height: 600, show: false, resizable: false });
let launchPreferences = function() {
let configPath = path.resolve(__dirname, '../config.json');
console.log(configPath);
UserPreferences.loadFromFile(configPath).then(() => {
preferencesWindow.loadURL('file://' + __dirname + '/views/preferences.html');
preferencesWindow.show();
}).catch((err) => {
console.error(err);
});
};
var contextMenu = Menu.buildFromTemplate([
new MenuItem({ label: 'Preferences...', click: launchPreferences }),
new MenuItem({ type: 'separator' }),
appInterfaceManuItem,
item,
new MenuItem({ type: 'separator' }),
new MenuItem({ label: 'Quit', click: () => app.quit() })
]);
appIcon.setToolTip('This is my application.');
appIcon.setContextMenu(contextMenu);
server.run();
launchPreferences();
});
|
jsonp({"cep":"35348000","cidade":"Pingo-D'\u00c1gua","uf":"MG","estado":"Minas Gerais"});
|
import semver from 'semver'
import { getCachedResource } from '../../core/base-service/resource-cache.js'
// TODO: Incorporate this schema.
// const schema = Joi.object()
// .keys({
// offers: Joi.array()
// .items(
// Joi.object()
// .keys({
// version: Joi.string()
// .regex(/^\d+(\.\d+)?(\.\d+)?$/)
// .required(),
// })
// .required()
// )
// .required(),
// })
// .required()
async function getOfferedVersions() {
return getCachedResource({
url: 'https://api.wordpress.org/core/version-check/1.7/',
scraper: json => json.offers.map(v => v.version),
})
}
function toSemver(v) {
const parts = v.split('-')
if (parts.length > 2) {
return v
}
const version = parts[0]
const suffix = parts[1] ? parts[1] : ''
if (version.split('.').length === 2) {
return suffix !== '' ? `${version}.0-${suffix}` : `${version}.0`
} else {
return v
}
}
async function versionColorForWordpressVersion(version) {
const offeredVersions = await getOfferedVersions()
const latestVersion = toSemver(offeredVersions[0])
version = toSemver(version)
if (!semver.valid(latestVersion)) return 'lightgrey'
if (!semver.valid(version)) return 'lightgrey'
if (version === latestVersion || semver.gtr(version, latestVersion)) {
return 'brightgreen'
} else if (offeredVersions.includes(version)) {
return 'orange'
} else {
return 'yellow'
}
}
export { toSemver, getOfferedVersions, versionColorForWordpressVersion }
|
import React from 'react'
import Header from './Header';
import EchartSkill from './EchartSkill';
class About extends React.Component {
render () {
let styles={
root:{
width:'100vw',
height:'100vh',
}
}
return(
<div className="echartDiv" style={styles.root}>
<Header />
<EchartSkill />
</div>
)
}
}
export default About;
|
import { toggleValues } from 'platform/site-wide/feature-toggles/selectors';
import {
selectPatientFacilities,
selectVAPResidentialAddress,
} from 'platform/user/selectors';
export const selectIsCernerOnlyPatient = state =>
!!selectPatientFacilities(state)?.every(
f => f.isCerner && f.usesCernerAppointments,
);
export const selectIsCernerPatient = state =>
selectPatientFacilities(state)?.some(
f => f.isCerner && f.usesCernerAppointments,
);
export const selectRegisteredCernerFacilityIds = state =>
selectPatientFacilities(state)
?.filter(f => f.isCerner && f.usesCernerAppointments)
.map(f => f.facilityId) || [];
export const selectIsRegisteredToSacramentoVA = state =>
selectPatientFacilities(state)?.some(f => f.facilityId === '612');
export const selectFeatureApplication = state =>
toggleValues(state).vaOnlineScheduling;
export const selectFeatureCancel = state =>
toggleValues(state).vaOnlineSchedulingCancel;
export const selectFeatureRequests = state =>
toggleValues(state).vaOnlineSchedulingRequests;
export const selectFeatureCommunityCare = state =>
toggleValues(state).vaOnlineSchedulingCommunityCare;
export const selectFeatureDirectScheduling = state =>
toggleValues(state).vaOnlineSchedulingDirect;
export const selectFeatureToggleLoading = state => toggleValues(state).loading;
// Use flat facility page for non Cerner patients
export const selectUseFlatFacilityPage = state => !selectIsCernerPatient(state);
export const selectHasVAPResidentialAddress = state =>
!!selectVAPResidentialAddress(state)?.addressLine1;
export const selectSystemIds = state =>
selectPatientFacilities(state)?.map(f => f.facilityId) || null;
export const selectFeatureFacilitySelectionV22 = state =>
toggleValues(state).vaOnlineFacilitySelectionV22;
export const selectFeatureUnenrolledVaccine = state =>
toggleValues(state).vaOnlineSchedulingUnenrolledVaccine;
export const selectFeatureVAOSServiceRequests = state =>
toggleValues(state).vaOnlineSchedulingVAOSServiceRequests;
export const selectFeatureVAOSServiceVAAppointments = state =>
toggleValues(state).vaOnlineSchedulingVAOSServiceVAAppointments;
export const selectFeatureVAOSServiceCCAppointments = state =>
toggleValues(state).vaOnlineSchedulingVAOSServiceCCAppointments;
export const selectFeatureFacilitiesServiceV2 = state =>
toggleValues(state).vaOnlineSchedulingFacilitiesServiceV2;
export const selectFeatureVariantTesting = state =>
toggleValues(state).vaOnlineSchedulingVariantTesting;
export const selectFeaturePocHealthApt = state =>
toggleValues(state).vaOnlineSchedulingPocHealthApt;
export const selectFeatureStatusImprovement = state =>
toggleValues(state).vaOnlineSchedulingStatusImprovement;
|
var sizes = {
width: 960,
height: 500,
padding: 30
};
var formatNumber = d3.format(",.0f"),
asMoney = d3.format("$,.2f");
format = function(d) { return "$" + formatNumber(d); },
color = d3.scale.category10();
var svg = d3.select('#chart')
.append('svg')
.attr('width', sizes.width)
.attr('height', sizes.height)
;
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([sizes.width - sizes.padding, sizes.height - sizes.padding])
;
var path = sankey.link();
d3.json("data.json", function(data){
sankey
.nodes(data.nodes)
.links(data.links)
.layout(32);
var link = svg.append('g')
.selectAll('.links')
.data(data.links)
.enter()
.append('path')
.attr('class', 'link')
.attr('d', path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
;
link.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });
var node = svg.append("g").selectAll(".node")
.data(data.nodes)
.enter()
.append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
;
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) { return d.name + "\n" + format(d.value); });
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) {
return d.name + " = " + asMoney(d.value);
})
.filter(function(d) { return d.x < sizes.width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(sizes.height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);}
});
|
import {
FETCH_ENROLLMENT_STATUS_STARTED,
FETCH_ENROLLMENT_STATUS_SUCCEEDED,
FETCH_ENROLLMENT_STATUS_FAILED,
FETCH_DISMISSED_HCA_NOTIFICATION_STARTED,
FETCH_DISMISSED_HCA_NOTIFICATION_SUCCEEDED,
FETCH_DISMISSED_HCA_NOTIFICATION_FAILED,
SET_DISMISSED_HCA_NOTIFICATION,
SHOW_HCA_REAPPLY_CONTENT,
} from '../actions';
import { HCA_ENROLLMENT_STATUSES } from '../constants';
const initialState = {
applicationDate: null,
enrollmentDate: null,
preferredFacility: null,
enrollmentStatus: null,
enrollmentStatusEffectiveDate: null,
dismissedNotificationDate: null,
hasServerError: false,
isLoadingApplicationStatus: false,
isLoadingDismissedNotification: false,
isUserInMVI: false,
loginRequired: false,
noESRRecordFound: false,
showHCAReapplyContent: false,
};
function hcaEnrollmentStatus(state = initialState, action) {
switch (action.type) {
case FETCH_ENROLLMENT_STATUS_STARTED:
return { ...state, isLoadingApplicationStatus: true };
case FETCH_ENROLLMENT_STATUS_SUCCEEDED: {
const {
parsedStatus,
applicationDate,
effectiveDate: enrollmentStatusEffectiveDate,
enrollmentDate,
preferredFacility,
} = action.data;
const enrollmentStatus = parsedStatus;
const isInESR =
enrollmentStatus !== HCA_ENROLLMENT_STATUSES.noneOfTheAbove;
return {
...state,
hasServerError: false,
enrollmentStatus,
enrollmentStatusEffectiveDate,
applicationDate,
enrollmentDate,
preferredFacility,
loginRequired: isInESR,
noESRRecordFound: !isInESR,
isLoadingApplicationStatus: false,
isUserInMVI: true,
};
}
case FETCH_ENROLLMENT_STATUS_FAILED: {
const { errors } = action;
const noESRRecordFound =
errors && errors.some(error => error.code === '404');
const hasRateLimitError =
errors && errors.some(error => error.code === '429');
// if the error is not given special handling, treat it like a server error
const hasServerError = !noESRRecordFound && !hasRateLimitError;
return {
...state,
hasServerError,
isLoadingApplicationStatus: false,
loginRequired: hasRateLimitError,
noESRRecordFound,
};
}
case SHOW_HCA_REAPPLY_CONTENT:
return { ...state, showHCAReapplyContent: true };
case FETCH_DISMISSED_HCA_NOTIFICATION_STARTED:
return { ...state, isLoadingDismissedNotification: true };
case FETCH_DISMISSED_HCA_NOTIFICATION_SUCCEEDED: {
const {
statusEffectiveAt: dismissedNotificationDate,
} = action.response.data.attributes;
return {
...state,
dismissedNotificationDate,
isLoadingDismissedNotification: false,
};
}
case FETCH_DISMISSED_HCA_NOTIFICATION_FAILED: {
return {
...state,
isLoadingDismissedNotification: false,
};
}
case SET_DISMISSED_HCA_NOTIFICATION: {
return {
...state,
dismissedNotificationDate: action.data,
};
}
default:
return state;
}
}
export default hcaEnrollmentStatus;
|
// Filename: models/deviceConfig.js
define([
'backbone'
], function(Backbone) {
var DeviceConfigurationModel = Backbone.Model.extend({
initialize: function(options, url) {
this.url = url;
}
});
return DeviceConfigurationModel;
});
|
// start the popup specefic scripts
// safe to use $
jQuery(document).ready(function($) {
var zillas = {
loadVals: function()
{
var shortcode = $('#_zilla_shortcode').text(),
uShortcode = shortcode;
// fill in the gaps eg {{param}}
$('.zilla-input').each(function() {
var input = $(this),
id = input.attr('id'),
id = id.replace('zilla_', ''), // gets rid of the zilla_ prefix
re = new RegExp("{{"+id+"}}","g");
uShortcode = uShortcode.replace(re, input.val());
});
// adds the filled-in shortcode as hidden input
$('#_zilla_ushortcode').remove();
$('#zilla-sc-form-table').prepend('<div id="_zilla_ushortcode" class="hidden">' + uShortcode + '</div>');
},
cLoadVals: function()
{
var shortcode = $('#_zilla_cshortcode').text(),
pShortcode = '';
shortcodes = '';
// fill in the gaps eg {{param}}
$('.child-clone-row').each(function() {
var row = $(this),
rShortcode = shortcode;
$('.zilla-cinput', this).each(function() {
var input = $(this),
id = input.attr('id'),
id = id.replace('zilla_', '') // gets rid of the zilla_ prefix
re = new RegExp("{{"+id+"}}","g");
rShortcode = rShortcode.replace(re, input.val());
});
shortcodes = shortcodes + rShortcode + "\n";
});
// adds the filled-in shortcode as hidden input
$('#_zilla_cshortcodes').remove();
$('.child-clone-rows').prepend('<div id="_zilla_cshortcodes" class="hidden">' + shortcodes + '</div>');
// add to parent shortcode
this.loadVals();
pShortcode = $('#_zilla_ushortcode').text().replace('{{child_shortcode}}', shortcodes);
// add updated parent shortcode
$('#_zilla_ushortcode').remove();
$('#zilla-sc-form-table').prepend('<div id="_zilla_ushortcode" class="hidden">' + pShortcode + '</div>');
},
children: function()
{
// assign the cloning plugin
$('.child-clone-rows').appendo({
subSelect: '> div.child-clone-row:last-child',
allowDelete: false,
focusFirst: false
});
// remove button
$('.child-clone-row-remove').live('click', function() {
var btn = $(this),
row = btn.parent();
if( $('.child-clone-row').size() > 1 )
{
row.remove();
}
else
{
alert('You need a minimum of one row');
}
return false;
});
// assign jUI sortable
$( ".child-clone-rows" ).sortable({
placeholder: "sortable-placeholder",
items: '.child-clone-row'
});
},
resizeTB: function()
{
var ajaxCont = $('#TB_ajaxContent'),
tbWindow = $('#TB_window'),
zillaPopup = $('#zilla-popup');
tbWindow.css({
//height: zillaPopup.outerHeight() + 50,
height: 550,
width: zillaPopup.outerWidth() +17,
marginLeft: -(zillaPopup.outerWidth()/2)
});
ajaxCont.css({
paddingTop: 0,
paddingLeft: 0,
paddingRight: 0,
height: 500,
width: 577,
//height: (tbWindow.outerHeight()-47),
overflow: 'auto', // IMPORTANT
//width: zillaPopup.outerWidth()
});
$('#zilla-popup').addClass('no_preview');
},
load: function()
{
var zillas = this,
popup = $('#zilla-popup'),
form = $('#zilla-sc-form', popup),
shortcode = $('#_zilla_shortcode', form).text(),
popupType = $('#_zilla_popup', form).text(),
uShortcode = '';
// resize TB
zillas.resizeTB();
$(window).resize(function() { zillas.resizeTB() });
// initialise
zillas.loadVals();
zillas.children();
zillas.cLoadVals();
// update on children value change
$('.zilla-cinput', form).live('change', function() {
zillas.cLoadVals();
});
// update on value change
$('.zilla-input', form).change(function() {
zillas.loadVals();
});
// when insert is clicked
$('.zilla-insert', form).click(function() {
if(window.tinyMCE)
{
window.tinyMCE.execInstanceCommand('content', 'mceInsertContent', false, $('#_zilla_ushortcode', form).html());
tb_remove();
}
});
}
}
// run
$('#zilla-popup').livequery( function() { zillas.load(); } );
});
|
module.exports = {
dist: {
options: {
cwd : '',
domainPath : '/languages',
exclude : [],
include : [],
mainFile : '',
potComments : '',
potFilename : 'required-wp-rating.pot',
potHeaders : {
poedit : true,
'x-poedit-keywordslist': true,
'report-msgid-bugs-to' : 'http://required.ch',
'last-translator' : 'required+',
'language-team' : 'required+'
},
processPot : null,
type : 'wp-plugin',
updateTimestamp: true
}
}
};
|
/*
Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colorbutton', 'sr', {
auto: 'Аутоматски',
bgColorTitle: 'Боја позадине',
colors: {
'000': 'Црно',
'800000': 'Бордо',
'8B4513': 'Браон',
'2F4F4F': 'Тамно тиркизно',
'008080': 'Tиркизно',
'000080': 'Кралјевско плаво',
'4B0082': 'Индиго плаво',
'696969': 'Сиво',
B22222: 'Цигла црвено',
A52A2A: 'Бакарно',
DAA520: 'Златно жуто',
'006400': 'Тамно зелено',
'40E0D0': 'Tиркизно',
'0000CD': 'Плаво',
'800080': 'Љубичасто',
'808080': 'Сиво',
F00: 'Црвено',
FF8C00: 'Тамно наранџасто',
FFD700: 'Златно',
'008000': 'Зелено',
'0FF': 'Циан',
'00F': 'Плаво',
EE82EE: 'Розе',
A9A9A9: 'Тамно сиво',
FFA07A: 'Лосос',
FFA500: 'Наранџасто',
FFFF00: 'Жуто',
'00FF00': 'Неон зелено',
AFEEEE: 'Светло тиркизно',
ADD8E6: 'Светло плаво',
DDA0DD: 'Цветло љубичасто',
D3D3D3: 'Светло сиво',
FFF0F5: 'Лаванда',
FAEBD7: 'Прљаво бело',
FFFFE0: 'Светло жуто',
F0FFF0: 'Мента',
F0FFFF: 'Aзурно плаво',
F0F8FF: 'Светло плво',
E6E6FA: 'Лаванда',
FFF: 'Бело',
'1ABC9C': 'Тамно циан',
'2ECC71': 'Смарагдно',
'3498DB': 'Сјајно плаво',
'9B59B6': 'Aметист',
'4E5F70': 'Сивкасто плаво',
'F1C40F': 'Светло жуто',
'16A085': 'Тамно циан',
'27AE60': 'Тамно смарагдно',
'2980B9': 'Тамно плаво',
'8E44AD': 'Тамно љубичасто',
'2C3E50': 'Светло плаво',
'F39C12': 'Наранџасто',
'E67E22': 'Шаргрепа',
'E74C3C': 'Светло бакарно',
'ECF0F1': 'Сјајно сребрно',
'95A5A6': 'Светло сивкасто циан',
'DDD': 'Светло сиво',
'D35400': 'Бундева',
'C0392B': 'Тамно црвено',
'BDC3C7': 'Сребрно',
'7F8C8D': 'Сивкасто циан',
'999': 'Тамно сив'
},
more: 'Више боја...',
panelTitle: 'Боје',
textColorTitle: 'Боја текста'
} );
|
define(["require", "exports"], function (require, exports) {
"use strict";
exports.DwtIframe = DwtIframe;
});
|
/**
* Created by Dogfish on 2017/6/3.
*/
import attrListener from "../../components/AttrListener"
import ob from "../observe"
import callback from "./functional"
let mainAttrListener = new attrListener()
/*
mainAttrListener.add("data-page",callback.innerPageJumping)
mainAttrListener.add("data-href",callback.hrefJumping )
mainAttrListener.add("data-anchor",callback.anchorJumping)
mainAttrListener.add("id",callback.idEventDispatch)
*/
mainAttrListener.add("data-page",(eventTarget,attrVal)=>{ob.emit("data-page",{eventTarget,attrVal,key:"data-page"})})
mainAttrListener.add("data-href",(eventTarget,attrVal)=>{ob.emit("data-href",{eventTarget,attrVal,key:"data-href"})})
mainAttrListener.add("data-anchor",(eventTarget,attrVal)=>{ob.emit("data-anchor",{eventTarget,attrVal,key:"data-anchor"})})
mainAttrListener.add("id",(eventTarget,attrVal)=>{ob.emit("data-id",{eventTarget,attrVal,key:"id"})})
//根据 class-active 设置 active 状态名,根据class-tag取消/设置同类
mainAttrListener.add("tag-key",(eventTarget,attrVal)=>{callback.activeClass({eventTarget,attrVal,key:"tag-key"})})
export default mainAttrListener
|
// =========================================================================================== //
// To import OS.File into your main.js code, add the following lines at the start of your
// script (replacing TextEncoder with TextDecoder, both, or neither as needed):
// const {TextEncoder, OS, TextDecoder} = Cu.import("resource://gre/modules/osfile.jsm", {});
const {Cu,Cc,Ci} = require("chrome");
const {TextDecoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
//var fileIO = require("sdk/io/file");
var tabs = require("sdk/tabs");
var defaultSnortPathLog = "C:\\snort\\log"; //default snort log path
var cls = Cc['@mozilla.org/network/dns-service;1'];
var iface = Ci.nsIDNSService;
var dns = cls.getService(iface); //dns object
// =========================================================================================== //
// Function to get hostname and translate hostname to IP address
// =========================================================================================== //
// Capture the URL after load
tabs.on('ready', function(tab){
tabs.on('load', function(tab){
//console.log(tab.url);
hostToIP(tab.url);
});
});
function hostToIP(taburl){
var url = require("sdk/url").URL(taburl);
// console.log("HOST: " + url.host);
var nsrecord = dns.resolve(url.host, true);
while (nsrecord && nsrecord.hasMore()){
ipAddress = (nsrecord.getNextAddrAsString());
//console.log(ipAddress);
}
findDirectory(ipAddress); // Call function
}
// =========================================================================================== //
// Load content of the log file
// =========================================================================================== //
function readTextFromFileLog(logFile) {
var fileIO = require("sdk/io/file");
var textLogFile = null;
if (fileIO.exists(logFile)) {
var TextReader = fileIO.open(logFile, "r");
if (!TextReader.closed) {
textLogFile = TextReader.read();
TextReader.close();
}
}
//console.log(" function readTextFromFileLog " + logFile);
return textLogFile;
};
// =========================================================================================== //
// Create button, panel and open/load the log file in the panel
// =========================================================================================== //
var button = ToggleButton({
id: "button",
label: "Intrusion Alert",
icon: {"32": "./darkpig.png"
},
//onChange: handleChange
});
// Insert information to panel
function infoPanel(logFile){
var textLogFile = readTextFromFileLog(logFile);// Call function for capture text log / return log text
//console.log(" function infoPanel " + textLogFile);
// Panel configuration
var panel = panels.Panel({
contentURL: "data:text/html," + ("Attack: " + tabs.activeTab.title + textLogFile), // Show the content text log in panel
contentStyle: "body { border: 4px solid red; }",
});
panel.show({position: button});
button.state(button, {"icon": "./pig.png",});
/*
button.on("click", handleClick)
function handleClick(state) {
console.log("button '" + state.label + "' was clicked " + tabs.activeTab.url);
hostToIP(tabs.activeTab.url);
panel.show({position: button});
}
*/
}
// =========================================================================================== //
// Iterate through the directory and find the directory log
// =========================================================================================== //
function findDirectory(ipAddress){
let iterator = new OS.File.DirectoryIterator(defaultSnortPathLog); // Open iterator
let subdirs = [];
// ## Recently code
var nsrecord = dns.resolve(dns.myHostName, 0);
var noIPv6 = 0;
console.log("hostname: " + dns.myHostName);
while (noIPv6 < 2){
noIPv6++;
console.log(noIPv6);
nsrecord.getNextAddrAsString();
if (noIPv6 == 1){
myIP = (nsrecord.getNextAddrAsString());
console.log("myIP: " + myIP);
}
}
// ## End
// ## Incluir função para carregar arquivo com data mais atual. ##
let promise = iterator.forEach(
function onEntry(entry) {
//console.log(entry.path);
if (entry.isDir && entry.name == ipAddress ) {
// if ((entry.isDir && entry.name == ipAddress ) || (entry.name == myIP))) {
//console.log("Yes, I find it!");
iterator.close(); // Close iterator
existPath(ipAddress); // Call function
} else {
//console.log("I not find it!");
subdirs.push(entry); // get other path
}
}
);
// Close the iterator
promise.then(
function onSuccess() {
//console.log("Close the iterator: OK");
iterator.close();
return subdirs;
},
function onFailure(reason) {
//console.log("Close the iterator: FAILURE");
iterator.close();
throw reason;
}
);
}
// =========================================================================================== //
// Function list all logs files of the directory
// =========================================================================================== //
function existPath(ipAddress){
//console.log("Finding path of IP address: " + ipAddress);
let iterator2 = new OS.File.DirectoryIterator(defaultSnortPathLog + "\\" + ipAddress); // Open iterator
let subdirs2 = [];
let promise = iterator2.forEach(
function onEntry2(entry2) {
console.log(entry2.path); // --
logFile = (entry2.path);
if (entry2.isDir) {
subdirs2.push(entry2);
} else {
infoPanel(logFile); // Function for insert the file log information in the panel
//iterator2.close();
}
}
);
// Close the iterator
promise.then(
function onSuccess() {
//console.log("Close the iterator2: OK");
iterator2.close();
return subdirs2;
},
function onFailure(reason) {
//console.log("Close the iterator2: FAILURE " + reason);
iterator2.close();
throw reason;
}
);
}
|
// ref: http://stackoverflow.com/a/1293163/2343
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
const CSVToArray = ( strData, strDelimiter ) => {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
// eslint-disable-next-line
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
strMatchedDelimiter !== strDelimiter
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
var strMatchedValue;
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}
export default CSVToArray;
|
var qalc_load_file = cwrap("qalc_load_file", null, ["string"]);
var _qalc = cwrap("qalc", "number", ["string"]);
var qalc_toload = ["data/prefixes.xml",
"data/currencies.xml",
"data/units.xml",
"data/functions.xml",
"data/datasets.xml",
"data/variables.xml"];
function qalc_load_next() {
var x = qalc_toload.shift();
console.log(x);
qalc_load_file(x);
}
function qalc_load_all_files() {
while(qalc_toload.length > 0) qalc_load_next();
}
function qalc(inp) {
var addr = _qalc(inp);
var oup = Pointer_stringify(addr);
_free(addr);
return oup;
}
Module['noExitRuntime'] = true;
Module['_main'] = function() {
qalc_load_file("data/units.xml");
return 0;
}
|
// Content type form
Drupal.behaviors.og_content_type = function() {
// Disable the group limit textarea if the content type is not a standard group post
$('input[name="og_content_type_usage"]').click(function(){
if (!$('#edit-og-content-type-usage-group-post-standard').attr('checked') && !$('#edit-og-content-type-usage-group-post-wiki').attr('checked')) {
$('#edit-og-max-groups').attr('disabled','disabled');
} else {
$('#edit-og-max-groups').removeAttr('disabled');
}
});
// Initial check to see if content type is standard group post
if (!$('#edit-og-content-type-usage-group-post-standard').attr('checked') && !$('#edit-og-content-type-usage-group-post-wiki').attr('checked')) {
$('#edit-og-max-groups').attr('disabled','disabled');
}
};
Drupal.verticalTabs = Drupal.verticalTabs || {};
Drupal.verticalTabs.og_nodeapi = function() {
var values = [];
$('.vertical-tabs-og_nodeapi #edit-og-groups :selected')
.each(function (i, selected) {
values[i] = $(selected).text();
});
return Drupal.checkPlain(values.join(', '));
}
Drupal.verticalTabs.og = function() {
var type = $('.vertical-tabs-og input[type=radio]:checked').val();
switch (type) {
case 'group':
return Drupal.t('Group node');
break;
case 'omitted':
return Drupal.t('May not be posted into a group.');
break;
case 'group_post_standard':
return Drupal.t('Standard group post');
break;
case 'group_post_wiki':
return Drupal.t('Wiki group post');
break;
}
};
|
define("dijit/PopupMenuBarItem", [
"dojo/_base/declare", // declare
"./PopupMenuItem",
"./MenuBarItem"
], function(declare, PopupMenuItem, MenuBarItem){
// module:
// dijit/PopupMenuBarItem
// summary:
// Item in a MenuBar like "File" or "Edit", that spawns a submenu when pressed (or hovered)
var _MenuBarItemMixin = MenuBarItem._MenuBarItemMixin;
/*=====
var PopupMenuItem = dijit.PopupMenuItem;
var _MenuBarItemMixin = dijit._MenuBarItemMixin;
=====*/
return declare("dijit.PopupMenuBarItem", [PopupMenuItem, _MenuBarItemMixin], {
// summary:
// Item in a MenuBar like "File" or "Edit", that spawns a submenu when pressed (or hovered)
});
});
|
describe("ko.bindingHandlers.kendoSlider", function(){
//standard cases
ko.kendo.generateBindingSpecs("kendoSlider", {
html: "<input />",
defaultValue: 5,
newValue: 6
});
//additional kendoSlider cases
});
|
var HUD = (function() {
function HUD() {
// Set player and game objects
this.init();
}
HUD.prototype = {
constructor : HUD,
init : function() {
// Remove any previous scores
$("#ui #score .score").addClass("inactive").html("");
},
update : function() {
if(this.lastScore !== window.spaceRocks.score) {
$("#ui #hud #points #count").html("" + window.spaceRocks.score);
$("#ui #hud #points-container #count").addClass("pulse animated").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$(this).removeClass("pulse animated");
});
this.lastScore = window.spaceRocks.score;
}
if(this.lastLevel !== window.spaceRocks.level) {
$("#ui #hud #points #multiplier sup").html("x" + window.spaceRocks.level);
this.lastLevel = window.spaceRocks.level;
}
if(this.lastMissiles !== window.spaceRocks.player.missileCount) {
var missileCount = window.spaceRocks.player.missileCount;
$.each($("#ui #hud #missiles .missile"), function(i, element) {
if(i < missileCount) {
$(element).removeClass("empty");
} else {
$(element).addClass("empty");
}
});
this.lastMissiles = missileCount;
}
if(this.lastLives !== window.spaceRocks.player.lifeCount) {
var lifeCount = window.spaceRocks.player.lifeCount;
$.each($("#ui #hud #lives .life"), function(i, element) {
if(i < lifeCount) {
$(element).removeClass("empty");
} else {
$(element).addClass("empty");
}
});
this.lastLives = lifeCount;
}
},
triggerScoreAnimation : function(score, x, y) {
// Find the next available score node
var availableNodes = $("#ui #score .score.inactive");
if(availableNodes.length === 0) return;
var scoreNode = $(availableNodes[0]);
scoreNode.css({
"position" : "absolute",
"left" : x / window.devicePixelRatio,
"top" : y / window.devicePixelRatio,
"font-size" : (Math.log(score / this.lastLevel) * 0.7) + "em"
})
scoreNode.html(score);
// Add animations
scoreNode.addClass("fadeInUp animated").removeClass("inactive");
scoreNode.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
scoreNode.removeClass("fadeInUp").addClass("fadeOut").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
// Reset node state allowing it to be reused
scoreNode.removeClass("animated fadeOut").addClass("inactive");
});
});
}
}
return HUD;
})();
|
import { Renderer2D } from '@inwebo/render.js'
import { Vector2D } from "@inwebo/vector";
export default class RendererVector extends Renderer2D {
/**
* Must be overrided
* @param {[Vector2D]} subject
* @protected
*/
_draw(...subject) {
/**
* @type {Particle}
*/
const particle = subject[0][0];
this.getCtx().beginPath();
this.getCtx().fillStyle ='rgba(0,0,0,1)';
this.getCtx().arc(particle.getPosition().getX(), particle.getPosition().getY(), 15, 0, 2 * Math.PI, false);
this.getCtx().fill();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.