text
stringlengths 2
6.14k
|
|---|
/* eslint-env node, mocha */
const mongoose = require('mongoose');
const logger = require('../../../../lib/logger');
var indexBuiltCallback = function() {};
before(function(done){
mongoose.model('EnterpriseInternationalPublic').on('index', handleIndexBuild);
done();
});
function handleIndexBuild(err) {
if (err) {
logger.error('Failed to rebuild index ' + err);
}
logger.debug('db_util handling index build');
indexBuiltCallback();
// clear callback to avoid case where mongoose raises event multiple times
// For testing we only care that the index was built at least once and now
// it exists.
indexBuiltCallback = function() {};
}
function rebuildIndexes(done) {
indexBuiltCallback = done;
mongoose.model('EnterpriseInternationalPublic').ensureIndexes();
}
module.exports.cleanDatabase = function(done) {
mongoose.connection.dropDatabase(function() {
rebuildIndexes(done);
});
};
|
$(document).ready(function(){
// body...
if($(window).width()<=410){
$(".weather pre").css("margin-left","0em");
}
});
$( window ).on( "orientationchange", function() {
if ($(window).width()<=320) {
$(".weather pre").css("margin-left","3em");
$(".weather pre").append($(window).width()+"");
}
else{
$(".weather pre").css("margin-left","0em");
$(".weather pre").append($(window).width()+"");
}
});
|
"use strict";
const HTMLElementImpl = require("./HTMLElement-impl").implementation;
const { stripAndCollapseASCIIWhitespace } = require("../helpers/strings");
const { domSymbolTree } = require("../helpers/internal-constants");
const { closest } = require("../helpers/traversal");
const { formOwner } = require("../helpers/form-controls");
class HTMLOptionElementImpl extends HTMLElementImpl {
constructor(globalObject, args, privateData) {
super(globalObject, args, privateData);
// whenever selectedness is set to true, make sure all
// other options set selectedness to false
this._selectedness = false;
this._dirtyness = false;
}
_removeOtherSelectedness() {
// Remove the selectedness flag from all other options in this select
const select = this._selectNode;
if (select && !select.hasAttributeNS(null, "multiple")) {
for (const option of select.options) {
if (option !== this) {
option._selectedness = false;
}
}
}
}
_askForAReset() {
const select = this._selectNode;
if (select) {
select._askedForAReset();
}
}
_attrModified(name) {
if (!this._dirtyness && name === "selected") {
this._selectedness = this.hasAttributeNS(null, "selected");
if (this._selectedness) {
this._removeOtherSelectedness();
}
this._askForAReset();
}
super._attrModified.apply(this, arguments);
}
get _selectNode() {
let select = domSymbolTree.parent(this);
if (!select) {
return null;
}
if (select.nodeName.toUpperCase() !== "SELECT") {
select = domSymbolTree.parent(select);
if (!select || select.nodeName.toUpperCase() !== "SELECT") {
return null;
}
}
return select;
}
get form() {
return formOwner(this);
}
get text() {
// TODO is not correctly excluding script and SVG script descendants
return stripAndCollapseASCIIWhitespace(this.textContent);
}
set text(value) {
this.textContent = value;
}
// https://html.spec.whatwg.org/multipage/form-elements.html#concept-option-value
_getValue() {
if (this.hasAttributeNS(null, "value")) {
return this.getAttributeNS(null, "value");
}
return this.text;
}
get value() {
return this._getValue();
}
set value(value) {
this.setAttributeNS(null, "value", value);
}
get index() {
const select = closest(this, "select");
if (select === null) {
return 0;
}
return select.options.indexOf(this);
}
get selected() {
return this._selectedness;
}
set selected(s) {
this._dirtyness = true;
this._selectedness = Boolean(s);
if (this._selectedness) {
this._removeOtherSelectedness();
}
this._askForAReset();
this._modified();
}
get label() {
if (this.hasAttributeNS(null, "label")) {
return this.getAttributeNS(null, "label");
}
return this.text;
}
set label(value) {
this.setAttributeNS(null, "label", value);
}
}
module.exports = {
implementation: HTMLOptionElementImpl
};
|
import _ from 'lodash';
import request from 'superagent';
import Promise from 'bluebird';
import { Feedable } from 'models/feedable';
import { User } from 'models/user';
import { Verification } from 'models/verification';
/**
* Signs up or logs in the user from either facebook or google
*
* Each user can have multiple verifications, which stores a provider's ID (i.e. facebooks or google's user id).
*
* For facebook and google the procedure is as follows: if the provider id exists in verifications.provider_id, then the user is already registered.
* Otherwise, create a new User then a Verification
*
*/
export default class {
constructor( payload ) {
this.provider = payload.provider;
this.accessToken = payload.accessToken;
this.userDetails = null;
this.user = null;
this.verification = null;
}
execute() {
return requestUserDetails.call( this )
.bind( this )
.then( setUserDetails )
.then( lookupProviderVerification )
.then( createUserAndVerificationIfRequired );
}
}
/////////////////
/// private
function requestUserDetails() {
let requesters = {
facebook: facebookDataRequester,
google: googleDataRequester
};
return requesters[ this.provider ].call( this );
}
function setUserDetails( userDetails ) {
this.userDetails = userDetails;
}
function facebookDataRequester() {
return new Promise( ( resolve, reject ) => {
request
.get( 'https://graph.facebook.com/me' )
.query( { access_token: this.accessToken } )
.set( 'Accept', 'application/json' )
.end( ( err, res ) => {
if ( err ) {
reject( err );
} else {
resolve( res.body );
}
} );
} )
.then( extractIdAndName );
function extractIdAndName( data ) {
return {
id: data.id,
name: data.name,
imageUrl: `https://graph.facebook.com/${data.id}/picture`
};
}
}
function googleDataRequester() {
return new Promise( ( resolve, reject ) => {
request
.get( 'https://www.googleapis.com/plus/v1/people/me' )
.query( { access_token: this.accessToken } )
.set( 'Accept', 'application/json' )
.end( ( err, res ) => {
if ( err ) {
reject( err );
} else {
resolve( res.body );
}
} );
} )
.then( extractIdAndName );
function extractIdAndName( data ) {
return {
id: data.id,
name: data.displayName,
imageUrl: _.get( data, 'image.url' )
};
}
}
function lookupProviderVerification() {
return Verification
.forge( {
provider_name: this.provider,
provider_id: this.userDetails.id
} )
.fetch();
}
function createUserAndVerificationIfRequired( verification ) {
if ( verification ) {
//user exists - update load_logged in
return getUser.call( this, verification.get( 'user_id' ) )
.then( setUser.bind( this ) )
.then( updateLastLogin.bind( this ) )
.then( setUser.bind( this ) )
.then( returnUser.bind( this ) );
} else {
//user doesn't exist :-
// 1. create a user
// 2. create a verification and link to user
// 3. return new user
return createUser.call( this )
.then( setUser.bind( this ) )
.then( createVerificationForUser.bind( this ) )
.then( createFeedableForNewUser.bind( this ) )
.then( returnUser.bind( this ) );
}
}
function createUser() {
return User
.forge( {
name: this.userDetails.name,
image_url: this.userDetails.imageUrl,
last_logged_in: new Date()
} )
.save();
}
function setUser( user ) {
this.user = user;
}
function updateLastLogin() {
return this.user.save( { last_logged_in: new Date() }, { patch: true } );
}
function createVerificationForUser() {
return Verification
.forge( {
user_id: this.user.id,
provider_name: this.provider,
provider_id: this.userDetails.id
} )
.save();
}
function createFeedableForNewUser() {
return Feedable
.forge( {
feedable_id: this.user.get( 'id' ),
feedable_type: 'users',
feedable_meta: {
user: {
id: this.user.get( 'id' ),
name: this.user.get( 'name' ),
image_url: this.user.get( 'image_url' )
}
}
} )
.save();
}
function returnUser() {
return this.user;
}
function getUser( userId ) {
return User
.forge( { id: userId } )
.fetch();
}
|
import {describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach} from 'angular2/test_lib';
import {bootstrap, appDocumentToken, appElementToken}
from 'angular2/src/core/application';
import {Component} from 'angular2/src/core/annotations/annotations';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {ListWrapper} from 'angular2/src/facade/collection';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {bind, Inject} from 'angular2/di';
import {Template} from 'angular2/src/core/annotations/template';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
@Component({selector: 'hello-app'})
@Template({inline: '{{greeting}} world!'})
class HelloRootCmp {
greeting:string;
constructor() {
this.greeting = 'hello';
}
}
@Component({selector: 'hello-app-2'})
@Template({inline: '{{greeting}} world, again!'})
class HelloRootCmp2 {
greeting:string;
constructor() {
this.greeting = 'hello';
}
}
@Component({selector: 'hello-app'})
@Template({inline: ''})
class HelloRootCmp3 {
appBinding;
constructor(@Inject("appBinding") appBinding) {
this.appBinding = appBinding;
}
}
@Component({selector: 'hello-app'})
@Template({inline: ''})
class HelloRootCmp4 {
lc;
constructor(@Inject(LifeCycle) lc) {
this.lc = lc;
}
}
export function main() {
var fakeDoc, el, el2, testBindings;
beforeEach(() => {
fakeDoc = DOM.createHtmlDocument();
el = DOM.createElement('hello-app', fakeDoc);
el2 = DOM.createElement('hello-app-2', fakeDoc);
DOM.appendChild(fakeDoc.body, el);
DOM.appendChild(fakeDoc.body, el2);
testBindings = [bind(appDocumentToken).toValue(fakeDoc)];
});
describe('bootstrap factory method', () => {
it('should throw if no element is found', (done) => {
var injectorPromise = bootstrap(HelloRootCmp, [], (e,t) => {throw e;});
PromiseWrapper.then(injectorPromise, null, (reason) => {
expect(reason.message).toContain(
'The app selector "hello-app" did not match any elements');
done();
});
});
it('should create an injector promise', () => {
var injectorPromise = bootstrap(HelloRootCmp, testBindings);
expect(injectorPromise).not.toBe(null);
});
it('should resolve an injector promise and contain bindings', (done) => {
var injectorPromise = bootstrap(HelloRootCmp, testBindings);
injectorPromise.then((injector) => {
expect(injector.get(appElementToken)).toBe(el);
done();
});
});
it('should provide the application component in the injector', (done) => {
var injectorPromise = bootstrap(HelloRootCmp, testBindings);
injectorPromise.then((injector) => {
expect(injector.get(HelloRootCmp)).toBeAnInstanceOf(HelloRootCmp);
done();
});
});
it('should display hello world', (done) => {
var injectorPromise = bootstrap(HelloRootCmp, testBindings);
injectorPromise.then((injector) => {
expect(injector.get(appElementToken)
.shadowRoot.childNodes[0].nodeValue).toEqual('hello world!');
done();
});
});
it('should support multiple calls to bootstrap', (done) => {
var injectorPromise1 = bootstrap(HelloRootCmp, testBindings);
var injectorPromise2 = bootstrap(HelloRootCmp2, testBindings);
PromiseWrapper.all([injectorPromise1, injectorPromise2]).then((injectors) => {
expect(injectors[0].get(appElementToken)
.shadowRoot.childNodes[0].nodeValue).toEqual('hello world!');
expect(injectors[1].get(appElementToken)
.shadowRoot.childNodes[0].nodeValue).toEqual('hello world, again!');
done();
});
});
it("should make the provided bindings available to the application component", (done) => {
var injectorPromise = bootstrap(HelloRootCmp3, [
testBindings,
bind("appBinding").toValue("BoundValue")
]);
injectorPromise.then((injector) => {
expect(injector.get(HelloRootCmp3).appBinding).toEqual("BoundValue");
done();
});
});
it("should avoid cyclic dependencies when root component requires Lifecycle through DI", (done) => {
var injectorPromise = bootstrap(HelloRootCmp4, testBindings);
injectorPromise.then((injector) => {
expect(injector.get(HelloRootCmp4).lc).toBe(injector.get(LifeCycle));
done();
});
});
});
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';
import example from './images/example.png';
import controlPanel from './controlPanel';
const metadata = new ChartMetadata({
category: t('Part of a Whole'),
credits: ['https://bl.ocks.org/kerryrodden/7090426'],
description: t(
'Uses circles to visualize the flow of data through different stages of a system. Hover over individual paths in the visualization to understand the stages a value took. Useful for multi-stage, multi-group visualizing funnels and pipelines.',
),
exampleGallery: [{ url: example }],
name: t('Sunburst Chart'),
tags: [t('Aesthetic'), t('Legacy'), t('Multi-Levels'), t('Proportional')],
thumbnail,
useLegacyApi: true,
});
export default class SunburstChartPlugin extends ChartPlugin {
constructor() {
super({
loadChart: () => import('./ReactSunburst'),
metadata,
transformProps,
controlPanel,
});
}
}
|
module.exports = function(HAPnode, config, functions)
{
var Accessory = HAPnode.Accessory;
var Service = HAPnode.Service;
var Characteristic = HAPnode.Characteristic;
var uuid = HAPnode.uuid;
var debug = HAPnode.debug;
var module = {};
module.newDevice = function(device, tempDisplayUnit)
{
var temperatureDisplayUnit = tempDisplayUnit;
var Sensor = {
getTemperature: function() {
temperature = functions.getVariable(device.id, 'temperature','number');
if (this.veraIsUsingFahrenheit()){
temperature = this.fahrenheitToCelsius(temperature);
}
return temperature;
},
veraIsUsingFahrenheit: function(){
return this.getTemperatureDisplayUnits() == Characteristic.TemperatureDisplayUnits.FAHRENHEIT
},
fahrenheitToCelsius: function(temperature) {
return (temperature - 32) / 1.8;
},
celsiusToFahrenheit: function(temperature) {
return (temperature * 1.8) + 32;
},
getTemperatureDisplayUnits: function(){
if (temperatureDisplayUnit == "C"){
return Characteristic.TemperatureDisplayUnits.CELSIUS
}else{
return Characteristic.TemperatureDisplayUnits.FAHRENHEIT
}
}
};
var sensorUUID = uuid.generate('device:tempsense:'+config.cardinality+':'+device.id);
var sensor = new Accessory(device.name, sensorUUID);
sensor.username = functions.genMac('device:'+config.cardinality+':'+device.id);
sensor.pincode = config.pincode;
sensor.deviceid = device.id;
sensor
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, device.manufacturer)
.setCharacteristic(Characteristic.Model, device.model)
.setCharacteristic(Characteristic.SerialNumber, "Vera ID: "+device.id);
sensor
.addService(Service.TemperatureSensor)
.getCharacteristic(Characteristic.CurrentTemperature)
.setProps({
minValue: -100,
maxValue: 100
})
.on('get', function(callback)
{
debug('Getting latest value for %s', device.name);
callback(null, Sensor.getTemperature());
});
return sensor;
};
return module;
};
|
Meteor.methods({
"userExists": function(username){
return !!Meteor.users.findOne({username: username});
},
});
|
var SetCache = require('./_SetCache'),
arrayIncludes = require('./_arrayIncludes'),
arrayIncludesWith = require('./_arrayIncludesWith'),
arrayMap = require('./_arrayMap'),
baseUnary = require('./_baseUnary'),
cacheHas = require('./_cacheHas');
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
module.exports = baseDifference;
|
import PlaylistItemView from 'foreground/view/leftPane/playlistItemView';
import PlaylistItem from 'background/model/playlistItem';
import StreamItems from 'background/collection/streamItems';
import ListItemType from 'common/enum/listItemType';
import ViewTestUtility from 'test/foreground/view/viewTestUtility';
describe('PlaylistItemView', function() {
beforeEach(function() {
this.documentFragment = document.createDocumentFragment();
this.view = new PlaylistItemView({
model: new PlaylistItem(),
streamItems: new StreamItems(),
player: TestUtility.buildPlayer(),
type: ListItemType.PlaylistItem,
parentId: 'playlistItems-list'
});
});
afterEach(function() {
this.view.destroy();
});
ViewTestUtility.ensureBasicAssumptions.call(this);
});
|
CNVR_onResponse('HELLO WORLD');
|
// Copyright 2014 The Oppia Authors. 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.
/**
* @fileoverview Directive for bar chart visualization.
*
* @author sll@google.com (Sean Lip)
*/
oppia.directive('barChart', [function() {
return {
restrict: 'E',
scope: {
// A read-only array representing the table of chart data.
data: '&',
// A read-only object containing several chart options. This object
// should have the following keys: chartAreaWidth, colors, height,
// legendPosition and width.
options: '&'
},
controller: ['$scope', '$element', function($scope, $element) {
if (!$.isArray($scope.data())) {
return;
}
var options = $scope.options();
var chart = new google.visualization.BarChart($element[0]);
var redrawChart = function() {
chart.draw(google.visualization.arrayToDataTable($scope.data()), {
chartArea: {
left: 0,
width: options.chartAreaWidth
},
colors: options.colors,
hAxis: {
gridlines: {
color: 'transparent'
}
},
height: options.height,
isStacked: true,
legend: {
position: options.legendPosition || 'none'
},
width: options.width
});
};
$scope.$watch('data()', redrawChart);
$(window).resize(redrawChart);
}]
};
}]);
|
import {extend} from "lodash";
import SeqCollection from "../model/SeqCollection";
const TreeHelper = function(msa) {
this.msa = msa;
return this;
};
var tf =
{loadTree: function(cb) {
return this.msa.g.package.loadPackages(["msa-tnt", "biojs-io-newick"], cb);
},
showTree: function(newickStr) {
var newick = window.require("biojs-io-newick");
var mt = window.require("msa-tnt");
if (typeof newickStr === "string") {
var newickObj = newick.parse_newick(newickStr);
} else {
newickObj = newickStr;
}
var sel = new mt.selections();
var treeDiv;
if(this.msa.el.getElementsByClassName('tnt_groupDiv').length === 0){
treeDiv = document.createElement("div");
this.msa.el.appendChild(treeDiv);
} else {
console.log('A tree already exists. It will be overridden.');
treeDiv = this.msa.el.getElementsByClassName('tnt_groupDiv')[0].parentNode;
treeDiv.innerHTML = '';
}
const seqs = this.msa.seqs.toJSON();
//adapt tree ids to sequence ids
function iterateTree(nwck){
if(nwck.children != null){
nwck.children.forEach(x => iterateTree(x));
} else {
//found a leave
let seq = seqs.filter(s => s.name === nwck.name)[0];
if(seq != null){
if(typeof seq.id === 'number'){
//no tree has been uploaded so far, seqs have standard IDs
seq.ids = [`s${seq.id + 1}`];
nwck.name = `s${seq.id + 1}`;
} else {
//seqs have custom ids - don't mess with these
nwck.name = seq.id;
}
}
}
}
iterateTree(newickObj);
var nodes = mt.app({
seqs: seqs,
tree: newickObj
});
var t = new mt.adapters.tree({
model: nodes,
el: treeDiv,
sel: sel
});
//treeDiv.style.width = "500px"
// construct msa in a virtual dom
var m = new mt.adapters.msa({
model: nodes,
sel: sel,
msa: this.msa
});
// remove top collection
nodes.models.forEach((e) => {
delete e.collection;
return Object.setPrototypeOf(e, require("backbone-thin").Model.prototype);
});
this.msa.seqs.reset(nodes.models);
//@msa.draw()
//@msa.render()
return console.log(this.msa.seqs);
},
// workaround against browserify's static analysis
require(pkg) {
return require(pkg);
}
};
extend(TreeHelper.prototype , tf);
export default TreeHelper;
|
/**
* Created by zhangjh on 2015/10/27.
*/
(function ($) {
"use strict";
var path = $.basepath();
var newURL = path + "/system/userinfo/new";
var user_infoURL = path + "/system/userinfo/info/";
var editURL = path + "/system/userinfo/edit";
var _0URL = path + "/system/permission/user-tab/0";
var usertypeURL = path + "/system/userinfo/usertype";
var fileUploadURL = path + "/files/upload";
var uploadFileInfos = [];
var isSubmitAction = "N";//是否点击的
var $fileInput = $("#fileLocation");
var $fileListLi = $("#filesList");
$.extend({
saveuserinfo: saveuserinfo
});
var fieldsDesc =
{
name: {
validators: {
notEmpty: {
message: '名称为必填项'
}
}
},
aliases: {
validators: {
notEmpty: {
message: '用户别名为必填项'
}
}
},
password: {
validators: {
notEmpty: {
message: '密码为必填项'
}
}
},
rptUserPwd: {
validators: {
notEmpty: {
message: '密码确认为必填项'
}
}
},
userType: {
validators: {
notEmpty: {
message: '用户类型为必填项'
}
}
},
userEmail: {
validators: {
notEmpty: {
message: '用户邮箱为必填项'
}
}
},
userMobile: {
validators: {
notEmpty: {
message: '用户手机为必填项'
}
}
}
};
var doSaveAction = function () {
var formDataStr = $("#userinfoForm").serialize();
formDataStr = decodeURIComponent(formDataStr);
var natrualkey = $("#natrualkey").val();
var url;
if (natrualkey == '' || natrualkey == 'null') {
url = newURL;
} else {
url = editURL;
}
var userInfo = $.strToJson(formDataStr);
userInfo.fileInfos = uploadFileInfos;
$.sendJsonAjax(url, userInfo, function () {
window.location.href = _0URL;
})
}
function saveuserinfo() {
//执行表单监听
$('#userinfoForm').bootstrapValidator('validate');
}
//启动表单校验监听
$('#userinfoForm').bootstrapValidator({
//live: 'disabled',
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: fieldsDesc
}).on('success.form.bv', function (e) { //表单校验成功,ajax提交数据
$fileInput.fileinput('upload');//批量提交
var hasExtraData = $.isEmptyObject($fileInput.fileinput("getExtraData"));
if (hasExtraData) {
doSaveAction();
}
isSubmitAction = "Y";
});
$(function () {
//用户类型
$.sendRestFulAjax(usertypeURL, null, 'GET', 'json', initSelect);
//initFileLocation(null, null);
$.fileInputAddListenr($fileListLi, $fileInput, uploadFileInfos, doSaveAction, getIsSubmitAction);
})
function getIsSubmitAction() {
return isSubmitAction;
}
function initSelectCallback() {
var natrualkey = $("#natrualkey").val();
if (natrualkey != '') {
$.sendRestFulAjax(user_infoURL + natrualkey, null, 'GET', 'json', initFormFields);
}
}
function initFormFields(_data) {
//初始化赋值
Object.keys(_data).map(function (key) {
//下拉框
$("#" + key).val(_data[key]);
});
$.loadFileInput($fileInput, $fileListLi, _data["fileinfosMap"], fileUploadURL);
}
/**
*
* @param data
*/
var initSelect = function (data) {
$("#userType").empty();
$("<option></option>").val('').text("请选择...").appendTo($("#userType"));
$.each(data, function (key, value) {
$("<option></option>")
.val(key)
.text(value)
.appendTo($("#userType"));
});
initSelectCallback();
}
}(jQuery));
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var App = require('app');
App.WizardStep1Controller = Em.Controller.extend({
name: 'wizardStep1Controller'
});
|
exports.printMsg = function() {
console.log("Visit https://wedding.rampatra.com !");
};
|
// Copyright 2013 The Closure Library Authors. 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.
/**
* @fileoverview Unit tests for goog.labs.userAgent.browser.
*/
goog.provide('goog.labs.userAgent.browserTest');
goog.require('goog.labs.userAgent.browser');
goog.require('goog.labs.userAgent.testAgents');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.setTestOnly('goog.labs.userAgent.browserTest');
var propertyReplacer = new goog.testing.PropertyReplacer();
function setUp() {
// disable memoization
propertyReplacer.set(goog.memoize, 'ENABLE_MEMOIZE', false);
}
function tearDown() {
propertyReplacer.reset();
}
function testOpera() {
setGlobalUAString(goog.labs.userAgent.testAgents.OPERA_10);
assertTrue(goog.labs.userAgent.browser.isOpera());
assertVersion('10.00');
assertVersionBetween('10.00', '10.10');
setGlobalUAString(goog.labs.userAgent.testAgents.OPERA_MAC);
assertTrue(goog.labs.userAgent.browser.isOpera());
assertVersion('11.52');
assertVersionBetween('11.50', '12.00');
setGlobalUAString(goog.labs.userAgent.testAgents.OPERA_LINUX);
assertTrue(goog.labs.userAgent.browser.isOpera());
assertVersion('11.50');
assertVersionBetween('11.00', '12.00');
}
function testIE() {
setGlobalUAString(goog.labs.userAgent.testAgents.IE_10);
assertTrue(goog.labs.userAgent.browser.isIE());
assertVersion('10.6');
assertVersionBetween('10.0', '11.0');
setGlobalUAString(goog.labs.userAgent.testAgents.IE_9);
assertTrue(goog.labs.userAgent.browser.isIE());
assertVersion('9.0');
assertVersionBetween('8.0', '10.0');
setGlobalUAString(goog.labs.userAgent.testAgents.IE_8);
assertTrue(goog.labs.userAgent.browser.isIE());
assertVersion('8.0');
assertVersionBetween('7.0', '9.0');
setGlobalUAString(goog.labs.userAgent.testAgents.IE_8_COMPATIBILITY);
// Test Document mode override
setDocumentMode('9');
assertTrue(goog.labs.userAgent.browser.isIE());
assertVersion('9');
setGlobalUAString(goog.labs.userAgent.testAgents.IE_9_COMPATIBILITY);
setDocumentMode('9');
assertTrue(goog.labs.userAgent.browser.isIE());
assertVersion('9');
setGlobalUAString(goog.labs.userAgent.testAgents.IE_9_COMPATIBILITY);
setDocumentMode('8');
assertTrue(goog.labs.userAgent.browser.isIE());
assertVersion('8');
}
function testFirefox() {
setGlobalUAString(goog.labs.userAgent.testAgents.FIREFOX_19);
assertTrue(goog.labs.userAgent.browser.isFirefox());
assertVersion('19.0');
assertVersionBetween('18.0', '20.0');
setGlobalUAString(goog.labs.userAgent.testAgents.FIREFOX_WINDOWS);
assertTrue(goog.labs.userAgent.browser.isFirefox());
assertVersion('14.0.1');
assertVersionBetween('14.0', '15.0');
setGlobalUAString(goog.labs.userAgent.testAgents.FIREFOX_LINUX);
assertTrue(goog.labs.userAgent.browser.isFirefox());
assertVersion('15.0.1');
}
function testChrome() {
setGlobalUAString(goog.labs.userAgent.testAgents.CHROME_ANDROID);
assertTrue(goog.labs.userAgent.browser.isChrome());
assertVersion('18.0.1025.133');
assertVersionBetween('18.0', '19.0');
assertVersionBetween('17.0', '18.1');
setGlobalUAString(goog.labs.userAgent.testAgents.CHROME_IPHONE);
assertTrue(goog.labs.userAgent.browser.isChrome());
assertVersion('22.0.1194.0');
assertVersionBetween('22.0', '23.0');
assertVersionBetween('22.0', '22.10');
setGlobalUAString(goog.labs.userAgent.testAgents.CHROME_MAC);
assertTrue(goog.labs.userAgent.browser.isChrome());
assertVersion('24.0.1309.0');
assertVersionBetween('24.0', '25.0');
assertVersionBetween('24.0', '24.10');
}
function testSafari() {
setGlobalUAString(goog.labs.userAgent.testAgents.IPAD_6);
assertTrue(goog.labs.userAgent.browser.isSafari());
assertVersion('6.0');
assertVersionBetween('5.1', '7.0');
setGlobalUAString(goog.labs.userAgent.testAgents.SAFARI_6);
assertTrue(goog.labs.userAgent.browser.isSafari());
assertVersion('6.0');
assertVersionBetween('6.0', '7.0');
setGlobalUAString(goog.labs.userAgent.testAgents.SAFARI_IPHONE);
assertTrue(goog.labs.userAgent.browser.isSafari());
assertVersion('5.0.2');
assertVersionBetween('5.0', '6.0');
}
function testAndroidBrowser() {
setGlobalUAString(goog.labs.userAgent.testAgents.ANDROID_BROWSER_235);
assertTrue(goog.labs.userAgent.browser.isAndroidBrowser());
assertVersion('4.0');
assertVersionBetween('3.0', '5.0');
setGlobalUAString(goog.labs.userAgent.testAgents.ANDROID_BROWSER_403);
assertTrue(goog.labs.userAgent.browser.isAndroidBrowser());
assertVersion('4.0');
assertVersionBetween('3.0', '5.0');
setGlobalUAString(goog.labs.userAgent.testAgents.ANDROID_BROWSER_233);
assertTrue(goog.labs.userAgent.browser.isAndroidBrowser());
assertVersion('4.0');
assertVersionBetween('3.0', '5.0');
}
function setGlobalUAString(uaString) {
var mockGlobal = {
'navigator': {
'userAgent': uaString
}
};
propertyReplacer.set(goog, 'global', mockGlobal);
}
function setDocumentMode(docMode) {
var mockDocument = {
'documentMode': docMode
};
propertyReplacer.set(goog.global, 'document', mockDocument);
}
function assertVersion(version) {
assertEquals(version, goog.labs.userAgent.browser.getVersion());
}
function assertVersionBetween(lowVersion, highVersion) {
assertTrue(goog.labs.userAgent.browser.isVersionOrHigher(lowVersion));
assertFalse(goog.labs.userAgent.browser.isVersionOrHigher(highVersion));
}
|
var path = require('path');
module.exports = {
sass: [path.join(__dirname, 'sass')],
js: [path.join(__dirname, 'js/**/*.js')],
fonts: [path.join(__dirname, 'fonts/**/*.{eot,svg,ttf,woff}')]
}
|
'use strict';
var items = require('../_items');
var _ = require('lodash');
module.exports = function(req, res, next) {
var item = _.findWhere(items, {id: +req.params.id});
if (!item) {
return next(new restify.ResourceNotFoundError('条目未找到:' + req.params.id));
}
res.send(item);
};
|
'use strict';
define([
'jquery',
'underscore',
'backbone',
'<%= viewPath %>'
], function ($, _, Backbone, <%= viewName %>) {
describe('<%= viewName %> view', function () {
beforeEach(function () {
this.view = new <%= viewName %>();
this.view.render();
});
it('render() should return the view object', function () {
expect(this.view.render()).<%=assert.toequal%>(this.view);
});<% if(!templateExists) { %>
it('should contain 2 regions', function () {
expect(this.view.render().$el.find('div').length).<%=assert.toequal%>(2);
});<% } %>
});
});
|
/**
* @license
* 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.
*/
CLASS({
package: 'foam.net',
name: 'WebHTTPRequest',
extends: 'foam.net.BaseHTTPRequest',
requires: [
'foam.net.HTTPResponse'
],
methods: [
function fromUrl(url) {
var u = new URL(url);
this.protocol = u.protocol.substring(0, u.protocol.length-1);
this.hostname = u.hostname;
if ( u.port ) this.port = u.port;
this.path = u.pathname + u.search;
},
function asend() {
if ( this.url ) this.fromUrl(this.url);
var fut = afuture();
var xhr = new XMLHttpRequest();
xhr.open(this.method || "GET", this.protocol + "://" + this.hostname +
( this.port ? (':' + this.port) : '' ) + this.path);
var self = this;
xhr.addEventListener('readystatechange', function() {
if ( this.readyState == this.DONE ) {
var response = self.HTTPResponse.create({
status: this.status,
payload: this.response
});
fut.set(response);
}
});
xhr.send(this.payload);
return fut.get;
}
]
});
|
import expect, { createSpy } from 'expect'
import { collectionsReducer } from '../src/reducers.js'
import deepFreeze from 'deep-freeze'
import {
FETCH, FETCH_SUCCESS, FETCH_ERROR,
CREATE_SUCCESS, DELETE_SUCCESS, GARBAGE_COLLECT
} from '../src/actionTypes'
const initialCollection = {
params: { page: 0 },
otherInfo: {},
ids: [],
fetchTime: Date.now() - 400, // arbitrary time
error: null
}
const initialCollection2 = Object.assign({}, initialCollection, { params: { page: 1 } })
const initialState = [
initialCollection,
initialCollection2
]
deepFreeze(initialState)
const newCollection = { mock: true, params: { page: 0 }, ids: [1] }
const updatedCollection = { mock: true, params: { page: 0 }, ids: [2] }
describe('collectionsReducer', () => {
it('does nothing if action.meta.params is undefined', () => {
const action = { type: FETCH, meta: {} }
deepFreeze(action)
const newState = collectionsReducer(initialState, action)
expect(newState).toEqual(initialState)
})
describe('fetch_* tests', () => {
const fetchTestsArray = [
{ actionType: FETCH, testName: 'FETCH' },
{ actionType: FETCH_SUCCESS, testName: 'FETCH_SUCCESS' },
{ actionType: FETCH_ERROR, testName: 'FETCH_ERROR' }
]
describe('collection is already defined', () => {
const params = { page: 0 }
const collectionReducer = createSpy().andReturn(updatedCollection)
fetchTestsArray.forEach(({ actionType, testName }) => {
it(testName, () => {
const action = { type: actionType, meta: { params } }
deepFreeze(action)
const newState = collectionsReducer(initialState, action, { collectionReducer })
// behaviour check
expect(collectionReducer).toHaveBeenCalledWith(initialCollection, action)
expect(newState[0]).toEqual(updatedCollection)
// sanity check
expect(newState[1]).toEqual(initialCollection2)
expect(newState[2]).toEqual(undefined)
})
})
})
describe('collection is not defined yet', () => {
const params = { page: 2 }
const collectionReducer = createSpy().andReturn(newCollection)
fetchTestsArray.forEach(({ actionType, testName }) => {
it(testName, () => {
const action = { type: actionType, meta: { params } }
deepFreeze(action)
const newState = collectionsReducer(initialState, action, { collectionReducer })
// behaviour check
expect(collectionReducer).toHaveBeenCalledWith(undefined, action)
expect(newState[2]).toEqual(newCollection)
// sanity check
expect(newState[0]).toEqual(initialCollection)
expect(newState[1]).toEqual(initialCollection2)
})
})
})
})
describe('create/delete success', () => {
// TODO this seems like incorrect behaviour
it('CREATE_SUCCESS sets fetchTime to null', () => {
const action = { type: CREATE_SUCCESS }
deepFreeze(action)
const newState = collectionsReducer(initialState, action)
expect(newState[0].fetchTime).toEqual(null)
expect(newState[1].fetchTime).toEqual(null)
})
it('DELETE_SUCCESS sets fetchTime to null', () => {
const action = { type: DELETE_SUCCESS }
deepFreeze(action)
const newState = collectionsReducer(initialState, action)
expect(newState[0].fetchTime).toEqual(null)
expect(newState[1].fetchTime).toEqual(null)
})
})
describe('garbage collect', () => {
it('filters out records older than ten minutes', () => {
const elevenMinutes = 11 * 60 * 1000
const now = 12345678
const oldCollection = Object.assign({}, initialCollection, { fetchTime: now - elevenMinutes })
const initialStatePlusOldCollection = initialState.concat([oldCollection])
deepFreeze(initialStatePlusOldCollection)
const action = { type: GARBAGE_COLLECT, meta: { now } }
deepFreeze(action)
const newState = collectionsReducer(initialStatePlusOldCollection, action)
expect(initialStatePlusOldCollection.length).toEqual(3)
expect(newState.length).toEqual(2)
expect(newState[0]).toEqual(initialStatePlusOldCollection[0])
expect(newState[1]).toEqual(initialStatePlusOldCollection[1])
})
})
})
|
$(document).ready(function () {
console.log('Ready page Start');
world = '001';
room = 'middle';
currentRoom = room; //Maybe declare all sessions when ready with event handlers.
//Then join various sessions on click
});
|
/**
* Copyright 2015 The AMP HTML Authors. 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.
*/
import {Curves, bezierCurve, getCurve} from '#core/data-structures/curve';
describes.sandboxed('data structures - Curve', {}, () => {
it('bezierCurve', () => {
let curve = bezierCurve(0.75, 0, 0.75, 0.9);
expect(curve(0.2)).to.be.closeTo(0.024374631, 1e-6);
expect(curve(0.6)).to.be.closeTo(0.317459494, 1e-6);
expect(curve(0.9)).to.be.closeTo(0.905205002, 1e-6);
curve = bezierCurve(0, 0, 0.58, 1);
expect(curve(0.2)).to.be.closeTo(0.308366667, 1e-6);
expect(curve(0.6)).to.be.closeTo(0.785139061, 1e-6);
expect(curve(0.9)).to.be.closeTo(0.982973389, 1e-6);
});
it('getCurve on common curves', () => {
// Null case.
expect(getCurve(null)).to.equal(null);
expect(getCurve(undefined)).to.equal(null);
// Function is passed through.
const func = () => {};
expect(getCurve(func)).to.equal(func);
// String is translated.
expect(getCurve('linear')).to.equal(Curves.LINEAR);
expect(getCurve('ease')).to.equal(Curves.EASE);
expect(getCurve('ease-in')).to.equal(Curves.EASE_IN);
expect(getCurve('ease-out')).to.equal(Curves.EASE_OUT);
expect(getCurve('ease-in-out')).to.equal(Curves.EASE_IN_OUT);
});
it('getCurve on cubic-bezier curves', () => {
expect(getCurve('cubic-bezier(1)')).to.equal(null);
expect(getCurve('cubic-bezier(a)')).to.equal(null);
expect(getCurve('cubic-bezier(0.4, 0, 0.2)')).to.equal(null);
expect(getCurve('cubic-bezier(0.4, 0, 0.2, a)')).to.equal(null);
const curveExpected = bezierCurve(0.4, 0, 0.2, 1);
const curveGet = getCurve('cubic-bezier(0.4, 0, 0.2, 1)');
expect(curveExpected(0.2)).to.be.closeTo(curveGet(0.2), 1e-6);
expect(curveExpected(0.6)).to.be.closeTo(curveGet(0.6), 1e-6);
expect(curveExpected(0.9)).to.be.closeTo(curveGet(0.9), 1e-6);
});
});
|
define(['backbone', 'models/chat-message'], function(Backbone, ChatMessage){
var ChatMessageList = Backbone.Collection.extend({
model : ChatMessage
});
return ChatMessageList;
});
|
'use strict';
import { module } from 'angular';
import { AUTO_SCROLL_DIRECTIVE } from './autoScroll/autoScroll.directive';
import { ANY_FIELD_FILTER } from './anyFieldFilter/anyField.filter';
import { LINK_WITH_CLIPBOARD } from './linkWithClipboard.component';
import { PAGE_NAVIGATOR_COMPONENT } from './navigation/pageNavigator.component';
import { PAGE_SECTION_COMPONENT } from './navigation/pageSection.component';
import { REPLACE_FILTER } from './replace.filter';
import { ROBOT_TO_HUMAN_FILTER } from './robotToHumanFilter/robotToHuman.filter';
import { domPurifyOpenLinksInNewWindow } from './domPurifyOpenLinksInNewWindow';
import './flex-layout.less';
import './details.less';
import './main.less';
import './navPopover.less';
import { CORE_PRESENTATION_COLLAPSIBLESECTION_COLLAPSIBLESECTION_DIRECTIVE } from './collapsibleSection/collapsibleSection.directive';
import { CORE_PRESENTATION_ISVISIBLE_ISVISIBLE_DIRECTIVE } from './isVisible/isVisible.directive';
import { CORE_PRESENTATION_SORTTOGGLE_SORTTOGGLE_DIRECTIVE } from './sortToggle/sorttoggle.directive';
import { CORE_PRESENTATION_PERCENT_FILTER } from './percent.filter';
import { CORE_PRESENTATION_MARKDOWN } from './markdown.component';
export const CORE_PRESENTATION_PRESENTATION_MODULE = 'spinnaker.core.presentation';
export const name = CORE_PRESENTATION_PRESENTATION_MODULE; // for backwards compatibility
module(CORE_PRESENTATION_PRESENTATION_MODULE, [
ANY_FIELD_FILTER,
AUTO_SCROLL_DIRECTIVE,
LINK_WITH_CLIPBOARD,
PAGE_NAVIGATOR_COMPONENT,
PAGE_SECTION_COMPONENT,
CORE_PRESENTATION_COLLAPSIBLESECTION_COLLAPSIBLESECTION_DIRECTIVE,
CORE_PRESENTATION_ISVISIBLE_ISVISIBLE_DIRECTIVE,
CORE_PRESENTATION_MARKDOWN,
ROBOT_TO_HUMAN_FILTER,
CORE_PRESENTATION_SORTTOGGLE_SORTTOGGLE_DIRECTIVE,
CORE_PRESENTATION_PERCENT_FILTER,
REPLACE_FILTER,
]).run(domPurifyOpenLinksInNewWindow);
|
;(function(commonjs){
// Blacklist common values.
var BLACKLIST = [
"00000000000",
"11111111111",
"22222222222",
"33333333333",
"44444444444",
"55555555555",
"66666666666",
"77777777777",
"88888888888",
"99999999999",
"12345678909"
];
var STRICT_STRIP_REGEX = /[.-]/g;
var LOOSE_STRIP_REGEX = /[^\d]/g;
var verifierDigit = function(numbers) {
numbers = numbers
.split("")
.map(function(number){ return parseInt(number, 10); })
;
var modulus = numbers.length + 1;
var multiplied = numbers.map(function(number, index) {
return number * (modulus - index);
});
var mod = multiplied.reduce(function(buffer, number){
return buffer + number;
}) % 11;
return (mod < 2 ? 0 : 11 - mod);
};
var CPF = {};
CPF.format = function(number) {
return this.strip(number).replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, "$1.$2.$3-$4");
};
CPF.strip = function(number, strict) {
var regex = strict ? STRICT_STRIP_REGEX : LOOSE_STRIP_REGEX;
return (number || "").toString().replace(regex, "");
};
CPF.isValid = function(number, strict) {
var stripped = this.strip(number, strict);
// CPF must be defined
if (!stripped) { return false; }
// CPF must have 11 chars
if (stripped.length !== 11) { return false; }
// CPF can't be blacklisted
if (BLACKLIST.indexOf(stripped) >= 0) { return false; }
var numbers = stripped.substr(0, 9);
numbers += verifierDigit(numbers);
numbers += verifierDigit(numbers);
return numbers.substr(-2) === stripped.substr(-2);
};
CPF.generate = function(formatted) {
var numbers = "";
for (var i = 0; i < 9; i++) {
numbers += Math.floor(Math.random() * 9);
}
numbers += verifierDigit(numbers);
numbers += verifierDigit(numbers);
return (formatted ? this.format(numbers) : numbers);
};
if (commonjs) {
module.exports = CPF;
} else {
window.CPF = CPF;
}
})(typeof(exports) !== "undefined");
|
import { badge } from "../variables";
/*
DISCLAIMER:
Do not change this file because it is core styling.
Customizing core files will make updating Atlas much more difficult in the future.
To customize any core styling, copy the part you want to customize to styles/native/app/ so the core styling is overwritten.
==========================================================================
Badge
//== Design Properties
//## Helper classes to change the look and feel of the widget
========================================================================== */
// Badge Colors
export const badgePrimary = {
container: {
backgroundColor: badge.primary.backgroundColor,
},
caption: {
color: badge.primary.color,
},
};
export const badgeSuccess = {
container: {
backgroundColor: badge.success.backgroundColor,
},
caption: {
color: badge.success.color,
},
};
export const badgeWarning = {
container: {
backgroundColor: badge.warning.backgroundColor,
},
caption: {
color: badge.warning.color,
},
};
export const badgeDanger = {
container: {
backgroundColor: badge.danger.backgroundColor,
},
caption: {
color: badge.danger.color,
},
};
|
export const usolveDocs = {
name: 'usolve',
category: 'Algebra',
syntax: [
'x=usolve(U, b)'
],
description:
'Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.',
examples: [
'x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'
],
seealso: [
'usolveAll', 'lup', 'lusolve', 'lsolve', 'matrix', 'sparse'
]
}
|
define ([
], function(
) {
/**
*
* @class
* @memberof
* @param
*/
function Star(game, parentGroup, posX, posY, color){
Phaser.Sprite.call(this, game, posX, posY, 'stars',0);
this.scale.setTo(0.4,0.4);
this.anchor.setTo(0.5,0.5);
parentGroup.add(this);
};
Star.prototype = Object.create(Phaser.Sprite.prototype);
Star.prototype.constructor = Star;
return Star;
});
|
'use strict';
var upsServices = angular.module('upsConsole');
upsServices.config(function($httpProvider) {
$httpProvider.interceptors.push(function($q, $interpolate, Notifications) {
return {
'responseError': function(rejection) {
var messageExpr, message;
if (rejection.status === 400 && typeof rejection.data === 'object') {
Object.keys(rejection.data).forEach( function( key ) {
message = rejection.data[key];
Notifications.error( message );
});
} else {
messageExpr = $interpolate('Server returned {{status}}: {{statusText}}');
message = messageExpr( rejection );
Notifications.error(messageExpr(rejection));
}
return $q.reject(rejection);
}
};
});
});
|
/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
define([
"underscore",
"contrail-view",
"contrail-list-model",
"sm-constants",
"sm-labels",
"sm-utils"
], function (_, ContrailView, ContrailListModel, smwc, smwl, smwu) {
var PackageListView = ContrailView.extend({
el: $(contentContainer),
render: function () {
var self = this;
var listModelConfig = {
remote: {
ajaxConfig: {
url: smwu.getObjectDetailUrl(smwc.IMAGE_PREFIX_ID, "filterInPackages")
}
},
cacheConfig: {
ucid: smwc.UCID_ALL_PACKAGE_LIST
}
};
var contrailListModel = new ContrailListModel(listModelConfig);
self.renderView4Config(this.$el, contrailListModel, getPackageListViewConfig());
}
});
var getPackageListViewConfig = function () {
return {
elementId: cowu.formatElementId([smwl.SM_PACKAGE_LIST_SECTION_ID]),
view: "SectionView",
viewConfig: {
rows: [
{
columns: [
{
elementId: smwl.SM_PACKAGE_GRID_VIEW_ID,
title: smwl.TITLE_PACKAGES,
view: "PackageGridView",
app: cowc.APP_CONTRAIL_SM,
viewConfig: {pagerOptions: { options: { pageSize: 25, pageSizeSelect: [25, 50, 100] } }}
}
]
}
]
}
};
};
return PackageListView;
});
|
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/model/json/JSONModel",
"sap/ui/demo/wt/controller/HelloDialog",
"sap/ui/Device"
], function (UIComponent, JSONModel, HelloDialog, Device) {
"use strict";
return UIComponent.extend("sap.ui.demo.wt.Component", {
metadata: {
manifest: "json"
},
init: function () {
// call the init function of the parent
UIComponent.prototype.init.apply(this, arguments);
// set data model
var oData = {
recipient: {
name: "World"
}
};
var oModel = new JSONModel(oData);
this.setModel(oModel);
// set device model
var oDeviceModel = new JSONModel(Device);
oDeviceModel.setDefaultBindingMode("OneWay");
this.setModel(oDeviceModel, "device");
// set dialog
this._helloDialog = new HelloDialog(this.getRootControl());
// create the views based on the url/hash
this.getRouter().initialize();
},
openHelloDialog : function () {
this._helloDialog.open();
},
getContentDensityClass : function() {
if (!this._sContentDensityClass) {
if (!sap.ui.Device.support.touch) {
this._sContentDensityClass = "sapUiSizeCompact";
} else {
this._sContentDensityClass = "sapUiSizeCozy";
}
}
return this._sContentDensityClass;
}
});
});
|
(function () {
'use strict';
angular.module('xos.diagnostic', [
'ngResource',
'ngCookies',
'ngAnimate',
'ui.router',
'xos.helpers'
])
.config(($stateProvider) => {
$stateProvider
.state('home', {
url: '/',
template: '<diagnostic-container></diagnostic-container>'
});
})
.config(function($httpProvider){
$httpProvider.interceptors.push('NoHyperlinks');
})
.run(($log) => {
$log.info('Diagnostic Started');
});
})();
|
// This file ensures that canceling a channel early does not
// send the request to the server (bug 350790)
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const Cr = Components.results;
Cu.import("resource://testing-common/httpd.js");
var observer = {
QueryInterface: function eventsink_qi(iid) {
if (iid.equals(Components.interfaces.nsISupports) ||
iid.equals(Components.interfaces.nsIObserver))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
},
observe: function(subject, topic, data) {
subject = subject.QueryInterface(Components.interfaces.nsIRequest);
subject.cancel(Components.results.NS_BINDING_ABORTED);
var obs = Components.classes["@mozilla.org/observer-service;1"].getService();
obs = obs.QueryInterface(Components.interfaces.nsIObserverService);
obs.removeObserver(observer, "http-on-modify-request");
}
};
var listener = {
onStartRequest: function test_onStartR(request, ctx) {
do_check_eq(request.status, Components.results.NS_BINDING_ABORTED);
},
onDataAvailable: function test_ODA() {
do_throw("Should not get any data!");
},
onStopRequest: function test_onStopR(request, ctx, status) {
httpserv.stop(do_test_finished);
}
};
function makeChan(url) {
var ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var chan = ios.newChannel(url, null, null)
.QueryInterface(Components.interfaces.nsIHttpChannel);
return chan;
}
var httpserv = null;
function execute_test() {
var chan = makeChan("http://localhost:4444/failtest");
var obs = Components.classes["@mozilla.org/observer-service;1"].getService();
obs = obs.QueryInterface(Components.interfaces.nsIObserverService);
obs.addObserver(observer, "http-on-modify-request", false);
chan.asyncOpen(listener, null);
}
function run_test() {
httpserv = new HttpServer();
httpserv.registerPathHandler("/failtest", failtest);
httpserv.start(4444);
execute_test();
do_test_pending();
}
// PATHS
// /failtest
function failtest(metadata, response) {
do_throw("This should not be reached");
}
|
// ECMAScript 5 strict mode
"use strict";
assert2(cr, "cr namespace not created");
assert2(cr.behaviors, "cr.behaviors not created");
/////////////////////////////////////
// Behavior class
cr.behaviors.Rex_layouter_text = function(runtime)
{
this.runtime = runtime;
};
(function ()
{
var behaviorProto = cr.behaviors.Rex_layouter_text.prototype;
/////////////////////////////////////
// Behavior type class
behaviorProto.Type = function(behavior, objtype)
{
this.behavior = behavior;
this.objtype = objtype;
this.runtime = behavior.runtime;
};
var behtypeProto = behaviorProto.Type.prototype;
behtypeProto.onCreate = function()
{
};
/////////////////////////////////////
// Behavior instance class
behaviorProto.Instance = function(type, inst)
{
this.type = type;
this.behavior = type.behavior;
this.inst = inst;
this.runtime = type.runtime;
};
var behinstProto = behaviorProto.Instance.prototype;
behinstProto.onCreate = function()
{
this.check_name = "LAYOUTER";
this.content = "";
this.character_object_sid = -1;
this.char2frameindex = {};
this._char2frameindex_set(this.properties[0]);
this._sprite_objtype = null;
this._sprite_index = 0; // temp var
this._insts = []; // temp list
};
behinstProto._char2frameindex_set = function (characters)
{
var c;
for (c in this.char2frameindex)
delete this.char2frameindex[c];
var i, cnt=characters.length;
for (i=0; i<cnt; i++)
{
c = characters.charAt(i);
this.char2frameindex[c] = i;
}
};
behinstProto.tick = function ()
{
};
behinstProto._get_character_object = function ()
{
if (this._sprite_objtype == null)
this._sprite_objtype = this.runtime.getObjectTypeBySid(this.character_object_sid);
return this._sprite_objtype;
};
behinstProto._get_sprite_inst = function ()
{
var inst = null;
var sprites = this.inst.sprites;
var sprites_cnt = sprites.length;
while (this._sprite_index < sprites_cnt)
{
inst = this.runtime.getObjectByUID(sprites[this._sprite_index]);
this._sprite_index += 1;
if (inst instanceof cr.plugins_.Sprite.prototype.Instance)
break;
else
inst = null;
}
return inst;
};
behinstProto.set_text = function (text)
{
var objtype = this._get_character_object();
if (!objtype)
return;
this.content = text;
var set_frameindex = cr.plugins_.Sprite.prototype.acts.SetAnimFrame;
var set_amin_speed = cr.plugins_.Sprite.prototype.acts.SetAnimSpeed;
var layouter=this.inst;
var sprites=layouter.sprites;
var i, text_len = text.length;
this._sprite_index = 0;
var inst, c, frame_index;
this._insts.length = 0;
var mode = null; // 0: add, 1: remove
for (i=0; i<text_len; i++)
{
inst = this._get_sprite_inst();
if (inst == null) // create a sprite inst
{
inst = this.inst.create_inst(objtype, 0, 0);
this._insts.push(inst);
mode = 0;
}
c = text.charAt(i);
frame_index = this.char2frameindex[c];
if (frame_index == null)
frame_index = -1;
if (inst.cur_frame != frame_index)
set_frameindex.call(inst, frame_index);
if (inst.cur_anim_speed != 0)
set_amin_speed.call(inst, 0);
}
if (mode == null)
{
inst = this._get_sprite_inst();
while (inst != null)
{
this._insts.push(inst);
inst = this._get_sprite_inst();
}
if (this._insts.length > 0)
mode = 1;
}
if (mode == 0)
this.inst.add_insts(this._insts);
else if (mode == 1)
this.inst.destroy_insts(this._insts);
this._insts.length = 0;
};
behinstProto.saveToJSON = function ()
{
return { "t": this.content,
"csid": this.character_object_sid,
"c2fi": this.char2frameindex,
};
};
behinstProto.loadFromJSON = function (o)
{
this.content = o["t"];
this.character_object_sid = o["csid"];
this.char2frameindex = o["c2fi"];
};
//////////////////////////////////////
// Conditions
function Cnds() {};
behaviorProto.cnds = new Cnds();
//////////////////////////////////////
// Actions
function Acts() {};
behaviorProto.acts = new Acts();
Acts.prototype.SetCharacterObject = function (objtype)
{
if (!objtype)
return;
assert2(cr.plugins_.Sprite, "Layouter text: you should assign a sprite objct for character.");
this._sprite_objtype = objtype;
this.character_object_sid = objtype.sid;
};
Acts.prototype.SetText = function(param)
{
if (cr.is_number(param) && param < 1e9)
param = Math.round(param * 1e10) / 1e10; // round to nearest ten billionth - hides floating point errors
var text_to_set = param.toString();
if (this.content !== text_to_set)
this.set_text(text_to_set);
};
//////////////////////////////////////
// Expressions
function Exps() {};
behaviorProto.exps = new Exps();
Exps.prototype.Value = function (ret)
{
ret.set_float(this.value);
};
}());
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
If thisArg is not null(defined) the called function is passed
ToObject(thisArg) as the this value
es5id: 15.3.4.4_A5_T7
description: thisArg is new Number()
---*/
var obj = new Number(1);
Function("this.touched= true;").call(obj);
//CHECK#1
if (!(obj.touched)) {
$ERROR('#1: If thisArg is not null(defined) the called function is passed ToObject(thisArg) as the this value');
}
|
"use strict";
exports.showErrorImpl = function (err) {
return err.stack || err.toString();
};
exports.error = function (msg) {
return new Error(msg);
};
exports.message = function (e) {
return e.message;
};
exports.name = function (e) {
return e.name || "Error";
};
exports.stackImpl = function (just) {
return function (nothing) {
return function (e) {
return e.stack ? just(e.stack) : nothing;
};
};
};
exports.throwException = function (e) {
return function () {
throw e;
};
};
exports.catchException = function (c) {
return function (t) {
return function () {
try {
return t();
} catch (e) {
if (e instanceof Error || Object.prototype.toString.call(e) === "[object Error]") {
return c(e)();
} else {
return c(new Error(e.toString()))();
}
}
};
};
};
|
/**
* Cloud Browser basic navigation support.
*/
var CloudBrowser = {
/** Submit the "next" page results form. */
submitForm: function (formId) {
document.getElementById(formId).submit();
return false;
},
/** Return key pressed */
enterPressed: function (event) {
var key = window.event ?
window.event.keyCode /*IE*/ :
event.which /*FF*/;
return key === 13;
},
/** Submit form on enter. */
submitOnEnter: function (event, formId) {
if (CloudBrowser.enterPressed(event)) {
CloudBrowser.submitForm(formId);
}
},
/** Get query string parameters. */
getQueryObj: function (query) {
var parts = query.split('?', 2);
var uri = parts[0];
var paramStrs = parts.length == 2 ? parts[1].split('&') : [];
// Chop up parameters.
var params = {};
for (var i = 0, len = paramStrs.length; i < len; i++) {
var paramParts = paramStrs[i].split('=', 2);
if (paramParts.length == 2) {
params[paramParts[0]] = paramParts[1];
}
}
return {
'uri': uri,
'params': params
};
},
/** Convert parameter object to string. */
toQueryString: function (queryObj) {
var uri = queryObj.uri;
var params = queryObj.params || {};
var paramStr = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
var value = params[key];
// Yes, I know this is inefficient.
paramStr += key + '=' + value;
}
}
return paramStr !== '' ? [uri, paramStr].join('?') : uri;
},
/** Set query parameters. */
setQueryParam: function (query, key, value) {
var queryObj = CloudBrowser.getQueryObj(query);
queryObj.params[key] = value;
return CloudBrowser.toQueryString(queryObj);
}
};
function align(to_this) {
var cr = to_this.getClientRects()[0];
var floater = document.getElementById('diff_float');
floater.style.left = cr.left+'px';
floater.style.top = (cr.top+24)+'px';
}
window.onload = function () {
var e = document.getElementsByClassName("diff_btn");
for (i = 0; i < e.length; i++) {
e[i].addEventListener('click',
function (e) {
e.stopPropagation();
var floating_dialog = document.getElementById('diff_float');
floating_dialog.style.display = 'block';
floating_dialog.title = e.target.title;
align(e.target);
});
}
document.body.addEventListener('click', function() {
document.getElementById('diff_float').style.display = 'none';
});
document.getElementById('diff_float')
.addEventListener('click', function(e) { e.stopPropagation(); });
}
function submitDiffForm() {
var title = document.getElementById('diff_float').title;
document.getElementById('diff_form_file').value = title;
document.getElementById("diff_form").submit();
return false;
}
|
(function ($) {
$.simplicity = $.simplicity || {};
/**
* The current version of Simplicity Widgets.
* <p>
* Do not use this for feature detection, instead use it for high level
* diagnostics to report which version of the widgets are
* currently in use.
* </p>
*
* @example
* console.log('Simplicity Widgets:', $.simplicity.version);
*/
$.simplicity.version = '4.0-dev';
}(jQuery));
|
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const db = require('../../models');
module.exports = (passport, secret) => {
passport.use(new GoogleStrategy({
clientID: secret.consumerKey,
clientSecret: secret.consumerSecret,
callbackURL: secret.callbackURL,
}, (token, tokenSecret, profile, done) => {
db.user.findOne({
where: {
googleId: profile.id
}
}).then(userExists => {
if (userExists) {
done(null, userExists);
} else {
let newUserCreated;
db.sequelize.transaction(t => {
return db.user.create({
googleId: profile.id,
token: token,
email: profile._json.emails[0].value,
name: profile.displayName,
picture: profile._json.image.url
}, { transaction: t })
.then(newUser => {
newUserCreated = newUser;
return db.setting.create({ userId: newUser.id }, { transaction: t });
});
}).then(() => {
done(null, newUserCreated);
}).catch(err => {
done(err);
});
}
return null;
}).catch(err => {
done(err);
});
}));
};
|
/**
* Pimcore
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.pimcore.org/license
*
* @copyright Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license New BSD License
*/
pimcore.registerNS("pimcore.report.analytics.elementnavigation");
pimcore.report.analytics.elementnavigation = Class.create(pimcore.report.abstract, {
matchType: function (type) {
var types = ["document_page"];
if (pimcore.report.abstract.prototype.matchTypeValidate(type, types)
&& pimcore.settings.google_analytics_enabled) {
return true;
}
return false;
},
getName: function () {
return "navigation";
},
getIconCls: function () {
return "pimcore_icon_analytics_navigation";
},
getPanel: function () {
var panel = new Ext.Panel({
title: t("navigation"),
layout: "border",
height: 680,
border: false,
items: [this.getFilterPanel(),this.getContentPanel()]
});
panel.on("afterrender", function (panel) {
this.loadMask = new Ext.LoadMask({
target: panel,
msg: t("please_wait")});
this.loadMask.enable();
}.bind(this));
return panel;
},
getContentPanel: function () {
this.flashContainerId = "analytics_navigation_" + this.type + "_" + this.reference.id;
this.contentPanel = new Ext.Panel({
region: "center",
layout: "fit",
autoScroll: true,
html: '<div id="' + this.flashContainerId + '"></div>',
listeners: {
afterrender: function () {
window.setTimeout(this.embedFlash.bind(this),2000);
}.bind(this)
}
});
return this.contentPanel;
},
embedFlash: function () {
var flashvars = {
xmlFile: this.getConfigFile()
};
var params = {
wmode: "opaque"
};
var height = this.contentPanel.getHeight()-10;
swfobject.embedSWF("/pimcore/static6/swf/analytics_navigation.swf", this.flashContainerId, "100%",
height, "10.0.0","/pimcore/static6/swf/expressInstall.swf", flashvars, params);
},
getConfigFile: function () {
var id = "";
var path = "";
var type = "";
if (this.type == "document_page") {
id = this.reference.id;
path = this.reference.data.path + this.reference.data.key;
type = "document";
}
var formValues = {
dateFrom: "",
dateTo: "",
site: ""
};
try {
formValues = this.filterPanel.getForm().getFieldValues();
} catch (e) {}
return "/admin/reports/analytics/navigation?path=" + path + "&id=" + id + "&type=" + type + "&dateFrom="
+ formValues.dateFrom + "&dateTo=" + formValues.dateTo + "&site=" + formValues.site;
},
getFilterPanel: function () {
if (!this.filterPanel) {
var today = new Date();
var fromDate = new Date(today.getTime() - (86400000 * 31));
this.filterPanel = new Ext.FormPanel({
region: 'north',
defaults: {
labelWidth: 40
},
height: 40,
layout: 'hbox',
bodyStyle: 'padding:7px 0 0 5px',
items: [{
xtype: "datefield",
fieldLabel: t('from'),
name: 'dateFrom',
value: fromDate,
itemCls: "pimcore_analytics_filter_form_item"
},{
xtype: "datefield",
fieldLabel: t('to'),
name: 'dateTo',
value: today,
itemCls: "pimcore_analytics_filter_form_item"
},{
xtype: "combo",
store: pimcore.globalmanager.get("sites"),
valueField: "id",
displayField: "domain",
triggerAction: "all",
name: "site",
fieldLabel: t("site"),
itemCls: "pimcore_analytics_filter_form_item"
},{
xtype: "button",
text: t("apply"),
itemCls: "pimcore_analytics_filter_form_item",
handler: function () {
this.embedFlash();
}.bind(this)
}
]
});
}
return this.filterPanel;
}
});
// add to report broker
pimcore.report.broker.addGroup("analytics", "google_analytics", "pimcore_icon_report_analytics_group");
pimcore.report.broker.addReport(pimcore.report.analytics.elementnavigation, "analytics");
|
var _ = require('underscore');
var AutoStyler = require('./auto-styler');
module.exports = AutoStyler.extend({
updateStyle: function (style) {
this.styles = style.auto_style;
this.colors.updateColors(style.auto_style);
this.colors.updateData(_.pluck(this.dataviewModel.get('data'), 'name'));
},
_getRange: function () {
return _.map(this.dataviewModel.get('data'), function (category) {
return this.colors.getColorByCategory(category.name);
}, this);
},
getDef: function () {
var model = this.dataviewModel;
var categories = model.get('data');
var range = this._getRange();
var definitions = {};
AutoStyler.FILL_SELECTORS.forEach(function (item) {
var definition = {};
var geom = item.substring(0, item.indexOf('-'));
definition = { color:
{ domain: _.pluck(categories, 'name'), range: range, attribute: model.get('column') }
};
definitions[geom === 'marker' ? 'point' : geom] = definition;
});
return definitions;
},
_getFillColor: function () {
var model = this.dataviewModel;
var categories = model.get('data');
var column = model.get('column');
return this._getCategoryRamp(categories, column);
},
_getCategoryRamp: function (categories, column) {
var ramp = 'ramp([' + column + '], ';
var catListColors = '';
var catListValues = '';
for (var i = 0; i < categories.length; i++) {
var cat = categories[i];
var next = i !== categories.length - 1 ? ', ' : '';
catListColors += '"' + this.colors.getColorByCategory(cat.name) + '"' + next;
if (!cat.agg) {
if (typeof cat.name !== 'string') {
catListValues += cat.name + next;
} else {
catListValues += '"' + String(cat.name).replace(/"/g, '\\"') + '"' + next;
}
} else if (i === categories.length - 1) {
catListValues = catListValues.substring(0, catListValues.length - 2);
}
}
return ramp + '(' + catListColors + '), (' + catListValues + '), \'=\')';
}
});
|
var HttpRequestStack = require('../lib/http-stack').HttpRequestStack;
// Create the 'low-level' net.Stream we're going to be 'stacking' on
var conn = require('net').createConnection(80, 'www.yahoo.com');
conn.on('connect', function() {
console.log('connected!');
// Create our first "stack", the HttpRequestStack instance. This class is
// responsible for writing an HTTP request to the provided 'conn', and then
// parsing the response into a 'response' event and clean 'data' events.
var req = new HttpRequestStack(conn);
req.get("/", [
"Host: www.yahoo.com"
//"Connection: close",
//"Accept-Encoding: gzip"
]);
//req.end();
// 'response' is fired after the final HTTP header has been parsed. 'res'
// is a ReadStream, that also contains 'rawHeaders', 'headers' properties.
req.on('response', function(res) {
res.pipe(process.stdout);
res.on('data', function(chunk) {
//console.error(chunk.toString());
});
res.on('end', function() {
console.error('received FIN packet from "conn"');
});
});
});
|
var Promise = require('bluebird');
var pm2 = require('pm2');
pm2.connect = Promise.promisify(pm2.connect);
pm2.disconnect = Promise.promisify(pm2.disconnect);
pm2.start = Promise.promisify(pm2.start);
pm2.kill = Promise.promisify(pm2.killDaemon);
var config = require(__dirname+'/../../config/environment.js')
var logger = require(__dirname+'/../../lib/data/logs.js');
var processSet = require(__dirname+'/index.js');
function parseNameFromPath(path) {
return 'gatewayd:'+path.split('/').pop().replace('.js', '');
}
function Supervisor() {}
Supervisor.prototype.start = function() {
return new Promise(function(resolve, reject) {
var processes;
var debug = config.get('NODE_DEBUG');
var processNum = 0;
return pm2.connect()
.then(function() {
return Promise.map(processSet.toArray(), function(path) {
var processName = parseNameFromPath(path);
var args = {
name: processName,
};
// If we want to debug,
// start each process with its own debugger on ports 5858, 6868, 7878, 8888, 9898 etc
if (debug) {
var debugPort = 5858 + processNum * 1010;
args.nodeArgs = ['--debug=' + debugPort];
processNum++;
logger.warn('[DEBUG]Starting ' + processName + ' in debug mode, port: ' + debugPort);
}
return pm2.start(path, args);
});
})
.then(function(started) {
processes = started;
//logger.info(started[0]);
return pm2.list();
})
.then(function() {
resolve(processes);
})
.error(function(error) {
pm2.disconnect().then(function() {
reject(error);
})
.error(reject);
});
});
};
Supervisor.prototype.stop = function() {
return pm2.connect()
.then(function() {
return pm2.kill();
}).then(function() {
return pm2.disconnect(process.exit(0));
});
};
module.exports = Supervisor;
|
describe('Unit : youtubePlugin content services', function () {
describe('Unit: Buildfire Provider', function () {
var Buildfire;
beforeEach(module('youtubePluginContent'));
beforeEach(inject(function (_Buildfire_) {
Buildfire = _Buildfire_;
}));
it('Buildfire should exist and be an object', function () {
expect(typeof Buildfire).toEqual('object');
});
});
describe('Unit : DataStore Factory', function () {
var DataStore, Buildfire, STATUS_MESSAGES, STATUS_CODE, q;
beforeEach(module('youtubePluginContent'));
beforeEach(inject(function (_DataStore_, _STATUS_CODE_, _STATUS_MESSAGES_) {
DataStore = _DataStore_;
STATUS_CODE = _STATUS_CODE_;
STATUS_MESSAGES = _STATUS_MESSAGES_;
Buildfire = {
datastore: {}
};
Buildfire.datastore = jasmine.createSpyObj('Buildfire.datastore', ['get','insert','update', 'save', 'delete']);
}));
it('DataStore should exist and be an object', function () {
expect(typeof DataStore).toEqual('object');
});
it('DataStore.get should exist and be a function', function () {
expect(typeof DataStore.get).toEqual('function');
});
it('DataStore.save should exist and be a function', function () {
expect(typeof DataStore.save).toEqual('function');
});
});
describe('Unit : Utils Factory', function () {
var Utils;
beforeEach(module('youtubePluginContent'));
beforeEach(inject(function (_Utils_) {
Utils = _Utils_;
}));
it('Utils should exist and be an object', function () {
expect(typeof Utils).toEqual('object');
});
it('Utils.extractSingleVideoId should exist and be a function', function () {
expect(typeof Utils.extractSingleVideoId).toEqual('function');
});
it('Utils.extractChannelId should exist and be a function', function () {
expect(typeof Utils.extractChannelId).toEqual('function');
});
it('Utils.extractSingleVideoId should return a valid videoId', function () {
var url = "https://www.youtube.com/watch?v=0wYYjQJcGW8";
var videoId = Utils.extractSingleVideoId(url);
expect(videoId).toEqual('0wYYjQJcGW8');
});
it('Utils.extractChannelId should return an object', function () {
var url1 = "https://www.youtube.com/channel/UCuTaETsuCOkJ0H_GAztWt0Q";
var url2 = "https://www.youtube.com/user/gopromx";
var url3 = "https://www.youtube.com/c/creatoracademy";
var channelId = Utils.extractChannelId(url1);
var username = Utils.extractChannelId(url2);
var _username = Utils.extractChannelId(url3);
expect(channelId).toEqual({channel :'UCuTaETsuCOkJ0H_GAztWt0Q'});
expect(username).toEqual({user :'gopromx'});
expect(_username).toEqual({c :'creatoracademy'});
});
});
});
|
/**
* @author: Dennis Hernández
* @webSite: http://djhvscf.github.io/Blog
* @version: v1.0.0
*/
!function ($) {
'use strict';
var isSearch = false;
var rowAttr = function (row, index) {
return {
id: 'customId_' + index
};
};
$.extend($.fn.bootstrapTable.defaults, {
reorderableRows: false,
onDragStyle: null,
onDropStyle: null,
onDragClass: "reorder_rows_onDragClass",
dragHandle: null,
useRowAttrFunc: false,
onReorderRowsDrag: function (table, row) {
return false;
},
onReorderRowsDrop: function (table, row) {
return false;
},
onReorderRow: function (newData) {
return false;
}
});
$.extend($.fn.bootstrapTable.Constructor.EVENTS, {
'reorder-row.bs.table': 'onReorderRow'
});
var BootstrapTable = $.fn.bootstrapTable.Constructor,
_init = BootstrapTable.prototype.init,
_initSearch = BootstrapTable.prototype.initSearch;
BootstrapTable.prototype.init = function () {
if (!this.options.reorderableRows) {
_init.apply(this, Array.prototype.slice.apply(arguments));
return;
}
var that = this;
if (this.options.useRowAttrFunc) {
this.options.rowAttributes = rowAttr;
}
var onPostBody = this.options.onPostBody;
this.options.onPostBody = function () {
setTimeout(function () {
that.makeRowsReorderable();
onPostBody.apply();
}, 1);
};
_init.apply(this, Array.prototype.slice.apply(arguments));
};
BootstrapTable.prototype.initSearch = function () {
_initSearch.apply(this, Array.prototype.slice.apply(arguments));
if (!this.options.reorderableRows) {
return;
}
//Known issue after search if you reorder the rows the data is not display properly
//isSearch = true;
};
BootstrapTable.prototype.makeRowsReorderable = function () {
if (this.options.cardView) {
return;
}
var that = this;
this.$el.tableDnD({
onDragStyle: that.options.onDragStyle,
onDropStyle: that.options.onDropStyle,
onDragClass: that.options.onDragClass,
onDrop: that.onDrop,
onDragStart: that.options.onReorderRowsDrag,
dragHandle: that.options.dragHandle
});
};
BootstrapTable.prototype.onDrop = function (table, droppedRow) {
var tableBs = $(table),
tableBsData = tableBs.data('bootstrap.table'),
tableBsOptions = tableBs.data('bootstrap.table').options,
row = null,
newData = [];
for (var i = 0; i < table.tBodies[0].rows.length; i++) {
row = $(table.tBodies[0].rows[i]);
newData.push(tableBsOptions.data[row.data('index')]);
row.data('index', i).attr('data-index', i);
}
tableBsOptions.data = newData;
//Call the user defined function
tableBsOptions.onReorderRowsDrop.apply(table, [table, droppedRow]);
//Call the event reorder-row
tableBsData.trigger('reorder-row', newData);
};
}(jQuery);
|
define({
"_widgetLabel": "Kaldvaatur",
"locateButtonLabel": "Valige peamisel kaardil punkt kaldpiltide kuvamiseks.",
"clearButtonLabel": "Kustuta kogu graafika",
"zoomButtonLabel": "Suumi kaldpildi ulatuses",
"syncButtonLabel": "Sünkroniseeri nadiirkaart",
"rasterListLabel": "Kuva saadaolevad kaldpildid",
"measureWidgetLabel": "Mõõtmise valikud",
"intialScaleLabel": "Vali kaldpiltide algne mõõtkava",
"smallBuildingLabel": "Linnapiirkond: väike hoone",
"buildingLabel": "Linnapiirkond: hoone",
"azimuthChangeNotification": "Valitud juhises pole andmeid.",
"noImageNotification": "Sellel alal ei leitud pilte. Valige peamisel kaardil teine asukoht."
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:1f792858194799d7baee9c92b71369620f20b27976c9db4d5edb0e1ea118891b
size 18585
|
a >= b
|
var util = require('util');
function UnexpectedError(inner) {
this.message = "Unexpected Error";
this.inner = inner;
Error.call(this, this.message);
Error.captureStackTrace(this, this.constructor);
}
util.inherits(UnexpectedError, Error);
UnexpectedError.wrap = function (err) {
return (err instanceof UnexpectedError) ? err : new UnexpectedError(err);
};
module.exports = UnexpectedError;
|
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = function () {
// Init module configuration options
var applicationModuleName = 'agileTek';
var applicationModuleVendorDependencies = [
'ngResource',
'ngCookies',
'ngAnimate',
'ngTouch',
'ngSanitize',
'ui.router',
'ui.bootstrap',
'ui.utils'
];
// Add a new vertical module
var registerModule = function (moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule: registerModule
};
}();'use strict';
//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config([
'$locationProvider',
function ($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
//Then define the init function for starting up the application
angular.element(document).ready(function () {
//Fixing facebook bug with redirect
if (window.location.hash === '#_=_')
window.location.hash = '#!';
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
|
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. 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.
///////////////////////////////////////////////////////////////////////////
define(['dojo/_base/declare',
'./_BasicServiceChooser',
'./_GpServiceChooserContent'
],
function(declare, _BasicServiceChooser, _GpServiceChooserContent) {
return declare([_BasicServiceChooser], {
baseClass: 'jimu-gp-service-chooser',
declaredClass: 'jimu.dijit.GpServiceChooser',
//public methods:
//getUrl
//methods to be override:
//_createServiceChooserContent
//to be override, return a service chooser content
_createServiceChooserContent: function(args){
return new _GpServiceChooserContent(args);
}
});
});
|
"use strict";
var childProcess = require("child_process");
var os = require("os");
module.exports = function opener(args, options, callback) {
var platform = process.platform;
// Attempt to detect Windows Subystem for Linux (WSL). WSL itself as Linux (which works in most cases), but in
// this specific case we need to treat it as actually being Windows. The "Windows-way" of opening things through
// cmd.exe works just fine here, whereas using xdg-open does not, since there is no X Windows in WSL.
if (platform === "linux" && os.release().indexOf("Microsoft") !== -1) {
platform = "win32";
}
// http://stackoverflow.com/q/1480971/3191, but see below for Windows.
var command;
switch (platform) {
case "win32": {
command = "cmd";
break;
}
case "darwin": {
command = "open";
break;
}
default: {
command = "xdg-open";
break;
}
}
if (typeof args === "string") {
args = [args];
}
if (typeof options === "function") {
callback = options;
options = {};
}
if (options && typeof options === "object" && options.command) {
if (platform === "win32") {
// *always* use cmd on windows
args = [options.command].concat(args);
} else {
command = options.command;
}
}
if (platform === "win32") {
// On Windows, we really want to use the "start" command. But, the rules regarding arguments with spaces, and
// escaping them with quotes, can get really arcane. So the easiest way to deal with this is to pass off the
// responsibility to "cmd /c", which has that logic built in.
//
// Furthermore, if "cmd /c" double-quoted the first parameter, then "start" will interpret it as a window title,
// so we need to add a dummy empty-string window title: http://stackoverflow.com/a/154090/3191
//
// Additionally, on Windows ampersand needs to be escaped when passed to "start"
args = args.map(function (value) {
return value.replace(/&/g, "^&");
});
args = ["/c", "start", "\"\""].concat(args);
}
return childProcess.execFile(command, args, options, callback);
};
|
import reducer from '../../../src/renderer/reducers/auth';
describe('reducer/auth', () => {
const initialState = {
mail: ''
};
it('should return the initial state', () => {
const expectedResult = initialState;
expect(reducer(undefined, {})).toEqual(expectedResult);
});
it('should handle LOGIN', () => {
expect(reducer(undefined, { type: 'LOGIN' })).toEqual(initialState);
});
it('should handle LOGOUT', () => {
expect(reducer(undefined, { type: 'LOGOUT' })).toEqual(initialState);
});
it('should handle LOGIN_SUCCESS', () => {
const expectedResult = Object.assign({}, initialState, {
mail: 'a@b.com'
});
expect(reducer(undefined, {
type : 'LOGIN_SUCCESS',
payload: {
mail: 'a@b.com'
}
})).toEqual(expectedResult);
});
it('should handle LOGOUT_SUCCESS', () => {
const expectedResult = Object.assign({}, initialState, {
mail: ''
});
expect(reducer(undefined, { type: 'LOGOUT_SUCCESS' })).toEqual(expectedResult);
});
});
|
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const _ = require("underscore")
const sinon = require("sinon")
const benv = require("benv")
const rewire = require("rewire")
const Backbone = require("backbone")
const ResultsView = rewire("../view.coffee")
const PartnerCellView = benv.requireWithJadeify(
require.resolve("../../partner_cell/view"),
["template"]
)
describe("ResultsView", function () {
const nPartners = range =>
range.map(i => ({
name: "Gallery" + i,
id: "gallery-" + i,
initials: "IDK",
locations: [{ city: "New York" }],
profile: {
id: "gallery-" + i,
href: "/gallery-" + i,
image: { cropped: { url: `/gallery-${i}.jpeg` } },
},
}))
before(done =>
benv.setup(() => {
benv.expose({ $: benv.require("jquery"), jQuery: benv.require("jquery") })
Backbone.$ = $
ResultsView.__set__("PartnerCellView", PartnerCellView)
$.onInfiniteScroll = sinon.stub()
return done()
})
)
after(() => benv.teardown())
beforeEach(function () {
this.filterPartners = new Backbone.Model()
this.params = new Backbone.Model()
$("body").html(`\
<div class=galleries-institutions-results-grid></div>
<div class=galleries-institutions-spinner>
<div class=loading-spinner></div>
</div>'\
`)
this.view = new ResultsView({
params: this.params,
filterPartners: this.filterPartners,
el: "body",
})
return (this.view.fetch = sinon.stub())
})
describe("#render", function () {
beforeEach(function () {
return (this.partners = nPartners(_.range(1, 11)))
})
it("sets state for not all fetched yet", function () {
this.filterPartners.allFetched = false
this.view.render(this.partners)
return this.view.$el.attr("data-state").should.equal("")
})
it("sets state for all fetched", function () {
this.filterPartners.allFetched = true
this.view.render(this.partners)
return this.view.$el.attr("data-state").should.equal("finished-paging")
})
return it("renders grid", function () {
this.view.render(this.partners)
this.view.$gridContainer.children().length.should.equal(10)
const names1 = _.pluck(this.partners, "name")
this.view
.$(".partner-cell-name")
.map(function () {
return $(this).text()
})
.get()
.should.eql(names1)
const partnersPage2 = nPartners(_.range(11, 21))
const names2 = _.pluck(partnersPage2, "name")
this.view.render(partnersPage2)
this.view.$gridContainer.children().length.should.equal(20)
return this.view
.$(".partner-cell-name")
.map(function () {
return $(this).text()
})
.get()
.should.eql(names1.concat(names2))
})
})
describe("#reset", () =>
it("clears the ui and starts a new fetch", function () {
this.view.$gridContainer.html("<div></div>")
this.view.reset()
this.view.$gridContainer.html().should.equal("")
return this.view.fetch.calledOnce.should.be.true()
}))
return describe("#fetchNextPage", function () {
beforeEach(function () {
return (this.params.hasSelection = sinon.stub())
})
it("does not fetch if no params selected", function () {
this.params.hasSelection.returns(false)
this.filterPartners.allFetched = false
this.view.fetchNextPage()
return this.view.fetch.called.should.be.false()
})
it("does not fetch if all results are fetched", function () {
this.params.hasSelection.returns(true)
this.filterPartners.allFetched = true
this.view.fetchNextPage()
return this.view.fetch.called.should.be.false()
})
return it("fetches otherwise", function () {
this.params.hasSelection.returns(true)
this.filterPartners.allFetched = false
this.view.fetchNextPage()
return this.view.fetch.calledOnce.should.be.true()
})
})
})
|
class Foo {
static test() {
return babelHelpers.classPrivateFieldLooseBase(Foo, _bar)[_bar];
}
test() {
return babelHelpers.classPrivateFieldLooseBase(Foo, _bar)[_bar];
}
}
var _bar = babelHelpers.classPrivateFieldLooseKey("bar");
Object.defineProperty(Foo, _bar, {
writable: true,
value: "foo"
});
|
/*
* Copyright (c) 2017. MIT-license for Jari Van Melckebeke
* Note that there was a lot of educational work in this project,
* this project was (or is) used for an assignment from Realdolmen in Belgium.
* Please just don't abuse my work
*/
/*
* DateJS Culture String File
* Country Code: de-LU
* Name: German (Luxembourg)
* Format: "key" : "value"
* Key is the en-US term, Value is the Key in the current language.
*/
Date.CultureStrings = Date.CultureStrings || {};
Date.CultureStrings["de-LU"] = {
"name": "de-LU",
"englishName": "German (Luxembourg)",
"nativeName": "Deutsch (Luxemburg)",
"Sunday": "Sonntag",
"Monday": "Montag",
"Tuesday": "Dienstag",
"Wednesday": "Mittwoch",
"Thursday": "Donnerstag",
"Friday": "Freitag",
"Saturday": "Samstag",
"Sun": "Son",
"Mon": "Mon",
"Tue": "Die",
"Wed": "Mit",
"Thu": "Don",
"Fri": "Fre",
"Sat": "Sam",
"Su": "So",
"Mo": "Mo",
"Tu": "Di",
"We": "Mi",
"Th": "Do",
"Fr": "Fr",
"Sa": "Sa",
"S_Sun_Initial": "S",
"M_Mon_Initial": "M",
"T_Tue_Initial": "D",
"W_Wed_Initial": "M",
"T_Thu_Initial": "D",
"F_Fri_Initial": "F",
"S_Sat_Initial": "S",
"January": "Januar",
"February": "Februar",
"March": "März",
"April": "April",
"May": "Mai",
"June": "Juni",
"July": "Juli",
"August": "August",
"September": "September",
"October": "Oktober",
"November": "November",
"December": "Dezember",
"Jan_Abbr": "Jan",
"Feb_Abbr": "Feb",
"Mar_Abbr": "Mrz",
"Apr_Abbr": "Apr",
"May_Abbr": "Mai",
"Jun_Abbr": "Jun",
"Jul_Abbr": "Jul",
"Aug_Abbr": "Aug",
"Sep_Abbr": "Sep",
"Oct_Abbr": "Okt",
"Nov_Abbr": "Nov",
"Dec_Abbr": "Dez",
"AM": "",
"PM": "",
"firstDayOfWeek": 1,
"twoDigitYearMax": 2029,
"mdy": "dmy",
"M/d/yyyy": "dd.MM.yyyy",
"dddd, MMMM dd, yyyy": "dddd, d. MMMM yyyy",
"h:mm tt": "HH:mm",
"h:mm:ss tt": "HH:mm:ss",
"dddd, MMMM dd, yyyy h:mm:ss tt": "dddd, d. MMMM yyyy HH:mm:ss",
"yyyy-MM-ddTHH:mm:ss": "yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-dd HH:mm:ssZ": "yyyy-MM-dd HH:mm:ssZ",
"ddd, dd MMM yyyy HH:mm:ss": "ddd, dd MMM yyyy HH:mm:ss",
"MMMM dd": "dd MMMM",
"MMMM, yyyy": "MMMM yyyy",
"/jan(uary)?/": "jan(uar)?",
"/feb(ruary)?/": "feb(ruar)?",
"/mar(ch)?/": "märz",
"/apr(il)?/": "apr(il)?",
"/may/": "mai",
"/jun(e)?/": "jun(i)?",
"/jul(y)?/": "jul(i)?",
"/aug(ust)?/": "aug(ust)?",
"/sep(t(ember)?)?/": "sep(t(ember)?)?",
"/oct(ober)?/": "okt(ober)?",
"/nov(ember)?/": "nov(ember)?",
"/dec(ember)?/": "dez(ember)?",
"/^su(n(day)?)?/": "^sonntag",
"/^mo(n(day)?)?/": "^montag",
"/^tu(e(s(day)?)?)?/": "^dienstag",
"/^we(d(nesday)?)?/": "^mittwoch",
"/^th(u(r(s(day)?)?)?)?/": "^donnerstag",
"/^fr(i(day)?)?/": "^freitag",
"/^sa(t(urday)?)?/": "^samstag",
"/^next/": "^nächste(r|s|n)?",
"/^last|past|prev(ious)?/": "^letzte(r|s|n)?|vergangene(r|s|n)?|vorherige(r|s|n)?",
"/^(\\+|aft(er)?|from|hence)/": "^(\\+|(da)?nach(er)?|von|daher|in)",
"/^(\\-|bef(ore)?|ago)/": "^(\\-|(be|zu)?vor|früher)",
"/^yes(terday)?/": "^gestern",
"/^t(od(ay)?)?/": "^heute",
"/^tom(orrow)?/": "^morgen",
"/^n(ow)?/": "^jetzt|sofort|gleich",
"/^ms|milli(second)?s?/": "^ms|milli(sekunde(n)?)?",
"/^sec(ond)?s?/": "^sek(unde(n)?)?",
"/^mn|min(ute)?s?/": "^mn|min(ute(n)?)?",
"/^h(our)?s?/": "^h|st(d|unde(n)?)?",
"/^w(eek)?s?/": "^w(oche(n)?)?",
"/^m(onth)?s?/": "^m(onat(e)?)?",
"/^d(ay)?s?/": "^d|t(ag(en)?)?",
"/^y(ear)?s?/": "^y|j(ahr(en)?)?",
"/^(a|p)/": "^(a|p)",
"/^(a\\.?m?\\.?|p\\.?m?\\.?)/": "^(a\\.?m?\\.?|p\\.?m?\\.?)",
"/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/": "^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)",
"/^\\s*(st|nd|rd|th)/": "^\\s*(st|nd|rd|th)",
"/^\\s*(\\:|a(?!u|p)|p)/": "^\\s*(\\:|a(?!u|p)|p)",
"LINT": "LINT",
"TOT": "TOT",
"CHAST": "CHAST",
"NZST": "NZST",
"NFT": "NFT",
"SBT": "SBT",
"AEST": "AEST",
"ACST": "ACST",
"JST": "JST",
"CWST": "CWST",
"CT": "CT",
"ICT": "ICT",
"MMT": "MMT",
"BIOT": "BST",
"NPT": "NPT",
"IST": "IST",
"PKT": "PKT",
"AFT": "AFT",
"MSK": "MSK",
"IRST": "IRST",
"FET": "FET",
"EET": "EET",
"CET": "CET",
"UTC": "UTC",
"GMT": "GMT",
"CVT": "CVT",
"GST": "GST",
"BRT": "BRT",
"NST": "NST",
"AST": "AST",
"EST": "EST",
"CST": "CST",
"MST": "MST",
"PST": "PST",
"AKST": "AKST",
"MIT": "MIT",
"HST": "HST",
"SST": "SST",
"BIT": "BIT",
"CHADT": "CHADT",
"NZDT": "NZDT",
"AEDT": "AEDT",
"ACDT": "ACDT",
"AZST": "AZST",
"IRDT": "IRDT",
"EEST": "EEST",
"CEST": "CEST",
"BST": "BST",
"PMDT": "PMDT",
"ADT": "ADT",
"NDT": "NDT",
"EDT": "EDT",
"CDT": "CDT",
"MDT": "MDT",
"PDT": "PDT",
"AKDT": "AKDT",
"HADT": "HADT"
};
Date.CultureStrings.lang = "de-LU";
|
var url_util = require('url');
var common = require("./url_common.js");
exports._constructUrl = function (url, query, params) {
var url_parts = url_util.parse(url);
return common.buildUrl(
url_parts.protocol + "//" + url_parts.host + url_parts.pathname,
url_parts.search,
query,
params
);
};
exports._encodeParams = common._encodeParams;
|
var baseInvoke = require('./_baseInvoke'),
rest = require('./rest');
/**
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
*/
var invoke = rest(baseInvoke);
module.exports = invoke;
|
/*global angular */
'use strict';
var angular = require('angular');
var angularMocks = require('angular-mocks');
// var angular = require('angular');
var localisationService = require('../../../src/app/services/localisationService');
describe('Unit: LocalisationService', function() {
var service;
beforeEach(function() {
// instantiate the app module
angular.mock.module('myTestApp');
// mock the service
angular.mock.inject(function(LocalisationService) {
service = LocalisationService;
});
});
it('Service is defined', function () {
expect(service).toBeDefined();
});
it('init() method is type of function', function () {
expect(typeof service.init).toBe('function');
});
it('localise() method is type of function', function () {
expect(typeof service.localise).toBe('function');
});
it('test en-US locale', function () {
service.init('en-US').then(function () {
expect(service.localise('localeTestGreeting', { name: 'Brad' })).toEqual('Hey Brad');
});
});
it('test en-GB locale', function () {
service.init('en-GB').then(function () {
expect(service.localise('localeTestGreeting', { name: 'Timothy' })).toEqual('Hello Timothy');
});
});
});
|
export function getNewVersion() {
return require('../../package.json').version;
}
|
var Player = function (game, x, y) {
Phaser.Sprite.call(this, game, x, y, 'testsprite');
game.add.existing(this);
}
Player.prototype = Object.create(Phaser.Sprite.prototype);
Player.prototype.constructor = Player;
/**
* Automatically called by World.update
*/
Player.prototype.update = function() {
};
module.exports = Player;
|
module.exports = {
description: 'handles call of aliased external function (#957)',
warnings() {},
context: {
require(id) {
if (id === 'foo') {
return () => 42;
}
}
}
};
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const EditorFormatIndentIncrease = (props) => (
<SvgIcon {...props}>
<path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/>
</SvgIcon>
);
EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease';
EditorFormatIndentIncrease.muiName = 'SvgIcon';
export default EditorFormatIndentIncrease;
|
/* globals module require */
module.exports = require("./data-loader");
|
define(
"gridx/nls/kk/PaginationBar", ({
pagerWai: 'Пейджер',
pageIndex: '${0}',
pageIndexTitle: '${0}-бет',
firstPageTitle: 'Бірінші бет',
prevPageTitle: 'Алдыңғы бет',
nextPageTitle: 'Келесі бет',
lastPageTitle: 'Соңғы бет',
pageSize: '${0}',
pageSizeTitle: 'Бетіне ${0} элемент',
pageSizeAll: 'Барлығы',
pageSizeAllTitle: 'Барлық элементтер',
description: '${0} - ${2} элементтің ${1} элементі.',
descriptionEmpty: 'Тор – бос.',
// OneUI blueprint
summary: 'Барлығы: ${0}',
summaryWithSelection: 'Барлығы: ${0} Таңдалды: ${1}',
gotoBtnTitle: 'Белгілі бір бетке өту',
gotoDialogTitle: 'Бетке өту',
gotoDialogMainMsg: 'Бет санын көрсетіңіз:',
gotoDialogPageCount: ' (${0} бет)',
gotoDialogOKBtn: 'Өту',
gotoDialogCancelBtn: 'Болдырмау',
// for drop down pagination bar
pageLabel: 'Бет',
pageSizeLabel: 'Жолдар'
})
);
|
module("Script Value", {
setup : function() {
stop();
var that = this;
this.cb = function(e) {
ok(true, "Scene loaded");
that.doc = document.getElementById("xml3dframe").contentDocument;
start();
};
loadDocument("scenes/script-value.xhtml"+window.location.search, this.cb);
},
teardown : function() {
var v = document.getElementById("xml3dframe");
v.removeEventListener("load", this.cb, true);
}
});
test("Set script value attached to document", function() {
var posValue = this.doc.getElementById("posValue"),
sizeValue = this.doc.getElementById("pointSize"),
dataElement = this.doc.getElementById("pointData"),
originalContent = "0 -1 0 1 0 0";
equal(posValue.textContent, originalContent, "Position has correct text content");
var result = dataElement.getResult();
QUnit.closeArray(result.getValue("position"), new Float32Array(originalContent.split(/\s+/)),
EPSILON, "Position has correct Xflow result");
var newPos = new Float32Array([0,0,0, 1, 1, 1]);
posValue.setScriptValue(newPos);
equal(posValue.textContent, "[value set by script]", "Position has correct text content after setScriptValue()");
result = dataElement.getResult();
QUnit.closeArray(result.getValue("position"), newPos,
EPSILON, "Position has correct Xflow result after setScriptValue()");
newPos[1] = 2;
posValue.setScriptValue(newPos);
equal(posValue.textContent, "[value set by script]", "Position has correct text content after setScriptValue() #2");
result = dataElement.getResult();
QUnit.closeArray(result.getValue("position"), newPos,
EPSILON, "Position has correct Xflow result after setScriptValue() #2");
var newSize = new Float32Array([1.0]);
sizeValue.setScriptValue(newSize);
equal(sizeValue.textContent, "[value set by script]", "PointSize has correct text content after setScriptValue()");
result = dataElement.getResult();
QUnit.closeArray(result.getValue("pointSize"), newSize,
EPSILON, "PointSize has correct Xflow result after setScriptValue()");
posValue.textContent = originalContent;
equal(posValue.textContent, originalContent, "Position has correct text content after undoing changes");
var result = dataElement.getResult();
QUnit.closeArray(result.getValue("position"), new Float32Array(originalContent.split(/\s+/)),
EPSILON, "Position has correct Xflow result after undoing changes");
});
test("Set script value detached from document", function() {
var colorValue = this.doc.createElementNS(XML3D.xml3dNS, "float3"),
dataElement = this.doc.getElementById("pointData");
var colorArray = new Float32Array([1,0,0, 0,0,1]);
colorValue.name = "color";
colorValue.setScriptValue(colorArray);
dataElement.appendChild(colorValue);
equal(colorValue.textContent, "[value set by script]", "Color has correct text content");
var result = dataElement.getResult();
QUnit.closeArray(result.getValue("color"), colorArray,
EPSILON, "Color has correct Xflow result");
dataElement.removeChild(colorValue);
equal(colorValue.textContent, "[value set by script]", "Color has correct text content after removal");
var result = dataElement.getResult();
equal(result.getValue("color"), null, EPSILON, "Color has correct Xflow result after removal");
dataElement.appendChild(colorValue);
equal(colorValue.textContent, "[value set by script]", "Color has correct text content after readding");
var result = dataElement.getResult();
QUnit.closeArray(result.getValue("color"), colorArray,
EPSILON, "Color has correct Xflow result after readding");
dataElement.removeChild(colorValue);
var colorTextValue = "1 1 0 0 1 1";
colorValue.textContent = colorTextValue;
dataElement.appendChild(colorValue);
var result = dataElement.getResult();
QUnit.closeArray(result.getValue("color"), new Float32Array(colorTextValue.split(/\s+/)),
EPSILON, "Color has correct Xflow result after readding #2");
});
|
define(['jquery', 'underscore', './filter/segment-filter', './segment-choice', 'jquery-ui'],
function($, _, SegmentFilter) {
'use strict';
/**
* Apply segment widget
*/
$.widget('orosegment.segmentCondition', {
options: {
segmentChoice: {},
segmentChoiceClass: 'select',
filters: [],
filterContainerClass: 'active-filter'
},
_create: function() {
var data = this.element.data('value');
this.$segmentChoice = $('<input>').addClass(this.options.segmentChoiceClass);
this.$filterContainer = $('<span>').addClass(this.options.filterContainerClass);
this.element.append(this.$segmentChoice, this.$filterContainer);
this.$segmentChoice.segmentChoice(this.options.segmentChoice);
if (data && data.columnName) {
this.selectSegment(data);
this._renderFilter(data.columnName);
}
this.$segmentChoice.on('changed', _.bind(function(e, filterId) {
$(':focus').blur();
// reset current value on segment change
this.element.data('value', {});
this._renderFilter(filterId);
e.stopPropagation();
}, this));
this.$filterContainer.on('change', _.bind(function() {
if (this.filter) {
this.filter.applyValue();
}
}, this));
},
_getCreateOptions: function() {
return $.extend(true, {}, this.options);
},
_renderFilter: function(fieldId) {
var segmentId = fieldId.split('_')[1];
var filterId = this._getSegmentFilterId();
var data = this.element.find('input.select').inputWidget('data');
if (_.has(data, 'id')) {
data.value = segmentId;
// pre-set data
this.element.data('value', {
criterion: {
filter: 'segment',
data: data
}
});
}
var options = this.options.filters[filterId];
this._createFilter(options);
},
/**
* Find filter in metadata array and return it's index there
*
* @returns {*}
* @private
*/
_getSegmentFilterId: function() {
var filterId = null;
_.each(this.options.filters, function(filter, id) {
if ('segment' === filter.name) {
filterId = id;
}
});
return filterId;
},
/**
* Creates filter instance
*
* @param options {Object}
* @private
*/
_createFilter: function(options) {
var filter = new (SegmentFilter.extend(options))();
this._appendFilter(filter);
},
_appendFilter: function(filter) {
var value = this.element.data('value');
this.filter = filter;
if (value && value.criterion) {
this.filter.value = value.criterion.data;
}
this.filter.render(this.$segmentChoice);
this.$filterContainer.empty().append(this.filter.$el);
this.filter.on('update', _.bind(this._onUpdate, this));
this._onUpdate();
},
_onUpdate: function() {
var value;
if (!this.filter.isEmptyValue()) {
value = {
columnName: this.filter.entity_ids[this.$segmentChoice.data('entity')],
criteria: 'condition-segment',
criterion: {
filter: this.filter.name,
data: this.filter.getValue()
}
};
} else {
value = {};
}
this.element.data('value', value);
this.element.trigger('changed');
},
selectSegment: function(data) {
this.$segmentChoice.segmentChoice('setValue', data.columnName);
}
});
return $;
});
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* Describes network resource usage.
*
*/
class Usage {
/**
* Create a Usage.
* @member {string} [id] Resource identifier.
* @member {number} currentValue The current value of the usage.
* @member {number} limit The limit of usage.
* @member {object} name The name of the type of usage.
* @member {string} [name.value] A string describing the resource name.
* @member {string} [name.localizedValue] A localized string describing the
* resource name.
*/
constructor() {
}
/**
* Defines the metadata of Usage
*
* @returns {object} metadata of Usage
*
*/
mapper() {
return {
required: false,
serializedName: 'Usage',
type: {
name: 'Composite',
className: 'Usage',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
unit: {
required: true,
isConstant: true,
serializedName: 'unit',
defaultValue: 'Count',
type: {
name: 'String'
}
},
currentValue: {
required: true,
serializedName: 'currentValue',
type: {
name: 'Number'
}
},
limit: {
required: true,
serializedName: 'limit',
type: {
name: 'Number'
}
},
name: {
required: true,
serializedName: 'name',
type: {
name: 'Composite',
className: 'UsageName'
}
}
}
}
};
}
}
module.exports = Usage;
|
module.exports = {
plugins: [
require('autoprefixer')({
browsers: [
'last 3 version',
'ie >= 10',
'safari 5'
],
})
]
};
|
/*------------------------------------*\
ABOUT
\*------------------------------------*/
/* jslint node: true */
/**
* @fileOverview Progressive realtime web framework config-driven or API-driven for building easily serverless files, websites and webapps component-based and service-oriented.
* @author {@link https://www.lesieur.name/ Bruno Lesieur}
* @license {@link https://raw.githubusercontent.com/Haeresis/NodeAtlas/master/LICENSE GNU GENERAL PUBLIC LICENSE Version 2}
* @module node-atlas
* @requires {@link NA#modules.external:async}
* @requires {@link NA#modules.external:body-parser}
* @requires {@link NA#modules.external:clean-css}
* @requires {@link NA#modules.external:commander}
* @requires {@link NA#modules.external:compression}
* @requires {@link NA#modules.external:cookie-parser}
* @requires {@link NA#modules.external:css-parse}
* @requires {@link NA#modules.external:ejs}
* @requires {@link NA#modules.external:express}
* @requires {@link NA#modules.external:express-session}
* @requires {@link NA#modules.external:extend}
* @requires {@link NA#modules.external:jsdom}
* @requires {@link NA#modules.external:less}
* @requires {@link NA#modules.external:less-middleware}
* @requires {@link NA#modules.external:mkpath}
* @requires {@link NA#modules.external:open}
* @requires {@link NA#modules.external:pug}
* @requires {@link NA#modules.external:socketio}
* @requires {@link NA#modules.external:stylus}
* @requires {@link NA#modules.external:copy-dir}
* @requires {@link NA#modules.external:uglify-js}
*/
/*------------------------------------*\
ALIAS
\*------------------------------------*/
var NA = require("./bin/node-atlas.js");
/* Run script with CLI. */
if (require.main === module) {
/* Expose the NA object for isomorphism */
global.NA = new NA();
global.NA.start();
}
/* Run script with require as an API. */
module.exports = NA;
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'indent', 'cs', {
indent: 'Zvětšit odsazení',
outdent: 'Zmenšit odsazení'
} );
|
// import("store.js")
|
//>>built
define("dojox/editor/plugins/nls/sv/InsertEntity",({insertEntity:"Infoga symbol"}));
|
define("dojox/sketch", [
"dojo/_base/kernel",
"dojo/_base/lang",
"./xml/DomParser",
"./sketch/UndoStack",
"./sketch/Figure",
"./sketch/Toolbar"
], function(dojo){
dojo.getObject("sketch", true, dojox);
/*=====
return {
// summary:
// Deprecated. Should require dojox/sketch modules directly rather than trying to access them through
// this module.
};
=====*/
return dojox.sketch;
});
|
(function ($) {
"use strict";
/**
* Auto-hide summary textarea if empty and show hide and unhide links.
*/
Drupal.behaviors.textSummary = {
attach: function (context, settings) {
$(context).find('.text-summary').once('text-summary', function () {
var $widget = $(this).closest('.text-format-wrapper');
var $summary = $widget.find('.text-summary-wrapper');
var $summaryLabel = $summary.find('label');
var $full = $widget.find('.text-full').closest('.form-item');
var $fullLabel = $full.find('label');
// Create a placeholder label when the field cardinality is greater
// than 1.
if ($fullLabel.length === 0) {
$fullLabel = $('<label></label>').prependTo($full);
}
// Set up the edit/hide summary link.
var $link = $('<span class="field-edit-link">(<a class="link-edit-summary" href="#nogo">' + Drupal.t('Hide summary') + '</a>)</span>');
var $a = $link.find('a');
$link.toggle(
function (e) {
e.preventDefault();
$summary.hide();
$a.html(Drupal.t('Edit summary'));
$link.appendTo($fullLabel);
},
function (e) {
e.preventDefault();
$summary.show();
$a.html(Drupal.t('Hide summary'));
$link.appendTo($summaryLabel);
}
).appendTo($summaryLabel);
// If no summary is set, hide the summary field.
if ($widget.find('.text-summary').val() === '') {
$link.click();
}
});
}
};
})(jQuery);
|
tinyMCE.addI18n('fi.advlink_dlg',{
title:"Lis\u00E4\u00E4/muokkaa linkki\u00E4",
url:"Linkin URL",
target:"Kohde (target)",
titlefield:"Otsikko",
is_email:"Sy\u00F6tt\u00E4m\u00E4si URL n\u00E4ytt\u00E4\u00E4 olevan s\u00E4hk\u00F6postiosoite, haluatko lis\u00E4t\u00E4 mailto: etuliitteen?",
is_external:"Sy\u00F6tt\u00E4m\u00E4si URL n\u00E4ytt\u00E4\u00E4 olevan sivuston ulkoinen osoite, haluatko lis\u00E4t\u00E4 http:// etuliitteen?",
list:"Linkkilista",
general_tab:"Yleiset",
popup_tab:"Ponnahdusikkuna",
events_tab:"Tapahtumat",
advanced_tab:"Edistynyt",
general_props:"Yleiset asetukset",
popup_props:"Ponnahdusikkunan asetukset",
event_props:"Tapahtumat (events)",
advanced_props:"Edistyneet asetukset",
popup_opts:"Valinta",
anchor_names:"Ankkurit",
target_same:"Avaa t\u00E4ss\u00E4 ikkunassa",
target_parent:"Avaa ylemm\u00E4ss\u00E4 ikkunassa",
target_top:"Avaa ylimm\u00E4ss\u00E4 ruudussa (korvaa kaikki ruudut)",
target_blank:"Avaa uudessa ikkunassa",
popup:"Javascript ponnahdusikkuna",
popup_url:"Ponnahdusikkunan URL",
popup_name:"Ikkunan nimi",
popup_return:"Lis\u00E4\u00E4 'return false'",
popup_scrollbars:"N\u00E4yt\u00E4 vierityspalkit",
popup_statusbar:"N\u00E4yt\u00E4 tilapalkki",
popup_toolbar:"N\u00E4yt\u00E4 ty\u00F6kalut",
popup_menubar:"N\u00E4yt\u00E4 valikkopalkki",
popup_location:"N\u00E4yt\u00E4 sijaintipalkki",
popup_resizable:"Tee ikkunan koko muokattavaksi",
popup_dependent:"Riippuvainen (vain Mozilla/Firefox)",
popup_size:"Koko",
popup_position:"Sijainti (X/Y)",
id:"Id",
style:"Tyyli",
classes:"Luokat",
target_name:"Kohteen nimi",
langdir:"Kielen suunta",
target_langcode:"Kohteen kieli",
langcode:"Kielen koodi",
encoding:"Kohteen merkist\u00F6koodaus",
mime:"Kohteen MIME-tyyppi",
rel:"Sivun suhde kohteeseen",
rev:"Kohteen suhde sivuun",
tabindex:"Tabindex",
accesskey:"Accesskey",
ltr:"Vasemmalta oikealle",
rtl:"Oikealta vasemmalle",
link_list:"Linkkilista"
});
|
define(
({
showArcgisBasemaps: "Inclure les fonds de carte du portail",
settings: "Paramètres",
add: "Cliquez pour ajouter un nouveau fond de carte",
edit: "Propriétés",
title: "Titre",
titlePH: "Titre du fond de carte",
thumbnail: "Miniature",
thumbnailHint: "Cliquez sur l’image pour la modifier",
url: "URL",
urlPH: "URL de la couche",
addlayer: "Ajouter un fond de carte",
actions: "Actions",
warning: "Entrée incorrecte",
save: "Retour et enregistrer",
back: "Retour et annuler",
addUrl: "Ajouter une URL",
autoCheck: "Vérification automatique",
checking: "Vérification...",
ok: "OK",
cancel: "Annuler",
result: "Enregistrement réussi",
spError: "Tous les fonds de carte ajoutés à la bibliothèque requièrent les mêmes références spatiales.",
invalidTitle1:"Un fond de carte nommé '",
invalidTitle2:"' existe déjà. Choisissez un autre titre.",
invalidBasemapUrl1: "Ce type de couche ne peut pas être utilisé comme fond de carte.",
invalidBasemapUrl2: "Référence spatiale différente de la carte actuelle.",
addBaselayer: "Ajouter une couche de fonds de carte"
})
);
|
var searchData=
[
['tealeaf_5fcanvas_5ft',['tealeaf_canvas_t',['../structtealeaf__canvas__t.html',1,'']]],
['texture_5f2d_5ft',['texture_2d_t',['../structtexture__2d__t.html',1,'']]],
['texture_5fmanager_5ft',['texture_manager_t',['../structtexture__manager__t.html',1,'']]]
];
|
var ControlMultipleBaseItemView = require( 'elementor-views/controls/base-multiple' ),
ControlOrderItemView;
ControlOrderItemView = ControlMultipleBaseItemView.extend( {
ui: function() {
var ui = ControlMultipleBaseItemView.prototype.ui.apply( this, arguments );
ui.reverseOrderLabel = '.elementor-control-order-label';
return ui;
},
changeLabelTitle: function() {
var reverseOrder = this.getControlValue( 'reverse_order' );
this.ui.reverseOrderLabel.attr( 'title', elementor.translate( reverseOrder ? 'asc' : 'desc' ) );
},
onRender: function() {
ControlMultipleBaseItemView.prototype.onRender.apply( this, arguments );
this.changeLabelTitle();
},
onInputChange: function() {
this.changeLabelTitle();
}
} );
module.exports = ControlOrderItemView;
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Components } from "@reactioncommerce/reaction-components";
import { formatPriceString } from "/client/api";
class ProductGridItems extends Component {
static propTypes = {
additionalMedia: PropTypes.func,
canEdit: PropTypes.bool,
connectDragSource: PropTypes.func,
connectDropTarget: PropTypes.func,
displayPrice: PropTypes.func,
isMediumWeight: PropTypes.func,
isSearch: PropTypes.bool,
isSelected: PropTypes.func,
media: PropTypes.func,
onClick: PropTypes.func,
onDoubleClick: PropTypes.func,
pdpPath: PropTypes.func,
positions: PropTypes.func,
product: PropTypes.object,
weightClass: PropTypes.func
}
handleDoubleClick = (event) => {
if (this.props.onDoubleClick) {
this.props.onDoubleClick(event);
}
}
handleClick = (event) => {
if (this.props.onClick) {
this.props.onClick(event);
}
}
renderPinned() {
return this.props.positions().pinned ? "pinned" : "";
}
renderVisible() {
return this.props.product.isVisible ? "" : "not-visible";
}
renderOverlay() {
if (this.props.product.isVisible === false) {
return (
<div className="product-grid-overlay" />
);
}
}
renderMedia() {
if (this.props.media() === false) {
return (
<span className="product-image" style={{ backgroundImage: "url('/resources/placeholder.gif')" }} />
);
}
return (
<span className="product-image" style={{ backgroundImage: `url('${this.props.media().url({ store: "large" })}')` }}/>
);
}
renderAdditionalMedia() {
if (this.props.additionalMedia() !== false) {
if (this.props.isMediumWeight()) {
return (
<div className={`product-additional-images ${this.renderVisible()}`}>
{this.props.additionalMedia().map((media) => {
return <span key={media._id} className="product-image" style={{ backgroundImage: `url('${media.url({ store: "medium" })}')` }} />;
})}
{this.renderOverlay()}
</div>
);
}
}
}
renderNotices() {
return (
<div className="grid-alerts">
<Components.GridItemNotice product={this.props.product} />
<Components.GridItemControls product={this.props.product} />
</div>
);
}
renderGridContent() {
return (
<div className="grid-content">
<a
href={this.props.pdpPath()}
data-event-category="grid"
data-event-action="product-click"
data-event-label="grid product click"
data-event-value={this.props.product._id}
onDoubleClick={this.handleDoubleClick}
onClick={this.handleClick}
>
<div className="overlay">
<div className="overlay-title">{this.props.product.title}</div>
<div className="currency-symbol">{formatPriceString(this.props.displayPrice())}</div>
{this.props.isSearch &&
<div className="overlay-description">{this.props.product.description}</div>
}
</div>
</a>
</div>
);
}
renderHoverClassName() {
return this.props.isSearch ? "item-content" : "";
}
render() {
const productItem = (
<li
className={`product-grid-item ${this.renderPinned()} ${this.props.weightClass()} ${this.props.isSelected()}`}
data-id={this.props.product._id}
id={this.props.product._id}
>
<div className={this.renderHoverClassName()}>
<span className="product-grid-item-alerts" />
<a className="product-grid-item-images"
href={this.props.pdpPath()}
data-event-category="grid"
data-event-label="grid product click"
data-event-value={this.props.product._id}
onDoubleClick={this.handleDoubleClick}
onClick={this.handleClick}
>
<div className={`product-primary-images ${this.renderVisible()}`}>
{this.renderMedia()}
{this.renderOverlay()}
</div>
{this.renderAdditionalMedia()}
</a>
{!this.props.isSearch && this.renderNotices()}
{this.renderGridContent()}
</div>
</li>
);
if (this.props.canEdit) {
return (
this.props.connectDropTarget(
this.props.connectDragSource(productItem)
)
);
}
return productItem;
}
}
export default ProductGridItems;
|
'use strict';
var db = require('../../database');
module.exports = {
name: 'Update registration type',
timestamp: Date.UTC(2019, 5, 4),
method: function (callback) {
const meta = require('../../meta');
const registrationType = meta.config.registrationType || 'normal';
if (registrationType === 'admin-approval' || registrationType === 'admin-approval-ip') {
db.setObject('config', {
registrationType: 'normal',
registrationApprovalType: registrationType,
}, callback);
} else {
setImmediate(callback);
}
},
};
|
/**
* @typedef {import('../types.js').MdastListContent} MdastListContent
*/
/**
* @param {Array.<MdastListContent>} children
* @returns {boolean}
*/
export function listItemsSpread(children) {
let index = -1
if (children.length > 1) {
while (++index < children.length) {
if (children[index].spread) {
return true
}
}
}
return false
}
|
$(function() {
$('input#email').focus();
$('.select2').select2();
$('.date').mask('99/99/9999');
$('#cpf').mask('999.999.999-99');
$('#telefone').mask('(99) 9999-9999');
$('#criar_pessoa').parsley().subscribe('parsley:form:validated', function (formInstance) {
if (formInstance.isValid()) {
$('#submit').val(_('Sending...')).addClass('disabled');
}
});
});
|
erpnext.setup_auto_gst_taxation = (doctype) => {
frappe.ui.form.on(doctype, {
company_address: function(frm) {
frm.trigger('get_tax_template');
},
shipping_address: function(frm) {
frm.trigger('get_tax_template');
},
tax_category: function(frm) {
frm.trigger('get_tax_template');
},
get_tax_template: function(frm) {
let party_details = {
'shipping_address': frm.doc.shipping_address || '',
'shipping_address_name': frm.doc.shipping_address_name || '',
'customer_address': frm.doc.customer_address || '',
'customer': frm.doc.customer,
'supplier': frm.doc.supplier,
'supplier_gstin': frm.doc.supplier_gstin,
'company_gstin': frm.doc.company_gstin,
'tax_category': frm.doc.tax_category
};
frappe.call({
method: 'erpnext.regional.india.utils.get_regional_address_details',
args: {
party_details: JSON.stringify(party_details),
doctype: frm.doc.doctype,
company: frm.doc.company,
return_taxes: 1
},
callback: function(r) {
if(r.message) {
frm.set_value('taxes_and_charges', r.message.taxes_and_charges);
}
}
});
}
});
};
|
var trusted = [
'52.16.188.185',
'54.94.239.50',
'54.174.74.156',
'54.172.25.93',
'54.174.75.126',
'54.173.232.137',
'52.7.205.180',
'52.7.218.44',
'52.7.205.152',
'52.7.224.174',
'92.51.165.126',
'84.117.82.122',
'73.40.58.88',
'178.19.221.38',
'185.37.145.18',
'172.31.39.87',
'86.120.171.69',
'86.123.155.6',
'188.24.81.133',
'::ffff:127.0.0.1',
];
var banned = [
// '198.48.150.206'
];
module.exports = {
trusted: trusted,
banned: banned
};
|
/**
* Rule the words! KKuTu Online
* Copyright (C) 2017 JJoriping(op@jjo.kr)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var MODE;
var BEAT = [ null,
"10000000",
"10001000",
"10010010",
"10011010",
"11011010",
"11011110",
"11011111",
"11111111"
];
var NULL_USER = {
profile: { title: L['null'] },
data: { score: 0 }
};
var MOREMI_PART;
var AVAIL_EQUIP;
var RULE;
var OPTIONS;
var MAX_LEVEL = 360;
var TICK = 30;
var EXP = [];
var BAD = new RegExp([ "느으*[^가-힣]*금마?", "니[^가-힣]*(엄|앰|엠)", "(ㅄ|ㅅㅂ|ㅂㅅ)", "미친(년|놈)?", "(병|븅|빙)[^가-힣]*신", "보[^가-힣]*지", "(새|섀|쌔|썌)[^가-힣]*(기|끼)", "섹[^가-힣]*스", "(시|씨|쉬|쒸)이*입?[^가-힣]*(발|빨|벌|뻘|팔|펄)", "십[^가-힣]*새", "씹", "(애|에)[^가-힣]*미", "자[^가-힣]*지", "존[^가-힣]*나", "좆|죶", "지랄", "창[^가-힣]*(녀|년|놈)", "fuck", "sex" ].join('|'), "g");
var ws, rws;
var $stage;
var $sound = {};
var $_sound = {}; // 현재 재생 중인 것들
var $data = {};
var $lib = { Classic: {}, Jaqwi: {}, Crossword: {}, Typing: {}, Hunmin: {}, Daneo: {}, Sock: {} };
var $rec;
var mobile;
var audioContext = window.hasOwnProperty("AudioContext") ? (new AudioContext()) : false;
var _WebSocket = window['WebSocket'];
var _setInterval = setInterval;
var _setTimeout = setTimeout;
|
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/*
* Implementation of the JAIN-SIP Authorization .
* @see gov/nist/javax/sip/header/Authorization.java
* @author Yuemin Qin (yuemin.qin@orange.com)
* @author Laurent STRULLU (laurent.strullu@orange.com)
* @version 1.0
*/
function Authorization() {
if(logger!=undefined) logger.debug("Authorization:Authorization()");
this.classname="Authorization";
this.headerName=this.NAME;
this.parameters = new NameValueList();
this.duplicates = new DuplicateNameValueList();
this.parameters.setSeparator(this.COMMA);
this.scheme = this.DIGEST;
}
Authorization.prototype = new AuthenticationHeader();
Authorization.prototype.constructor=Authorization;
Authorization.prototype.NAME = "Authorization";
Authorization.prototype.COMMA = ",";
Authorization.prototype.DIGEST = "Digest";
|
import getObjectPool from 'consul-ui/utils/get-object-pool';
import { module, skip } from 'qunit';
import test from 'ember-sinon-qunit/test-support/test';
module('Unit | Utility | get object pool', function() {
skip('Decide what to do if you add 2 objects with the same id');
test('acquire adds objects', function(assert) {
const actual = [];
const expected = {
hi: 'there',
id: 'hi-there-123',
};
const expected2 = {
hi: 'there',
id: 'hi-there-456',
};
const pool = getObjectPool(function() {}, 10, actual);
pool.acquire(expected, expected.id);
assert.deepEqual(actual[0], expected);
pool.acquire(expected2, expected2.id);
assert.deepEqual(actual[1], expected2);
});
test('acquire adds objects and returns the id', function(assert) {
const arr = [];
const expected = 'hi-there-123';
const obj = {
hi: 'there',
id: expected,
};
const pool = getObjectPool(function() {}, 10, arr);
const actual = pool.acquire(obj, expected);
assert.equal(actual, expected);
});
test('acquire adds objects, and disposes when there is no room', function(assert) {
const actual = [];
const expected = {
hi: 'there',
id: 'hi-there-123',
};
const expected2 = {
hi: 'there',
id: 'hi-there-456',
};
const dispose = this.stub()
.withArgs(expected)
.returnsArg(0);
const pool = getObjectPool(dispose, 1, actual);
pool.acquire(expected, expected.id);
assert.deepEqual(actual[0], expected);
pool.acquire(expected2, expected2.id);
assert.deepEqual(actual[0], expected2);
assert.ok(dispose.calledOnce);
});
test('it disposes', function(assert) {
const arr = [];
const expected = {
hi: 'there',
id: 'hi-there-123',
};
const expected2 = {
hi: 'there',
id: 'hi-there-456',
};
const dispose = this.stub().returnsArg(0);
const pool = getObjectPool(dispose, 2, arr);
const id = pool.acquire(expected, expected.id);
assert.deepEqual(arr[0], expected);
pool.acquire(expected2, expected2.id);
assert.deepEqual(arr[1], expected2);
const actual = pool.dispose(id);
assert.ok(dispose.calledOnce);
assert.equal(arr.length, 1, 'object was removed from array');
assert.deepEqual(actual, expected, 'returned object is expected object');
assert.deepEqual(arr[0], expected2, 'object in the pool is expected object');
});
test('it purges', function(assert) {
const arr = [];
const expected = {
hi: 'there',
id: 'hi-there-123',
};
const expected2 = {
hi: 'there',
id: 'hi-there-456',
};
const dispose = this.stub().returnsArg(0);
const pool = getObjectPool(dispose, 2, arr);
pool.acquire(expected, expected.id);
assert.deepEqual(arr[0], expected);
pool.acquire(expected2, expected2.id);
assert.deepEqual(arr[1], expected2);
const actual = pool.purge();
assert.ok(dispose.calledTwice, 'dispose was called on everything');
assert.equal(arr.length, 0, 'the pool is empty');
assert.deepEqual(actual[0], expected, 'the first purged object is correct');
assert.deepEqual(actual[1], expected2, 'the second purged object is correct');
});
});
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2015 Digi International Inc., All Rights Reserved.
*/
'use strict';
describe('Directive: gaugeWidget', function() {
beforeEach(module('XBeeGatewayApp'));
var scope, element, gaugeScope;
beforeEach(inject(function ($httpBackend) {
$httpBackend.whenGET("/api/devices/AAA/data").respond({items: []});
$httpBackend.expectGET("/api/devices/AAA/data");
}));
beforeEach(inject(function($rootScope, $compile) {
var outerscope = $rootScope.$new();
element = angular.element('<div gauge-widget="widget"></div>');
// Append the element to document.body, because Karma doesn't do that
// for us. The widget, or at least the div within the gauge directive
// template, needs to be present within the document in order for
// justGage to function properly.
$(element).appendTo(document.body);
outerscope.widget = {device: "AAA", id: 1, type: "gauge", gets: "DIO0"};
$compile(element)(outerscope);
outerscope.$apply();
// the gauge-widget directive creates a new isolate scope within
// outerscope - so we need to get a reference to it
scope = outerscope.$$childHead;
gaugeScope = angular.element($(element).find(".widget-gauge"))
.scope().$$childHead;
}));
it('should be able to find the gauge', function () {
expect(gaugeScope).not.toBeUndefined();
});
it('should have the correct widget in the scope', function() {
expect(scope.widget).toBeDefined();
expect(scope.widget.type).toBe("gauge");
expect(scope.widget.gets).toBe("DIO0");
});
it('should have correct gaugeScope parent (SCOPE OF TESTING)', function () {
expect(scope.$$childHead.$id).toBe(gaugeScope.$id);
});
it('should have the correct default starting value', function() {
expect(gaugeScope).toBeDefined();
expect(gaugeScope.value).toBe(undefined);
});
it('should have the gauge update correctly on update', function() {
scope.$apply(function () {
scope.value = 40;
});
expect(gaugeScope.value).toBe(40);
});
it("should not allow high value less than or equal to low value", inject(function (_widgetRegistry_, _utils_) {
// Sanity check for settings validation, and boosts code coverage.
var utils = _utils_;
var registry = _widgetRegistry_;
var defn = registry.get('gauge');
expect(defn).toBeDefined();
// utils.verify_widget should throw an error on a widget with high
// value <= low value
var widget = {
id: "a",
type: "gauge",
label: "Gauge",
device: "A",
radio: "B",
gets: "DIO0",
low: 100,
high: 99
};
var expectedError = new Error("(high) High value must be greater than low value");
expect(function () { utils.verify_widget(widget, defn); }).toThrow(expectedError);
}));
});
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//-----------------------------------------------------------------------------
var BUGNUMBER = 398485;
var summary = 'Date.prototype.toLocaleString should not clamp year';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var d;
var y;
var l;
var maxms = 8640000000000000;
d = new Date(-maxms );
y = d.getFullYear();
l = d.toLocaleString();
print(l);
actual = y;
expect = -271821;
reportCompare(expect, actual, summary + ': check year');
actual = l.match(new RegExp(y)) + '';
expect = y + '';
reportCompare(expect, actual, summary + ': check toLocaleString');
d = new Date(maxms );
y = d.getFullYear();
l = d.toLocaleString();
print(l);
actual = y;
expect = 275760;
reportCompare(expect, actual, summary + ': check year');
actual = l.match(new RegExp(y)) + '';
expect = y + '';
reportCompare(expect, actual, summary + ': check toLocaleString');
exitFunc ('test');
}
|
"use strict";
var NativeDragItemTypes = require("../constants/NativeDragItemTypes");
function isNativeDraggedItemType(itemType) {
switch (itemType) {
case NativeDragItemTypes.FILE:
case NativeDragItemTypes.URL:
return true;
default:
return false;
}
}
module.exports = isNativeDraggedItemType;
|
import { readOnly } from '@ember/object/computed';
import EmberObject, { computed } from '@ember/object';
import Ember from 'ember';
import ol from 'openlayers';
import geographicDistance from '../utils/geo-distance';
import getNextSmallerIndex from '../utils/next-smaller-index';
import computedPoint from '../computed/computed-point';
import safeComputed from '../computed/safe-computed';
let Fix = EmberObject.extend({
fixCalc: null,
_t: readOnly('fixCalc.time'),
t: computed('_t', 'flight.{startTime,endTime}', function() {
let _t = this._t;
if (_t === -1) {
return this.get('flight.endTime');
} else if (_t >= this.get('flight.startTime') && _t <= this.get('flight.endTime')) {
return _t;
}
}),
_index: safeComputed('t', 'flight.time', (t, time) => getNextSmallerIndex(time, t)),
t_prev: safeComputed('_index', 'flight.time', (index, time) => time[index]),
t_next: safeComputed('_index', 'flight.time', (index, time) => time[index + 1]),
time: readOnly('t_prev'),
coordinate: safeComputed('t', 'flight.geometry', (time, geometry) => geometry.getCoordinateAtM(time)),
lon: readOnly('coordinate.0'),
lat: readOnly('coordinate.1'),
'alt-msl': safeComputed('coordinate.2', 'flight.geoid', (altitude, geoid) => altitude - geoid),
'alt-gnd': safeComputed('alt-msl', 'elevation', (altitude, elevation) => {
let value = altitude - elevation;
return value >= 0 ? value : 0;
}),
point: computedPoint('coordinate'),
pointXY: computedPoint('coordinate', 'XY'),
heading: safeComputed('_coordinate_prev', '_coordinate_next', (prev, next) =>
Math.atan2(next[0] - prev[0], next[1] - prev[1]),
),
vario: safeComputed('_coordinate_prev.2', '_coordinate_next.2', '_dt', (prev, next, dt) => (next - prev) / dt),
speed: safeComputed('_coordinate_prev', '_coordinate_next', '_dt', (prev, next, dt) => {
let loc_prev = ol.proj.transform(prev, 'EPSG:3857', 'EPSG:4326');
let loc_next = ol.proj.transform(next, 'EPSG:3857', 'EPSG:4326');
return geographicDistance(loc_next, loc_prev) / dt;
}),
_dt: safeComputed('t_prev', 't_next', (prev, next) => next - prev),
_coordinate_prev: safeComputed('t_prev', 'flight.geometry', (time, geometry) => geometry.getCoordinateAtM(time)),
_coordinate_next: safeComputed('t_next', 'flight.geometry', (time, geometry) => geometry.getCoordinateAtM(time)),
elevation: safeComputed('flight.elev_h', '_elev_index', (elev_h, index) => elev_h[index]),
_elev_index: safeComputed('flight.elev_t', 't', (elev_t, t) => getNextSmallerIndex(elev_t, t)),
});
Fix[Ember.NAME_KEY] = 'Fix';
export default Fix;
|
/*# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################*/
openerp.pos_price_confirm = function (instance) {
var module = instance.point_of_sale;
var QWeb = instance.web.qweb;
var _t = instance.web._t;
module.RemoveLineConfirmPopupWidget = module.PopUpWidget.extend({
template: 'RemoveLineConfirmPopupWidget',
show: function(options){
var self = this;
this._super();
this.message = options.message || '';
this.renderElement();
this.$('.button.cancel').click(function(){
self.pos_widget.screen_selector.close_popup();
if( options.cancel ){
options.cancel.call(self);
}
});
this.$('.button.confirm').click(function(){
var login = self.$(".username")[0].value;
var password = self.$('.password')[0].value;
self.pos_widget.screen_selector.close_popup();
if( options.confirm ){
options.confirm.call(self, login, password);
}
});
},
});
module.PosWidget = module.PosWidget.extend({
// Overloaded method to add the new widget
build_widgets: function() {
this._super();
this.remove_line_confirm_popup = new module.RemoveLineConfirmPopupWidget(this, {});
this.remove_line_confirm_popup.appendTo($(this.$el));
this.screen_selector.popup_set['remove-line-confirm'] = this.remove_line_confirm_popup;
// Hide the popup
this.remove_line_confirm_popup.hide();
},
});
module.NumpadWidget = module.NumpadWidget.extend({
start: function() {
this._super();
this.authRemoveLine = false;
var self = this;
var user_model = new instance.web.Model('res.users');
user_model.call('has_group', ['pos_remove_line_confirm.group_pos_remove']).then(function(result) {
if (result) {
self.authRemoveLine = true;
} else {
self.authRemoveLine = false;
}
}, function(error, event){
event.preventDefault();
self.pos_widget.screen_selector.show_popup('error',{
'message':_t('Error: Could not check your permissions.'),
'comment':_t('Your Internet connection is probably down.'),
});
});
},
clickDeleteLastChar: function() {
var mode = this.state.get('mode');
if (mode == 'quantity') {
if (!this.authRemoveLine) {
var _super = this._super.bind(this);
var self = this;
self.pos.pos_widget.screen_selector.show_popup('remove-line-confirm', {
message: _t('Please authenticate as an authorized user.'),
confirm: function(login, password){
var user_model = new instance.web.Model('res.users');
user_model.call('pos_verify_remove_line', [login, password]).then(function(result) {
if (result == 'go') {
self.state.set({'buffer': ""})
return _super();
} else if (result == 'no-group') {
self.pos_widget.screen_selector.show_popup('error',{
'message':_t('Error: User permissions.'),
'comment':_t('The user is not able to remove lines.'),
});
} else {
self.pos_widget.screen_selector.show_popup('error',{
'message':_t('Error: Could not login.'),
'comment':_t('Your user or password is incorrect.'),
});
}
}, function(error, event){
event.preventDefault();
self.pos_widget.screen_selector.show_popup('error',{
'message':_t('Error: Could not verify the login.'),
'comment':_t('Your Internet connection is probably down.'),
});
});
},
});
return false;
} else {
return this._super();
}
}
else {
return this._super();
}
},
});
};
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import InnerHeader from 'flavours/glitch/features/account/components/header';
import ActionBar from 'flavours/glitch/features/account/components/action_bar';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import { NavLink } from 'react-router-dom';
import MovedNote from './moved_note';
export default class Header extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map,
identity_proofs: ImmutablePropTypes.list,
onFollow: PropTypes.func.isRequired,
onBlock: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
onDirect: PropTypes.func.isRequired,
onReblogToggle: PropTypes.func.isRequired,
onReport: PropTypes.func.isRequired,
onMute: PropTypes.func.isRequired,
onBlockDomain: PropTypes.func.isRequired,
onUnblockDomain: PropTypes.func.isRequired,
onEndorseToggle: PropTypes.func.isRequired,
onAddToList: PropTypes.func.isRequired,
hideTabs: PropTypes.bool,
domain: PropTypes.string.isRequired,
};
static contextTypes = {
router: PropTypes.object,
};
handleFollow = () => {
this.props.onFollow(this.props.account);
}
handleBlock = () => {
this.props.onBlock(this.props.account);
}
handleMention = () => {
this.props.onMention(this.props.account, this.context.router.history);
}
handleDirect = () => {
this.props.onDirect(this.props.account, this.context.router.history);
}
handleReport = () => {
this.props.onReport(this.props.account);
}
handleReblogToggle = () => {
this.props.onReblogToggle(this.props.account);
}
handleNotifyToggle = () => {
this.props.onNotifyToggle(this.props.account);
}
handleMute = () => {
this.props.onMute(this.props.account);
}
handleBlockDomain = () => {
const domain = this.props.account.get('acct').split('@')[1];
if (!domain) return;
this.props.onBlockDomain(domain);
}
handleUnblockDomain = () => {
const domain = this.props.account.get('acct').split('@')[1];
if (!domain) return;
this.props.onUnblockDomain(domain);
}
handleEndorseToggle = () => {
this.props.onEndorseToggle(this.props.account);
}
handleAddToList = () => {
this.props.onAddToList(this.props.account);
}
handleEditAccountNote = () => {
this.props.onEditAccountNote(this.props.account);
}
render () {
const { account, hideTabs, identity_proofs } = this.props;
if (account === null) {
return null;
}
return (
<div className='account-timeline__header'>
{account.get('moved') && <MovedNote from={account} to={account.get('moved')} />}
<InnerHeader
account={account}
identity_proofs={identity_proofs}
onFollow={this.handleFollow}
onBlock={this.handleBlock}
onMention={this.handleMention}
onDirect={this.handleDirect}
onReblogToggle={this.handleReblogToggle}
onNotifyToggle={this.handleNotifyToggle}
onReport={this.handleReport}
onMute={this.handleMute}
onBlockDomain={this.handleBlockDomain}
onUnblockDomain={this.handleUnblockDomain}
onEndorseToggle={this.handleEndorseToggle}
onAddToList={this.handleAddToList}
onEditAccountNote={this.handleEditAccountNote}
domain={this.props.domain}
/>
<ActionBar
account={account}
/>
{!hideTabs && (
<div className='account__section-headline'>
<NavLink exact to={`/@${account.get('acct')}`}><FormattedMessage id='account.posts' defaultMessage='Toots' /></NavLink>
<NavLink exact to={`/@${account.get('acct')}/with_replies`}><FormattedMessage id='account.posts_with_replies' defaultMessage='Toots with replies' /></NavLink>
<NavLink exact to={`/@${account.get('acct')}/media`}><FormattedMessage id='account.media' defaultMessage='Media' /></NavLink>
</div>
)}
</div>
);
}
}
|
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['panel-footer', 'field-group__toolbar'],
classNameBindings: ['collapsed:hidden']
});
|
define(function (require) {
'use strict';
var p5 = require('core');
var frames = [];
/**
* Save the current canvas as an image. In Safari, will open the
* image in the window and the user must provide their own
* filename on save-as. Other browsers will either save the
* file immediately, or prompt the user with a dialogue window.
*
* @param {[String]} filename
* @param {[String]} extension 'jpg' or 'png'
* @param {[Canvas]} canvas a variable representing a
* specific html5 canvas (optional).
*/
p5.prototype.saveCanvas = function(_cnv, filename, extension) {
if (!extension) {
extension = p5.prototype._checkFileExtension(filename, extension)[1];
if (extension === '') {
extension = 'png';
}
}
var cnv;
if (_cnv) {
cnv = _cnv;
} else if (this._curElement && this._curElement.elt) {
cnv = this._curElement.elt;
}
if ( p5.prototype._isSafari() ) {
var aText = 'Hello, Safari user!\n';
aText += 'Now capturing a screenshot...\n';
aText += 'To save this image,\n';
aText += 'go to File --> Save As.\n';
alert(aText);
window.location.href = cnv.toDataURL();
} else {
var mimeType;
if (typeof(extension) === 'undefined') {
extension = 'png';
mimeType = 'image/png';
}
else {
switch(extension){
case 'png':
mimeType = 'image/png';
break;
case 'jpeg':
mimeType = 'image/jpeg';
break;
case 'jpg':
mimeType = 'image/jpeg';
break;
default:
mimeType = 'image/png';
break;
}
}
var downloadMime = 'image/octet-stream';
var imageData = cnv.toDataURL(mimeType);
imageData = imageData.replace(mimeType, downloadMime);
p5.prototype.downloadFile(imageData, filename, extension);
}
};
/**
* Capture a sequence of frames that can be used to create a movie.
* Accepts a callback. For example, you may wish to send the frames
* to a server where they can be stored or converted into a movie.
* If no callback is provided, the browser will attempt to download
* all of the images that have just been created.
*
* @param {[type]} filename [description]
* @param {[type]} extension [description]
* @param {[type]} _duration [description]
* @param {[type]} _fps [description]
* @param {[Function]} callback [description]
* @return {[type]} [description]
*/
p5.prototype.saveFrames = function(fName, ext, _duration, _fps, callback) {
var duration = _duration || 3;
duration = p5.prototype.constrain(duration, 0, 15);
duration = duration * 1000;
var fps = _fps || 15;
fps = p5.prototype.constrain(fps, 0, 22);
var count = 0;
var makeFrame = p5.prototype._makeFrame;
var cnv = this._curElement.elt;
var frameFactory = setInterval(function(){
makeFrame(fName + count, ext, cnv);
count++;
},1000/fps);
setTimeout(function(){
clearInterval(frameFactory);
if (callback) {
callback(frames);
}
else {
for (var i = 0; i < frames.length; i++) {
var f = frames[i];
p5.prototype.downloadFile(f.imageData, f.filename, f.ext);
}
}
frames = []; // clear frames
}, duration + 0.01);
};
p5.prototype._makeFrame = function(filename, extension, _cnv) {
var cnv;
if (this) {
cnv = this._curElement.elt;
} else {
cnv = _cnv;
}
var mimeType;
if (!extension) {
extension = 'png';
mimeType = 'image/png';
}
else {
switch(extension.toLowerCase()){
case 'png':
mimeType = 'image/png';
break;
case 'jpeg':
mimeType = 'image/jpeg';
break;
case 'jpg':
mimeType = 'image/jpeg';
break;
default:
mimeType = 'image/png';
break;
}
}
var downloadMime = 'image/octet-stream';
var imageData = cnv.toDataURL(mimeType);
imageData = imageData.replace(mimeType, downloadMime);
var thisFrame = {};
thisFrame.imageData = imageData;
thisFrame.filename = filename;
thisFrame.ext = extension;
frames.push(thisFrame);
};
return p5;
});
|
exports.host = 'localhost'; // RethinkDB host
exports.port = 28015; // RethinkDB driver port
exports.authKey = ''; // Authentification key (leave an empty string if you did not set one)
exports.db = 'pascani'; // Database name
|
$(function() {
$("#txt_button").click(function() {
$(this).attr('disabled',true);
var data = $("#data").val();
if (!data)
return;
var url = 'api/create/txt?title=' + $("#title").val();
if (data.split(/\n/).length == 1) {
var reg = /(https?|ftp):\/\/[^\/?:]+(:[0-9]{1,5})?(\/?|(\/[^\/]+)*(\?[^\s"']+)?)/;
if (reg.test(data)) {
url = 'api/create/url';
data = {'data': data};
}
}
$.ajax({
"url" : url,
'data': data,
'type' : 'post',
'contentType' : 'text/plain',
"dataType" : "json",
success : function (j) {
$("#result").html("");
$("#progress").html("");
if (j.ok) {
if (j.url) {
window.location = j.url;
}
var url = location.protocol + "//" + location.host + location.pathname + 'c/' + j.code;
$("#result").append($("<div class='alert alert-success'><p>短地址: </p></div>").append($('<a target="_blank">' + url + '</a>').attr("href", url)));
$("#data").val("");
//qrcodeToggle("result", "显示短地址QR Code", "隐藏短地址QR Code");
} else {
$("#result").append($('<div class="alert alert-error">Oops</div>')).append($("<p></p>").text("ERROR: " + j.msg));
}
$("#txt_button").attr('disabled',false);
}});;
});
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target);
if (e.type == "dragover") {
target.addClass("hover");
} else {
target.removeClass("hover");
}
}
function FileSelectHandler(e) {
$("#progress").html("");
// cancel event and hover styling
FileDragHover(e);
var files = false;
if(e.originalEvent.dataTransfer){
if(e.originalEvent.dataTransfer.files.length) {
e.preventDefault();
e.stopPropagation();
files = e.originalEvent.dataTransfer.files;
}
}
if (!files)
return;
var file = files[0];
if (file.size == 0) {
alert("Emtry File");
return;
}
if (file.size > 1024*1024*10) {
alert("Must less than 10mb");
return;
}
var o = document.getElementById("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
$("#result").html("");
if (xhr.status == 200) {
var j = eval("(" + xhr.responseText +")");
if (j.ok) {
var url = location.protocol + "//" + location.host + location.pathname + 'c/' + j.code;
$("#result").append($('<div class="alert alert-success">Success</div>')).append($("<p>共享文件地址: </p>").append($('<a target="_blank">' + url + '</a>').attr("href", url))).append($('<p id="result-qrcode" style="display: none"></p>').append($('<img/>').attr('src', 'https://chart.googleapis.com/chart?chs=72x72&cht=qr&choe=UTF-8&chl=' + encodeURIComponent(url)))).append($('<p><a href="javascript:void(0);" id="result-qrcode-str">显示短地址QR Code</a></p>'));;
qrcodeToggle("result", "显示短地址QR Code", "隐藏短地址QR Code");
} else {
$("#result").append($('<div class="alert alert-error">Oops</div>')).append($("<p></p>").text("ERROR: " + j.msg));
}
return;
}
}
};
xhr.open("POST", "api/create/file", true);
xhr.setRequestHeader("X-File-Name", Base64.encode(file.name));
xhr.setRequestHeader("X-File-Size", file.size);
xhr.send(file);
}
$("#data").bind("dragover", FileDragHover);
$("#data").bind("dragleave",FileDragHover);
$("#data").bind("drop", FileSelectHandler);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.