code
stringlengths 2
1.05M
|
|---|
ScalaJS.modules.org_littlewings_scalajs_ScalaJsGettingStarted().main();
|
/* eslint-env es5,node */
require('babel-register');
let config;
if (process.env.NODE_ENV === 'production')
config = require('./webpack.production').default;
else
config = require('./webpack.development').default;
module.exports = config;
|
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
'use strict';
var createAPIRequest = require('../../lib/apirequest');
/**
* Google Cloud Vision API
*
* Integrates Google Vision features, including image labeling, face, logo, and landmark detection, optical character recognition (OCR), and detection of explicit content, into applications.
*
* @example
* var google = require('googleapis');
* var vision = google.vision('v1');
*
* @namespace vision
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Vision
*/
function Vision(options) { // eslint-disable-line
var self = this;
self._options = options || {};
self.images = {
/**
* vision.images.annotate
*
* @desc Run image detection and annotation for a batch of images.
*
* @example
* // PRE-REQUISITES:
* // ---------------
* // 1. If not already done, enable the Google Cloud Vision API
* // and check the quota for your project at
* // https://console.developers.google.com/apis/api/vision
* // 2. This sample uses Application Default Credentials for Auth.
* // If not already done, install the gcloud CLI from
* // https://cloud.google.com/sdk/ and run 'gcloud auth application-default login'
* // 3. To install the client library and Application Default Credentials library, run:
* // 'npm install googleapis --save'
* var google = require('googleapis');
* var vision = google.vision('v1');
*
* google.auth.getApplicationDefault(function(err, authClient) {
* if (err) {
* console.log('Authentication failed because of ', err);
* return;
* }
* if (authClient.createScopedRequired && authClient.createScopedRequired()) {
* var scopes = ['https://www.googleapis.com/auth/cloud-platform'];
* authClient = authClient.createScoped(scopes);
* }
*
* var request = {
* // TODO: Change placeholders below to appropriate parameter values for the 'annotate' method:
*
* resource: {},
* // Auth client
* auth: authClient
* };
*
* vision.images.annotate(request, function(err, result) {
* if (err) {
* console.log(err);
* } else {
* console.log(result);
* }
* });
* });
*
* @alias vision.images.annotate
* @memberOf! vision(v1)
*
* @param {object} params Parameters for request
* @param {object} params.resource Request body data
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
annotate: function (params, callback) {
var parameters = {
options: {
url: 'https://vision.googleapis.com/v1/images:annotate',
method: 'POST'
},
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
module.exports = Vision;
|
/**
* Author jmorrison
* Date: 8/29/11
* Time: 12:20 PM
*/
function isArray(obj) {
return (obj.constructor.toString().indexOf(”Array”) != -1);
}
|
'use strict';
angular.module('mean').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('users', {
url: '/admin/users',
templateUrl: 'mean-admin/views/users.html'
}).state('themes', {
url: '/admin/themes',
templateUrl: 'mean-admin/views/themes.html'
}).state('settings', {
url: '/admin/settings',
templateUrl: 'mean-admin/views/settings.html'
}).state('modules', {
url: '/admin/modules',
templateUrl: 'mean-admin/views/modules.html'
}).state('administration', {
url: '/admin/administration',
templateUrl: 'mean-admin/views/administration.html'
});
}
]);
|
var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
}),
preLoaders: {
pug: 'pug-html-loader'
}
}
|
import {
LOAD_DATA_INITIATION,
LOAD_DATA_SUCCESS,
LOAD_DATA_FAILURE,
CLEAR_DATA_ERROR,
} from './constants';
const initialState = {
isLoading: false,
data: {},
error: {},
};
/**
* @function featureComponent
* @description A redux reducer function
* Takes state and an action and returns next state.
* @param {state} - the state tree of the application
* @param {action} - the dispatched redux action
*/
const featureComponent = (state = initialState, action) => {
switch (action.type) {
case LOAD_DATA_INITIATION:
return Object.assign({}, state, {
isLoading: true,
});
case LOAD_DATA_SUCCESS:
return Object.assign({}, state, {
isLoading: false,
data: action.data,
});
case LOAD_DATA_FAILURE:
return Object.assign({}, state, {
isLoading: false,
error: action.error,
});
case CLEAR_DATA_ERROR:
return Object.assign({}, state, {
error: {},
});
default:
return state;
}
};
export default featureComponent;
|
'use strict';
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const sassGlob = require('gulp-sass-glob');
const scssLint = require('gulp-scss-lint');
const webpack = require('webpack-stream');
const publicDir = './public/';
const scriptsDir = './assets/scripts/';
const stylesDir = './assets/styles/';
const scripts = [scriptsDir + '**/*.js', scriptsDir + '**/*.vue'];
const styles = stylesDir + '**/*.scss';
const webpackConfig = require('./webpack.config.js');
function webpackError() {
this.emit('end');
}
gulp.task('js', () => {
gulp.src(scriptsDir + 'main.js')
.pipe(webpack(webpackConfig))
.on('error', webpackError)
.pipe(gulp.dest(publicDir))
.pipe(browserSync.stream());
});
gulp.task('scssLint', () => {
gulp.src(styles)
.pipe(scssLint({
'config': 'config/scss-lint.yml'
}));
});
gulp.task('sass', ['scssLint'], () => {
gulp.src(stylesDir + 'main.scss')
.pipe(sassGlob())
.pipe(sass({outputStyle: 'compressed'})
.on('error', sass.logError)
)
.pipe(autoprefixer())
.pipe(gulp.dest(publicDir))
.pipe(browserSync.stream());
});
gulp.task('reload', () => {
browserSync.reload();
});
gulp.task('default', ['sass'], () => {
browserSync.init({
server: publicDir,
});
gulp.watch(scripts, ['js']);
gulp.watch(styles, ['scssLint', 'sass']);
gulp.watch(publicDir + '**/*.html', ['reload']);
});
|
// Deprecated
/* istanbul ignore file */
import styled from 'styled-components'
export const config = {
borderWidth: '2px',
}
const AvatarStackUI = styled('div')`
display: flex;
position: relative;
&.is-withLayerStack {
padding-left: calc(${config.borderWidth} * 3);
}
`
export const AvatarStackLayeringUI = styled(AvatarStackUI)`
align-items: center;
justify-content: center;
margin: auto;
max-width: 230px;
min-height: 64px;
width: 100%;
min-width: 0;
`
export const ItemUI = styled('div')`
position: relative;
&.is-withLayerStack {
margin-left: 0;
}
`
|
// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage
module.exports = {
'default e2e tests': function test(browser) {
// automatically uses dev Server port from /config.index.js
// default: http://localhost:8080
// see nightwatch.conf.js
const devServer = browser.globals.devServerURL;
browser
.url(devServer)
.waitForElementVisible('#app', 5000)
.assert.containsText('p', 'App')
.end();
},
};
|
import React, { useState, useCallback } from 'react';
// component
import MaintenaceBanner from './component';
// utils
import { getMaintenanceBannerAccepted, setMaintenanceBannerAccepted } from './helpers';
const MaintenaceBannerContainer = () => {
const [maintenanceBannerAccepted, setMaintenanceBannerAcceptance] = useState(getMaintenanceBannerAccepted());
const memoizedCallback = useCallback(
() => { setMaintenanceBannerAccepted(); },
[],
);
const handleMaintenanceBanner = () => {
setMaintenanceBannerAcceptance(true);
memoizedCallback();
};
return !maintenanceBannerAccepted
? (
<MaintenaceBanner
handleMaintenanceBanner={handleMaintenanceBanner}
timeText="Monday 27th April 2020 (10:00 to 16:00 CET)"
/>
) : null;
};
export default MaintenaceBannerContainer;
|
'use strict';
module.exports = function (stamp, flags) {
if (stamp.p === 'win32' && flags.ci) {
return {
allow: false,
note: 'headless windows CI seems to fail'
};
}
return {
deployFilesFrom: [ 'opn' ]
};
};
|
'use strict';
const mongoose = require('mongoose');
module.exports = mongoose.model('buys',
mongoose.Schema({
name: String,
symbol: String,
quantity: String,
price: String
})
);
|
/**
* Source Backup Main Application
* @author Anthony G. Rivera Cosme
* @copyright Anthony G. Rivera Cosme
* @license MIT
* @version 1.0
*/
onload = function() {
AppInit(function() {
LoadMainWindow(function() {
});
});
};
function AppInit(callback) {
LoadSettings(function() {
LoadBackupHardDriveLocation(function() {
CheckForDeviceUnplugged(function() {
LoadDirectories(function() {
setNotifySettings(function() {
CreateMenu(function() {
CheckIfApplicationProgramDataExists(function() {
callback();
CheckForUpdates(function() {
});
});
});
});
});
});
});
});
}
function InitialBackup(callback) {
if(!IsDeviceUnplugged) {
IsUserBackup = false;
IsSyncing = true;
Backup(function() {
});
}
callback();
}
function StartUpLaunchToggle(callback) {
if(!IsStartUpToggleExecuted) {
var nwAppLauncher = new AutoLaunch({
name: gui.App.manifest.name.replace("_", " "),
path: process.execPath
});
if(jQuery("#StartUpExecute").is(":checked")) {
nwAppLauncher.isEnabled(function(enabled) {
if(enabled) {
IsStartUpToggleExecuted = true;
}
else {
nwAppLauncher.enable(function(err) {
if(err) {
nwNotify.notify("Error", err);
jQuery("#StartUpExecute").removeAttr("checked");
}
else
nwNotify.notify("Success", "Source Backup is enabled on startup!");
IsStartUpToggleExecuted = true;
});
}
});
}
else {
nwAppLauncher.isEnabled(function(enabled){
if(!enabled) {
IsStartUpToggleExecuted = true;
}
else {
nwAppLauncher.disable(function(err) {
if(err) {
nwNotify.notify("Error", err);
jQuery("#StartUpExecute").attr("checked");
}
else
nwNotify.notify("Success", "Source Backup is disabled on startup!");
IsStartUpToggleExecuted = true;
});
}
});
}
}
callback();
}
function StartBackup(callback) {
IsUserBackup = true;
Backup(function() {
});
callback();
}
function ResetValues(callback) {
IsAlreadyWatching = false;
CopyError = false;
IsSyncing = true;
WalkIndex = 0;
Files = [];
Dirs = [];
if(IsUserBackup) {
jQuery("#BackupProgress").removeClass("hide");
NumberFiles = 0;
}
callback();
}
function SelectBackupHardDrive(callback) {
BackupHardDrive = jQuery("#btnSelectBackupHardDrive").val().replace(path.sep, "");
if(!IsWindows()) {
BackupHardDrive = path.sep + BackupHardDrive;
}
jQuery("#BackupHardDrive").html("<h1>" +BackupHardDrive + "</h1><i class='fa fa-download fa-3x'></i>");
callback();
}
function CheckIfBackupDeviceIsConnected(callback) {
fs.exists(BackupHardDrive, function(exists) {
if(!exists) {
FirstLaunch = true;
if(!IsDeviceUnPluggedNotificationShowed) {
if(jQuery.trim(BackupHardDrive) == "" || BackupHardDrive == null) {
nwNotify.notify("Device Undetected", "No backup device have been selected!");
}
else {
nwNotify.notify("Device Undetected", "The backup device is unplugged!");
}
IsSyncing = false;
if(IsMac()) {
fs.exists(BackupHardDrive + "/Users", function(exists) {
if(!exists)
{
fs.unlink(BackupHardDrive, function(err) {
if(err)
nwNotify("Error", err);
});
}
});
}
IsDeviceUnPluggedNotificationShowed = true;
IsDeviceUnplugged = true;
callback();
}
}
else {
if(FirstLaunch && ShowStatusNotification()) {
nwNotify.notify("Device Detected", "The backup device is plugged in!");
IsDeviceUnplugged = false;
FirstLaunch = false;
IsDeviceUnPluggedNotificationShowed = false;
if(jQuery("#AutoBackupStartUp").is(":checked")) {
InitialBackup(function() {
});
}
callback();
}
else if(IsDeviceUnplugged) {
nwNotify.notify("Device Detected", "The backup device is plugged in!");
IsDeviceUnplugged = false;
IsDeviceUnPluggedNotificationShowed = true;
if(jQuery("#AutoBackupStartUp").is(":checked")) {
InitialBackup(function() {
});
}
else if(confirm("Do you want to start backing up your data now?")) {
StartBackup(function() {
});
} else {
WatchDirectories(function() {
});
}
callback();
}
else {
FirstLaunch = false;
callback();
}
}
});
}
function CheckForDeviceUnplugged(callback) {
setInterval(function() {
CheckIfBackupDeviceIsConnected(function() {
});
}, 1000);
callback();
}
function LoadDirectories(callback) {
fs.exists(Application.GetOSProgramDataFolder() + "directories.json", function(exists) {
if(exists) {
fs.readFile(Application.GetOSProgramDataFolder() + "directories.json", function name(err, data) {
if(err) {
nwNotify.notify("Error", err);
callback();
}
else {
var jsondata = JSON.parse(data);
jQuery("#dirs").empty();
directories = {};
for(var index=0;index<Object.keys(jsondata).length; index++) {
jQuery("#dirs").append("<li class='list-group-item'>" + jsondata["directory" + index] + " <span style='cursor:pointer' id='btn" + index + "' class='badge' onclick='RemoveDirectory(" + index + ")'><i class='fa fa-remove'></i></span></li>");
directories["directory" + index] = jsondata["directory" + index];
}
jQuery("#directories-content").removeClass("hide");
callback();
}
});
}
else {
jQuery("#directories-content").removeClass("hide");
callback();
}
});
}
function LoadBackupHardDriveLocation(callback) {
fs.exists(Application.GetOSProgramDataFolder() + "backup-directory.json", function(exists) {
if(exists) {
fs.readFile(Application.GetOSProgramDataFolder() + "backup-directory.json", function name(err, data) {
if(err) {
nwNotify.notify("Error", err);
callback();
}
else {
var jsondata = JSON.parse(data);
BackupHardDrive = jsondata["Backup-Directory"];
jQuery("#BackupHardDrive").html("<h1>" + jsondata["Backup-Directory"] + "</h1><i class='fa fa-download fa-3x'></i>");
callback();
}
});
}
else {
jQuery("#directories-content").removeClass("hide");
callback();
}
});
}
function CheckIfApplicationProgramDataExists(callback) {
fs.mkdirs(Application.GetOSProgramDataFolder(), function (err) {
if(err) {
bootbox.alert(err);
}
});
callback();
}
function LoadSettings(callback) {
fs.exists(Application.GetOSProgramDataFolder() + "settings.json", function(exists) {
if(exists) {
fs.readFile(Application.GetOSProgramDataFolder() + "settings.json", function name(err, data) {
if(err) {
nwNotify.notify("Error", err);
}
else {
var jsondata = JSON.parse(data);
jQuery("input[value=" + jsondata["Delete-Option"] + "]").attr("checked", true);
jQuery("input[value=" + jsondata["Notification"] + "]").attr("checked", true);
jQuery("input[value=" + jsondata["Notification-Time"] + "]").attr("checked", true);
if(jsondata["StartUpExecute"] == "") {
jQuery("#StartUpExecute").removeAttr("checked");
}
if(jsondata["AutoBackupStartUp"] == "") {
jQuery("#AutoBackupStartUp").removeAttr("checked");
}
StartUpLaunchToggle(function() {
});
}
});
}
});
callback();
}
function AddDirectory(callback) {
for(var index=0;index>-1;index++) {
if(jQuery("#btnSelectDirectory").val() === "") {
break;
}
else if(directories["directory" + index] == jQuery("#btnSelectDirectory").val()) {
bootbox.alert("The directory is already selected!");
jQuery("#btnSelectDirectory").val("");
break;
}
else if(!directories.hasOwnProperty("directory" + index)) {
directories["directory" + index] = jQuery("#btnSelectDirectory").val();
jQuery("#dirs").append("<li class='list-group-item'>" + jQuery("#btnSelectDirectory").val() + " <span style='cursor:pointer' id='btn" + index + "' class='badge' onclick='RemoveDirectory(" + index + ")'><i class='fa fa-remove'></i></span></li>");
jQuery("#btnSelectDirectory").val("");
break;
}
}
callback();
}
function RemoveDirectory(index) {
jQuery("li").eq(index).remove();
delete directories["directory" + index];
}
function SaveInitialSettings(callback) {
fs.writeFile(Application.GetOSProgramDataFolder() + "settings.json",
JSON.stringify({
"Delete-Option": jQuery("[name=DeleteOption]:checked").val(),
"Notification": jQuery("[name=Notification]:checked").val(),
"Notification-Time": jQuery("[name=NotificationTime]:checked").val(),
"StartUpExecute" : (jQuery("#StartUpExecute").is(":checked")) ? "checked": "",
"AutoBackupStartUp" : (jQuery("#AutoBackupStartUp").is(":checked")) ? "checked": ""}, null, 4),
function(err) {
if(err) {
nwNotify.notify("Error", err);
}
else {
nwNotify.notify("Completed", "All settings were saved!");
}
});
callback();
}
function SaveSettings(callback) {
fs.writeFile(Application.GetOSProgramDataFolder() + "directories.json", JSON.stringify(directories, null, 4), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
});
fs.writeFile(Application.GetOSProgramDataFolder() + "backup-directory.json", JSON.stringify({"Backup-Directory": BackupHardDrive}, null, 4), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
});
fs.writeFile(Application.GetOSProgramDataFolder() + "settings.json",
JSON.stringify({
"Delete-Option": jQuery("[name=DeleteOption]:checked").val(),
"Notification": jQuery("[name=Notification]:checked").val(),
"Notification-Time": jQuery("[name=NotificationTime]:checked").val(),
"StartUpExecute" : (jQuery("#StartUpExecute").is(":checked")) ? "checked": "",
"AutoBackupStartUp" : (jQuery("#AutoBackupStartUp").is(":checked")) ? "checked": ""}, null, 4),
function(err) {
if(err) {
nwNotify.notify("Error", err);
}
});
callback();
}
function Backup(callback) {
if(Object.keys(directories).length == 0) {
IsSyncing = false;
bootbox.alert("Select at least one directory for backup", function() {
jQuery('#btnSelectDirectory').click();
});
}
else if(BackupHardDrive == "") {
IsSyncing = false;
bootbox.alert("Select the backup device", function() {
jQuery('#btnSelectBackupHardDrive').click();
});
}
else if(IsDeviceUnplugged) {
IsSyncing = false;
bootbox.alert("Device undetected, please select the backup device", function() {
jQuery('#btnSelectBackupHardDrive').click();
});
}
else {
RemoveMonitors(function () {
ResetValues(function() {
SaveSettings(function() {
nwNotify.notify("Sync Started", "Source Backup started synchronizing!");
for(var index=0;index<Object.keys(directories).length; index++) {
var walker = walk.walk(directories["directory" + index]);
walker.on("file", function (root, fileStats, next) {
jQuery("#TotalFiles").text("Total of Files: " + ++NumberFiles);
jQuery("#progress-text").text("Copying: " + path.join(root, fileStats.name));
CheckCreateFile(path.join(root, fileStats.name), function() {
next();
});
});
walker.on("errors", function (root, nodeStatsArray, next) {
console.log(nodeStatsArray);
CopyError = true;
next();
});
walker.on("end", function () {
if(++WalkIndex == Object.keys(directories).length) {
jQuery("#progress-text").text("Process Completed!");
ProcessCompleted(function() {
});
}
});
}
});
});
});
}
callback();
}
function CheckCreateFile(file, callback) {
if(!IsDeviceUnplugged) {
fs.exists(BackupHardDrive + Application.osPath(file), function(exists) {
if(!exists) {
fs.copy(file, BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
CopyError = true;
}
callback();
});
}
else {
callback();
}
});
}
else {
CopyError = true;
ProcessCompleted(function() {
});
callback();
}
}
function ProcessCompleted(callback) {
IsSyncing = false;
CheckIfCompletedWithNoError(function() {
if(CopyError) {
CheckIfCompletedWithError(function() {
});
}
});
callback();
}
function CheckIfCompletedWithNoError(callback) {
nwNotify.notify("Sync Completed", "All files were backed up!");
CheckIfApplicationCloseRequested(function() {
});
WatchDirectories(function() {
});
callback();
}
function CheckIfCompletedWithError(callback) {
alert("The process finished with some errors copying the files or directories. Please check that folder or files aren't protected or used by the OS or an external program and that your backup device is plugged in and try again!");
CheckIfApplicationCloseRequested(function() {
});
WatchDirectories(function() {
});
callback();
}
jQuery(document).ready(function() {
jQuery("[name=NotificationTime]").change(function(){
setNotifySettings(function() {
});
});
});
function setNotifySettings(callback) {
nwNotify.setConfig({
appIcon: nwNotify.getAppPath() + 'img/icon.png',
displayTime: jQuery("[name=NotificationTime]:checked").val(),
defaultStyleText: {
color: '#272b30;'
}
});
callback();
}
function ShowStatusNotification() {
return jQuery("[name=Notification]:checked").val() == "yes";
}
function WatchDirectories(callback) {
if(!IsAlreadyWatching) {
IsAlreadyWatching = true;
RemoveMonitors(function() {
for(var index = 0; index < Object.keys(directories).length; index++) {
watch.createMonitor(directories["directory" + index], {/*ignoreDotFiles: true*/}, function (monitor) {
monitor.on("created", function (file, stat) {
MonitorFileCreated(file, stat, function() {
});
})
monitor.on("changed", function (file, curr, prev) {
MonitorFileChanged(file, curr, prev, function() {
});
})
monitor.on("removed", function (file, stat) {
MonitorFileDeleted(file, stat, function() {
});
})
MonitorsOn.push(monitor);
});
}
});
}
callback();
}
function MonitorFileCreated(file, stat, callback) {
fs.exists(BackupHardDrive + Application.osPath(file), function(exist) {
if(exist && FileDirectory.IsFile(file)) {
fs.remove(BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
else {
fs.copy(file, BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
else if(ShowStatusNotification()) {
nwNotify.notify("Completed", FileDirectory.LastDirNameOrFileName(file) + " was copied.");
}
});
}
});
}
else if(exist && (file)) {
}
else {
fs.copy(file, BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
console.log(err);
}
else if(ShowStatusNotification()) {
nwNotify.notify("Completed", FileDirectory.LastDirNameOrFileName(file) + " was copied.");
}
});
}
});
callback();
}
function MonitorFileChanged(file, curr, prev, callback) {
fs.exists(BackupHardDrive + Application.osPath(file), function(exist) {
if(exist) {
fs.remove(BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
else {
fs.copy(file, BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
else if(ShowStatusNotification()) {
nwNotify.notify("Completed", FileDirectory.LastDirNameOrFileName(file) + " was copied");
}
});
}
});
}
else {
fs.copy(file, BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
else if(ShowStatusNotification()) {
nwNotify.notify("Completed", FileDirectory.LastDirNameOrFileName(file) + " was copied.");
}
});
}
});
callback();
}
function MonitorFileDeleted(file, stat, callback) {
if(jQuery("[name=DeleteOption]:checked").val() == "nothing")
return;
else if(jQuery("[name=DeleteOption]:checked").val() == "ask") {
gui.Window.get().requestAttention();
if(confirm("Do you want to delete the file or folder " + FileDirectory.LastDirNameOrFileName(file) + " from the backup location?")) {
RemoveWatchDirectory(file, stat, function() {
});
}
}
else if(jQuery("[name=DeleteOption]:checked").val() == "delete") {
RemoveWatchDirectory(file, stat, function() {
});
}
callback();
}
function RemoveWatchDirectory(file, stat, callback) {
fs.exists(BackupHardDrive + Application.osPath(file), function(exist) {
if(exist) {
fs.remove(BackupHardDrive + Application.osPath(file), function(err) {
if(err) {
nwNotify.notify("Error", err);
}
else if(ShowStatusNotification()) {
nwNotify.notify("Completed", FileDirectory.LastDirNameOrFileName(file) + " was deleted.");
}
});
}
});
callback();
}
function RemoveMonitors(callback) {
for(var index = 0; index < MonitorsOn.length;index++) {
MonitorsOn[index].stop();
}
MonitorsOn = [];
callback();
}
function IsFirstBackupDone() {
if(BackupHardDrive != "" && Object.keys(directories).length > 0)
return true;
else
return false;
}
|
/* @noflow */
import React from 'react';
import Redirect from '../';
import {shallow, mount} from 'enzyme';
describe('<Redirect>', () => {
var context, navigate, serverResult;
beforeEach(() => {
serverResult = {};
navigate = jest.fn();
context = {
router: {
linkMiddleware: [],
location: {},
urls: {
makeLocation({urlName, params}) {
expect(urlName).toEqual('user:profile');
expect(params).toEqual({username: 'x'});
return {pathname: "/u/x/", search: '?a=b'};
},
match() {
return {};
}
},
navigate,
history: {
createHref(location) {
expect(location).toEqual({pathname: "/u/x/", search: "?a=b"});
return "/u/x/?a=b";
}
},
listen: () => () => {},
serverResult
}
};
});
it('should redirect on mount', () => {
mount(<Redirect urlName="user:profile" params={{username: 'x'}} state={{statevar: 1}} />, {context});
expect(navigate).toBeCalledWith(jasmine.objectContaining({urlName: "user:profile", params: {username: 'x'}, state: {statevar: 1}}), false);
});
it('should replace if instructed', () => {
mount(<Redirect urlName="user:profile" params={{username: 'x'}} state={{statevar: 1}} replace={true} />, {context});
expect(navigate).toBeCalledWith(jasmine.objectContaining({urlName: "user:profile", params: {username: 'x'}, state: {statevar: 1}}), true);
});
it('should update serverResult if provided', () => {
const wrapper = shallow(<Redirect urlName="user:profile" params={{username: 'x'}} query={{a: 'b'}} state={{statevar: 1}} />, {context});
// Shallow again because of withRouter decorator
shallow(wrapper.node, {context});
expect(navigate).not.toBeCalled();
expect(serverResult.redirect).toEqual('/u/x/?a=b');
});
});
|
'use strict';
var _Promise = require('babel-runtime/core-js/promise')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var utils = {};
utils.formatSectionsIntoPage = function (mapData) {
mapData.html = mapData.html.replace('</body>', '<script>' + mapData.js + '</script></body>');
mapData.html = mapData.html.replace('</head>', '<style>' + mapData.css + '</style></head>');
return _Promise.resolve(mapData.html);
};
exports['default'] = utils;
module.exports = exports['default'];
|
ace.define("ace/ext/searchbox",["require","exports","module","ace/lib/dom","ace/lib/lang","ace/lib/event","ace/keyboard/hash_handler","ace/lib/keys"], function(acequire, exports, module) {
"use strict";
var dom = acequire("../lib/dom");
var lang = acequire("../lib/lang");
var event = acequire("../lib/event");
var searchboxCss = "\
.ace_search {\
background-color: #ddd;\
border: 1px solid #cbcbcb;\
border-top: 0 none;\
max-width: 297px;\
overflow: hidden;\
margin: 0;\
padding: 4px;\
padding-right: 6px;\
padding-bottom: 0;\
position: absolute;\
top: 0px;\
z-index: 99;\
white-space: normal;\
}\
.ace_search.left {\
border-left: 0 none;\
border-radius: 0px 0px 5px 0px;\
left: 0;\
}\
.ace_search.right {\
border-radius: 0px 0px 0px 5px;\
border-right: 0 none;\
right: 0;\
}\
.ace_search_form, .ace_replace_form {\
border-radius: 3px;\
border: 1px solid #cbcbcb;\
float: left;\
margin-bottom: 4px;\
overflow: hidden;\
}\
.ace_search_form.ace_nomatch {\
outline: 1px solid red;\
}\
.ace_search_field {\
background-color: white;\
border-right: 1px solid #cbcbcb;\
border: 0 none;\
-webkit-box-sizing: border-box;\
-moz-box-sizing: border-box;\
box-sizing: border-box;\
display: block;\
float: left;\
height: 22px;\
outline: 0;\
padding: 0 7px;\
width: 214px;\
margin: 0;\
}\
.ace_searchbtn,\
.ace_replacebtn {\
background: #fff;\
border: 0 none;\
border-left: 1px solid #dcdcdc;\
cursor: pointer;\
display: block;\
float: left;\
height: 22px;\
margin: 0;\
padding: 0;\
position: relative;\
}\
.ace_searchbtn:last-child,\
.ace_replacebtn:last-child {\
border-top-right-radius: 3px;\
border-bottom-right-radius: 3px;\
}\
.ace_searchbtn:disabled {\
background: none;\
cursor: default;\
}\
.ace_searchbtn {\
background-position: 50% 50%;\
background-repeat: no-repeat;\
width: 27px;\
}\
.ace_searchbtn.prev {\
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=); \
}\
.ace_searchbtn.next {\
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=); \
}\
.ace_searchbtn_close {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\
border-radius: 50%;\
border: 0 none;\
color: #656565;\
cursor: pointer;\
display: block;\
float: right;\
font-family: Arial;\
font-size: 16px;\
height: 14px;\
line-height: 16px;\
margin: 5px 1px 9px 5px;\
padding: 0;\
text-align: center;\
width: 14px;\
}\
.ace_searchbtn_close:hover {\
background-color: #656565;\
background-position: 50% 100%;\
color: white;\
}\
.ace_replacebtn.prev {\
width: 54px\
}\
.ace_replacebtn.next {\
width: 27px\
}\
.ace_button {\
margin-left: 2px;\
cursor: pointer;\
-webkit-user-select: none;\
-moz-user-select: none;\
-o-user-select: none;\
-ms-user-select: none;\
user-select: none;\
overflow: hidden;\
opacity: 0.7;\
border: 1px solid rgba(100,100,100,0.23);\
padding: 1px;\
-moz-box-sizing: border-box;\
box-sizing: border-box;\
color: black;\
}\
.ace_button:hover {\
background-color: #eee;\
opacity:1;\
}\
.ace_button:active {\
background-color: #ddd;\
}\
.ace_button.checked {\
border-color: #3399ff;\
opacity:1;\
}\
.ace_search_options{\
margin-bottom: 3px;\
text-align: right;\
-webkit-user-select: none;\
-moz-user-select: none;\
-o-user-select: none;\
-ms-user-select: none;\
user-select: none;\
}";
var HashHandler = acequire("../keyboard/hash_handler").HashHandler;
var keyUtil = acequire("../lib/keys");
dom.importCssString(searchboxCss, "ace_searchbox");
var html = '<div class="ace_search right">\
<button type="button" action="hide" class="ace_searchbtn_close"></button>\
<div class="ace_search_form">\
<input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\
<button type="button" action="findNext" class="ace_searchbtn next"></button>\
<button type="button" action="findPrev" class="ace_searchbtn prev"></button>\
</div>\
<div class="ace_replace_form">\
<input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\
<button type="button" action="replaceAndFindNext" class="ace_replacebtn">Replace</button>\
<button type="button" action="replaceAll" class="ace_replacebtn">All</button>\
</div>\
<div class="ace_search_options">\
<span action="toggleRegexpMode" class="ace_button" title="RegExp Search">.*</span>\
<span action="toggleCaseSensitive" class="ace_button" title="CaseSensitive Search">Aa</span>\
<span action="toggleWholeWords" class="ace_button" title="Whole Word Search">\\b</span>\
</div>\
</div>'.replace(/>\s+/g, ">");
var SearchBox = function(editor, range, showReplaceForm) {
var div = dom.createElement("div");
div.innerHTML = html;
this.element = div.firstChild;
this.$init();
this.setEditor(editor);
};
(function() {
this.setEditor = function(editor) {
editor.searchBox = this;
editor.container.appendChild(this.element);
this.editor = editor;
};
this.$initElements = function(sb) {
this.searchBox = sb.querySelector(".ace_search_form");
this.replaceBox = sb.querySelector(".ace_replace_form");
this.searchOptions = sb.querySelector(".ace_search_options");
this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
this.searchInput = this.searchBox.querySelector(".ace_search_field");
this.replaceInput = this.replaceBox.querySelector(".ace_search_field");
};
this.$init = function() {
var sb = this.element;
this.$initElements(sb);
var _this = this;
event.addListener(sb, "mousedown", function(e) {
setTimeout(function(){
_this.activeInput.focus();
}, 0);
event.stopPropagation(e);
});
event.addListener(sb, "click", function(e) {
var t = e.target || e.srcElement;
var action = t.getAttribute("action");
if (action && _this[action])
_this[action]();
else if (_this.$searchBarKb.commands[action])
_this.$searchBarKb.commands[action].exec(_this);
event.stopPropagation(e);
});
event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
var keyString = keyUtil.keyCodeToString(keyCode);
var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
if (command && command.exec) {
command.exec(_this);
event.stopEvent(e);
}
});
this.$onChange = lang.delayedCall(function() {
_this.find(false, false);
});
event.addListener(this.searchInput, "input", function() {
_this.$onChange.schedule(20);
});
event.addListener(this.searchInput, "focus", function() {
_this.activeInput = _this.searchInput;
_this.searchInput.value && _this.highlight();
});
event.addListener(this.replaceInput, "focus", function() {
_this.activeInput = _this.replaceInput;
_this.searchInput.value && _this.highlight();
});
};
this.$closeSearchBarKb = new HashHandler([{
bindKey: "Esc",
name: "closeSearchBar",
exec: function(editor) {
editor.searchBox.hide();
}
}]);
this.$searchBarKb = new HashHandler();
this.$searchBarKb.bindKeys({
"Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function(sb) {
var isReplace = sb.isReplace = !sb.isReplace;
sb.replaceBox.style.display = isReplace ? "" : "none";
sb[isReplace ? "replaceInput" : "searchInput"].focus();
},
"Ctrl-G|Command-G": function(sb) {
sb.findNext();
},
"Ctrl-Shift-G|Command-Shift-G": function(sb) {
sb.findPrev();
},
"esc": function(sb) {
setTimeout(function() { sb.hide();});
},
"Return": function(sb) {
if (sb.activeInput == sb.replaceInput)
sb.replace();
sb.findNext();
},
"Shift-Return": function(sb) {
if (sb.activeInput == sb.replaceInput)
sb.replace();
sb.findPrev();
},
"Tab": function(sb) {
(sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
}
});
this.$searchBarKb.addCommands([{
name: "toggleRegexpMode",
bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
exec: function(sb) {
sb.regExpOption.checked = !sb.regExpOption.checked;
sb.$syncOptions();
}
}, {
name: "toggleCaseSensitive",
bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
exec: function(sb) {
sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
sb.$syncOptions();
}
}, {
name: "toggleWholeWords",
bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
exec: function(sb) {
sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
sb.$syncOptions();
}
}]);
this.$syncOptions = function() {
dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
this.find(false, false);
};
this.highlight = function(re) {
this.editor.session.highlight(re || this.editor.$search.$options.re);
this.editor.renderer.updateBackMarkers()
};
this.find = function(skipCurrent, backwards) {
var range = this.editor.find(this.searchInput.value, {
skipCurrent: skipCurrent,
backwards: backwards,
wrap: true,
regExp: this.regExpOption.checked,
caseSensitive: this.caseSensitiveOption.checked,
wholeWord: this.wholeWordOption.checked
});
var noMatch = !range && this.searchInput.value;
dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
this.editor._emit("findSearchBox", { match: !noMatch });
this.highlight();
};
this.findNext = function() {
this.find(true, false);
};
this.findPrev = function() {
this.find(true, true);
};
this.replace = function() {
if (!this.editor.getReadOnly())
this.editor.replace(this.replaceInput.value);
};
this.replaceAndFindNext = function() {
if (!this.editor.getReadOnly()) {
this.editor.replace(this.replaceInput.value);
this.findNext()
}
};
this.replaceAll = function() {
if (!this.editor.getReadOnly())
this.editor.replaceAll(this.replaceInput.value);
};
this.hide = function() {
this.element.style.display = "none";
this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
this.editor.focus();
};
this.show = function(value, isReplace) {
this.element.style.display = "";
this.replaceBox.style.display = isReplace ? "" : "none";
this.isReplace = isReplace;
if (value)
this.searchInput.value = value;
this.searchInput.focus();
this.searchInput.select();
this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
};
}).call(SearchBox.prototype);
exports.SearchBox = SearchBox;
exports.Search = function(editor, isReplace) {
var sb = editor.searchBox || new SearchBox(editor);
sb.show(editor.session.getTextRange(), isReplace);
};
});
;
(function() {
ace.acequire(["ace/ext/searchbox"], function() {});
})();
|
var mongoose = require('mongoose')
, Truck = mongoose.model('Truck')
, Feed = mongoose.model('Feed')
exports.get = function (req, res) {
Truck
.find({})
.exec(function (err, trucks) {
if (err) throw err
if (trucks) res.json(trucks)
})
}
function populateTruck (params, truck, user) {
console.log(user)
//if (!user) return null
//Populate the trucks
truck.date=Date.now()
if (params.temporality) truck.temporality = params.temporality
if (params.location) truck.location = params.location
if (params.validity) truck.validity = params.validity
truck.version++
Feed
.findOne({})
.exec(function (err, tweets) {
if (err) throw err
if (tweets) {
tweets = tweets.tweets
for (i in tweets) {
var tweet = tweets[i]
if (tweet._id==params.id) {
var twt = {
username : user,
version: truck.version,
screen_name: tweet.screen_name,
content: tweet.content,
geo: tweet.geo,
datePosted: tweet.datePosted,
avatar: tweet.avatar
}
if (twt.geo && !truck.location) truck.location = twt.geo
tweet.username = user
tweet.version = truck.version
truck.tweets.push(twt)
console.log(truck)
}
}
}
truck.save()
})
}
exports.del = function (req, res) {
var now = new Date()
//just for testing, to avoid using mocha
Truck
.find({date: {$lt: now.setDate(now.getDate()-1)}, temporality:"today"})
.exec(function(err, trucks){
if (err) throw err
console.log(trucks)
})
Truck
.remove({})
.exec(function(err,slt) {
res.send("Removed")
})
}
exports.post = function (req, res) {
var params = null
if (req.params) params = req.params
if (req.body) params = req.body
if (!params) return null
Truck
.findOne({truckName: params.truckname})
.exec(function (err, truck) {
if (err) throw err
if (!truck) {
console.log("New truck created...")
var truck = new Truck()
truck.truckName=params.truckname
}
console.log(truck)
populateTruck(params, truck, req.user)
})
Truck
.remove({date: {$lt: now.setDate(now.getDate()-1)}, temporality:"today"})
.exec(function(err, trucks){
if (err) throw err
console.log(trucks)
})
res.send("ok")
return null
}
|
var nano = require('nano');
var Q = require('q');
var exp = {
setup : setup,
nano : nano
}
function setup(config){
var d = Q.defer();
nano = nano(config.couchdbUrl);
function fin(){
design(config)
.then(function (cfg) {
var theDb = nano.db.use('liblib')
var dbq = {
view : function(view, params){
var d = Q.defer();
var design;
if(/\//.test(view)){
design = view.split('/')[0];
view = view.split('/')[1];
} else {
design = designDocName;
}
theDb.view(design, view, params, function(err, data){
if(err){
d.reject(err);
} else {
d.resolve(data);
}
});
return d.promise;
},
fetch : Q.nbind(theDb.fetch, theDb),
insert : Q.nbind(theDb.insert, theDb),
list : Q.nbind(theDb.list, theDb),
get : Q.nbind(theDb.get, theDb),
destroy : Q.nbind(theDb.destroy, theDb)
}
var ret = {
config : cfg,
q : dbq
}
d.resolve(ret)
})
}
nano.db.get('liblib', function(err, body){
if(err){
nano.db.create('liblib', function(err, body){
if(err){
d.reject(new Error("couchDB problem: " + err));
} else {
fin();
}
});
} else {
fin();
}
});
return d.promise;
}
function design(config){
var d = Q.defer();
nano.db.use(config.dbName).insert({
views : {
all : {
map : function(doc){
emit(doc.id);
}
}
},
lists : {
ul : function (head, req) {
provides('html', function(){
html = "<html><body><ul>\n";
while (row = getRow()) {
html += "<li>" + row.key + ":" + row.value + "</li>\n";
}
html += "</ul></body></head>";
return html;
});
}
}
}, '_design/liblib', function (err, res) {
d.resolve(config);
});
return d.promise;
}
module.exports = exp
|
//vendors
let modules = [];
if(process.env.npm_lifecycle_event === 'server') {
require('bootstrap-sass/eyeglass-exports');
require('./styles/bootstrap.scss');
require('angular');
require('angular-vs-repeat/src/angular-vs-repeat.min.js');
modules.push(require('angular-animate'));
modules.push('vs-repeat');
var _ = require('lodash');
var moment = require('moment/moment.js');
}
if(process.env.npm_lifecycle_event === 'server' || process.env.npm_lifecycle_event === 'build') {
//eonasdan-bootstrap-datetimepicker
require('eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css');
require('eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker.js');
require('./styles/calendar.scss');
require('./styles/datetimepicker.scss');
}
//controllers
import CalendarCtrl from './controllers/calendar-ctrl.js';
import TimepickerCtrl from './controllers/timepicker-ctrl.js';
import CheckDatesCtrl from './controllers/check-dates-ctrl.js';
import CalendarTestCtrl from './controllers/calendar-test-ctrl.js';
import DateTimePickerCtrl from './controllers/date-time-picker-ctrl.js';
//services
import CalendarService from './services/calendar.service.js';
//directives
import availabilityCalendar from './directives/availablity-calendar.js';
import calendarInfiniteScroll from './directives/calendar-infinite-scroll.js';
import cellTimepicker from './directives/cell-timepicker.js';
import mouseOver from './directives/mouse-over.js';
import showPicker from './directives/show-picker.js';
import cellDatepicker from './directives/cell-datepicker.js';
import checkerDates from './directives/check-dates.js';
import dateTimePicker from './directives/datetimepicker.js';
const MODULE_NAME = 'availabilityCalendar';
angular
.module(MODULE_NAME, modules)
//services
.service('CalendarService', CalendarService)
//controllers
.controller('CalendarCtrl', CalendarCtrl)
.controller('TimepickerCtrl', TimepickerCtrl)
.controller('CheckDatesCtrl', CheckDatesCtrl)
.controller('CalendarTestCtrl', CalendarTestCtrl)
.controller('DateTimePickerCtrl', DateTimePickerCtrl)
//directives
.directive('availabilityCalendar', availabilityCalendar)
.directive('calendarInfiniteScroll', calendarInfiniteScroll)
.directive('cellTimepicker', cellTimepicker)
.directive('mouseOver', mouseOver)
.directive('showPicker', showPicker)
.directive('cellDatepicker', cellDatepicker)
.directive('checkerDates', checkerDates)
.directive('dateTimePicker', dateTimePicker)
;
export default MODULE_NAME;
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdBusiness(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M24 14h20v28H4V6h20v8zM12 38v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm8 24v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm20 24V18H24v4h4v4h-4v4h4v4h-4v4h16zm-4-16h-4v4h4v-4zm0 8h-4v4h4v-4z" />
</IconBase>
);
}
export default MdBusiness;
|
var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = require('./_testPostCSS');
var getFixture = require('./_getFixture');
function testColorMutation (t, color, method) {
if (!method) {
method = 'deuteranopia';
}
return testPostCSS(
t,
getFixture(color),
getFixture(colorblind[method.toLowerCase().trim()](color)),
{method: method}
);
}
['#123', '#000', '#fff', '#f06d06'].forEach(function(hex, index) {
test(
'should transform hex (' + (index + 1) + ')',
testColorMutation,
hex
);
});
[{
from: '#1234',
hex: '#123',
alpha: '0.27',
}, {
from: '#9344ABCD',
hex: '#9344AB',
alpha: '0.8',
}, {
from: '#FFFFFFFF',
hex: '#FFFFFF',
alpha: '1',
}, {
from: '#0000',
hex: '#000',
alpha: '0',
}, {
from: 'rgba(30, 50, 200, 1)',
hex: '#1E32C8',
alpha: 1,
}, {
from: 'rgba(100, 200, 0, 0)',
hex: '#64C800',
alpha: 0,
}, {
from: 'rgba(150,50,50,.4)',
hex: '#963232',
alpha: .4,
}, {
from: 'hsla(30, 50%, 50%, 1)',
hex: '#BF8040',
alpha: 1,
}, {
from: 'hsla(100, 80%, 30%, 0)',
hex: '#388A0F',
alpha: 0,
}, {
from: 'hsla(150,50%,50%,.4)',
hex: '#40BF80',
alpha: .4,
}].forEach(function(map, index) {
test(
`should transform ${map.from} (${index + 1})`,
testPostCSS,
getFixture(map.from),
getFixture(onecolor(colorblind.deuteranopia(map.hex)).alpha(map.alpha).cssa())
);
});
var solidColors = {
/* hex/rgb */
'#1E32C8': 'rgb(30, 50, 200)',
'#64C800': 'rgb(100, 200, 0)',
'#963232': 'rgb(150,50,50)',
/* hex/hsl */
'#BF8040': 'hsl(30, 50%, 50%)',
'#388A0F': 'hsl(100, 80%, 30%)',
'#40BF80': 'hsl(150,50%,50%)',
}
Object.keys(solidColors).forEach(function(key, index) {
var out = solidColors[key];
test(
`should transform ${out} (${index + 1})`,
testPostCSS,
getFixture(out),
getFixture(onecolor(colorblind.deuteranopia(key)).css())
);
});
var keywordMap = {
mediumSeaGreen: '#3CB371',
PapayaWhip: '#FFEFD5',
thistle: '#D8BFD8',
BlanchedAlmond: '#FFEBCD',
rebeccaPurple: '#639',
};
Object.keys(keywordMap).forEach(function(keyword, index) {
var hex = keywordMap[keyword];
test(
'should transform named color (' + (index + 1) + ')',
testColorMutation,
keyword
);
});
test(
'should do a simple hex deuteranopia transform',
testColorMutation,
`#FFCC00`
);
test(
'should do a simple hex achromatopsia transform',
testColorMutation,
`#D929E2`,
'achromatopsia'
);
test(
'should do a simple named color deuteranopia transform',
testPostCSS,
`.some-color { border: 3px red solid; font-size: 12px }`,
`.some-color { border: 3px ${colorblind.deuteranopia(colorNames.red)} solid; font-size: 12px }`
);
test(
'should do a multi tritanopia transform',
testPostCSS,
`.some-color { border: 3px #D929E2 solid; color: lime }`,
`.some-color { border: 3px ${colorblind.tritanopia('#D929E2')} solid; color: ${colorblind.tritanopia('lime')} }`,
{method: 'tritanopia'}
);
test(
'should work inside gradients',
testPostCSS,
`.some-color { background: linear-gradient(#000000, hsla(120, 30%, 80%, .8)) }`,
`.some-color { background: linear-gradient(#000000, ${onecolor(colorblind.deuteranopia('#bddbbd')).alpha('0.8').cssa()}) }`
);
test('should process images and yield an inlined data url', t => {
return getProcessor().process(`a{background:url(${path.join(__dirname, 'fixture.jpg')})}`).then(function(result) {
t.deepEqual(result.css.indexOf('data:image/jpeg;base64'), 17);
});
});
test(
'should handle weird capitalization of method names',
testColorMutation,
'#FFCC00',
'DEuTerAnopiA'
);
test(
'should handle weird whitespace',
testColorMutation,
'#FFCC00',
' deuteranopia '
);
test(
'should handle capitalized color names',
testColorMutation,
'ALICebLuE'
);
test('should throw an error on a bad method name', function(t) {
t.throws(function () {
return testPostCSS(t, 'h1{}', 'h1{}', {method:'bad method name'})
});
});
|
/*
* opLoadBalancer.js: lbaas APIs
* for Openstack networking
*
* (C) 2015 Hopebaytech
*
* P. Hsuan
*/
var urlJoin = require('url-join');
var _ = require('lodash');
var lbaasHealthMonitorPath = '/lb/health_monitors';
// Declaring variables for helper functions defined later
var _convertcreateToWireFormat;
/***
Health monitor list (GET)
***/
exports.getHealthMonitors = function (options, callback) {
var self = this;
if (typeof options === 'function') {
callback = options;
options = {};
}
var getlbaasOpts = {
path: lbaasHealthMonitorPath,
};
this._request(getlbaasOpts, function (err, body) {
if (err) {
return callback(err);
}
else if (!body || !body.health_monitors || !(body.health_monitors instanceof Array)) {
return new Error('Malformed API Response');
}
return callback(err, body.health_monitors.map(function (lbaasvip) {
return new self.models.HealthMonitor(self, lbaasvip);
}));
});
};
/**
show Health Monitor
*/
exports.getHealthMonitor = function (option, callback) {
var self = this,
monitorID = option instanceof this.models.HealthMonitor ? option.id : option;
self.emit('log::trace', 'Getting details for lbaas health monitor', monitorID);
this._request({
path: urlJoin(lbaasHealthMonitorPath, monitorID),
method: 'GET'
}, function (err, body) {
if (err) {
return callback(err);
}
if (!body ||!body.health_monitor) {
return new Error('Malformed API Response');
}
callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
create Health monitor
{
"health_monitor":{
"admin_state_up": true,
"delay": "1",
"expected_codes": "200,201,202",
"http_method": "GET",
"max_retries": 5,
"pool_id": "74aa2010-a59f-4d35-a436-60a6da882819",
"timeout": 1,
"type": "HTTP",
"url_path": "/index.html"
}
}
*/
exports.createHealthMonitor = function (options, callback) {
var self = this,
monitor = typeof options === 'object' ? options : {};
var monitor_create = _convertcreateToWireFormat(monitor);
var creatmonitorOpts = {
method: 'POST',
path: lbaasHealthMonitorPath,
body: { 'health_monitor' : monitor_create}
};
self.emit('log::trace', 'Creating Health Monitor', monitor);
this._request(creatmonitorOpts, function (err,body) {
return err
? callback(err)
: callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
update Health monitor
*/
exports.updateHealthMonitor = function (options, callback) {
var self = this,
monitor = typeof options === 'object' ? options : {};
var monitor_update = _.pick(monitor, ['delay', 'timeout', 'max_retries', 'http_method', 'url_path', 'expected_codes', 'admin_state_up']);
var updateMonitorOpts = {
method: 'PUT',
path: urlJoin(lbaasHealthMonitorPath, monitor.id),
contentType: 'application/json',
body: { 'health_monitor' : monitor_update}
};
self.emit('log::trace', 'update health monitor', monitor);
this._request(updateMonitorOpts, function (err,body) {
return err
? callback(err)
: callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
Delete Health monitor
*/
exports.destroyHealthMonitor = function (options, callback) {
var self = this,
monitorID = options instanceof this.models.HealthMonitor ? options.id : options;
console.log(urlJoin(lbaasHealthMonitorPath, monitorID));
self.emit('log::trace', 'Deleting lbaas health monitor', monitorID);
this._request({
path: urlJoin(lbaasHealthMonitorPath, monitorID),
contentType: 'application/json',
method: 'DELETE'
}, function (err) {
if (err) {
return callback(err);
}
callback(err, monitorID);
});
};
/*
convert create to wire format
*/
_convertcreateToWireFormat = function (details){
var wireFormat = {};
wireFormat.type = details.type || null;
wireFormat.delay = details.delay || null;
wireFormat.timeout = details.timeout || null;
wireFormat.max_retries = details.max_retries || null;
if(wireFormat.type === 'HTTP' || wireFormat.type === 'HTTPS')
{
wireFormat.http_method = details.http_method || null;
wireFormat.url_path = details.url_path || null;
wireFormat.expected_codes = details.expected_codes || null;
}
return wireFormat;
};
|
let deserialize = require('./src/deserialize');
let serialize = require('./src/serialize');
let prettyHrtime = require('pretty-hrtime');
let Instruction = require('./src/Instruction');
let start = process.hrtime(), data;
let tree = [
new Instruction('test', { a: 1, b: 2, c: 3 })
];
let sMethods = {
'test': ({ a, b, c }) => [a, b, c]
};
let dsMethods = {
'test': ([a, b, c]) => ({ a, b, c })
};
for (let i = 0; i < 10000; i++) {
data = serialize(
tree, sMethods
);
}
let end = process.hrtime(start);
let stime = prettyHrtime(end, {precise:true});
setTimeout(() => console.log('data is', data));
setTimeout(() => console.log(`serialization 10000x took ${stime}`));
let result;
start = process.hrtime();
for(let i = 0; i < 10000; i++) {
result = deserialize(data, dsMethods);
}
end = process.hrtime(start);
let dtime = prettyHrtime(end, {precise:true});
setTimeout(() => console.log('result is', result));
setTimeout(() => console.log(`deserialization 10000x took ${dtime}`));
|
const { exitChrome } = require('./chrome-launcher')
async function exit () {
await exitChrome()
process.exit(0)
}
async function exitWithError () {
await exitChrome()
process.exit(1)
}
module.exports = {
exit,
exitWithError
}
|
(bbn_resolve) => {
((bbn) => {
let script = document.createElement('script');
script.innerHTML = `<div :class="componentClass">
<div class="bbn-hidden" v-if="$slots.default" ref="slot">
<slot></slot>
</div>
<div :class="getComponentName() + '-content'">
<div v-for="(li, idx) in filteredData"
v-if="!pageable || ((idx >= start) && (idx < start + currentLimit))"
:key="li.key"
:class="['bbn-w-25', 'bbn-mobile-w-50', getComponentName() + '-items']">
<component v-if="currentComponent"
:is="currentComponent"
v-bind="componentOptions"
:source="li.data"
:index="li.index"
@remove="remove(idx)"
:key="li.key">
</component>
<component v-else
:is="li.data && li.data.url && !li.data[children] ? 'a' : 'span'"
@click.prevent="() => {}"
class="bbn-block bbn-padded"
:title="li.data[sourceText]"
:href="li.data && li.data.url ? li.data.url : null"
:key="li.key">
<span class="bbn-top-left"
v-if="selection || (mode === 'options')">
<i v-if="li.data.selected"
class="nf nf-fa-check"></i>
</span>
<img v-if="li.data.image"
:src="li.data.image"
class="bbn-bottom-space">
<p class="bbn-large"
v-html="li.data[sourceText]"/>
<p v-if="li.data.price"
:class="componentClass + '-price'"
v-html="li.data.price"/>
<p v-if="li.data.desc"
:class="componentClass + '-desc'"
v-html="li.data.desc"/>
</component>
</div>
</div>
<div class="bbn-w-100 bbn-c"
v-if="pageable && (numPages > 1)">
<div class="bbn-iblock">
<bbn-pager :element="_self"
:extra-controls="false"
:numeric-selector="false"
:buttons="false"/>
</div>
</div>
</div>
`;
script.setAttribute('id', 'bbn-tpl-component-block-list');
script.setAttribute('type', 'text/x-template');document.body.insertAdjacentElement('beforeend', script);
let css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('href', bbn.vue.libURL + 'dist/js/components/block-list/block-list.css');
document.head.insertAdjacentElement('beforeend', css);
/**
* @file bbn-combo component
* @description The easy-to-implement bbn-combo component allows you to choose a single value from a user-supplied list or to write new.
* @copyright BBN Solutions
* @author BBN Solutions
* @created 10/02/2017.
*/
(function(bbn){
"use strict";
Vue.component('bbn-block-list', {
/**
* @mixin bbn.vue.basicComponent
* @mixin bbn.vue.listComponent
* @mixin bbn.vue.componentInsideComponent
*/
mixins: [
bbn.vue.basicComponent,
bbn.vue.listComponent,
bbn.vue.componentInsideComponent
],
mounted(){
this.ready = true;
}
});
})(bbn);
if (bbn_resolve) {bbn_resolve("ok");}
})(bbn);
}
|
var utils = {}
var config = require('./configuration');
var models = require('./models');
var User = models.User;
var Email = models.Email;
var extend = require('util')._extend;
var countries = require('country-data').countries;
function get_permission_checker(permission) {
var required = permission.split('/');
var allowed = config.permissions;
for(var i = 0; i < required.length; i++)
{
if(typeof allowed == 'undefined') {
console.log("Permission checker for unspecified permission requested: " + permission);
return function(username) {
return false;
}
};
allowed = allowed[required[i]];
}
// This function return is so we can make it optimized for require_permission
return function(username) {
if(allowed.indexOf('*anonymous*') != -1)
{
return true;
}
else if((allowed.indexOf('*authenticated*') != -1) && (username != null))
{
return true;
}
else if(allowed.indexOf(username) != -1)
{
return true;
}
else
{
return false;
}
};
};
utils.get_permission_checker = get_permission_checker;
utils.has_permission = function(permission, options) {
if(get_permission_checker(permission)(options.data.root.session.currentUser))
{
return options.fn(this);
}
else
{
return options.inverse(this);
}
};
utils.require_permission = function(permission) {
if(typeof permission === 'string') {
permission = [permission];
}
var checkers = [];
for(var perm in permission) {
perm = permission[perm];
checkers.push(get_permission_checker(perm));
}
return function(req, res, next) {
var has_one = false;
for(var checker in checkers) {
checker = checkers[checker];
if(checker(req.session.currentUser)) {
has_one = true;
break;
}
}
if(has_one)
{
next();
}
else
{
console.log("Unauthorized request: " + req.session.currentUser + " needed " + permission);
res.status(401).render('auth/no_permission', { required_permission: JSON.stringify(permission) });
}
};
};
utils.require_login = function(req, res, next) {
if(req.session.currentUser == null) {
res.status(401).render('auth/no_permission', { required_permission: 'Login' });
} else {
next();
}
};
utils.require_feature = function(feature) {
if(config[feature]['enabled']) {
return function(req, res, next) {
next();
}
} else {
return function(req, res, next) {
res.render('auth/no_permission', { required_permission: 'Feature disabled' });
}
}
};
utils.get_user = function(req, res, next) {
if(!req.session.currentUser) {
next();
return;
}
User.find({
where: {
email: req.session.currentUser
}
})
.catch(function(error) {
res.status(500).send('Error retrieving user object');
})
.then(function(user) {
if(user) {
req.user = user;
res.locals.user = user;
next();
} else {
next();
}
});
}
utils.require_user = function(req, res, next) {
if(!req.session.currentUser) {
res.status(401).render('auth/no_permission', { required_permission: 'Login' });
return;
}
if(!req.user) {
// Redirect to register
res.redirect(302, '/authg/register?origin=' + req.originalUrl);
} else {
next();
}
};
utils.send_email = function(req, res, recipient, template, variables, cb) {
if(recipient == null) {
recipient = req.user.id;
} else {
recipient = recipient.id;
}
variables.layout = false;
req.app.render('email/' + template, variables, function(err, html) {
if(!!err) {
console.log('Error rendering email: ' + err);
res.status(500).send('Error rendering email');
return null;
} else {
var split = html.split('\n');
var subject = split[0];
var contents = split.slice(2).join('\n');
var info = {
UserId: recipient,
sent: false,
subject: subject,
body: contents
};
Email.create(info)
.catch(function(err) {
console.log('Error saving email: ' + err);
res.status(500).send('Error sending email');
return null;
})
.then(function(err, email) {
cb();
});
}
});
};
utils.get_reg_fields = function (request, registration, skip_internal) {
var fields = {};
for(var field in config['registration']['fields']) {
if (skip_internal && config['registration']['fields'][field]['internal'])
continue;
fields[field] = extend({}, config['registration']['fields'][field]);
if(fields[field]['type'] == 'country') {
fields[field]['type'] = 'select';
var options = fields[field]['options'];
if (options === undefined)
options = [];
for(var country in countries.all) {
options.push(countries.all[country].name);
};
fields[field]['options'] = options;
}
};
if(request)
console.log(request.body);
for(field in fields) {
if(request && ('field_' + field) in request.body) {
fields[field].value = request.body['field_' + field];
} else if(registration != null) {
for(var info in registration.RegistrationInfos) {
info = registration.RegistrationInfos[info];
if(info.field == field) {
fields[field].value = info.value;
}
}
} else {
fields[field].value = '';
}
};
return fields;
}
module.exports = utils;
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["items", "disabled", "className", "name", "error", "variant", "design", "label", "children", "size", "fontWeight", "paragraphStyle", "labelProps"],
_excluded2 = ["id", "className"];
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import classNames from 'classnames';
import { RadioButton } from '../../form/radio-button';
import { pxToRem } from '../../../helpers/utils/typography';
import { Label } from '../../form/label';
var StyledRadioButtonSet = styled.fieldset.withConfig({
displayName: "radio-button-set__StyledRadioButtonSet",
componentId: "sc-1bde3vb-0"
})(["margin:0;padding:0;border:0;line-height:1.3rem;& > legend{padding:0;}.k-Form-RadioButtonSet__label{margin-bottom:", ";}.k-Form-RadioButtonSet__radioContainer{display:flex;flex-direction:column;gap:", " 0;.k-Form-RadioButtonSet__radioButton.k-Form-RadioButton{margin:0;}}"], pxToRem(10), pxToRem(5));
export var RadioButtonSet = function RadioButtonSet(_ref) {
var items = _ref.items,
disabled = _ref.disabled,
className = _ref.className,
name = _ref.name,
error = _ref.error,
variant = _ref.variant,
design = _ref.design,
label = _ref.label,
children = _ref.children,
size = _ref.size,
fontWeight = _ref.fontWeight,
paragraphStyle = _ref.paragraphStyle,
labelProps = _ref.labelProps,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement(StyledRadioButtonSet, _extends({
className: classNames('k-Form-RadioButtonSet', className, "k-Form-RadioButtonSet--" + variant),
disabled: disabled
}, props), label && /*#__PURE__*/React.createElement(Label, _extends({
tag: "legend"
}, labelProps, {
className: classNames('k-Form-RadioButtonSet__label', labelProps.className)
}), label), children && !label && /*#__PURE__*/React.createElement("legend", null, children), /*#__PURE__*/React.createElement("div", {
className: "k-Form-RadioButtonSet__radioContainer"
}, items.map(function (_ref2) {
var id = _ref2.id,
className = _ref2.className,
itemProps = _objectWithoutPropertiesLoose(_ref2, _excluded2);
return /*#__PURE__*/React.createElement(RadioButton, _extends({
id: id,
variant: variant,
design: design,
error: error,
size: size,
fontWeight: fontWeight,
paragraphStyle: paragraphStyle,
name: name,
key: id
}, itemProps, {
className: classNames('k-Form-RadioButtonSet__radioButton', className)
}));
})));
};
RadioButtonSet.propTypes = {
name: PropTypes.string.isRequired,
error: PropTypes.bool,
label: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape({
text: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
defaultChecked: PropTypes.bool
})),
size: PropTypes.oneOf(['small', 'regular', 'big']),
variant: PropTypes.oneOf(['andromeda', 'orion']),
design: PropTypes.oneOf(['disc', 'check']),
disabled: PropTypes.bool,
labelProps: PropTypes.object,
fontWeight: PropTypes.oneOf(['light', 'regular', 'bold']),
paragraphStyle: false
};
RadioButtonSet.defaultProps = {
name: 'radioButtonSet',
error: false,
label: null,
items: [{
text: 'filter 1',
children: 'lorem ipsum dolor',
defaultChecked: true,
id: 'myRadioButton' // Replace by a real value
}],
variant: 'orion',
design: 'disc',
disabled: false,
labelProps: {},
size: 'regular',
fontWeight: 'regular',
paragraphStyle: false
};
|
// HINT TASK
// =============================================================================
"use strict";
var taskName = 'hint';
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var config = require('./config');
require('jshint-stylish');
gulp.task('hint', function() {
return gulp.src(config.lint.src)
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('lint', function() {
return gulp.src(config.lint.src)
.pipe(plumber())
.pipe(jshint());
});
|
var votesControllers = angular.module('votesControllers', []);
votesControllers.controller('VotesCtrl', ['$scope','$routeParams','$location', '$http','$rootScope','$cookies','GetVotes','GetLastVotes','GetVotesById',
function($scope,$routeParams,$location, $http,$rootScope,$cookies,GetVotes,GetLastVotes,GetVotesById) {
$scope.summoner=$routeParams.summoner;
$scope.loading_data=true;
var pagin=0;
$('#decrease_pagination').hide();
$scope.votes;
$scope.pagination=1;
$scope.game_mode;
$scope.no_game=false;
$scope.stats;
$scope.messages;
$scope.profile_name;
$scope.show_recent_votes=true;
$scope.loading_votes=true
$scope.league;
$scope.skip=0;
$scope.pagination_number=1;
var json_data={data:{name:$scope.summoner,pagination:$scope.pagination}};
GetVotes.query(json_data,function(data) {
console.log(data);
$scope.votes=data;
var matchid;
setTimeout(function(){
for (var i = 0; i < data.length; i++) {
matchid=data[i].match_id;
console.log(matchid);
$("#"+ data[i].match_id).hover(function () {
$("#"+ this.id +"_stats").slideToggle("fast");
});
}
}, 1000);
pagin=$scope.votes.length/5;
if ( $scope.pagination_number>pagin-1) {
setTimeout(function(){
$('#increase_pagination').fadeOut();
console.log(pagin);
}, 1000);
}
$scope.loading_data=false;
var json_data={data:{name:$scope.summoner,match_id:data[0].match_id}};
// GetLastVotes.query(json_data,function(data) {
// console.log(data);
// $scope.messages=data[0][0];
// $scope.stats=data[2][0];
// $scope.loading_votes=false;
// });
// $(document).ready(function() {
// $("#champ-panel").hide();
// });
});
$scope.votesById=function(target)
{
$('#p2').css("visibility","visible");
$scope.loading_votes=true;
var json_data={data:{name:$scope.summoner,match_id:target}};
GetVotesById.query(json_data,function(data) {
$scope.show_recent_votes=false;
$('#p2').css("visibility","hidden");
$scope.messages=data[0][0];
$scope.stats=data[2][0];
console.log($scope.stats);
$scope.loading_votes=false;
});
}
$scope.increase_pagination=function()
{
console.log(pagin);
if ( $scope.pagination_number>pagin-1) {
console.log(pagin);
$('#increase_pagination').fadeOut()
}
$scope.skip+=5;
$scope.pagination_number++;
$('#decrease_pagination').fadeIn()
}
$scope.decrease_pagination=function()
{
$('#increase_pagination').fadeIn()
$scope.skip-=5;
$scope.pagination_number--;
if ($scope.pagination_number==1) {
$('#decrease_pagination').fadeOut();
}
}
}]);
|
var content_output2 = '<h2> Output In File JS test2 </h2>'
+ '<p>getAllParams: ' + JSON.stringify(PaserCurrentFileJs.getAllParams())
+ '<p>getAllAttributes: ' + JSON.stringify(PaserCurrentFileJs.getAllAttributes())
+ '<p>getValueParam param1: ' + JSON.stringify(PaserCurrentFileJs.getValueParam('param1'))
+ '<p>getValueParam param2: ' + JSON.stringify(PaserCurrentFileJs.getValueParam('param2'))
+ '<p>getValueAttribute attr-param1: ' + JSON.stringify(PaserCurrentFileJs.getValueAttribute('attr-param1'))
+ '<p>getValueAttribute attr-param2: ' + JSON.stringify(PaserCurrentFileJs.getValueAttribute('attr-param2'))
+ '<p>-----------------------------------------------------------------------------';
document.write(content_output2);
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', '@uirouter/core', './ui-view-spinner', './content-cache'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('@uirouter/core'), require('./ui-view-spinner'), require('./content-cache'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.core, global.uiViewSpinner, global.contentCache);
global.uiViewController = mod.exports;
}
})(this, function (exports, _core, _uiViewSpinner, _contentCache) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _uiViewSpinner2 = _interopRequireDefault(_uiViewSpinner);
var _contentCache2 = _interopRequireDefault(_contentCache);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var UiViewController = function () {
function UiViewController($animate, $state, $element, $scope, $q) {
_classCallCheck(this, UiViewController);
this.onDestroyCallbacks = [];
$animate.enabled($element, false);
this.$state = $state;
this.$element = $element;
var spinner = _uiViewSpinner2.default.attachTo($element);
var _$element$data = $element.data('$uiView'),
$cfg = _$element$data.$cfg;
this.deps = $cfg && $cfg.viewDecl.resolve || [];
if ($cfg) {
$element.html(_contentCache2.default.get($cfg.viewDecl) || undefined);
}
this.$scope = $scope;
if (this.deps.length) {
var resolveCtx = $cfg.path && new _core.ResolveContext($cfg.path);
$scope.$watchGroup(this.deps.map(function (token) {
return function () {
return resolveCtx.getResolvable(token).get(resolveCtx);
};
}), function (promises) {
spinner.show();
if (!(0, _core.any)(function (p) {
return p !== undefined;
})(promises)) {
return;
}
$q.all(promises).finally(function () {
return spinner.hide();
});
});
}
}
_createClass(UiViewController, [{
key: '$onDestroy',
value: function $onDestroy() {
var $uiView = this.$element.data('$uiView');
if (!$uiView || !$uiView.$cfg) return;
var $cfg = $uiView.$cfg;
var $element = this.$element;
var trans = this.$state.transition;
if (trans) {
var entering = trans.entering();
var exiting = trans.exiting().filter(function (node) {
return entering.indexOf(node) === -1;
});
if (exiting.indexOf($cfg.viewDecl.$context.self) !== -1) {
_contentCache2.default.delete($cfg.viewDecl);
} else {
_contentCache2.default.set($cfg.viewDecl, $element.html());
}
}
this.onDestroyCallbacks.forEach(function (fn) {
return fn();
});
}
}, {
key: 'onDestroy',
value: function onDestroy(fn) {
this.onDestroyCallbacks.push(fn);
}
}]);
return UiViewController;
}();
exports.default = UiViewController;
UiViewController.$inject = ['$animate', '$state', '$element', '$scope', '$q'];
});
|
Package.describe({
name: 'iron:url',
summary: 'Url utilities and support for compiling a url into a regular expression.',
version: '1.1.0',
git: 'https://github.com/iron-meteor/iron-url'
});
Package.on_use(function (api) {
api.versionsFrom('METEOR@0.9.2');
api.use('underscore');
api.use('iron:core@1.0.11');
api.imply('iron:core');
api.add_files('lib/compiler.js');
api.add_files('lib/url.js');
});
Package.on_test(function (api) {
api.use('iron:url');
api.use('tinytest');
api.use('test-helpers');
api.add_files('test/url_test.js', ['client', 'server']);
});
|
module.exports = {
moduleFileExtensions: ['js', 'json', 'vue'],
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.vue$': '@vue/vue3-jest',
},
testMatch: ['**/tests/**/*.test.js'],
};
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["require","exports","../../core/tsSupport/declareExtendsHelper","../../core/tsSupport/decorateHelper","../../core/accessorSupport/decorators","../../core/Accessor","../../portal/Portal"],function(r,t,e,o,p,s,l){var n=a=function(r){function t(){var t=null!==r&&r.apply(this,arguments)||this;return t.portal=null,t}return e(t,r),t.prototype.clone=function(){return new a({name:this.name,styleUrl:this.styleUrl,styleName:this.styleName,portal:this.portal})},t}(p.declared(s));o([p.property({type:String})],n.prototype,"name",void 0),o([p.property({type:String})],n.prototype,"styleUrl",void 0),o([p.property({type:String})],n.prototype,"styleName",void 0),o([p.property({type:l})],n.prototype,"portal",void 0),n=a=o([p.subclass("esri.symbols.support.StyleOrigin")],n);var a;return n});
|
var SOURCE_FOLDER = __dirname + '/src/';
var DIST_FOLDER = __dirname + '/dist/';
var BUNDLE_NAME = 'visible.min.js';
var webpack = require('webpack');
module.exports = {
entry: SOURCE_FOLDER + '/visible.js',
target: 'web',
output: {
library: 'visible',
path: DIST_FOLDER,
filename: BUNDLE_NAME,
publicPath: '/'
},
externals: [
{
visible: "visible"
}
],
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false,
semicolons: true
}
})
],
module: {
loaders: [
{ test: /\.(js|jsx)$/, exclude: /(bower_components|node_modules)/, loader: 'babel-loader' }
]
},
devServer: {
port: 8080,
host: '0.0.0.0',
lazy: true,
contentBase: SOURCE_FOLDER,
stats: { colors: true }
}
};
|
var CML__IO_8h =
[
[ "IOError", "classIOError.html", "classIOError" ],
[ "IOModuleSettings", "structIOModuleSettings.html", "structIOModuleSettings" ],
[ "IOModule", "classIOModule.html", "classIOModule" ],
[ "DigOutPDO", "classIOModule_1_1DigOutPDO.html", "classIOModule_1_1DigOutPDO" ],
[ "AlgOutPDO", "classIOModule_1_1AlgOutPDO.html", "classIOModule_1_1AlgOutPDO" ],
[ "DigInPDO", "classIOModule_1_1DigInPDO.html", "classIOModule_1_1DigInPDO" ],
[ "AlgInPDO", "classIOModule_1_1AlgInPDO.html", "classIOModule_1_1AlgInPDO" ],
[ "IO_AIN_TRIG_TYPE", "CML__IO_8h.html#a40ae20ad10991639d19890205786b048", [
[ "IOAINTRIG_UPPER_LIM", "CML__IO_8h.html#a40ae20ad10991639d19890205786b048aeb5efe8c33129c3f022abfdb7449aefb", null ],
[ "IOAINTRIG_LOWER_LIM", "CML__IO_8h.html#a40ae20ad10991639d19890205786b048affa901f2f2a9fd0795ab0ac804b8e17b", null ],
[ "IOAINTRIG_UDELTA", "CML__IO_8h.html#a40ae20ad10991639d19890205786b048ab62ec27b3d31a8aa3e13fec3b1995000", null ],
[ "IOAINTRIG_NDELTA", "CML__IO_8h.html#a40ae20ad10991639d19890205786b048a86970c16f123f79de2943dc6f0dae1a4", null ],
[ "IOAINTRIG_PDELTA", "CML__IO_8h.html#a40ae20ad10991639d19890205786b048a0669cbb34e7aac4c73a34a168fc7cf31", null ]
] ],
[ "IO_OBJID", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630", [
[ "IOOBJID_DIN_8_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a1aeddf890f5a1e2a495de5070997a53a", null ],
[ "IOOBJID_DIN_8_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a0062790ac8cecf0c6d876ec1e458d489", null ],
[ "IOOBJID_DIN_8_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a708936c861ee81b6ca2eb7601e12b8c3", null ],
[ "IOOBJID_DIN_INTENA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a9ab96ec7d8ee0bb61eea4005263fcd87", null ],
[ "IOOBJID_DIN_8_MASK_ANY", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a60fe35480ecf78019e60caa358588a99", null ],
[ "IOOBJID_DIN_8_MASK_L2H", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a241aabc144feaa882e2516d37e8fd9ee", null ],
[ "IOOBJID_DIN_8_MASK_H2L", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a1c2b261d62b5db21a791eec87e888131", null ],
[ "IOOBJID_DIN_1_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630aa4f29fa5ed5f6630ed89987dc3701adb", null ],
[ "IOOBJID_DIN_1_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630aa6027327b9a82ea341a8053804567021", null ],
[ "IOOBJID_DIN_1_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a410b22b5cd0b996c93da0a652997f8ee", null ],
[ "IOOBJID_DIN_1_MASK_ANY", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a8ff6ea4ca1d6a6c9a6dcb3d46c7686ff", null ],
[ "IOOBJID_DIN_1_MASK_L2H", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ab44e07687a621c20837fc37330622856", null ],
[ "IOOBJID_DIN_1_MASK_H2L", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a025110571061a0d36820039ba201fe85", null ],
[ "IOOBJID_DIN_16_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a88b5191721270db32c23983e5313921e", null ],
[ "IOOBJID_DIN_16_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ad3c3c32c5b3be2532cd177596dfd2827", null ],
[ "IOOBJID_DIN_16_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630aa6fcafbd4664abd2ebaa09d65abc276e", null ],
[ "IOOBJID_DIN_16_MASK_ANY", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630afa2eb8d8cf9db66ecdcfabf348cc7353", null ],
[ "IOOBJID_DIN_16_MASK_L2H", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a92b537d400a80b8f3fb6e02d9d7e26f8", null ],
[ "IOOBJID_DIN_16_MASK_H2L", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ab617cc852f436f8b532b9f4cb388e780", null ],
[ "IOOBJID_DIN_32_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630adfbe843d8c7c561b2ff9b6bf73351716", null ],
[ "IOOBJID_DIN_32_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ae1e2a6c524557c51afb15ab712ea6eac", null ],
[ "IOOBJID_DIN_32_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a1122fb8a2f2efa2dc651f1a81e4dd37e", null ],
[ "IOOBJID_DIN_32_MASK_ANY", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a0c126b0943dd51ba0a4d81da3e370095", null ],
[ "IOOBJID_DIN_32_MASK_L2H", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630af7b7efcf50b8aaa903a808ac157c7b2e", null ],
[ "IOOBJID_DIN_32_MASK_H2L", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a3cf0d3449f25162126184f7c5de8049c", null ],
[ "IOOBJID_DOUT_8_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a08b32b554595b82d78a1c2eafccc2b34", null ],
[ "IOOBJID_DOUT_8_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a2dba139bab8ab7bacea8f384dc754090", null ],
[ "IOOBJID_DOUT_8_ERRMODE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630adfffc1d5f98f3cd7a61f95397199eabd", null ],
[ "IOOBJID_DOUT_8_ERRVAL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a661937ebc6d74a80838301852be74692", null ],
[ "IOOBJID_DOUT_8_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a754a70428821c36427272bcd20fbd66b", null ],
[ "IOOBJID_DOUT_1_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a8c40489c3933c4336cb878760979a6c1", null ],
[ "IOOBJID_DOUT_1_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a6eb9813f25f70a2483ea737aee91baa5", null ],
[ "IOOBJID_DOUT_1_ERRMODE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630adbce4c8d0509cc3d9f3b584eea10a382", null ],
[ "IOOBJID_DOUT_1_ERRVAL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a6185f29fa5ab71d24f87e1050adebe00", null ],
[ "IOOBJID_DOUT_1_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a20d054f9d42d1ebb8ab3e486f072911b", null ],
[ "IOOBJID_DOUT_16_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a341ff794e63bd76f7e0965c60da8aadb", null ],
[ "IOOBJID_DOUT_16_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a8ebd674fe0a82073effb557d0deb0471", null ],
[ "IOOBJID_DOUT_16_ERRMODE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a8db303c9a9af520df1424359dacc3a78", null ],
[ "IOOBJID_DOUT_16_ERRVAL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a20e9a886c5aaae641921c19bfc331b1e", null ],
[ "IOOBJID_DOUT_16_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a3a4d577cdfb4b62926396e61124bb543", null ],
[ "IOOBJID_DOUT_32_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a621e2cfbcd791645bd90c9dbd1e7e6f6", null ],
[ "IOOBJID_DOUT_32_POL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a89901def78adcb9340478b71a3e61ff9", null ],
[ "IOOBJID_DOUT_32_ERRMODE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630af806e2ef8186aa823ca2196481d98766", null ],
[ "IOOBJID_DOUT_32_ERRVAL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ab481bc897a2e0a664ace7ff31145c50b", null ],
[ "IOOBJID_DOUT_32_FILT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a4c26737b300b5598dcd8464fcb5e72f8", null ],
[ "IOOBJID_AIN_8_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a9b63aa31ce12083a2edcf4d02082b047", null ],
[ "IOOBJID_AIN_16_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a7d39a95936b6f5e409a575aa5e00300d", null ],
[ "IOOBJID_AIN_32_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630abfd01cc535debe06ead48fab44333018", null ],
[ "IOOBJID_AIN_FLT_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ad35464986b3f590b970a229c34a1d11a", null ],
[ "IOOBJID_AIN_MFG_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630af3fee0c7b74c3c2fb67160e7179e24d8", null ],
[ "IOOBJID_AOUT_8_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ab7dd6f1e6df0f81e9ac160b14019163b", null ],
[ "IOOBJID_AOUT_16_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a098cb6b4a16035ccbf119bb76b5c3ff0", null ],
[ "IOOBJID_AOUT_32_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a8ad5acdfd9b3a7923cb0c1c1db7f9d1c", null ],
[ "IOOBJID_AOUT_FLT_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a462139ac95228c21808c6131392736dc", null ],
[ "IOOBJID_AOUT_MFG_VALUE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a637c02ab464998c6a96266b9d2d31ed5", null ],
[ "IOOBJID_AIN_TRIG", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a81a2bf9b595993f982506435ec43e853", null ],
[ "IOOBJID_AIN_INTSRC", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ac31715c734b7bb9d0ec686c83bfc3b6f", null ],
[ "IOOBJID_AIN_INTENA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a84807dd227c9eed67b6001b4a7db3d0a", null ],
[ "IOOBJID_AIN_32_UPLIM", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a5ff54cc1b86f1f311f08c201857a8da1", null ],
[ "IOOBJID_AIN_32_LWLIM", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a5e0726e03817e7354208fac76e6a1b1d", null ],
[ "IOOBJID_AIN_32_UDELTA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a7177a8b7064a88a85b3b4bf656b4aaaa", null ],
[ "IOOBJID_AIN_32_NDELTA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a1a2466603f8eba7ac6ba44f66e9b201a", null ],
[ "IOOBJID_AIN_32_PDELTA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a080f3e7509484d193d819d9af5c01d5e", null ],
[ "IOOBJID_AIN_FLT_UPLIM", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630abd12e2d3966c3a4af8ce8d51063857e9", null ],
[ "IOOBJID_AIN_FLT_LWLIM", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a96777b15ffec1092f5878b3835fc5805", null ],
[ "IOOBJID_AIN_FLT_UDELTA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a47ab5a971039426d8c8d522733ed1144", null ],
[ "IOOBJID_AIN_FLT_NDELTA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a6163b9c51e124e7ab43424c7016ab771", null ],
[ "IOOBJID_AIN_FLT_PDELTA", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630acab3e771a879a84a587972e8671c468f", null ],
[ "IOOBJID_AIN_FLT_OFFSET", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a5814674b9f662e9163e52cdfbbfee5a5", null ],
[ "IOOBJID_AIN_FLT_SCALE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630aa1557bb8fa696d7935adf626dde1efe2", null ],
[ "IOOBJID_AIN_UNIT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a11246cc29a3a01673163f7dd02ea8ec6", null ],
[ "IOOBJID_AIN_32_OFFSET", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a0051c8b42024b1687e0693ba9b66dd9e", null ],
[ "IOOBJID_AIN_32_SCALE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a37ec66dec7945876d58437908ffcac1a", null ],
[ "IOOBJID_AOUT_FLT_OFFSET", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a35b7c8ab543308f5a2435f063110426e", null ],
[ "IOOBJID_AOUT_FLT_SCALE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a694c91f640c81b727f2d2814b188aae3", null ],
[ "IOOBJID_AOUT_ERRMODE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a0c1e7aa12673d77b06ffcfda58e34b57", null ],
[ "IOOBJID_AOUT_32_ERRVAL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630aa348003ae01dbb913b257316523b2264", null ],
[ "IOOBJID_AOUT_FLT_ERRVAL", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a2a9d7c380fd7ab00799afff92cc57f37", null ],
[ "IOOBJID_AOUT_32_OFFSET", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630a057060626d6be5ad84c7568ffddfb5a1", null ],
[ "IOOBJID_AOUT_32_SCALE", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630ad6f368d6661be27423693caf79ad23f0", null ],
[ "IOOBJID_AOUT_UNIT", "CML__IO_8h.html#a53ed1e8a64fc610775814df38899c630aa0b685b857b914fa0f03f72ea518a7b6", null ]
] ],
[ "IOMODULE_EVENTS", "CML__IO_8h.html#a3682230c657b6de8db65f5bcdfddff0b", [
[ "IOEVENT_DIN_PDO0", "CML__IO_8h.html#a3682230c657b6de8db65f5bcdfddff0ba3b9664af79dfe73a2f86453feba0fcf1", null ],
[ "IOEVENT_AIN_PDO0", "CML__IO_8h.html#a3682230c657b6de8db65f5bcdfddff0baecf7b3d84cbfae6ac86b1f538b579089", null ],
[ "IOEVENT_AIN_PDO1", "CML__IO_8h.html#a3682230c657b6de8db65f5bcdfddff0ba9ca0b11c0acacb53e0f279bbbc715f18", null ],
[ "IOEVENT_AIN_PDO2", "CML__IO_8h.html#a3682230c657b6de8db65f5bcdfddff0ba54446511091a59f17d4db487ea948a6a", null ]
] ]
];
|
var express = require('express');
var router = express.Router();
var mkdirp = require('mkdirp');
var fs = require("fs");
var file = __dirname + "/../database/panoinfo.db";
var exists = fs.existsSync(file);
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);
/* GET users listing. */
router.get('/', function(req, res, next) {
var panoinfoPath = __dirname + "/../public/panoinfo";
mkdirp(panoinfoPath);
db.all("SELECT info FROM panoinfo", function(err, rows) {
for (var i = 0; i < rows.length; i++) {
var data = JSON.parse(rows[i].info);
console.log(data.location.pano)
var filePath = panoinfoPath + '/' + data.location.pano;
fs.writeFile(filePath, rows[i].info)
};
});
res.send('');
});
module.exports = router;
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define("require exports ../../../../core/tsSupport/extendsHelper ../../../../core/tsSupport/decorateHelper ../../../../core/tsSupport/assignHelper ../../../../core/libs/gl-matrix-2/mat4 ../../../../core/libs/gl-matrix-2/mat4f64 ../core/shaderTechnique/ReloadableShaderModule ../core/shaderTechnique/ShaderTechnique ../core/shaderTechnique/ShaderTechniqueConfiguration ./LaserlinePath.glsl ../../../webgl/Program ../../../webgl/renderState ../../../webgl/renderState".split(" "),function(l,e,f,m,d,n,p,
q,r,g,t,u,v,h){Object.defineProperty(e,"__esModule",{value:!0});d=function(a){function b(){return null!==a&&a.apply(this,arguments)||this}f(b,a);b.prototype.initializeProgram=function(c){var a=b.shader.get().build(this.configuration);return new u(c.rctx,a.generateSource("vertex"),a.generateSource("fragment"),b.attributeLocations)};b.prototype.bind=function(c,b,a){this.program.setUniform3fv("innerColor",c.innerColor);this.program.setUniform1f("innerWidth",c.innerWidth*a.pixelRatio);this.program.setUniform3fv("glowColor",
c.glowColor);this.program.setUniform1f("glowWidth",c.glowWidth*a.pixelRatio);this.program.setUniform1f("glowFalloff",c.glowFalloff);this.program.setUniform1f("globalAlpha",c.globalAlpha);this.program.setUniform1f("perScreenPixelRatio",a.perScreenPixelRatio);this.program.setUniform2f("pixelToNDC",2/a.fullWidth,2/a.fullHeight);this.program.setUniformMatrix4fv("uProjectionMatrix",a.projectionMatrix);n.mat4.translate(k,a.viewMatrix,b);this.program.setUniformMatrix4fv("uModelViewMatrix",k);this.configuration.contrastControlEnabled&&
this.program.setUniform1f("globalAlphaContrastBoost",null!=c.globalAlphaContrastBoost?c.globalAlphaContrastBoost:1)};b.prototype.initializePipeline=function(){return h.makePipelineState({blending:v.simpleBlendingParams(1,771),colorWrite:h.defaultColorWriteParams})};b.prototype.bindPipelineState=function(a){a.setPipelineState(this.pipeline)};b.shader=new q.ReloadableShaderModule(t,"./LaserlinePath.glsl",l);b.attributeLocations={start:0,end:1,up:2,extrude:3};return b}(r.ShaderTechnique);e.LaserlinePathTechnique=
d;d=function(a){function b(){var b=null!==a&&a.apply(this,arguments)||this;b.contrastControlEnabled=!1;return b}f(b,a);m([g.parameter()],b.prototype,"contrastControlEnabled",void 0);return b}(g.ShaderTechniqueConfiguration);e.LaserlinePathTechniqueConfiguration=d;var k=p.mat4f64.create()});
|
import arrays from './arrays';
import core from './core';
export default {
core,
arrays,
};
|
import React, { Component } from 'react'
import { Card, CardTitle, Divider } from "material-ui";
import Build from 'material-ui/svg-icons/action/build'
import Header from './basic/Header'
import Paragraph from './basic/Paragraph'
class NotFoundCard extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Card zDepth={2}
style={{
padding: "35px"
}}>
<CardTitle>
<Header text="404 Not Found">
<Build style={{
paddingRight: "20px"
}} />
</Header>
</CardTitle>
<Divider />
<Paragraph text=" We tried really hard, but we couldn't find this page anywhere." />
<Paragraph text="We suggest you go back. There is nothing to see here."/>
</Card>
)
}
}
export default NotFoundCard
|
var palloc_8h =
[
[ "palloc_t", "dc/d36/structpalloc__t.html", "dc/d36/structpalloc__t" ],
[ "MAX_PALLOC", "dc/df7/palloc_8h.html#ae98cf2dde32dd7752510faa08edec1ef", null ],
[ "PALLOC_MAX_BLOCKS", "dc/df7/palloc_8h.html#a6acb1947dc49f45d9429e9cc660ce2b1", null ],
[ "PALLOC_SIZE", "dc/df7/palloc_8h.html#a8399f294aa979d4bcd17fc199326234c", null ],
[ "palloc", "dc/df7/palloc_8h.html#ab8008be59211cc4129d9fed478ba32ac", null ],
[ "pfree", "dc/df7/palloc_8h.html#a955b5e8e3baff742271da3ff44669e43", null ],
[ "pgetusable", "dc/df7/palloc_8h.html#a4d92f3937b1e63849c7466119e561b7f", null ],
[ "pinit", "dc/df7/palloc_8h.html#acea7f1b315e15a2d1024c45b87b6276d", null ],
[ "ptotalsize", "dc/df7/palloc_8h.html#a5a2279e2e824d45690599172b2436807", null ],
[ "pusedmem", "dc/df7/palloc_8h.html#a0988517ae62414ef09cf2694c4b02b75", null ]
];
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, requireNativeComponent, NativeModules, View, ViewPropTypes, Image, Platform, UIManager, findNodeHandle, Dimensions } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
import TextTrackType from './TextTrackType';
import FilterType from './FilterType';
import VideoResizeMode from './VideoResizeMode.js';
const styles = StyleSheet.create({
base: {
overflow: 'hidden',
},
});
export { TextTrackType, FilterType };
export default class Video extends Component {
constructor(props) {
super(props);
this.state = {
showPoster: !!props.poster,
androidFullScreen: false,
videoContainerLayout_x: 0,
videoContainerLayout_y: 0,
};
this.getDimension();
}
/**
* @description this is will set the width and height needs to be considered for full screen
*/
getDimension() {
if (Dimensions.get('window').width < Dimensions.get('window').height) {
this.width = Math.round(Dimensions.get('window').height);
this.height = Math.round(Dimensions.get('window').width);
}
else {
this.width = Math.round(Dimensions.get('window').width);
this.height = Math.round(Dimensions.get('window').height);
}
}
componentDidMount() {
UIManager.measure(findNodeHandle(this._videoContainer), (x, y) => {
this.setState({
videoContainerLayout_x: x,
videoContainerLayout_y: y,
});
});
}
setNativeProps(nativeProps) {
this._root.setNativeProps(nativeProps);
}
toTypeString(x) {
switch (typeof x) {
case 'object':
return x instanceof Date
? x.toISOString()
: JSON.stringify(x); // object, null
case 'undefined':
return '';
default: // boolean, number, string
return x.toString();
}
}
stringsOnlyObject(obj) {
const strObj = {};
Object.keys(obj).forEach(x => {
strObj[x] = this.toTypeString(obj[x]);
});
return strObj;
}
seek = (time, tolerance = 100) => {
if (isNaN(time)) {throw new Error('Specified time is not a number');}
if (Platform.OS === 'ios') {
this.setNativeProps({
seek: {
time,
tolerance,
},
});
} else {
this.setNativeProps({ seek: time });
}
};
presentFullscreenPlayer = () => {
this.setNativeProps({ fullscreen: true });
};
dismissFullscreenPlayer = () => {
this.setNativeProps({ fullscreen: false });
};
save = async (options?) => {
return await NativeModules.VideoManager.save(options, findNodeHandle(this._root));
}
restoreUserInterfaceForPictureInPictureStopCompleted = (restored) => {
this.setNativeProps({ restoreUserInterfaceForPIPStopCompletionHandler: restored });
};
_assignRoot = (component) => {
this._root = component;
};
_hidePoster = () => {
if (this.state.showPoster) {
this.setState({ showPoster: false });
}
}
_onLoadStart = (event) => {
if (this.props.onLoadStart) {
this.props.onLoadStart(event.nativeEvent);
}
};
_onLoad = (event) => {
// Need to hide poster here for windows as onReadyForDisplay is not implemented
if (Platform.OS === 'windows') {
this._hidePoster();
}
if (this.props.onLoad) {
this.props.onLoad(event.nativeEvent);
}
};
_onError = (event) => {
if (this.props.onError) {
this.props.onError(event.nativeEvent);
}
};
_onProgress = (event) => {
if (this.props.onProgress) {
this.props.onProgress(event.nativeEvent);
}
};
_onBandwidthUpdate = (event) => {
if (this.props.onBandwidthUpdate) {
this.props.onBandwidthUpdate(event.nativeEvent);
}
};
_onSeek = (event) => {
if (this.props.onSeek) {
this.props.onSeek(event.nativeEvent);
}
};
_onEnd = (event) => {
if (this.props.onEnd) {
this.props.onEnd(event.nativeEvent);
}
};
_onTimedMetadata = (event) => {
if (this.props.onTimedMetadata) {
this.props.onTimedMetadata(event.nativeEvent);
}
};
_onFullscreenPlayerWillPresent = (event) => {
Platform.OS === 'android' && this.setState({ androidFullScreen: true });
if (this.props.onFullscreenPlayerWillPresent) {
this.props.onFullscreenPlayerWillPresent(event.nativeEvent);
}
};
_onFullscreenPlayerDidPresent = (event) => {
if (this.props.onFullscreenPlayerDidPresent) {
this.props.onFullscreenPlayerDidPresent(event.nativeEvent);
}
};
_onFullscreenPlayerWillDismiss = (event) => {
Platform.OS === 'android' && this.setState({ androidFullScreen: false });
if (this.props.onFullscreenPlayerWillDismiss) {
this.props.onFullscreenPlayerWillDismiss(event.nativeEvent);
}
};
_onFullscreenPlayerDidDismiss = (event) => {
if (this.props.onFullscreenPlayerDidDismiss) {
this.props.onFullscreenPlayerDidDismiss(event.nativeEvent);
}
};
_onReadyForDisplay = (event) => {
if (!this.props.audioOnly) {
this._hidePoster();
}
if (this.props.onReadyForDisplay) {
this.props.onReadyForDisplay(event.nativeEvent);
}
};
_onPlaybackStalled = (event) => {
if (this.props.onPlaybackStalled) {
this.props.onPlaybackStalled(event.nativeEvent);
}
};
_onPlaybackResume = (event) => {
if (this.props.onPlaybackResume) {
this.props.onPlaybackResume(event.nativeEvent);
}
};
_onPlaybackRateChange = (event) => {
if (this.props.onPlaybackRateChange) {
this.props.onPlaybackRateChange(event.nativeEvent);
}
};
_onExternalPlaybackChange = (event) => {
if (this.props.onExternalPlaybackChange) {
this.props.onExternalPlaybackChange(event.nativeEvent);
}
}
_onAudioBecomingNoisy = () => {
if (this.props.onAudioBecomingNoisy) {
this.props.onAudioBecomingNoisy();
}
};
_onPictureInPictureStatusChanged = (event) => {
if (this.props.onPictureInPictureStatusChanged) {
this.props.onPictureInPictureStatusChanged(event.nativeEvent);
}
};
_onRestoreUserInterfaceForPictureInPictureStop = (event) => {
if (this.props.onRestoreUserInterfaceForPictureInPictureStop) {
this.props.onRestoreUserInterfaceForPictureInPictureStop();
}
};
_onAudioFocusChanged = (event) => {
if (this.props.onAudioFocusChanged) {
this.props.onAudioFocusChanged(event.nativeEvent);
}
};
_onBuffer = (event) => {
if (this.props.onBuffer) {
this.props.onBuffer(event.nativeEvent);
}
};
getViewManagerConfig = viewManagerName => {
if (!NativeModules.UIManager.getViewManagerConfig) {
return NativeModules.UIManager[viewManagerName];
}
return NativeModules.UIManager.getViewManagerConfig(viewManagerName);
};
render() {
const resizeMode = this.props.resizeMode;
const source = resolveAssetSource(this.props.source) || {};
const shouldCache = !source.__packager_asset;
let uri = source.uri || '';
if (uri && uri.match(/^\//)) {
uri = `file://${uri}`;
}
if (!uri) {
console.warn('Trying to load empty source.');
}
const isNetwork = !!(uri && uri.match(/^https?:/));
const isAsset = !!(uri && uri.match(/^(assets-library|ipod-library|file|content|ms-appx|ms-appdata):/));
let nativeResizeMode;
const RCTVideoInstance = this.getViewManagerConfig('RCTVideo');
if (resizeMode === VideoResizeMode.stretch) {
nativeResizeMode = RCTVideoInstance.Constants.ScaleToFill;
} else if (resizeMode === VideoResizeMode.contain) {
nativeResizeMode = RCTVideoInstance.Constants.ScaleAspectFit;
} else if (resizeMode === VideoResizeMode.cover) {
nativeResizeMode = RCTVideoInstance.Constants.ScaleAspectFill;
} else {
nativeResizeMode = RCTVideoInstance.Constants.ScaleNone;
}
const nativeProps = Object.assign({}, this.props);
Object.assign(nativeProps, {
style: [styles.base, nativeProps.style],
resizeMode: nativeResizeMode,
src: {
uri,
isNetwork,
isAsset,
shouldCache,
type: source.type || '',
mainVer: source.mainVer || 0,
patchVer: source.patchVer || 0,
requestHeaders: source.headers ? this.stringsOnlyObject(source.headers) : {},
},
onVideoLoadStart: this._onLoadStart,
onVideoLoad: this._onLoad,
onVideoError: this._onError,
onVideoProgress: this._onProgress,
onVideoSeek: this._onSeek,
onVideoEnd: this._onEnd,
onVideoBuffer: this._onBuffer,
onVideoBandwidthUpdate: this._onBandwidthUpdate,
onTimedMetadata: this._onTimedMetadata,
onVideoAudioBecomingNoisy: this._onAudioBecomingNoisy,
onVideoExternalPlaybackChange: this._onExternalPlaybackChange,
onVideoFullscreenPlayerWillPresent: this._onFullscreenPlayerWillPresent,
onVideoFullscreenPlayerDidPresent: this._onFullscreenPlayerDidPresent,
onVideoFullscreenPlayerWillDismiss: this._onFullscreenPlayerWillDismiss,
onVideoFullscreenPlayerDidDismiss: this._onFullscreenPlayerDidDismiss,
onReadyForDisplay: this._onReadyForDisplay,
onPlaybackStalled: this._onPlaybackStalled,
onPlaybackResume: this._onPlaybackResume,
onPlaybackRateChange: this._onPlaybackRateChange,
onAudioFocusChanged: this._onAudioFocusChanged,
onAudioBecomingNoisy: this._onAudioBecomingNoisy,
onPictureInPictureStatusChanged: this._onPictureInPictureStatusChanged,
onRestoreUserInterfaceForPictureInPictureStop: this._onRestoreUserInterfaceForPictureInPictureStop,
});
const posterStyle = {
...StyleSheet.absoluteFillObject,
resizeMode: this.props.posterResizeMode || 'contain',
};
//androidFullScreen property will only impact on android. It will be always false for iOS.
const videoStyle = this.state.androidFullScreen ? {
position: 'absolute',
top: 0,
left: 0,
width: this.width,
height: this.height,
backgroundColor: '#ffffff',
justifyContent: 'center',
zIndex: 99999,
marginTop: -1 * (this.state.videoContainerLayout_y ? parseFloat(this.state.videoContainerLayout_y) : 0), //margin: 0 - is not working properly. So, updated all the margin individually with 0.
marginLeft: -1 * (this.state.videoContainerLayout_x ? parseFloat(this.state.videoContainerLayout_x) : 0),
} : {};
return (
<View ref={(videoContainer) => {
this._videoContainer = videoContainer;
return videoContainer;
}} style={[nativeProps.style, videoStyle]}>
<RCTVideo
ref={this._assignRoot}
{...nativeProps}
style={StyleSheet.absoluteFill}
/>
{this.state.showPoster && (
<Image style={posterStyle} source={{ uri: this.props.poster }} />
)}
</View>
);
}
}
Video.propTypes = {
filter: PropTypes.oneOf([
FilterType.NONE,
FilterType.INVERT,
FilterType.MONOCHROME,
FilterType.POSTERIZE,
FilterType.FALSE,
FilterType.MAXIMUMCOMPONENT,
FilterType.MINIMUMCOMPONENT,
FilterType.CHROME,
FilterType.FADE,
FilterType.INSTANT,
FilterType.MONO,
FilterType.NOIR,
FilterType.PROCESS,
FilterType.TONAL,
FilterType.TRANSFER,
FilterType.SEPIA,
]),
filterEnabled: PropTypes.bool,
/* Native only */
src: PropTypes.object,
seek: PropTypes.oneOfType([
PropTypes.number,
PropTypes.object,
]),
fullscreen: PropTypes.bool,
onVideoLoadStart: PropTypes.func,
onVideoLoad: PropTypes.func,
onVideoBuffer: PropTypes.func,
onVideoError: PropTypes.func,
onVideoProgress: PropTypes.func,
onVideoBandwidthUpdate: PropTypes.func,
onVideoSeek: PropTypes.func,
onVideoEnd: PropTypes.func,
onTimedMetadata: PropTypes.func,
onVideoAudioBecomingNoisy: PropTypes.func,
onVideoExternalPlaybackChange: PropTypes.func,
onVideoFullscreenPlayerWillPresent: PropTypes.func,
onVideoFullscreenPlayerDidPresent: PropTypes.func,
onVideoFullscreenPlayerWillDismiss: PropTypes.func,
onVideoFullscreenPlayerDidDismiss: PropTypes.func,
/* Wrapper component */
source: PropTypes.oneOfType([
PropTypes.shape({
uri: PropTypes.string,
}),
// Opaque type returned by require('./video.mp4')
PropTypes.number,
]),
minLoadRetryCount: PropTypes.number,
maxBitRate: PropTypes.number,
resizeMode: PropTypes.string,
poster: PropTypes.string,
posterResizeMode: Image.propTypes.resizeMode,
repeat: PropTypes.bool,
automaticallyWaitsToMinimizeStalling: PropTypes.bool,
allowsExternalPlayback: PropTypes.bool,
selectedAudioTrack: PropTypes.shape({
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
}),
selectedVideoTrack: PropTypes.shape({
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
}),
selectedTextTrack: PropTypes.shape({
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
}),
textTracks: PropTypes.arrayOf(
PropTypes.shape({
title: PropTypes.string,
uri: PropTypes.string.isRequired,
type: PropTypes.oneOf([
TextTrackType.SRT,
TextTrackType.TTML,
TextTrackType.VTT,
]),
language: PropTypes.string.isRequired,
})
),
paused: PropTypes.bool,
muted: PropTypes.bool,
volume: PropTypes.number,
bufferConfig: PropTypes.shape({
minBufferMs: PropTypes.number,
maxBufferMs: PropTypes.number,
bufferForPlaybackMs: PropTypes.number,
bufferForPlaybackAfterRebufferMs: PropTypes.number,
}),
stereoPan: PropTypes.number,
rate: PropTypes.number,
pictureInPicture: PropTypes.bool,
playInBackground: PropTypes.bool,
playWhenInactive: PropTypes.bool,
ignoreSilentSwitch: PropTypes.oneOf(['ignore', 'obey']),
reportBandwidth: PropTypes.bool,
disableFocus: PropTypes.bool,
controls: PropTypes.bool,
audioOnly: PropTypes.bool,
currentTime: PropTypes.number,
fullscreenAutorotate: PropTypes.bool,
fullscreenOrientation: PropTypes.oneOf(['all', 'landscape', 'portrait']),
progressUpdateInterval: PropTypes.number,
useTextureView: PropTypes.bool,
hideShutterView: PropTypes.bool,
onLoadStart: PropTypes.func,
onLoad: PropTypes.func,
onBuffer: PropTypes.func,
onError: PropTypes.func,
onProgress: PropTypes.func,
onBandwidthUpdate: PropTypes.func,
onSeek: PropTypes.func,
onEnd: PropTypes.func,
onFullscreenPlayerWillPresent: PropTypes.func,
onFullscreenPlayerDidPresent: PropTypes.func,
onFullscreenPlayerWillDismiss: PropTypes.func,
onFullscreenPlayerDidDismiss: PropTypes.func,
onReadyForDisplay: PropTypes.func,
onPlaybackStalled: PropTypes.func,
onPlaybackResume: PropTypes.func,
onPlaybackRateChange: PropTypes.func,
onAudioFocusChanged: PropTypes.func,
onAudioBecomingNoisy: PropTypes.func,
onPictureInPictureStatusChanged: PropTypes.func,
needsToRestoreUserInterfaceForPictureInPictureStop: PropTypes.func,
onExternalPlaybackChange: PropTypes.func,
/* Required by react-native */
scaleX: PropTypes.number,
scaleY: PropTypes.number,
translateX: PropTypes.number,
translateY: PropTypes.number,
rotation: PropTypes.number,
...ViewPropTypes,
};
const RCTVideo = requireNativeComponent('RCTVideo', Video, {
nativeOnly: {
src: true,
seek: true,
fullscreen: true,
},
});
|
module.exports = function(grunt) {
grunt.registerTask('default', ['compileAssets', 'watch']);
};
|
////////////////////////////////////////////////////////////////////////////////
//API routes
/* Instantiate Express Module*/
var express = require('express');
/* Instantiate Express Router*/
var router = express.Router();
//Instantiate Image model
var Image = require('../models/image_model.js');
//Instantiate User model
var User = require('../models/user_model.js');
////////////////////////////////////////////////////////////////////////////////
/* API */
router.get('/', function(req, res, next) {
res.setHeader(
'Content-Type',
'application/json',
'charset=utf-8'
);
res.send(200, JSON.stringify({
"message": "Requires Authentication",
"documentation_url": "https://developer.blobber.com/v1"
}));
});
///////////////////////////////////////////////////////////////////////////////
module.exports = router;
////////////////////////////////////////////////////////////////////////////////
|
function recordObj(){
this.id = '';
this.time = '';
this.value = new Object();
}
module.exports = recordObj;
|
// PMASETools Cards -- data model
// Loaded on both the client and the server
///////////////////////////////////////////////////////////////////////////////
// Cards
/*
Each card is represented by a document in the Cards collection:
x, y: Number (screen coordinates in the interval [0, 1])
text, description: String
Eventually:
owner: user id
*/
Cards = new Meteor.Collection("cards");
Cards.allow({
insert: function (userId, card) {
return false; // no cowboy inserts -- use createCard method
},
update: function (userId, card, fields, modifier) {
/* no users yet
if (userId !== card.owner)
return false; // not the owner
*/
var allowed = ["text", "description", "x", "y"];
if (_.difference(fields, allowed).length)
return false; // tried to write to forbidden field
// A good improvement would be to validate the type of the new
// value of the field (and if a string, the length.) In the
// future Meteor will have a schema system to makes that easier.
return true;
},
remove: function (userId, party) {
// cant remove yet
return false;
}
});
var NonEmptyString = Match.Where(function (x) {
check(x, String);
return x.length !== 0;
});
var Coordinate = Match.Where(function (x) {
check(x, Number);
return x >= 0 && x <= 500;
});
Meteor.methods({
// options should include: text, description, x, y
createCard: function (options) {
check(options, {
text: NonEmptyString,
// description: NonEmptyString,
x: Coordinate,
y: Coordinate
});
// tweak as necessary, showing some data validation
if (options.text.length > 100)
throw new Meteor.Error(413, "Text too long");
// if (options.description.length > 1000)
// throw new Meteor.Error(413, "Description too long");
/* no users yet
if (! this.userId)
throw new Meteor.Error(403, "You must be logged in");
*/
return Cards.insert({
// owner: this.userId,
x: options.x,
y: options.y,
text: options.text,
// description: options.description,
});
},
});
///////////////////////////////////////////////////////////////////////////////
// Users - Coming soon
/*
displayName = function (user) {
if (user.profile && user.profile.name)
return user.profile.name;
return user.emails[0].address;
};
var contactEmail = function (user) {
if (user.emails && user.emails.length)
return user.emails[0].address;
if (user.services && user.services.facebook && user.services.facebook.email)
return user.services.facebook.email;
return null;
};
*/
|
var express = require('express');
var router = express.Router();
db = new Firebase('https://codherjs.firebaseio.com/');
dbTweets = db.child('tweets');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { tweets: [] });
// dbTweets.on('child_added', function(snapshot) {
// res.render('index', { tweets: snapshot.val()});
// });
});
module.exports = router;
|
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('trainingsessions');
|
describe('tooltip', function() {
var elm,
elmBody,
scope,
elmScope,
tooltipScope;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip'));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><span tooltip="tooltip text" tooltip-animation="false">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it('should not be open initially', inject(function() {
expect( tooltipScope.isOpen ).toBe( false );
// We can only test *that* the tooltip-popup element wasn't created as the
// implementation is templated and replaced.
expect( elmBody.children().length ).toBe( 1 );
}));
it('should open on mouseenter', inject(function() {
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( true );
// We can only test *that* the tooltip-popup element was created as the
// implementation is templated and replaced.
expect( elmBody.children().length ).toBe( 2 );
}));
it('should close on mouseleave', inject(function() {
elm.trigger( 'mouseenter' );
elm.trigger( 'mouseleave' );
expect( tooltipScope.isOpen ).toBe( false );
}));
it('should not animate on animation set to false', inject(function() {
expect( tooltipScope.animation ).toBe( false );
}));
it('should have default placement of "top"', inject(function() {
elm.trigger( 'mouseenter' );
expect( tooltipScope.placement ).toBe( 'top' );
}));
it('should allow specification of placement', inject( function( $compile ) {
elm = $compile( angular.element(
'<span tooltip="tooltip text" tooltip-placement="bottom">Selector Text</span>'
) )( scope );
scope.$apply();
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
elm.trigger( 'mouseenter' );
expect( tooltipScope.placement ).toBe( 'bottom' );
}));
it('should update placement dynamically', inject( function( $compile, $timeout ) {
scope.place = 'bottom';
elm = $compile( angular.element(
'<span tooltip="tooltip text" tooltip-placement="{{place}}">Selector Text</span>'
) )( scope );
scope.$apply();
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
elm.trigger( 'mouseenter' );
expect( tooltipScope.placement ).toBe( 'bottom' );
scope.place = 'right';
scope.$digest();
$timeout.flush();
expect(tooltipScope.placement).toBe( 'right' );
}));
it('should work inside an ngRepeat', inject( function( $compile ) {
elm = $compile( angular.element(
'<ul>'+
'<li ng-repeat="item in items">'+
'<span tooltip="{{item.tooltip}}">{{item.name}}</span>'+
'</li>'+
'</ul>'
) )( scope );
scope.items = [
{ name: 'One', tooltip: 'First Tooltip' }
];
scope.$digest();
var tt = angular.element( elm.find('li > span')[0] );
tt.trigger( 'mouseenter' );
expect( tt.text() ).toBe( scope.items[0].name );
tooltipScope = tt.scope().$$childTail;
expect( tooltipScope.content ).toBe( scope.items[0].tooltip );
tt.trigger( 'mouseleave' );
}));
it('should show correct text when in an ngRepeat', inject( function( $compile, $timeout ) {
elm = $compile( angular.element(
'<ul>'+
'<li ng-repeat="item in items">'+
'<span tooltip="{{item.tooltip}}">{{item.name}}</span>'+
'</li>'+
'</ul>'
) )( scope );
scope.items = [
{ name: 'One', tooltip: 'First Tooltip' },
{ name: 'Second', tooltip: 'Second Tooltip' }
];
scope.$digest();
var tt_1 = angular.element( elm.find('li > span')[0] );
var tt_2 = angular.element( elm.find('li > span')[1] );
tt_1.trigger( 'mouseenter' );
tt_1.trigger( 'mouseleave' );
$timeout.flush();
tt_2.trigger( 'mouseenter' );
expect( tt_1.text() ).toBe( scope.items[0].name );
expect( tt_2.text() ).toBe( scope.items[1].name );
tooltipScope = tt_2.scope().$$childTail;
expect( tooltipScope.content ).toBe( scope.items[1].tooltip );
expect( elm.find( '.tooltip-inner' ).text() ).toBe( scope.items[1].tooltip );
tt_2.trigger( 'mouseleave' );
}));
it('should only have an isolate scope on the popup', inject( function ( $compile ) {
var ttScope;
scope.tooltipMsg = 'Tooltip Text';
scope.alt = 'Alt Message';
elmBody = $compile( angular.element(
'<div><span alt={{alt}} tooltip="{{tooltipMsg}}" tooltip-animation="false">Selector Text</span></div>'
) )( scope );
$compile( elmBody )( scope );
scope.$digest();
elm = elmBody.find( 'span' );
elmScope = elm.scope();
elm.trigger( 'mouseenter' );
expect( elm.attr( 'alt' ) ).toBe( scope.alt );
ttScope = angular.element( elmBody.children()[1] ).isolateScope();
expect( ttScope.placement ).toBe( 'top' );
expect( ttScope.content ).toBe( scope.tooltipMsg );
elm.trigger( 'mouseleave' );
//Isolate scope contents should be the same after hiding and showing again (issue 1191)
elm.trigger( 'mouseenter' );
ttScope = angular.element( elmBody.children()[1] ).isolateScope();
expect( ttScope.placement ).toBe( 'top' );
expect( ttScope.content ).toBe( scope.tooltipMsg );
}));
it('should not show tooltips if there is nothing to show - issue #129', inject(function ($compile) {
elmBody = $compile(angular.element(
'<div><span tooltip="">Selector Text</span></div>'
))(scope);
scope.$digest();
elmBody.find('span').trigger('mouseenter');
expect(elmBody.children().length).toBe(1);
}));
it( 'should close the tooltip when its trigger element is destroyed', inject( function() {
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( true );
elm.remove();
elmScope.$destroy();
expect( elmBody.children().length ).toBe( 0 );
}));
it('issue 1191 - scope on the popup should always be child of correct element scope', function () {
var ttScope;
elm.trigger( 'mouseenter' );
ttScope = angular.element( elmBody.children()[1] ).scope();
expect( ttScope.$parent ).toBe( tooltipScope );
elm.trigger( 'mouseleave' );
// After leaving and coming back, the scope's parent should be the same
elm.trigger( 'mouseenter' );
ttScope = angular.element( elmBody.children()[1] ).scope();
expect( ttScope.$parent ).toBe( tooltipScope );
elm.trigger( 'mouseleave' );
});
describe('with specified enable expression', function() {
beforeEach(inject(function ($compile) {
scope.enable = false;
elmBody = $compile(angular.element(
'<div><span tooltip="tooltip text" tooltip-enable="enable">Selector Text</span></div>'
))(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it('should not open ', inject(function () {
elm.trigger('mouseenter');
expect(tooltipScope.isOpen).toBeFalsy();
expect(elmBody.children().length).toBe(1);
}));
it('should open', inject(function () {
scope.enable = true;
scope.$digest();
elm.trigger('mouseenter');
expect(tooltipScope.isOpen).toBeTruthy();
expect(elmBody.children().length).toBe(2);
}));
});
describe('with specified popup delay', function () {
beforeEach(inject(function ($compile) {
scope.delay='1000';
elm = $compile(angular.element(
'<span tooltip="tooltip text" tooltip-popup-delay="{{delay}}">Selector Text</span>'
))(scope);
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
scope.$digest();
}));
it('should open after timeout', inject(function ($timeout) {
elm.trigger('mouseenter');
expect(tooltipScope.isOpen).toBe(false);
$timeout.flush();
expect(tooltipScope.isOpen).toBe(true);
}));
it('should not open if mouseleave before timeout', inject(function ($timeout) {
elm.trigger('mouseenter');
expect(tooltipScope.isOpen).toBe(false);
elm.trigger('mouseleave');
$timeout.flush();
expect(tooltipScope.isOpen).toBe(false);
}));
it('should use default popup delay if specified delay is not a number', function(){
scope.delay='text1000';
scope.$digest();
elm.trigger('mouseenter');
expect(tooltipScope.isOpen).toBe(true);
});
});
describe( 'with a trigger attribute', function() {
var scope, elmBody, elm, elmScope;
beforeEach( inject( function( $rootScope ) {
scope = $rootScope;
}));
it( 'should use it to show but set the hide trigger based on the map for mapped triggers', inject( function( $compile ) {
elmBody = angular.element(
'<div><input tooltip="Hello!" tooltip-trigger="focus" /></div>'
);
$compile(elmBody)(scope);
scope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect( tooltipScope.isOpen ).toBeFalsy();
elm.trigger('focus');
expect( tooltipScope.isOpen ).toBeTruthy();
elm.trigger('blur');
expect( tooltipScope.isOpen ).toBeFalsy();
}));
it( 'should use it as both the show and hide triggers for unmapped triggers', inject( function( $compile ) {
elmBody = angular.element(
'<div><input tooltip="Hello!" tooltip-trigger="fakeTriggerAttr" /></div>'
);
$compile(elmBody)(scope);
scope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect( tooltipScope.isOpen ).toBeFalsy();
elm.trigger('fakeTriggerAttr');
expect( tooltipScope.isOpen ).toBeTruthy();
elm.trigger('fakeTriggerAttr');
expect( tooltipScope.isOpen ).toBeFalsy();
}));
it('should only set up triggers once', inject( function ($compile) {
scope.test = true;
elmBody = angular.element(
'<div>' +
'<input tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' +
'<input tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' +
'</div>'
);
$compile(elmBody)(scope);
scope.$apply();
var elm1 = elmBody.find('input').eq(0);
var elm2 = elmBody.find('input').eq(1);
var elmScope1 = elm1.scope();
var elmScope2 = elm2.scope();
var tooltipScope2 = elmScope2.$$childTail;
scope.$apply('test = false');
// click trigger isn't set
elm2.click();
expect( tooltipScope2.isOpen ).toBeFalsy();
// mouseenter trigger is still set
elm2.trigger('mouseenter');
expect( tooltipScope2.isOpen ).toBeTruthy();
}));
});
describe( 'with an append-to-body attribute', function() {
var scope, elmBody, elm, elmScope, $body;
beforeEach( inject( function( $rootScope ) {
scope = $rootScope;
}));
afterEach(function () {
$body.find('.tooltip').remove();
});
it( 'should append to the body', inject( function( $compile, $document ) {
$body = $document.find( 'body' );
elmBody = angular.element(
'<div><span tooltip="tooltip text" tooltip-append-to-body="true">Selector Text</span></div>'
);
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
var bodyLength = $body.children().length;
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( true );
expect( elmBody.children().length ).toBe( 1 );
expect( $body.children().length ).toEqual( bodyLength + 1 );
}));
});
describe('cleanup', function () {
var elmBody, elm, elmScope, tooltipScope;
function inCache() {
var match = false;
angular.forEach(angular.element.cache, function (item) {
if (item.data && item.data.$scope === tooltipScope) {
match = true;
}
});
return match;
}
beforeEach(inject(function ( $compile, $rootScope ) {
elmBody = angular.element('<div><input tooltip="Hello!" tooltip-trigger="fooTrigger" /></div>');
$compile(elmBody)($rootScope);
$rootScope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
elm.trigger('fooTrigger');
tooltipScope = elmScope.$$childTail.$$childTail;
}));
it( 'should not contain a cached reference when not visible', inject( function( $timeout ) {
expect( inCache() ).toBeTruthy();
elmScope.$destroy();
expect( inCache() ).toBeFalsy();
}));
});
});
describe('tooltipWithDifferentSymbols', function() {
var elmBody;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip'));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
// configure interpolate provider to use [[ ]] instead of {{ }}
beforeEach(module( function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.startSymbol(']]');
}));
it( 'should show the correct tooltip text', inject( function ( $compile, $rootScope ) {
elmBody = angular.element(
'<div><input type="text" tooltip="My tooltip" tooltip-trigger="focus" tooltip-placement="right" /></div>'
);
$compile(elmBody)($rootScope);
$rootScope.$apply();
var elmInput = elmBody.find('input');
elmInput.trigger('focus');
expect( elmInput.next().find('div').next().html() ).toBe('My tooltip');
}));
});
describe( 'tooltip positioning', function() {
var elm, elmBody, elmScope, tooltipScope, scope;
var $position;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) {
$tooltipProvider.options({ animation: false });
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(inject(function($rootScope, $compile, _$position_) {
$position = _$position_;
spyOn($position, 'positionElements').and.callThrough();
scope = $rootScope;
scope.text = 'Some Text';
elmBody = $compile( angular.element(
'<div><span tooltip="{{ text }}">Selector Text</span></div>'
))( scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it( 'should re-position when value changes', inject( function ($timeout) {
elm.trigger( 'mouseenter' );
scope.$digest();
$timeout.flush();
var startingPositionCalls = $position.positionElements.calls.count();
scope.text = 'New Text';
scope.$digest();
$timeout.flush();
expect(elm.attr('tooltip')).toBe( 'New Text' );
expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1);
// Check that positionElements was called with elm
expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0])
.toBe(elm[0]);
scope.$digest();
$timeout.verifyNoPendingTasks();
expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1);
expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0])
.toBe(elm[0]);
scope.$digest();
}));
});
describe( 'tooltipHtml', function() {
var elm, elmBody, elmScope, tooltipScope, scope;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) {
$tooltipProvider.options({ animation: false });
}));
// load the template
beforeEach(module('template/tooltip/tooltip-html-popup.html'));
beforeEach(inject(function($rootScope, $compile, $sce) {
scope = $rootScope;
scope.html = 'I say: <strong class="hello">Hello!</strong>';
scope.safeHtml = $sce.trustAsHtml(scope.html);
elmBody = $compile( angular.element(
'<div><span tooltip-html="safeHtml">Selector Text</span></div>'
))( scope );
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it( 'should render html properly', inject( function () {
elm.trigger( 'mouseenter' );
expect( elmBody.find('.tooltip-inner').html() ).toBe( scope.html );
}));
it( 'should not open if html is empty', function () {
scope.safeHtml = null;
scope.$digest();
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( false );
});
it( 'should show on mouseenter and hide on mouseleave', inject( function ($sce) {
expect( tooltipScope.isOpen ).toBe( false );
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( true );
expect( elmBody.children().length ).toBe( 2 );
expect( $sce.getTrustedHtml(tooltipScope.contentExp()) ).toEqual( scope.html );
elm.trigger( 'mouseleave' );
expect( tooltipScope.isOpen ).toBe( false );
expect( elmBody.children().length ).toBe( 1 );
}));
});
describe( 'tooltipHtmlUnsafe', function() {
var elm, elmBody, elmScope, tooltipScope, scope;
var logWarnSpy;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) {
$tooltipProvider.options({ animation: false });
}));
// load the template
beforeEach(module('template/tooltip/tooltip-html-unsafe-popup.html'));
beforeEach(inject(function($rootScope, $compile, $log) {
scope = $rootScope;
scope.html = 'I say: <strong class="hello">Hello!</strong>';
logWarnSpy = spyOn($log, 'warn');
elmBody = $compile( angular.element(
'<div><span tooltip-html-unsafe="{{html}}">Selector Text</span></div>'
))( scope );
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it( 'should warn that this is deprecated', function () {
expect(logWarnSpy).toHaveBeenCalledWith(jasmine.stringMatching('deprecated'));
});
it( 'should render html properly', inject( function () {
elm.trigger( 'mouseenter' );
expect( elmBody.find('.tooltip-inner').html() ).toBe( scope.html );
}));
it( 'should show on mouseenter and hide on mouseleave', inject( function () {
expect( tooltipScope.isOpen ).toBe( false );
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( true );
expect( elmBody.children().length ).toBe( 2 );
expect( tooltipScope.content ).toEqual( scope.html );
elm.trigger( 'mouseleave' );
expect( tooltipScope.isOpen ).toBe( false );
expect( elmBody.children().length ).toBe( 1 );
}));
});
describe( '$tooltipProvider', function() {
var elm,
elmBody,
scope,
elmScope,
tooltipScope;
describe( 'popupDelay', function() {
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){
$tooltipProvider.options({popupDelay: 1000});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><span tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it('should open after timeout', inject(function($timeout) {
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( false );
$timeout.flush();
expect( tooltipScope.isOpen ).toBe( true );
}));
});
describe('appendToBody', function() {
var $body;
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(module('ui.bootstrap.tooltip', function ( $tooltipProvider ) {
$tooltipProvider.options({ appendToBody: true });
}));
afterEach(function () {
$body.find('.tooltip').remove();
});
it( 'should append to the body', inject( function( $rootScope, $compile, $document ) {
$body = $document.find( 'body' );
elmBody = angular.element(
'<div><span tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
var bodyLength = $body.children().length;
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( true );
expect( elmBody.children().length ).toBe( 1 );
expect( $body.children().length ).toEqual( bodyLength + 1 );
}));
it('should close on location change', inject( function( $rootScope, $compile) {
elmBody = angular.element(
'<div><span tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
elm.trigger( 'mouseenter' );
expect( tooltipScope.isOpen ).toBe( true );
scope.$broadcast('$locationChangeSuccess');
scope.$digest();
expect( tooltipScope.isOpen ).toBe( false );
}));
});
describe( 'triggers', function() {
describe( 'triggers with a mapped value', function() {
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){
$tooltipProvider.options({trigger: 'focus'});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
it( 'should use the show trigger and the mapped value for the hide trigger', inject( function ( $rootScope, $compile ) {
elmBody = angular.element(
'<div><input tooltip="tooltip text" /></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect( tooltipScope.isOpen ).toBeFalsy();
elm.trigger('focus');
expect( tooltipScope.isOpen ).toBeTruthy();
elm.trigger('blur');
expect( tooltipScope.isOpen ).toBeFalsy();
}));
it( 'should override the show and hide triggers if there is an attribute', inject( function ( $rootScope, $compile ) {
elmBody = angular.element(
'<div><input tooltip="tooltip text" tooltip-trigger="mouseenter"/></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect( tooltipScope.isOpen ).toBeFalsy();
elm.trigger('mouseenter');
expect( tooltipScope.isOpen ).toBeTruthy();
elm.trigger('mouseleave');
expect( tooltipScope.isOpen ).toBeFalsy();
}));
});
describe( 'triggers with a custom mapped value', function() {
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){
$tooltipProvider.setTriggers({ 'customOpenTrigger': 'customCloseTrigger' });
$tooltipProvider.options({trigger: 'customOpenTrigger'});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
it( 'should use the show trigger and the mapped value for the hide trigger', inject( function ( $rootScope, $compile ) {
elmBody = angular.element(
'<div><input tooltip="tooltip text" /></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect( tooltipScope.isOpen ).toBeFalsy();
elm.trigger('customOpenTrigger');
expect( tooltipScope.isOpen ).toBeTruthy();
elm.trigger('customCloseTrigger');
expect( tooltipScope.isOpen ).toBeFalsy();
}));
});
describe( 'triggers without a mapped value', function() {
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider){
$tooltipProvider.options({trigger: 'fakeTrigger'});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
it( 'should use the show trigger to hide', inject( function ( $rootScope, $compile ) {
elmBody = angular.element(
'<div><span tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect( tooltipScope.isOpen ).toBeFalsy();
elm.trigger('fakeTrigger');
expect( tooltipScope.isOpen ).toBeTruthy();
elm.trigger('fakeTrigger');
expect( tooltipScope.isOpen ).toBeFalsy();
}));
});
});
});
|
#! /usr/bin/env node
/*
* This is the Command Line Implementation of the `emptydir` module
*
* Command Line Argument Processing
* emptydir dirA dirB - empties the directories
* emptydir --version - show version
* emptydir --help - show this help message
* emptydir -v - be verbose in emptying the directory
*/
module.exports.run = run;
var emptydir = require('./emptydir'),
version = require('./package.json').version;
// Prints sucess and error messages
function print(path, error) {
if (error) {
process.stdout.write('FAIL\t' + path + '\t->' + error.code + '\n');
return;
}
process.stdout.write('OKAY\t' + path + '\n');
}
// Missing operand
var missing_operand = [
'emptydir: missing operand',
'Try \'emptydir --help\' for more information',
'\n'
];
// Invalid Options
var invalid_option = [
'emptydir: invalid_option',
'Try \'emptydir --help\' for more information',
'\n'
];
// Help Information
var help_info = [
'emptydir\n',
'Lets you recursively delete files in directories while maintaining the the directory structure\n',
' --help \t\t Show this help message',
' --version \t\t Show version information',
' -v, --verbose \t\t Be verbose while deleting',
'\nExample:\n\n\temptydir -v my_dir/ old_file',
'\n'
]
// Commandline runner
function run(args, options){
args = args || [];
if (!options) options = {};
missing_operand = options['missing_operand'] || '';
help_info = options['help_info'] || '';
version_info = options['version_info'] || '';
invalid_option = options['invalid_option'] || '';
// Shift twice to remove the node executable and filename
args.shift();
args.shift();
if (args.length == 0) {
process.stdout.write(missing_operand);
return missing_operand;
} else{
// 1 option commands
if (args.length == 1) {
if (args[0] == '--version') {
process.stdout.write(version_info);
return help_info;
} else if (args[0] == '--help') {
process.stdout.write(help_info);
return help_info;
}
}
// Are we verbose?
var verbose = false;
var new_args = [];
args.forEach(function (arg) {
if (arg == '--verbose' || arg == '-v') {
verbose = true;
} else{
new_args.push(arg);
}
});
args = new_args;
if (args.length == 0) {
process.stdout.write(missing_operand);
return missing_operand;
}
// Invalid option?
args_string = args.toString();
if (args_string.match(/^-/) || args_string.match(/,-/)) {
process.stdout.write(invalid_option);
return invalid_option;
}
// Lets get to Work
if (verbose) {
args.forEach(function (path) {
emptydir.emptyDirs('./' + path, function (error, w_path) {
if (error) {
print(w_path, error);
return;
}
print(w_path);
});
});
} else {
args.forEach(function (path) {
emptydir.emptyDir('./' + path, function (errors, w_path) {
if (errors) {
errors.forEach(function (error) {
print(error.path, error);
});
}
});
});
}
}
}
// Calls function and passes parameters
run(
process.argv,
{
'missing_operand': missing_operand.join('\n'),
'help_info': help_info.join('\n'),
'version_info': 'emptydir ' + version + '\n',
'invalid_option': invalid_option.join('\n')
}
);
/*
* NOTES FOR PROGRAMMER:
* This CLI should be as independent as possible, without requiring any
* external module
*
* Using emptydir.emptyDirs() causes an error when verbose is turned off.
* This is not Fixed yet. Try fix this behavior.
*/
|
import { schema } from 'normalizr';
const user = new schema.Entity('users');
const messages = new schema.Entity('messages', {
user,
});
export const message = new schema.Entity('message', {
user,
});
export const messagesList = [messages];
export default messagesList;
|
var zrUtil = require('zrender/lib/core/util');
// FIXME 公用?
/**
* @param {Array.<module:echarts/data/List>} datas
* @param {string} statisticType 'average' 'sum'
* @inner
*/
function dataStatistics(datas, statisticType) {
var dataNameMap = {};
var dims = ['value'];
zrUtil.each(datas, function (data) {
data.each(dims, function (value, idx) {
// Add prefix to avoid conflict with Object.prototype.
var mapKey = 'ec-' + data.getName(idx);
dataNameMap[mapKey] = dataNameMap[mapKey] || [];
if (!isNaN(value)) {
dataNameMap[mapKey].push(value);
}
});
});
return datas[0].map(dims, function (value, idx) {
var mapKey = 'ec-' + datas[0].getName(idx);
var sum = 0;
var min = Infinity;
var max = -Infinity;
var len = dataNameMap[mapKey].length;
for (var i = 0; i < len; i++) {
min = Math.min(min, dataNameMap[mapKey][i]);
max = Math.max(max, dataNameMap[mapKey][i]);
sum += dataNameMap[mapKey][i];
}
var result;
if (statisticType === 'min') {
result = min;
}
else if (statisticType === 'max') {
result = max;
}
else if (statisticType === 'average') {
result = sum / len;
}
else {
result = sum;
}
return len === 0 ? NaN : result;
});
}
module.exports = function (ecModel) {
var seriesGroups = {};
ecModel.eachSeriesByType('map', function (seriesModel) {
var hostGeoModel = seriesModel.getHostGeoModel();
var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
(seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
});
zrUtil.each(seriesGroups, function (seriesList, key) {
var data = dataStatistics(
zrUtil.map(seriesList, function (seriesModel) {
return seriesModel.getData();
}),
seriesList[0].get('mapValueCalculation')
);
for (var i = 0; i < seriesList.length; i++) {
seriesList[i].originalData = seriesList[i].getData();
}
// FIXME Put where?
for (var i = 0; i < seriesList.length; i++) {
seriesList[i].seriesGroup = seriesList;
seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
seriesList[i].setData(data.cloneShallow());
seriesList[i].mainSeries = seriesList[0];
}
});
};
|
// @flow
import React, { PureComponent as Component } from "react";
import Slider from "rc-slider/lib/Slider";
import { A, Icon } from "../common";
type Props = {
nodeId: number,
currentLine: Array<number>,
onChangeCurrentNode: (number) => any,
};
export default class BoardNav extends Component<Props> {
componentDidMount() {
document.addEventListener("keydown", this._onKeyDown);
}
componentWillUnmount() {
document.removeEventListener("keydown", this._onKeyDown);
}
render() {
let { nodeId, currentLine } = this.props;
if (typeof nodeId !== "number" || !currentLine) {
return <div className="BoardNav" />;
}
let moveNum = currentLine.indexOf(nodeId);
return (
<div className="BoardNav">
<div className="BoardNav-slide-container">
<div className="BoardNav-slide">
<Slider
min={0}
max={currentLine.length - 1}
step={1}
value={moveNum}
onChange={this._onChangeMoveNum}
/>
</div>
<div className="BoardNav-move">Move {moveNum}</div>
</div>
<div className="BoardNav-step">
<A className="BoardNav-prev" onClick={this._onPrev}>
<Icon name="chevron-left" />
</A>
<A className="BoardNav-next" onClick={this._onNext}>
<Icon name="chevron-right" />
</A>
</div>
</div>
);
}
_onChangeMoveNum = (val: number) => {
let { currentLine } = this.props;
let nodeId = currentLine[val];
this.props.onChangeCurrentNode(nodeId);
};
_onPrev = () => {
let { nodeId, currentLine } = this.props;
let idx = currentLine.indexOf(nodeId);
if (idx > 0) {
this.props.onChangeCurrentNode(currentLine[idx - 1]);
}
};
_onNext = () => {
let { nodeId, currentLine } = this.props;
let idx = currentLine.indexOf(nodeId);
if (idx < currentLine.length - 1) {
this.props.onChangeCurrentNode(currentLine[idx + 1]);
}
};
_onLast = () => {
let { currentLine } = this.props;
this.props.onChangeCurrentNode(currentLine[currentLine.length - 1]);
};
_onFirst = () => {
let { currentLine } = this.props;
this.props.onChangeCurrentNode(currentLine[0]);
};
_onKeyDown = (e: Object) => {
let node = e.target;
while (node) {
if (
node.nodeName === "INPUT" ||
node.nodeName === "SELECT" ||
node.nodeName === "TEXTAREA"
) {
if (node.value) {
return;
}
}
node = node.parentNode;
}
if (e.key === "ArrowLeft" || e.keyCode === 37) {
this._onPrev();
} else if (e.key === "ArrowRight" || e.keyCode === 39) {
this._onNext();
} else if (e.key === "ArrowUp" || e.keyCode === 38) {
this._onLast();
} else if (e.key === "ArrowDown" || e.keyCode === 40) {
this._onFirst();
}
};
}
|
/*global VisSense,it,expect*/
/* jshint undef: false */
describe('VisSense Globals', function () {
'use strict';
it('should have a `noConflict` method', function () {
expect(VisSense.noConflict).toBeDefined();
var _oldValue = VisSense;
var newCustomNameForVisSense = VisSense.noConflict();
expect(VisSense).not.toBeDefined();
expect(newCustomNameForVisSense).toBe(_oldValue);
// restore original state
window.VisSense = newCustomNameForVisSense.noConflict();
});
});
|
(function(win, doc, glue) {
'use strict';
function setStyles(collection, name, value) {
collection.each(function(element) {
element.style[name] = value;
});
}
function getStyle(element, property) {
var propertyValue, re = /(\-([a-z]){1})/g;
// Support both camelCase and dashed property names
property = property.replace(/([A-Z])/g, '-glue1').toLowerCase();
/* istanbul ignore else */
if (win.getComputedStyle /* && !glue.isTest*/) {
propertyValue = win.getComputedStyle(element, null).getPropertyValue(property);
} else if (doc.documentElement.currentStyle) {
if (property === 'float') {
property = 'styleFloat';
}
if (re.test(property)) {
property = property.replace(re, function() {
return arguments[2].toUpperCase();
});
}
propertyValue = element.currentStyle[property] ? element.currentStyle[property] : null;
}
return propertyValue;
}
function createXPath(node, path) {
var sibling, len, details = '',
name, selectorString;
path = path || [];
function isElement(obj) {
return obj.nodeType === 1;
}
/* istanbul ignore else - */
if (node.parentNode) {
path = createXPath(node.parentNode, path);
}
/* istanbul ignore else - */
if (node.previousSibling) {
len = 1;
sibling = node.previousSibling;
do {
if (isElement(sibling) && sibling.nodeName === node.nodeName) {
len++;
}
sibling = sibling.previousSibling;
} while (sibling);
if (len === 1) {
len = null;
}
} else if (node.nextSibling) {
sibling = node.nextSibling;
do {
if (isElement(sibling) && sibling.nodeName === node.nodeName) {
len = 1;
sibling = null;
} else {
len = null;
sibling = sibling.previousSibling;
}
} while (sibling);
}
if (isElement(node)) {
name = node.nodeName.toLowerCase();
/* istanbul ignore else - */
if (node.id) {
details = "#" + node.id;
} else if (node.className) {
details = "." + node.className;
} else if (len !== null) {
details = ":nth-of-type(" + len + ")";
}
path.push(name + details);
}
return path;
}
function css(context, property, value){
var collection = context,
isString = glue.isString(property),
isObject = glue.isPlainObject(property),
prop;
/* istanbul ignore else */
if (!collection.length || (!isString && !isObject)) {
return context;
} else if (isString) {
if (value === undefined) {
return getStyle(context[0], property);
} else {
setStyles(collection, property, value);
}
} else if (isObject) {
for (prop in property) { /* istanbul ignore else */
if (property.hasOwnProperty(prop)) {
setStyles(collection, prop, property[prop]);
}
}
}
return context;
}
function html(context, htmlString) {
if (htmlString) {
context.each(function(element) {
this.innerHTML = htmlString;
});
return context;
} else {
return context[0].innerHTML;
}
}
function createSelector(context, selector){
return createXPath(context).join(' ').substring(5) + ' ' + selector;
}
function parseHTML(element){
var div = doc.createElement('div');
div.innerHTML = element;
return div.firstChild;
}
function toggleDisplay(context, status){
var display = 'display', none = 'none';
if(status) {
context.css(display, status);
return context;
} else {
if (context.css(display) === none) {
context.css(display, 'block');
} else {
context.css(display, none);
}
return context;
}
}
function attr(context, name, value) {
if (!value) {
return context[0].getAttribute(name);
} else {
context[0].setAttribute(name, value);
return context;
}
}
function append(context, elementString){
var domObject = glue.parseHTML(elementString);
context[0].appendChild(domObject);
return context;
}
function prepend(context, elementString){
var domObject = glue.parseHTML(elementString),
parent = context[0];
parent.insertBefore(domObject, parent.firstChild);
return context;
}
function remove(context) {
context.each(function() {
var parent = this.parentNode;
parent.removeChild(this);
});
return context;
}
function find(context, selector){
var baseSelector = glue.getSelector();
if (glue.isString(selector) && glue.isString(baseSelector)) {
return glue(baseSelector + ' ' + selector);
} else {
return glue(context.selectorify(selector));
}
}
glue.fn.selectorify = function(selector) {
return createSelector(this, selector);
};
glue.parseHTML = function(element) {
return parseHTML(element);
};
glue.fn.extend({
css: function(property, value) {
return css(this, property, value);
},
html: function(htmlString) {
return html(this, htmlString);
},
hide: function() {
return toggleDisplay(this, 'none');
},
show: function() {
return toggleDisplay(this, 'block');
},
toggle: function() {
return toggleDisplay(this);
},
attr: function(name, value) {
return attr(this, name, value);
},
append: function(elementString) {
return append(this, elementString);
},
prepend: function(elementString) {
return prepend(this, elementString);
},
remove: function() {
return remove(this);
},
find: function(selector) {
return find(this, selector);
}
});
}(window, document, glue));
|
'use strict';
var myAppControllers = angular.module('myAppControllers',[]);
myAppControllers.controller('ContentQuery', ['$scope', 'Content', '$routeParams',
function($scope, Content, $routeParams){
$scope.contentItems = Content.query();
$scope.contentPath = $routeParams.contentId;
//$scope.picked = $scope.contentOptions[0];
}]);
myAppControllers.controller('ContentCtrl', ['$scope', '$routeParams', 'Content',
function($scope, $routeParams, Content){
$scope.pageContent = Content.get({contentId: $routeParams.contentId});
}]);
|
(function() {
'use strict';
angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service('ShoppingListCheckOffService', ShoppingListCheckOffService);
ToBuyController.$inject = ['ShoppingListCheckOffService'];
function ToBuyController(ShoppingListCheckOffService) {
var toBuyCtrl = this;
toBuyCtrl.buyList = ShoppingListCheckOffService.getToBuyItems();
toBuyCtrl.buyItem = function(index) {
ShoppingListCheckOffService.changeItem(index);
};
}
AlreadyBoughtController.$inject = ['ShoppingListCheckOffService'];
function AlreadyBoughtController(ShoppingListCheckOffService) {
var boughtCtrl = this;
boughtCtrl.boughtList = ShoppingListCheckOffService.getBoughtItems();
}
function ShoppingListCheckOffService() {
var service = this;
var toBuyItems = [{ name: "cookies", quantity: 10 }, { name: "breads", quantity: 2 }, { name: "muffins", quantity: 3 }, { name: "steaks", quantity: 5 }, { name: "fruits", quantity: 20 }];
var boughtItems = [];
service.getToBuyItems = function() {
return toBuyItems;
};
service.getBoughtItems = function() {
return boughtItems;
};
service.changeItem = function(index) {
boughtItems.push(toBuyItems[index]);
toBuyItems.splice(index, 1);
}
}
})();
|
import Parser from 'ember-graphql-adapter/parser';
import Generator from 'ember-graphql-adapter/generator';
import ArgumentSet from 'ember-graphql-adapter/types/argument-set';
import { Field, Operation } from 'ember-graphql-adapter/types';
export default {
compile(model, store, options) {
options = options || {};
let operationType = options['operationType']; // TODO: Must be query or mutation
let operationName = options['operationName'];
let operation = new Operation(operationType, operationName);
let rootFieldQuery = options['rootFieldQuery'] || {};
let rootFieldName = options['rootFieldName'] || model.modelName;
let rootFieldAlias = options['rootFieldAlias'];
let rootField = new Field(rootFieldName, rootFieldAlias, ArgumentSet.fromQuery(rootFieldQuery));
Parser.parse(model, store, operation, rootField, options);
return Generator.generate(operation);
}
};
|
import * as React from 'react';
import TopLayoutCompany from 'docs/src/modules/components/TopLayoutCompany';
import {
demos,
docs,
demoComponents,
} from 'docs/src/pages/careers/react-engineer.md?@mui/markdown';
export default function Page() {
return <TopLayoutCompany demos={demos} docs={docs} demoComponents={demoComponents} />;
}
|
// The client ID is obtained from the {{ Google Cloud Console }}
// at {{ https://cloud.google.com/console }}.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '111436808615-d7mam74ms4a49846vpq7iqmn8ihu6mdu.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
// Upon loading, the Google APIs JS client automatically invokes this callback.
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
// Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
// If the currently logged-in Google Account has previously authorized
// the client specified as the OAUTH2_CLIENT_ID, then the authorization
// succeeds with no user intervention. Otherwise, it fails and the
// user interface that prompts for authorization needs to display.
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
// client flow. The current function is called when that flow completes.
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
// Load the client interfaces for the YouTube Analytics and Data APIs, which
// are required to use the Google APIs JS client. More info is available at
// https://developers.google.com/api-client-library/javascript/dev/dev_jscript#loading-the-client-library-and-the-api
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
handleAPILoaded();
});
}
|
module( "max test" );
test('숫자 순차 배열의 최대값',function(){
var fn = Pascal.max([1,2,,3,4,5,10]);
deepEqual(fn, 10, "Pascal.fact([1,2,,3,4,5,10]) === 10");
});
test('순서 없는 숫자 배열의 최대값',function(){
var fn = Pascal.max([1,-2,-3,4,5,-10]);
deepEqual(fn, 5, "Pascal.fact(1,-2,-3,4,5,-10]) === 5");
});
test('문자열이 포함된 배열의 최대값',function(){
var fn = Pascal.max(['hello',1,-2,-3,4,5,-10]);
deepEqual(fn, 5, "Pascal.fact('hello',1,-2,-3,4,5,-10]) === 5");
});
test('숫자형 문자열이 포함된 배열의 최대값',function(){
var fn = Pascal.max(['1000',1,-2,-3,4,5,-10]);
deepEqual(fn, 1000, "Pascal.fact('-1000',1,-2,-3,4,5,-10]) === 1000");
});
|
'use strict';
// load gulp and gulp plugins
var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
// load node modules
var del = require('del');
var fs = require('fs');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
//
// Gulp config
//
// Override defaults with custom local config
try {
var localConfig = require('./gulpconfig.json');
} catch (err) {
var localConfig = {
bs: {
proxy: "www.bubs.dev",
logLevel: "info",
tunnel: "",
open: false
}
};
}
// Build themeDir variable based on current theme from config file, fallback to default
var themeRoot = 'wp-content/themes/';
var theme = localConfig.activeTheme || 'timber';
var themeDir = themeRoot + theme;
// Defaults
var config = {
theme: themeDir,
assets: themeDir + '/assets',
dist: themeDir + '/dist',
dev: themeDir + '/dev',
output: themeDir + '/dev', // default to dev
static: themeDir + '/static',
init: './_init'
};
// in production tasks, we set this to true
var isProduction = false;
// Error Handling
var handleErrors = function() {
var args = Array.prototype.slice.call(arguments);
$.notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
if ( isProduction ) {
// Tell Travis to Stop Bro
process.exit(1);
}
this.emit('end');
};
//
// Gulp Tasks
//
gulp.task('styles', function() {
var sassOptions = {
outputStyle: 'expanded'
};
var sourcemapsOptions = {
debug: true
};
var nanoOptions = {
autoprefixer: {
browsers: ['> 1%', 'last 2 versions', 'IE >= 8'],
add: true
}
};
return gulp.src(config.assets + '/scss/*.scss')
.pipe($.if(!isProduction, $.sourcemaps.init()))
.pipe($.sass(sassOptions).on('error', handleErrors))
.pipe($.if(isProduction, $.cssnano(nanoOptions)))
.pipe($.if(!isProduction, $.sourcemaps.write(sourcemapsOptions)))
.pipe(gulp.dest( config.output + '/css' ))
.pipe(browserSync.stream());
});
gulp.task('scripts', function() {
var assets = $.useref({
searchPath: './'
}).on('error', handleErrors);
var uglifyOptions = {
mangle: false,
compress: {
drop_console: true
}
};
return gulp.src( config.theme + '/views/layout.twig' )
.pipe(assets)
.pipe($.if('*.js', $.uglify(uglifyOptions).on('error', handleErrors)))
.pipe(gulp.dest( config.output ));
});
// copy unmodified files
gulp.task('copy', function (cb) {
return gulp.src( config.assets + '/{img,fonts}/**/*', {base: config.assets})
.pipe($.changed( config.output ))
.pipe(gulp.dest( config.output ));
});
// loops through the generated html and replaces all references to static versions
gulp.task('rev', function (cb) {
return gulp.src( config.dist + '/{css,js,fonts,img}/**/*' )
.pipe($.rev())
.pipe($.revCssUrl())
.pipe(gulp.dest( config.static ))
.pipe($.rev.manifest())
.pipe(gulp.dest( config.static ))
});
gulp.task('staticHeaders', function() {
return gulp.src( config.init + '/static.htaccess', { base: '' } )
.pipe($.rename(".htaccess"))
.pipe(gulp.dest( config.static ));
});
// clean output directory
gulp.task('clean', function (cb) {
return del([config.dev, config.static, config.dist], cb);
});
gulp.task('browser-sync', function() {
browserSync.init(null, {
proxy: localConfig.bs.proxy,
open: localConfig.bs.open || true,
tunnel: localConfig.bs.tunnel || false,
logLevel: localConfig.bs.logLevel || 'info'
});
});
gulp.task('watch', function() {
gulp.watch([config.theme + '/**/*.{twig,php}'], browserSync.reload);
gulp.watch([config.assets + '/scss/**/*.scss'], ['styles']);
gulp.watch([config.assets + '/js/**/*.js'], ['scripts', browserSync.reload]);
gulp.watch([config.assets + '/{img,fonts}/**'], ['copy', browserSync.reload]);
});
//
// Multi-step tasks
//
// build production files
gulp.task('release', function (cb) {
isProduction = true;
config.output = config.dist;
runSequence('clean', ['styles', 'scripts', 'copy'], ['rev', 'staticHeaders'], cb);
});
gulp.task('default', function (cb) {
runSequence('clean', ['styles', 'scripts', 'copy'], ['watch', 'browser-sync'], cb);
});
|
/*global io,data*/
(function(){
// give up and resort to `target=_blank`
// if we're not modern enough
if (!document.body.getBoundingClientRect
|| !document.body.querySelectorAll
|| !window.postMessage) {
return;
}
// the id for the script we capture
var id;
// listen on setup event from the parent
// to set up the id
window.addEventListener('message', function onmsg(e){
if (/^slackin:/.test(e.data)) {
id = e.data.replace(/^slackin:/, '');
document.body.addEventListener('click', function(ev){
var el = ev.target;
while (el && 'A' != el.nodeName) el = el.parentNode;
if (el && '_blank' == el.target) {
ev.preventDefault();
parent.postMessage('slackin-click:' + id, '*');
}
});
window.removeEventListener('message', onmsg);
// notify initial width
refresh();
}
});
// notify parent about current width
var button = document.querySelector('.slack-button');
var lastWidth;
function refresh(){
var width = button.getBoundingClientRect().width;
if (top != window && window.postMessage) {
var but = document.querySelector('.slack-button');
var width = Math.ceil(but.getBoundingClientRect().width);
if (lastWidth != width) {
lastWidth = width;
parent.postMessage('slackin-width:' + id + ':' + width, '*');
}
}
}
// initialize realtime events asynchronously
var script = document.createElement('script');
script.src = 'https://cdn.socket.io/socket.io-1.3.2.js';
script.onload = function(){
// use dom element for better cross browser compatibility
var url = document.createElement('a');
url.href = window.location;
var socket = io({path: (url.pathname + '/socket.io').replace('//','/')});
var count = document.getElementsByClassName('slack-count')[0];
socket.on('data', function(users){
for (var i in users) update(i, users[i]);
});
socket.on('total', function(n){ update('total', n) });
socket.on('active', function(n){ update('active', n) });
var anim;
function update(key, n) {
if (n != data[key]) {
data[key] = n;
var str = '';
if (data.active) str = data.active + '/';
if (data.total) str += data.total;
if (!str.length) str = '–';
if (anim) clearTimeout(anim);
count.innerHTML = str;
count.className = 'slack-count anim';
anim = setTimeout(function(){
count.className = 'slack-count';
}, 200);
refresh();
}
}
};
document.body.appendChild(script);
})();
|
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { Text } from 'native-base';
import Colors from '../../../native-base-theme/variables/commonColor';
const Messages = ({ message, type }) => (
<View
style={{
backgroundColor:
type === 'error' ? Colors.brandDanger : type === 'success' ? Colors.brandSuccess : Colors.brandInfo,
paddingVertical: 10,
paddingHorizontal: 5,
}}
>
<Text style={{ color: '#fff', textAlign: 'center' }}>{message}</Text>
</View>
);
Messages.propTypes = {
message: PropTypes.string,
type: PropTypes.oneOf(['error', 'success', 'info']),
};
Messages.defaultProps = {
message: 'An unexpected error came up',
type: 'error',
};
export default Messages;
|
function updateImprovementsDisplay(i) {
updateDisplay(
'desc_improvements',
`improvements: ${i}`
);
}
function updateGenerationsDisplay(g) {
updateDisplay(
'desc_generations',
`generations: ${g}`
);
}
function updateBestSimilarityDisplay(s) {
updateDisplay(
'best_desc_similarity',
`${s}% similar`
);
}
function updateScratchSimilarityDisplay(s) {
updateDisplay(
'scratch_desc_similarity',
`${s}% similar`
);
}
function updateScratchPhaseIdDisplay(id, n) {
updateDisplay(
'scratch_desc_phasenum',
`phase: ${id + 1} / ${n}`
);
}
function updateScratchTemperatureDisplay(t) {
updateDisplay(
'scratch_desc_temp',
`temperature: ${t}`
);
}
function updateScratchPhasePercentageDisplay(tries, max) {
const percentDone = (100 * tries / max).toFixed()
updateDisplay(
'scratch_desc_phase_percentage',
`phase progress: ${percentDone}%`
);
}
function updateDisplay(name, value) {
document.getElementById(name).innerHTML = value;
}
export {
updateImprovementsDisplay,
updateGenerationsDisplay,
updateBestSimilarityDisplay,
updateScratchSimilarityDisplay,
updateScratchPhaseIdDisplay,
updateScratchTemperatureDisplay,
updateScratchPhasePercentageDisplay,
};
|
import { createAction } from "redux-actions";
export default createAction("MARK_BLOCK");
|
/*
This is the example config file used to demonstrate
turning leds of different types and protocols on and off.
*/
// converts a number to a hex
function toHex(c) {
var hex = c.toString(16);
hex = hex.length == 1 ? "0" + hex : hex;
return "0x" + hex;
}
// formats an input to be received by a tri-color gpio led
function triGpioColor(c) {
if(c === 1) return 1;
if(c === 0) return 0;
var isArray = Array.isArray(c);
if(isArray && this._component.name === 'red') return c[0] === 255 ? 1 : 0;
if(isArray && this._component.name === 'blue') return c[1] === 255 ? 1: 0;
if(isArray && this._component.name === 'green') return c[2] === 255 ? 1: 0;
return c;
}
// formats the input to be received by the blinkM led
function blinkMInput(c) {
if(c === 1) return [255, 255, 255];
if(c === 0) return [0, 0, 0];
return [c[0] ,c[1],c[2]];
}
// formats the input to be received by a 5050led (apa102)
var apaIdx = 0;
function apa102Input(c, cmd) {
if(c === 1) return [0xff, 0xff, 0xff, 0xff];
else if(c === 0) return [0xff, 0x00, 0x00, 0x00];
return [0xff, toHex(c[2]), toHex(c[1]), toHex(c[0])];
}
module.exports = {
"name":"hello-world-leds",
"i2c-path": '/dev/i2c-1',
"components" : [{"type":"led", "name":"blue", "direction": "out",
"address":17, "interface": "gpio", "formatInput" : triGpioColor},
{"type":"led","name":"green", "address":27, "direction": "out",
"interface": "gpio", formatInput: triGpioColor},
{"type":"led","name":"red","address":22, "direction": "out",
"interface": "gpio", formatInput: triGpioColor },
{type:"led",path: 1, address: 0x09, "name":"blinkm",
interface: "i2c",
init: {type: 'write', cmd: 0x6f},
set:{type: 'write', cmd:0x6e , formatInput: blinkMInput}},
{type: "led", interface: "spi", name: "apa102",
address: "/dev/spidev0.0", set: [
{val: new Buffer(32).fill(0)},{formatInput: apa102Input}]}
]
};
|
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = merge(common, {
module: {
rules: [{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: 'css-loader',
fallback: 'style-loader',
}),
}],
},
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin({
filename: 'css/[name].css?[hash]-[chunkhash]-[contenthash]-[name]',
}),
],
});
|
const Request = require('request');
const env2 = require('env2');
const HapiCookie = require('hapi-auth-cookie');
env2('./config.env');
module.exports = {
path: '/welcome',
method: 'GET',
handler: (req, rep) => {
const accessUrl = `https://github.com/login/oauth/access_token`;
Request.post({
headers: {
// as recommended by the API documentation
Accept: `application/json`
},
url: accessUrl,
form: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: req.query.code
}
}, (err, res, body) => {
if (err) throw err;
let parsed = JSON.parse(body);
const userToken = {
access_token: parsed.access_token
};
Request.get({
headers: {
'User-Agent': 'GitPom',
// as recommended by the API documentation
Accept: `application/json`,
Authorization: `token ${userToken.access_token}`
},
url: `https://api.github.com/user`
}, (err, res, body) => {
if (err) throw err;
parsed = JSON.parse(body);
const userDetails = {
userName: parsed.login,
avatarUrl: parsed.avatar_url
};
// set the cookie containing the token, the username and the avatar url
req.cookieAuth.set(Object.assign(userToken, userDetails));
rep(`<a id="continue" href="/"></a>
<script>
window.addEventListener('load', function(){
document.getElementById("continue").click();
})
</script>`);
});
});
}
};
|
describe('Events:', function() {
var it_prepends_to_the_jobs_list_view = function() {
it('prepends to the jobs list view', function() {
expect_text('#jobs li:first-child', this.data.repository.name + ' #' + this.data.number)
});
};
var it_removes_the_job_from_the_jobs_list_view = function() {
it('removes the job from the jobs list view', function() {
expect($('#jobs li.empty').attr('style').match('display: none')).toBeFalsy();
});
};
describe('the job queue', function() {
beforeEach(function() {
this.repository = INIT_DATA.repositories[1];
go_to('#!/' + this.repository.name)
});
describe('an incoming event for the current build', function() {
describe('build:queued', function() {
beforeEach(function() {
this.data = build_queued_data(this.repository, { number: 2 });
Travis.app.trigger('build:queued', this.data);
waitsFor(jobs_list_populated(1));
});
it_prepends_to_the_jobs_list_view();
});
describe('build:started', function() {
beforeEach(function() {
this.data = build_started_data(this.repository);
Travis.app.trigger('build:started', this.data);
});
it_removes_the_job_from_the_jobs_list_view();
});
});
});
});
|
const {npmPublishPackage, npmPublishAll} = require(`../../utils/publish`);
module.exports = {
command: `package <packageName>`,
desc: `Publish a package to NPM`,
builder: {},
handler: ({packageName}) => {
if (packageName) {
switch (packageName.toLowerCase()) {
case `all`:
return npmPublishAll();
default:
return npmPublishPackage(packageName);
}
}
return false;
}
};
|
/**
* A Node.js module object. Every Node.js module receives a reference to
* itself through a local variable named "module", and its global context.
*
* @external module
* @see https://nodejs.org/api/modules.html#modules_the_module_object
*/
/**
* The Node.js built-in "path" module.
*
* @external path
* @see https://nodejs.org/api/path.html
*/
/**
* @member external:path.posix
* @see https://nodejs.org/api/path.html#path_path_posix
*/
/**
* @member external:path.win32
* @see https://nodejs.org/api/path.html#path_path_win32
*/
/**
* The Node.js built-in "util" module.
*
* @external util
* @see https://nodejs.org/api/util.html
*/
/**
* @see https://nodejs.org/api/util.html#util_util_format_format_args
*
* @function external:util.format
* @param {string} format - A printf-like format string.
* @param {...*} args - Replacement values.
*/
/**
* A Moment.js date time object.
*
* @external moment
* @see https://momentjs.com/docs/
*/
/**
* A lignin plug-in.
*
* @global
* @class Plugin
* @param {string} id - An instance identifier, provided for auditing.
* @param {Object} options - The options available to the configuration,
* used to construct the new plug-in instance.
* @param {ConfigurationState} context - The global logging configuration,
* used to resolve references to level names, filter names and plugin names.
*/
/**
* Performs asynchronous initialization. Since plug-ins may depend on
* configured filters and appenders, a recursive dependency resolution
* strategy is employed, as follows.
*
* <ol>
* <li>Attempt to invoke this method for all filters, then appenders.</li>
* <li>Those not responding are assumed to have initialized synchronously
* from the constructor.</li>
* <li>Those resolving to a truthy value or <code>undefined</code> are assumed
* properly initialized.</li>
* <li>Those resolving to any other value are assumed not yet able to
* initialize due to missing dependencies, and will be retried later.</li>
* <li>If all filters and appenders had finished initializing, configuration
* will proceed to initializing loggers.</li>
* <li>If some filters or appenders had finished initializing at this
* iteration, all plug-in instances that could not initialize at the previous
* iteration are retried with the same rules.</li>
* <li>If no filters or appenders could initialize in this iteration, while
* some are still pending initialization, an error will be thrown to indicate
* that their initialization conditions cannot be satisfied.</li>
* </ol>
*
* @method Plugin#setup
* @returns {boolean|Promise.<boolean>} A promise of initialization
* completion.
*/
/**
* Releases resources held by this instance. If implemented, it will be
* invoked before releasing the plug-in (for reconfiguration or termination),
* and be awaited for (if possible).
*
* @method Plugin#close
* @returns {Promise} A promise of termination completion.
*/
/**
* Filters a logging message. A filter plug-in must implement this method.
* It may transform, select or replace messages received by loggers and
* appenders.
*
* <ul>
* <li>If a message is dropped from a logger, it will not be received by
* subsequent filters, current appenders and parent loggers.</li>
* <li>If a message is replaced or transformed in a logger, the changes will
* be visible to subsequent filters, current appenders and parent
* loggers.</li>
* <li>Appenders are implemented by plug-ins, which may define their own
* processing rules for filters. It is recommended that implementors follow
* similar rules: changes should only be visible to subsequent filters first
* (if using a filter chain), then finally to the appender itself.</li>
* </ul>
*
* @method Plugin#filter
* @param {record} record - The message to process.
* @returns {Promise.<?record>} A promise for the original or replaced
* message for further processing, or <code>null</code> to prevent it from
* being further processed. Rejections will generate error events, instead of
* being logged anywhere, to prevent rejection loops. The original message
* and the offending plug-in will be part of the event data for auditing.
*/
/**
* Appends the message to some medium. An appender plug-in must implement this
* method. Appenders should not mutate the received log records, but that
* requirement will not be enforced. The logger will attempt to deliver a
* clone of the original log record, to prevent mutations from affecting other
* appenders, but some custom data in the record may not be cloneable or may
* not clone deeply enough for all use cases.
*
* @method Plugin#append
* @param {record} record - The message to record.
* @returns {Promise} A promise of completion. Rejections will generate
* error events, instead of being logged anywhere, to prevent rejection loops.
* The original message and the offending plug-in will be part of the event
* data for auditing.
*/
/**
* A log record. It is generated by loggers, and contains some standard fields
* for processing by filters and appenders. Other non-standard fields may be
* added by filters. If the record itself or any of its nested objects
* implement a <code>clone</code> method, it will be used to generate a clone
* of that object for appenders.
*
* @typedef {Object} record
* @property {string} message - The formatted message to be logged.
* @property {string} level - The name of the verbosity level at which the
* message was recorded.
* @property {external:moment} timestamp - The date and time of when the
* record was generated.
* @property {string} category - The name of the logger from which this record
* originated.
*/
|
// flow-typed signature: 03af697d18fe8a7b11299425ad8b778f
// flow-typed version: <<STUB>>/webpack-manifest-plugin_v^1.1.0/flow_v0.41.0
/**
* This is an autogenerated libdef stub for:
*
* 'webpack-manifest-plugin'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'webpack-manifest-plugin' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'webpack-manifest-plugin/lib/plugin' {
declare module.exports: any;
}
declare module 'webpack-manifest-plugin/spec/fixtures/file-two' {
declare module.exports: any;
}
declare module 'webpack-manifest-plugin/spec/fixtures/file' {
declare module.exports: any;
}
declare module 'webpack-manifest-plugin/spec/fixtures/nameless' {
declare module.exports: any;
}
declare module 'webpack-manifest-plugin/spec/plugin.spec' {
declare module.exports: any;
}
// Filename aliases
declare module 'webpack-manifest-plugin/index' {
declare module.exports: $Exports<'webpack-manifest-plugin'>;
}
declare module 'webpack-manifest-plugin/index.js' {
declare module.exports: $Exports<'webpack-manifest-plugin'>;
}
declare module 'webpack-manifest-plugin/lib/plugin.js' {
declare module.exports: $Exports<'webpack-manifest-plugin/lib/plugin'>;
}
declare module 'webpack-manifest-plugin/spec/fixtures/file-two.js' {
declare module.exports: $Exports<'webpack-manifest-plugin/spec/fixtures/file-two'>;
}
declare module 'webpack-manifest-plugin/spec/fixtures/file.js' {
declare module.exports: $Exports<'webpack-manifest-plugin/spec/fixtures/file'>;
}
declare module 'webpack-manifest-plugin/spec/fixtures/nameless.js' {
declare module.exports: $Exports<'webpack-manifest-plugin/spec/fixtures/nameless'>;
}
declare module 'webpack-manifest-plugin/spec/plugin.spec.js' {
declare module.exports: $Exports<'webpack-manifest-plugin/spec/plugin.spec'>;
}
|
/*
* The MainMenu state displays the game menu and enters the Game state after the user clicks the screen.
*/
Game.MainMenu = function(game) {
};
Game.MainMenu.prototype = {
create: function() {
this.add.sprite(0, 0, 'titlepage');
this.loadingText = this.add.text(510, 520, 'Click to start playing', {
font: '24px monospace',
fill: '#fff'
});
this.loadingText.anchor.setTo(0.5, 0.5);
},
update: function() {
if (this.input.activePointer.isDown) {
// The user is clicking, so enter the Game state where the actual game is played
this.state.start('Game');
}
}
};
|
const Path = require('path');
const webpack = require('webpack');
// Import the core config
const webpackConfig = require('@silverstripe/webpack-config');
const {
resolveJS,
externalJS,
moduleJS,
pluginJS,
moduleCSS,
pluginCSS,
} = webpackConfig;
const ENV = process.env.NODE_ENV;
const PATHS = {
MODULES: 'node_modules',
FILES_PATH: '../',
ROOT: Path.resolve(),
SRC: Path.resolve('client/src'),
DIST: Path.resolve('client/dist'),
THIRDPARTY: Path.resolve('thirdparty'),
};
const config = [
{
name: 'js',
entry: {
'segment-field': `${PATHS.SRC}/bundles/segment-field.js`,
},
output: {
path: PATHS.DIST,
filename: 'js/[name].js',
},
devtool: (ENV !== 'production') ? 'source-map' : '',
resolve: resolveJS(ENV, PATHS),
externals: externalJS(ENV, PATHS),
module: moduleJS(ENV, PATHS),
plugins: pluginJS(ENV, PATHS),
},
{
name: 'css',
entry: {
'segment-field': `${PATHS.SRC}/styles/segment-field.scss`,
},
output: {
path: PATHS.DIST,
filename: 'styles/[name].css'
},
devtool: (ENV !== 'production') ? 'source-map' : '',
module: moduleCSS(ENV, PATHS),
plugins: pluginCSS(ENV, PATHS),
},
];
module.exports = config;
|
export const getMockState = {
withNoNotes: ()=>({
byId: {},
ids: [],
openNoteId: null
}),
withOneNote: ()=>({
byId: {
'id-123': {
id: 'id-123',
content: 'Hello World',
timestamp: 1
}
},
ids: ['id-123'],
openNoteId: 'id-123'
}),
withTwoNotes: ()=>({
byId: {
'id-123': {
id: 'id-123',
content: 'Hello World',
timestamp: 1
},
'id-456': {
id: 'id-456',
content: 'Hello World 456',
timestamp: 2
}
},
ids: ['id-123', 'id-456'],
openNoteId: 'id-456'
}),
withNoOpenNotes: ()=>({
byId: {
'id-123': {
id: 'id-123',
content: 'Hello World',
timestamp: 1
}
},
ids: ['id-123'],
openNoteId: null
})
};
|
'use strict';
const path = require('path');
const { logError } = require('./util/logger');
const config = {
user: process.env.MC_USER,
pass: process.env.MC_PASS,
serverHost: process.env.MC_SERVER_HOST || 'simpvp.net',
serverPort: process.env.MC_SERVER_PORT || 25565,
logFilePath: process.env.LOG_FILE_PATH || path.join(__dirname, '..', 'data', 'master.log'),
markovOrder: 2
};
Object.keys(config).forEach((key) => {
if (!config[key]) {
logError(`WARNING: Missing configuration value: ${key}`);
}
});
module.exports = config;
|
'use strict';
angular.module(
'webtypesetting.questions',
[ 'sf.services', 'palaso.ui.listview', 'palaso.ui.typeahead', 'ui.bootstrap' ]
)
.controller('QuestionsCtrl', ['$scope', 'questionsService', '$routeParams', 'sessionService', 'linkService', 'breadcrumbService',
function($scope, questionsService, $routeParams, ss, linkService, bcs) {
var projectId = $routeParams.projectId;
var textId = $routeParams.textId;
$scope.projectId = projectId;
$scope.textId = textId;
$scope.projectName = $routeParams.projectName;
$scope.textName = $routeParams.textName;
// Rights
$scope.rights = {};
$scope.rights.deleteOther = false;
$scope.rights.create = false;
$scope.rights.editOther = false; //ss.hasRight(ss.realm.SITE(), ss.domain.PROJECTS, ss.operation.EDIT_OTHER);
$scope.rights.showControlBar = $scope.rights.deleteOther || $scope.rights.create || $scope.rights.editOther;
// Listview Selection
$scope.newQuestionCollapsed = true;
$scope.selected = [];
$scope.updateSelection = function(event, item) {
var selectedIndex = $scope.selected.indexOf(item);
var checkbox = event.target;
if (checkbox.checked && selectedIndex == -1) {
$scope.selected.push(item);
} else if (!checkbox.checked && selectedIndex != -1) {
$scope.selected.splice(selectedIndex, 1);
}
};
$scope.isSelected = function(item) {
return item != null && $scope.selected.indexOf(item) >= 0;
};
// Listview Data
$scope.questions = [];
$scope.queryQuestions = function() {
console.log("queryQuestions()");
questionsService.list(projectId, textId, function(result) {
if (result.ok) {
$scope.questions = result.data.entries;
$scope.questionsCount = result.data.count;
$scope.enhanceDto($scope.questions);
$scope.text = result.data.text;
$scope.project = result.data.project;
$scope.text.url = linkService.text(projectId, textId);
bcs.updateMap('project', $scope.project.id, $scope.project.name);
bcs.updateMap('text', $scope.text.id, $scope.text.title);
var rights = result.data.rights;
$scope.rights.deleteOther = ss.hasRight(rights, ss.domain.QUESTIONS, ss.operation.DELETE_OTHER);
$scope.rights.create = ss.hasRight(rights, ss.domain.QUESTIONS, ss.operation.CREATE);
$scope.rights.editOther = ss.hasRight(rights, ss.domain.TEXTS, ss.operation.EDIT_OTHER);
$scope.rights.showControlBar = $scope.rights.deleteOther || $scope.rights.create || $scope.rights.editOther;
}
});
};
// Remove
$scope.removeQuestions = function() {
console.log("removeQuestions()");
var questionIds = [];
for(var i = 0, l = $scope.selected.length; i < l; i++) {
questionIds.push($scope.selected[i].id);
}
if (l == 0) {
// TODO ERROR
return;
}
questionsService.remove(projectId, questionIds, function(result) {
if (result.ok) {
$scope.selected = []; // Reset the selection
$scope.queryQuestions();
// TODO
}
});
};
// Add
$scope.addQuestion = function() {
console.log("addQuestion()");
var model = {};
model.id = '';
model.textRef = textId;
model.title = $scope.questionTitle;
model.description = $scope.questionDescription;
questionsService.update(projectId, model, function(result) {
if (result.ok) {
$scope.queryQuestions();
}
});
};
// Fake data to make the page look good while it's being designed. To be
// replaced by real data once the appropriate API functions are writen.
var fakeData = {
answerCount: -3,
viewsCount: -27,
unreadAnswers: -1,
unreadComments: -5
};
$scope.getAnswerCount = function(question) {
return question.answerCount;
};
$scope.getViewsCount = function(question) {
return fakeData.viewsCount;
};
$scope.getUnreadAnswers = function(question) {
return fakeData.unreadAnswers;
};
$scope.getUnreadComments = function(question) {
return fakeData.unreadComments;
};
$scope.enhanceDto = function(items) {
for (var i in items) {
items[i].url = linkService.question(projectId, textId, items[i].id);
}
};
}])
.controller('QuestionsSettingsCtrl', ['$scope', 'textService', 'sessionService', '$routeParams', function($scope, textService, ss, $routeParams) {
var projectId = $routeParams.projectId;
var textId = $routeParams.textId;
var dto;
$scope.projectId = projectId;
$scope.textId = textId;
$scope.editedText = {
id: textId,
}
// Get name from text service. This really should be in the DTO, but this will work for now.
// TODO: Move this to the DTO (or BreadcrumbHelper?) so we don't have to do a second server round-trip. RM 2013-08
var text;
textService.settings_dto($scope.projectId, $scope.textId, function(result) {
if (result.ok) {
$scope.dto = result.data;
$scope.textTitle = $scope.dto.text.title;
$scope.editedText.title = $scope.dto.text.title;
$scope.rights = {
editOther: ss.hasRight($scope.dto.rights, ss.domain.TEXTS, ss.operation.EDIT_OTHER),
};
}
});
$scope.updateText = function(newText) {
if (!newText.content) {
delete newText.content;
}
textService.update($scope.projectId, newText, function(result) {
if (result.ok) {
$scope.textTitle = newText.title;
$scope.showMessage = true;
}
});
}
}])
;
|
"use strict";
let merge = (nums, index, length, increasing) => {
if (length > 1) {
let half = Math.floor(length / 2);
for (let i = index; i < index + half; i++) {
if ((nums[i] > nums[i + half] && increasing) ||
(nums[i] < nums[i + half] && !increasing)) {
[nums[i], nums[i + half]] = [nums[i + half], nums[i]];
}
}
merge(nums, index, half, increasing);
merge(nums, index + half, half, increasing);
}
}
let bitonicSort = (nums, index = 0, length = nums.length, increasing = true) => {
if (length > 1) {
let half = Math.floor(length / 2);
bitonicSort(nums, index, half, true);
bitonicSort(nums, index + half, half, false);
merge(nums, index, length, increasing);
}
}
let nums = [1, 5, 77, 34, 2, 18, 19, 20, 21, 10, 43, 99, 101, 77, 75, 71]; // Must be pow of 2
console.log(nums);
bitonicSort(nums);
console.log(nums);
|
// ***********************************
// Firebase & jQuery HTML5 chat
// ***********************************
var messagesRef = new Firebase('https://cesarstechinsights.firebaseio.com');
// When the user presses enter on the message input, write the message to firebase.
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
messagesRef.push({name:name, text:text});
$('#messageInput').val('');
}
});
// Add a callback that is triggered for each chat message.
messagesRef.limit(40).on('child_added', function (snapshot) {
var message = snapshot.val();
$('<div/>')
.text(message.text)
.prepend($('<strong/>')
.text(message.name+': '))
.appendTo($('#messagesDiv'));
});
|
module.exports = {
name: "datastore",
ns: "nedb",
description: "Nedb Datastore",
phrases: {
active: "Creating datastore"
},
dependencies: {
npm: {
nedb: require('nedb')
}
},
ports: {
input: {
options: {
title: "Options",
type: "object",
required: false,
properties: {
filename: {
type: "string",
description: "path to the file where the data is persisted. If left blank, the datastore is automatically considered in-memory only. It cannot end with a ~ which is used in the temporary files NeDB uses to perform crash-safe writes",
required: false
},
inMemoryOnly: {
Title: "In Memory only",
type: "boolean",
description: "In Memory Only",
"default": false
},
onload: {
title: "Onload",
type: "function",
description: "if you use autoloading, this is the handler called after the loadDatabase. It takes one error argument. If you use autoloading without specifying this handler, and an error happens during load, an error will be thrown.",
required: false
},
afterSerialization: {
title: "After serialization",
type: "function",
description: "hook you can use to transform data after it was serialized and before it is written to disk. Can be used for example to encrypt data before writing database to disk. This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a \n character (or data will be lost)",
required: false
},
beforeDeserialization: {
title: "Before Deserialization",
type: "function",
description: "reverse of afterSerialization. Make sure to include both and not just one or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. In addition, if too much data is detected as corrupt, NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below)",
required: false
},
corruptAlertThreshold: {
type: "number",
description: "between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you don't care",
minValue: 0,
maxValue: 1,
required: false
}
}
}
},
output: {
db: {
title: "Database",
type: "Datastore"
},
error: {
title: "Error",
type: "Error"
}
}
},
fn: function datastore(input, $, output, state, done, cb, on, nedb) {
var r = function() {
var db = new nedb($.options);
db.loadDatabase(function(err) {
if (err) {
output({
error: $.create(err)
});
} else {
output({
db: $.create(db)
});
}
});
}.call(this);
return {
output: output,
state: state,
on: on,
return: r
};
}
}
|
import React from "react";
import { Link } from "react-imvc/component";
import Layout from "../component/Layout";
export default function View({ state }) {
return (
<Layout>
{state.contents.map(({ type, list }) => {
return (
<div key={type}>
<h2>
{type}
</h2>
<List data={list} />
</div>
);
})}
</Layout>
);
}
function List({ data }) {
return (
<ul>
{data.map(item => <ListItem key={item.url} {...item} />)}
</ul>
);
}
function ListItem({ title, url, raw, ...rest }) {
return (
<li>
{!!raw &&
<a href={url} {...rest}>
{title}
</a>}
{!raw &&
<Link to={url} {...rest}>
{title}
</Link>}
</li>
);
}
|
var sha1sum = require('sha1sum')
module.exports = function (emitter, state) {
//vvv will all be refactored out.
//using this right now, to get a MVP going.
//later, replace with a merkle tree.
//track changes in doc...
emitter.on('open', function (doc) {
function onUpdate () {
console.log('update', doc.key, sha1sum(doc.sources))
emitter.emit('_change', doc.key, sha1sum(doc.sources))
}
doc.on('_update', onUpdate)
doc.once('dispose', function () {
doc.removeListener('_update', onUpdate)
})
})
emitter.on('_change', function (key, hash) {
state[key] = hash
})
//refactor this out to use a correctly commutative datastructure here.
return function syncState(kv) {
var STATE = '__state'
kv.has(STATE, function (_, stat) {
//there is a little race condition here,
//because this isn't append only.
//FIX ME after mvp.
function onReady() {
console.log('ON READY', state)
var s = kv.put(STATE)
function write(k,v) {
console.log('STATE', k, v)
s.write([k, v])
}
for(var k in state)
write(k, state[k])
emitter.on('_change', write)
emitter.ready = true
emitter.emit('ready')
}
if(stat) {
//read the file...
kv.get(STATE)
.on('data', function (data) {
var key = data.shift()
var value = data.shift()
state[key] = value
})
.on('error', function () {
console.log('ERRO')
})
.once('close', onReady)
} else
onReady()
})
}
//^^^ replace with merkle tree.
}
|
const subManager = new SubsManager();
BlazeComponent.extendComponent({
mixins() {
return [Mixins.InfiniteScrolling, Mixins.PerfectScrollbar];
},
calculateNextPeak() {
const cardElement = this.find('.js-card-details');
if (cardElement) {
const altitude = cardElement.scrollHeight;
this.callFirstWith(this, 'setNextPeak', altitude);
}
},
reachNextPeak() {
const activitiesComponent = this.childComponents('activities')[0];
activitiesComponent.loadNextPage();
},
onCreated() {
this.isLoaded = new ReactiveVar(false);
this.parentComponent().showOverlay.set(true);
this.parentComponent().mouseHasEnterCardDetails = false;
this.calculateNextPeak();
Meteor.subscribe('unsaved-edits');
},
isWatching() {
const card = this.currentData();
return card.findWatcher(Meteor.userId());
},
hiddenSystemMessages() {
return Meteor.user().hasHiddenSystemMessages();
},
canModifyCard() {
return Meteor.user() && Meteor.user().isBoardMember() && !Meteor.user().isCommentOnly();
},
scrollParentContainer() {
const cardPanelWidth = 510;
const bodyBoardComponent = this.parentComponent();
const $cardContainer = bodyBoardComponent.$('.js-lists');
const $cardView = this.$(this.firstNode());
const cardContainerScroll = $cardContainer.scrollLeft();
const cardContainerWidth = $cardContainer.width();
const cardViewStart = $cardView.offset().left;
const cardViewEnd = cardViewStart + cardPanelWidth;
let offset = false;
if (cardViewStart < 0) {
offset = cardViewStart;
} else if (cardViewEnd > cardContainerWidth) {
offset = cardViewEnd - cardContainerWidth;
}
if (offset) {
bodyBoardComponent.scrollLeft(cardContainerScroll + offset);
}
},
onRendered() {
if (!Utils.isMiniScreen()) this.scrollParentContainer();
},
onDestroyed() {
this.parentComponent().showOverlay.set(false);
},
events() {
const events = {
[`${CSSEvents.transitionend} .js-card-details`]() {
this.isLoaded.set(true);
},
[`${CSSEvents.animationend} .js-card-details`]() {
this.isLoaded.set(true);
},
};
return [{
...events,
'click .js-close-card-details' () {
Utils.goBoardId(this.data().boardId);
},
'click .js-open-card-details-menu': Popup.open('cardDetailsActions'),
'submit .js-card-description' (evt) {
evt.preventDefault();
const description = this.currentComponent().getValue();
this.data().setDescription(description);
},
'submit .js-card-details-title' (evt) {
evt.preventDefault();
const title = this.currentComponent().getValue().trim();
if (title) {
this.data().setTitle(title);
}
},
'click .js-member': Popup.open('cardMember'),
'click .js-add-members': Popup.open('cardMembers'),
'click .js-add-labels': Popup.open('cardLabels'),
'mouseenter .js-card-details' () {
this.parentComponent().showOverlay.set(true);
this.parentComponent().mouseHasEnterCardDetails = true;
},
'click #toggleButton'() {
Meteor.call('toggleSystemMessages');
},
}];
},
}).register('cardDetails');
// We extends the normal InlinedForm component to support UnsavedEdits draft
// feature.
(class extends InlinedForm {
_getUnsavedEditKey() {
return {
fieldName: 'cardDescription',
// XXX Recovering the currentCard identifier form a session variable is
// fragile because this variable may change for instance if the route
// change. We should use some component props instead.
docId: Session.get('currentCard'),
};
}
close(isReset = false) {
if (this.isOpen.get() && !isReset) {
const draft = this.getValue().trim();
if (draft !== Cards.findOne(Session.get('currentCard')).description) {
UnsavedEdits.set(this._getUnsavedEditKey(), this.getValue());
}
}
super.close();
}
reset() {
UnsavedEdits.reset(this._getUnsavedEditKey());
this.close(true);
}
events() {
const parentEvents = InlinedForm.prototype.events()[0];
return [{
...parentEvents,
'click .js-close-inlined-form': this.reset,
}];
}
}).register('inlinedCardDescription');
Template.cardDetailsActionsPopup.helpers({
isWatching() {
return this.findWatcher(Meteor.userId());
},
canModifyCard() {
return Meteor.user() && Meteor.user().isBoardMember() && !Meteor.user().isCommentOnly();
},
});
Template.cardDetailsActionsPopup.events({
'click .js-members': Popup.open('cardMembers'),
'click .js-labels': Popup.open('cardLabels'),
'click .js-attachments': Popup.open('cardAttachments'),
'click .js-start-date': Popup.open('editCardStartDate'),
'click .js-due-date': Popup.open('editCardDueDate'),
'click .js-spent-time': Popup.open('editCardSpentTime'),
'click .js-move-card': Popup.open('moveCard'),
'click .js-copy-card': Popup.open('copyCard'),
'click .js-move-card-to-top' (evt) {
evt.preventDefault();
const minOrder = _.min(this.list().cards().map((c) => c.sort));
this.move(this.listId, minOrder - 1);
},
'click .js-move-card-to-bottom' (evt) {
evt.preventDefault();
const maxOrder = _.max(this.list().cards().map((c) => c.sort));
this.move(this.listId, maxOrder + 1);
},
'click .js-archive' (evt) {
evt.preventDefault();
this.archive();
Popup.close();
},
'click .js-more': Popup.open('cardMore'),
'click .js-toggle-watch-card' () {
const currentCard = this;
const level = currentCard.findWatcher(Meteor.userId()) ? null : 'watching';
Meteor.call('watch', 'card', currentCard._id, level, (err, ret) => {
if (!err && ret) Popup.close();
});
},
});
Template.editCardTitleForm.onRendered(function () {
autosize(this.$('.js-edit-card-title'));
});
Template.editCardTitleForm.events({
'keydown .js-edit-card-title' (evt) {
// If enter key was pressed, submit the data
// Unless the shift key is also being pressed
if (evt.keyCode === 13 && !evt.shiftKey) {
$('.js-submit-edit-card-title-form').click();
}
},
});
Template.moveCardPopup.events({
'click .js-select-list' () {
// XXX We should *not* get the currentCard from the global state, but
// instead from a “component” state.
const card = Cards.findOne(Session.get('currentCard'));
const newListId = this._id;
card.move(newListId);
Popup.close();
},
});
BlazeComponent.extendComponent({
onCreated() {
this.selectedBoard = new ReactiveVar(Session.get('currentBoard'));
},
boards() {
const boards = Boards.find({
archived: false,
'members.userId': Meteor.userId(),
}, {
sort: ['title'],
});
return boards;
},
aBoardLists() {
subManager.subscribe('board', this.selectedBoard.get());
const board = Boards.findOne(this.selectedBoard.get());
return board.lists();
},
events() {
return [{
'change .js-select-boards'(evt) {
this.selectedBoard.set($(evt.currentTarget).val());
},
}];
},
}).register('boardsAndLists');
Template.copyCardPopup.events({
'click .js-select-list' (evt) {
const card = Cards.findOne(Session.get('currentCard'));
const oldId = card._id;
card._id = null;
card.listId = this._id;
const list = Lists.findOne(card.listId);
card.boardId = list.boardId;
const textarea = $(evt.currentTarget).parents('.content').find('textarea');
const title = textarea.val().trim();
// insert new card to the bottom of new list
card.sort = Lists.findOne(this._id).cards().count();
if (title) {
card.title = title;
card.coverId = '';
const _id = Cards.insert(card);
// In case the filter is active we need to add the newly inserted card in
// the list of exceptions -- cards that are not filtered. Otherwise the
// card will disappear instantly.
// See https://github.com/wekan/wekan/issues/80
Filter.addException(_id);
// copy checklists
let cursor = Checklists.find({cardId: oldId});
cursor.forEach(function() {
'use strict';
const checklist = arguments[0];
checklist.cardId = _id;
checklist._id = null;
Checklists.insert(checklist);
});
// copy card comments
cursor = CardComments.find({cardId: oldId});
cursor.forEach(function () {
'use strict';
const comment = arguments[0];
comment.cardId = _id;
comment._id = null;
CardComments.insert(comment);
});
Popup.close();
}
},
});
Template.cardMorePopup.events({
'click .js-copy-card-link-to-clipboard' () {
// Clipboard code from:
// https://stackoverflow.com/questions/6300213/copy-selected-text-to-the-clipboard-without-using-flash-must-be-cross-browser
const StringToCopyElement = document.getElementById('cardURL');
StringToCopyElement.select();
if (document.execCommand('copy')) {
StringToCopyElement.blur();
} else {
document.getElementById('cardURL').selectionStart = 0;
document.getElementById('cardURL').selectionEnd = 999;
document.execCommand('copy');
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
},
'click .js-delete': Popup.afterConfirm('cardDelete', function () {
Popup.close();
Cards.remove(this._id);
Utils.goBoardId(this.boardId);
}),
});
// Close the card details pane by pressing escape
EscapeActions.register('detailsPane',
() => {
Utils.goBoardId(Session.get('currentBoard'));
},
() => {
return !Session.equals('currentCard', null);
}, {
noClickEscapeOn: '.js-card-details,.board-sidebar,#header',
}
);
|
var expect = require("chai").expect,
proxyquire = require("proxyquire"),
sinon = require("sinon");
var models = {};
var app = sinon.stub();
var auth = { authenticated: sinon.stub() };
var get = app.get = sinon.stub();
var post = app.post = sinon.stub();
var Country = models.Country = sinon.stub();
var Vote = models.Vote = sinon.stub();
var vote = proxyquire("../routes/vote", {
"../models": models,
"./auth": auth
});
describe("routes/vote", function() {
var req = {}, res = {};
var spy = res.render = sinon.spy();
var display, submit;
before(function() {
vote(app);
display = get.args[0][2];
submit = post.args[0][2];
});
beforeEach(function() {
spy.reset();
});
describe("GET voting page", function() {
var countries = [ { id: 1, name: "Narnia" },
{ id: 2, name: "Transylvania" }];
var promise = sinon.stub();
promise.then = sinon.stub();
beforeEach(function() {
Country.findAll = sinon.stub();
Country.findAll.returns(promise);
promise.then.callsArgWith(0, countries);
});
it("should render voting page", function() {
display(req, res);
expect(spy.calledOnce).to.equal(true);
expect(spy.args[0][0]).to.equal("vote");
});
it("should set page title and navbarActive properties", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("title").that.equals("Vote");
expect(locals).to.have.property("navbarActive").that.equals("Vote");
});
it("should include countries in the response", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("countries").that.deep.equals(countries);
});
it("should order the countries by name", function() {
display(req, res);
var call = Country.findAll.getCall(0);
expect(call.args[0]).to.have.property("order").that.equals("name ASC");
});
});
describe("POST /submit", function() {
var votes = [ { id: 1, score: 12 },
{ id: 2, score: 10 },
{ id: 3, score: 8 } ];
var req = {};
req.body = { data: JSON.stringify(votes) };
res.send = sinon.stub();
res.sendStatus = sinon.stub();
res.status = sinon.stub().returns(res);
var promise = sinon.stub();
promise.then = sinon.stub();
promise.catch = sinon.stub();
Vote.create = sinon.stub().returns(promise);
var user = req.user = {};
user.getGroup = sinon.stub().returns(promise);
var group = {id: 1};
beforeEach(function() {
Vote.create.reset();
Vote.create.returns(promise);
promise.then.reset();
promise.then.onFirstCall().yields([group]).returns(promise);
promise.then.yields();
});
it("should insert all the votes", function() {
submit(req, res);
expect(Vote.create.callCount).to.equal(votes.length);
for (var i = 0; i < Vote.create.callCount; i++) {
var call = Vote.create.getCall(i);
expect(call.calledWith(sinon.match({
CountryId: votes[i].id,
score: votes[i].score
})));
}
});
it("should respond OK if no error thrown", function() {
submit(req, res);
expect(res.sendStatus.calledWith(200)).to.equal(true);
});
it("should respond with an error message if there is an error", function() {
var err = "test error";
promise.then.onSecondCall().yields([err]);
submit(req, res);
expect(res.status.calledWith(500)).to.equal(true);
expect(res.send.calledOnce).to.equal(true);
});
});
});
|
export default class Topic {
constructor({text, likes = 0}) {
this.text = text;
this.likes = likes;
}
addLike() {
this.likes++;
}
removeLike() {
this.likes--;
}
}
|
import_module('Athena.Math');
v1 = new Athena.Math.Vector3(10, 20, 30);
v = v1.negate();
CHECK_CLOSE(-10, v.x);
CHECK_CLOSE(-20, v.y);
CHECK_CLOSE(-30, v.z);
|
'use strict';
/**
* Gulp Task - browserify
*/
var gulp = require('gulp'),
gulpif = require('gulp-if'),
config = require('../config.json'),
sourcemaps = require('gulp-sourcemaps'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
browserify = require('browserify'),
watchify = require('watchify'),
browserSync = require('browser-sync'),
handleErrors = require('../utils/handle-errors');
gulp.task('browserify', function() {
var bundler = browserify(config.src + 'app/app.js', watchify.args),
bundle = function() {
return bundler
.bundle()
.on('error', handleErrors)
.pipe(source('main.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: false}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(config.dist + config.javascript))
.pipe(gulpif(global.isWatching, browserSync.reload({stream: true})));
};
if (global.isWatching) {
bundler = watchify(bundler);
bundler.on('update', bundle);
}
return bundle();
});
|
import assert from 'assert';
import Extractor from '../src/extractor';
describe('Sentence word extraction', () => {
it('.match', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in', 'vancouver' ]);
let tag = {
label: 'location',
start: 5,
end: 5
};
let match = e.match(tag, ['weather', 'in', 'berlin']);
assert.deepEqual(match, { tag: [ 'berlin' ], start: 2, matches: 2 });
match = e.match(tag, ['weather', 'nowhere']);
assert.deepEqual(match, { tag: null, start: -1, matches: 0 });
match = e.match(tag, ['in', 'nowhere']);
assert.deepEqual(match, { tag: [ 'nowhere' ], start: 1, matches: 1 });
match = e.match(tag, ['weather', 'in', 'berlin', 'weather', 'in', 'chicago'], 2);
assert.deepEqual(match, { tag: [ 'chicago' ], start: 5, matches: 2 });
});
it('.match until the end of the sentence', function() {
let e = new Extractor([ 'say', 'hi', 'to', 'the', 'world' ]);
let tag = {
label: 'subject',
start: 4,
end: -1
};
let match = e.match(tag, ['say', 'hi', 'to', 'the', 'whole', 'wide', 'world']);
assert.deepEqual(match, {
tag: [ 'whole', 'wide', 'world' ],
start: 4,
matches: 4
});
});
it('.extract does basic sentence word matching', () => {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in', 'vancouver' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
let result = e.extract([ 'hey', 'do', 'you', 'happen', 'to',
'know', 'the', 'weather', 'in', 'berlin' ]);
assert.deepEqual(result, { location: ['berlin'] });
result = e.extract([ 'what', '\'', 's', 'the', 'weather', 'in', 'chicago' ]);
assert.deepEqual(result, { location: [ 'chicago' ] });
});
it('.extract takes the best match and can match nothing', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in', 'vancouver' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
let result = e.extract([ 'weather', 'in', 'chicago',
'know', 'the', 'weather', 'in', 'berlin', 'weather', 'in', 'nuremberg' ]);
assert.deepEqual(result, { location: ['berlin'] });
result = e.extract([ 'weather', 'nowhere' ]);
assert.deepEqual(result, { location: null });
});
it('.extract multiple tag matching', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in',
'berlin', 'and', 'say', 'hi', 'to', 'the', 'world' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
e.tag({
label: 'subject',
start: 11,
end: -1
});
let result = e.extract([ 'do', 'you', 'know', 'the', 'weather', 'in',
'berlin', 'and', 'can', 'you', 'say', 'hi', 'to', 'the', 'wide', 'world' ]);
assert.deepEqual(result, { location: [ 'berlin' ], subject: [ 'wide', 'world' ]});
result = e.extract([ 'the', 'weather', 'in', 'tokyo' ]);
assert.deepEqual(result, { location: [ 'tokyo' ], subject: null });
result = e.extract(['say', 'hi', 'to', 'the', 'awesome', 'team']);
assert.deepEqual(result, { location: null, subject: ['awesome', 'team'] });
});
it.skip('.extract multiple tag matching uses previous tags', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in',
'nuremberg', 'tomorrow' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
e.tag({
label: 'time',
start: 6,
end: -1
});
// TODO
});
});
|
const filters = require('./filters');
const formats = require('./formats');
const tags = require('./tags');
const config = {
bootstrapNodes: [
{ address: 'router.bittorrent.com', port: 6881 },
{ address: 'dht.transmissionbt.com', port: 6881 },
],
crawler: {
address: '0.0.0.0',
port: 6881,
},
db: {
/*
* SQLITE DB
* client: 'sqlite3',
* connection: {
* filename: './db.sqlite3',
* },
* useNullAsDefault: true,
*/
client: 'mysql',
connection: {
database: 'alphareign',
host: '127.0.0.1',
password: 'alphareign',
user: 'root',
},
},
debug: false,
elasticsearch: {
host: '127.0.0.1',
port: 9200,
},
filters,
formats,
search: {
// Seconds between every bulk insert
frequency: 60,
// Amount of torrents to update in elasticsearch at once
limit: 1000,
},
tags,
tracker: {
// Minutes before we should try and update a torrent again
age: 360,
// Seconds between every scrape
frequency: 1,
host: 'udp://tracker.opentrackr.org:1337/announce',
limit: 75,
},
};
module.exports = config;
|
import React, { Component, PropTypes } from 'react';
import { DateBlock, RsvpBadge, Loading, SocialBtns } from '../';
import { eventsAPI } from '../../api';
import { dateTimeUtils, urlUtils } from '../../utils';
import { devMode } from '../../config';
import styles from './EventDetails.sass';
const renderAddress = (location) => {
const { address_lines: addressLines, locality, region, postal_code: postalCode } = location;
// Will have to see how this data structure holds up over different events
return (
<div className={styles.info}>
<div className={styles.infoLabel}>location</div>
{ addressLines[0] && <div>{addressLines[0]}</div> }
<div>{locality} {region}, {postalCode}</div>
</div>
);
};
const renderTimeRange = (startDate, endDate) => {
return (
<div className={styles.info}>
<div className={styles.infoLabel}>date & time</div>
<div>{dateTimeUtils.displayDateString(startDate, endDate)}</div>
<div>{dateTimeUtils.displayTimeString(startDate, endDate)}</div>
</div>
);
};
class EventDetails extends Component {
constructor() {
super();
this.state = {
isFetchingEvent: true,
event: null,
socialPopupOpen: false
};
this.toggleSocialPopup = this.toggleSocialPopup.bind(this);
this._handleDocumentClick = this.handleDocumentClick.bind(this);
}
componentDidMount() {
const { eventId } = this.props.match.params;
window.addEventListener('click', this._handleDocumentClick);
this.setState({ isFetchingEvent: true });
eventsAPI.getEventById(eventId)
.then(event => {
this.setState({ event, isFetchingEvent: false });
})
.catch(err => {
console.error(err);
this.setState({ isFetchingEvent: false });
});
}
componentWillUnmount() {
window.removeEventListener('click', this._handleDocumentClick);
}
// Close socialPopupOpen if clicking on the document (outside of the socialPopupOpen)
handleDocumentClick() {
this.setState({ socialPopupOpen: false });
}
toggleSocialPopup(e) {
e.stopPropagation();
this.setState({ socialPopupOpen: !this.state.socialPopupOpen });
}
render() {
const { event, isFetchingEvent, socialPopupOpen } = this.state;
// Depending on snappiness of server, may not need to display loading
if (isFetchingEvent) {
return <div className={styles.loadingWrapper}><Loading /></div>;
} else if (!event) {
return <div className={styles.noDataMsg}>No event data</div>;
}
const {
title,
start_date: startDate,
end_date: endDate,
browser_url: browserUrl,
featured_image_url: featuredImageUrl,
description,
total_accepted: totalAccepted,
location
} = event;
const descriptionHtml = description ? { __html: description.replace(/\n/g, '<br/>') } : null;
const featuredImageUrlOrDefault = (!devMode && featuredImageUrl) ?
urlUtils.getImageUrl(featuredImageUrl, 'c_lfill,w_800') :
'../static/img/default-event-600x360.png';
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable react/no-danger */
return (
<div className={styles.container}>
<div className={styles.titleWrapper}>
<div className={styles.badgesWrapper}>
<DateBlock
startDate={startDate}
endDate={endDate}
/>
{
totalAccepted > 0 &&
<RsvpBadge
totalAccepted={totalAccepted}
/>
}
</div>
<h1>{title}</h1>
{ location && location.locality &&
<div className={styles.location}>{location.locality}, {location.region}</div>
}
</div>
<div className={styles.content}>
<div className={styles.left}>
<img
src={featuredImageUrlOrDefault}
alt="featured event"
/>
</div>
<div className={styles.right}>
<div className={styles.infoLinks}>
{ browserUrl &&
<div className={styles.eventLink}>
<a
href={browserUrl}
target="_blank"
rel="noopener noreferrer"
className={styles.eventBtn}
>
EVENT PAGE
</a>
</div>
}
<div className={styles.sharing}>
<div
className={styles.shareBtnMobile}
onClick={this.toggleSocialPopup}
role="link"
>
SHARE
<div
className={styles.popoverWrapper}
style={{ visibility: socialPopupOpen ? 'visible' : 'hidden' }}
>
<SocialBtns
picture={featuredImageUrl}
title={title}
startDate={startDate}
description={description}
iconSize={25}
/>
</div>
</div>
<div>
<div className={styles.desktopSharing}>
<SocialBtns
picture={featuredImageUrl}
title={title}
startDate={startDate}
description={description}
iconSize={25}
/>
</div>
</div>
</div>
<div className={styles.locationAndDate}>
{location && renderAddress(location)}
{startDate && renderTimeRange(startDate, endDate)}
</div>
</div>
</div>
<div className={styles.description}>
<p dangerouslySetInnerHTML={descriptionHtml} />
</div>
</div>
</div>
);
/* eslint-enable jsx-a11y/no-static-element-interactions */
/* eslint-enable react/no-danger */
}
}
EventDetails.propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
eventId: PropTypes.string
})
}).isRequired
};
export default EventDetails;
|
{
var progressSpy = jasmine.createSpy("progress");
var instance = axios.create({
onUploadProgress: progressSpy
});
instance.get("/foo");
getAjaxRequest().then(function(request) {
done();
});
}
|
/*!
* express-outdatedhtml
*
* Make sites outdated by replace the new HTML5 element names,
* such as 'canvas', 'section', etc. with proven ones like 'div'.
* This is happening on the fly by parsing
* the view render results string of the Express framework.
* Of course only if an outdated browser is detected,
* in this case the Internet Explorer smaller than 9,
* so the browser can handle the retrieved HTML correctly.
*
* Copyright(c) 2011 Felix Gertz <nihil.baxter.dev@gmail.com>
*
* MIT Licensed
*/
/*
* The key in this map is the replacement
* for an matching HTML5-element-name in the according value array.
*/
var replacemap = {
"div": ['canvas','section','summary', 'header','footer', 'nav', 'menu', 'aside', 'article', 'hgroup', 'figure', 'figcaption'],
"span": ['time', 'mark']
};
var useragent = require('useragent');
/**
* If the user-agent is an Internet Explorer smaller then 9,
* this function returns a callback that can be passed
* to the Express 'render'-function as third argument.
*
* The callback replaces HTML5 element names (canvas, section, ..)
* in the Express 'render'-'result'-string
* with proven element names (div, span) defined in the replacemap
* to gain old browser compatibility.
* Then sends the result.
*
* @param req Request object
* @param res Response object
* @param force Force execution of replacement, even if no matching user-agent is found. (optional)
* @param rendercallback Pass another Express render callback (optional)
*/
exports.makeoutdated = function(req, res, force, rendercallback) {
if(typeof force === 'function') {
rendercallback = force;
force = false;
}
var agent = useragent.parse(req.headers['user-agent']);
// Looking for IE smaller then major release 9
if(force || (agent.family == 'IE' && parseInt(agent.major) < 9))
return function(err, result) {
for(replacement in replacemap) {
var elements = replacemap[replacement].join("|");
result = result.
replace(new RegExp("<(?:"+elements+")", "gi"), "<"+replacement).
replace(new RegExp("(?:"+elements+")>", "gi"), replacement+">");
}
if(typeof rendercallback !== 'function')
res.send(result);
else
rendercallback(err, result);
};
// Nothing happens
return function(err, result) {
if(typeof rendercallback !== 'function')
res.send(result);
else
rendercallback(err, result);
};
};
|
var Backbone = require('backbone');
exports = module.exports = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
roles: {
admin: false,
agent: false,
user: true,
app: false,
},
business: {
stage: 'test',
types: {
verify: false,
base: false,
whole: false
},
times: {
verify: 0,
vase: 0,
whole: 0
},
limit: -1,
expired: new Date()
},
app: {
app_id: '',
app_secret: '',
apis: {
verify: false,
base: false,
whole: false
}
},
balance: 0,
enable: true,
},
});
|
var express = require('express');
var router = express.Router();
var spider = require("./spider");
router.get("/info",function(req,res,next){
spider(`/product/iteminfo?device=iphone&channel=h5&swidth=375&sheight=667&zoneId=1479&v=2.3.0&terminal=wap&page=https%3A%2F%2Fm.haoshiqi.net%2F%23detail%3Fsid%3D14369%26channel_id%3Dh5&skuId=${req.query.id}`,function(data){
res.send(data);
});
})
router.get("/detail",function(req,res,next){
spider(`/product/productdetail?device=iphone&channel=h5&swidth=375&sheight=667&zoneId=1479&v=2.3.0&terminal=wap&page=https%3A%2F%2Fm.haoshiqi.net%2F%23detail%3Fsid%3D14435%26channel_id%3Dh5&productId=${req.query.id}`,function(data){
res.send(JSON.parse(data).data.graphicDetail); //返回产品的详细图片信息
});
})
module.exports =router;
|
module.exports = function(mode) {
return {
test: /\.js$/,
loader: "eslint-loader",
exclude: /node_modules/
};
};
|
// Math.random() devuelve número aleatorio entre 0 y 1.
var numero = Math.random();
if (numero <= 0.5){
console.log('\n' + numero + ' MENOR que 0,5 \n');
}
else{
console.log('\n' + numero + ' MAYOR que 0.5 \n');´
}
|
/**
* @venus-library jasmine
* @venus-include ../vendor/Reflection.js/reflection.min.js
* @venus-code ../src/functions.js
*/
describe('functions', function () {
it('should create two sub-objects of window', function () {
namespace('Foo.Bar');
expect(window.Foo).not.toBe(undefined);
expect(window.Foo.Bar).not.toBe(undefined);
delete window.Foo;
});
it('should create two sub-objects of own object', function () {
var custom = {};
namespace.call(custom, 'Foo.Bar');
expect(custom.Foo).not.toBe(undefined);
expect(custom.Foo.Bar).not.toBe(undefined);
});
it('should return nested value', function () {
var obj = {
foo: {
bar: {
baz: 'foobar'
}
}
};
expect(objectGetter.call(obj, 'foo.bar.baz')).toEqual('foobar');
});
it('should return undefined in case of unknown path', function () {
var obj = {};
expect(objectGetter.call(obj, 'foo.bar')).toEqual(undefined);
});
it('should set a nested value', function () {
var obj = {};
objectSetter.call(obj, 'foo.bar.baz', 'foobar');
expect(obj.foo.bar.baz).toEqual('foobar');
});
it('should return the value via the specific getter', function () {
var mock = function () {this.foo = 24;},
data = {};
mock.prototype = Object.create(Object.prototype, {
getFoo: {value: function () {return 42;}}
});
data.bar = new mock();
expect(reflectedObjectGetter.call(data, 'bar.foo')).toEqual(42);
});
it('should return the value via the generic getter', function () {
var mock = function () {this.foo = 24;},
data = {};
mock.prototype = Object.create(Object.prototype, {
get: {value: function (prop) {return prop;}}
});
data.bar = new mock();
expect(reflectedObjectGetter.call(data, 'bar.foo')).toEqual('foo');
});
it('should return the value via the property', function () {
var mock = function () {this.foo = 24;},
data = {};
data.bar = new mock();
expect(reflectedObjectGetter.call(data, 'bar.foo')).toEqual(24);
});
});
|
// https://sourceforge.net/rest/p/nagios
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.