text
stringlengths 2
6.14k
|
|---|
(function (exports) {
'use strict';
var obj = {
playlistFormat: 'http://open.live.bbc.co.uk/mediaselector/5/select/mediaset/http-icy-mp3-a/vpid/$station/format/pls.pls',
playableLinks: function (container) {
return container.querySelectorAll('a[data-player-html5-stream]');
},
playlistUrl: function playlistUrl(el) {
console.log('playlistUrl( %o )', el);
return new Promise(function (resolve, reject) {
var station = el.getAttribute('href').split('/').pop(),
playlistUrl;
if(station == '') {
reject(playlistUrl);
} else {
console.log('o', obj);
playlistUrl = obj.playlistFormat.replace('$station', station);
resolve(playlistUrl);
}
});
},
extractStreamForUrl: function (url) {
return obj.fetchPlsForUrl(url)
.then(obj.parseStreamFromPls);
},
fetchPlsForUrl: function (url) {
return xhr.get(url);
},
parseStreamFromPls: function (data) {
return new Promise(function (resolve, reject) {
var matches = data.match(/File[\d]=(.*)/);
matches && matches.length > 1 ? resolve(matches[1]) : reject();
});
}
}
exports.radio = obj;
})(window.bbc = window.bbc || {})
|
'use strict';
module.exports = function (app) {
var AbuseService = {
create: function (abuse) {
return app.daos.Abuse.create(abuse).then(function (id) {
return id;
});
},
update: function (abuse) {
return app.daos.Abuse.update(abuse).then(function (id) {
return id;
});
},
delete: function (id) {
return app.daos.Abuse.delete(id).then(function (ok) {
return ok;
});
},
readById: function (id) {
return app.daos.Abuse.readById(id).then(function (abuse) {
return abuse;
});
},
readByCriteria: function (criteria) {
return app.daos.Abuse.readByCriteria(criteria).then(function (abuse) {
return abuse;
});
}
};
return AbuseService;
};
|
// Copyright 2019 Google LLC
//
// 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
//
// https://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 Provides ByteString as a basic data type for protos.
*/
goog.module('proto.im.ByteString');
const Hashing = goog.require('proto.im.internal.Hashing');
const base64 = goog.require('goog.crypt.base64');
const {checkType} = goog.require('proto.im.internal.internalChecks');
/**
* Immutable sequence of bytes.
*
* Bytes can be obtained as an Array of numbers or a base64 encoded string.
* @final
*/
class ByteString {
/**
* @param {?Int8Array} bytes
* @param {?string} base64
* @private
*/
constructor(bytes, base64) {
/** @private */
this.bytes_ = bytes;
/** @private */
this.base64_ = base64;
/** @private */
this.hashCode_ = 0;
}
/**
* Constructs a ByteString instance from a base64 string.
* @param {string} value
* @returns {!ByteString}
*/
static fromBase64String(value) {
checkType(value != null);
return new ByteString(/* bytes */ null, value);
}
/**
* Constructs a ByteString from an array of numbers.
* @param {!Uint8Array|!Int8Array|!Array<number>} bytes
* @returns {!ByteString}
*/
static copyFrom(bytes) {
return new ByteString(new Int8Array(bytes), /* base 64 */ null);
}
/**
* Returns this ByteString as a Int8 byte array.
* @return {!Int8Array}
*/
toInt8Array() {
return new Int8Array(this.ensureBytes_());
}
/**
* Returns this ByteString as a Uint8 Byte array.
* @return {!Uint8Array}
*/
toUint8Array() {
return new Uint8Array(this.ensureBytes_());
}
/**
* Returns the number of bytes in the string.
* @return {number}
*/
size() {
return this.ensureBytes_().length;
}
/**
* Returns the byte value at position `index`
* @param {number} index
* @return {number}
*/
byteAt(index) {
return this.ensureBytes_()[index];
}
/**
* Returns this ByteString as a base64 encoded string.
* @return {string}
*/
toBase64String() {
return this.ensureBase64String_();
}
/**
* Returns true for Bytestrings that contain identical values.
* @param {*} other
* @return {boolean}
*/
equals(other) {
if (this === other) {
return true;
}
if (!(other instanceof ByteString)) {
return false;
}
const otherByteString = /** @type{!ByteString} */ (other);
return this.toBase64String() === otherByteString.toBase64String();
}
/**
* Returns a number (int32) that is suitable for using in hashed structures.
* @return {number}
*/
hashCode() {
if (this.hashCode_ == 0) {
this.hashCode_ = Hashing.hashString(this.toBase64String());
}
return this.hashCode_;
}
/**
* Returns true if the bytestring is empty.
* @return {boolean}
*/
isEmpty() {
if (this.bytes_ != null && this.bytes_.length == 0) {
return true;
}
if (this.base64_ != null && this.base64_.length == 0) {
return true;
}
return false;
}
/**
* @return {!Int8Array}
* @private
*/
ensureBytes_() {
if (this.bytes_ == null) {
const uint8Array =
base64.decodeStringToUint8Array(/** @type {string} */ (this.base64_));
this.bytes_ = new Int8Array(uint8Array.buffer);
}
return /** @type {!Int8Array} */ (this.bytes_);
}
/**
* @return {string}
* @private
*/
ensureBase64String_() {
if (this.base64_ == null) {
this.base64_ = base64.encodeByteArray(
new Uint8Array(/** @type {!Int8Array} */ (this.bytes_).buffer));
}
return /** @type {string} */ (this.base64_);
}
}
/** @const {!ByteString} */
ByteString.EMPTY = new ByteString(new Int8Array(0), '');
exports = ByteString;
|
import mongodb from 'mongodb';
import _ from 'lodash';
const debug = require('debug')('mongobless');
const models = [];
let DB;
const Model = new Function();
const isFunction = obj => typeof obj === 'function';
function extend(destination) {
const sources = Array.prototype.slice.call(arguments, 1);
for(let i in sources){
const source = sources[i];
Object.keys(source).forEach(function(property) {
Object.defineProperty(destination, property, Object.getOwnPropertyDescriptor(source, property));
});
}
return destination;
}
Model.bless = function(obj){
if (!obj) return;
obj.__proto__ = this.prototype;
obj.constructor = this;
return obj;
};
Model.findAll = function(...params){
const blessAll = data => data.map(obj => this.bless(obj));
const fn = params[params.length - 1];
if (isFunction(fn)) {
const cb = (err, res) => {
if(err) return fn(err);
fn(null, blessAll(res));
};
this.collection.find(...params.slice(0, -1)).toArray(cb);
return this;
}
return this.collection.find(...params).toArray().then(blessAll);
};
Model.findOne = function(...params){
const blessOne = obj => this.bless(obj);
const fn = params[params.length - 1];
if (isFunction(fn)) {
const cb = (err, res) => {
if(err) return fn(err);
fn(null, blessOne(res));
};
this.collection.findOne(...params.slice(0, -1), cb);
return this;
}
return this.collection.findOne(...params).then(blessOne);
}
Object.defineProperty(Model, 'collection', {
enumerable: true
, configurable: false
, get: function(){return this.db.collection(this.collectionName) }
});
Model.connect = function(db){
this.db = db;
}
Model.extendableProperties = ['connect', 'collection', 'findOne', 'findAll'];
export default function MongoBless(options = {}){
return function(constructor){
if(options.collection){
if(constructor.isPersistentRoot)throw new Error(`Cannot overload collection's name for class '${constructor.name}'`);
models.push(constructor);
constructor.collectionName = options.collection;
constructor.isPersistentRoot = true;
_.each(Model.extendableProperties, prop => {
Object.defineProperty(constructor, prop, Object.getOwnPropertyDescriptor(Model, prop));
});
if(!constructor.bless){
Object.defineProperty(constructor, 'bless', Object.getOwnPropertyDescriptor(Model, 'bless'));
}
}else{
constructor.isPersistentRoot = false;
}
}
}
MongoBless.close = cb => {
if (cb) return DB.close(cb);
return DB.close();
}
MongoBless.bless = function(obj){
return Model.bless.bind(this)(obj);
};
MongoBless.connect = function(opt, cb){
const options = _.extend({host: '127.0.0.1', port: 27017, auto_reconnect: true, poolSize: 10, w:1, strict: true, native_parser: true, verbose: true}, opt);
let mongoserver;
if (!options.replicaSet)
mongoserver = new mongodb.Server(options.host, options.port, options);
else {
const replicaServers = _.map(options.replicaSet.servers, function(server){
return new mongodb.Server( server.host, server.port, server.options);
});
mongoserver = new mongodb.ReplSet(replicaServers, _.extend({}, options.replicaSet.options, {rs_name: options.replicaSet.name}));
}
const dbconnector = new mongodb.Db(options.database, mongoserver, options);
const initModels = (db) => {
DB = db;
for(const i in models){ models[i].connect(db) }
debug("mongobless is ready for your requests ...");
return db;
};
if (cb) {
dbconnector.open((err, db) => {
if (err) return cb(err);
initModels(db);
cb(null, db);
});
} else {
return dbconnector.open().then(initModels);
}
};
export const ObjectId = mongodb.ObjectID;
|
var config = require('./config.js');
console.log("config: ", config);
var pack = require('./lib/package.js');
var send = require('./lib/send.js');
var inbox = require('./lib/inbox.js');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var http = require('http');
var FormData = require('form-data');
var fs = require('fs');
var multer = require('multer');
var autoReap = require('multer-autoreap');
autoReap.options = {
reapOnError: true
};
var async = require('async');
var app = express();
app.all('*', function(req, res, next) {
console.log("all request");
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
next();
});
app.use(multer({
dest: './uploads/'
}))
app.use(autoReap);
app.use(logger('dev'));
app.use('/docs', express.static('./swagger'));
app.get('/interop', function (req, res) {
res.send("Direct Node Server is up and running!!!");
});
//send new message
app.post('/api/v1/send', function(req, res) {
var filename = req.files.file.path;
var data = fs.readFileSync(filename).toString();
var to = req.body.to;
var from = req.body.from; //TODO: use patient's domain from config
var subject = req.body.subject;
var message = req.body.message;
var memberId = "STAN01";
//console.log(data);
console.log("/api/v1/send");
console.log("to: ", to);
console.log("from: ", from);
console.log("subject: ", subject);
console.log("message: ", message);
//package email
var attachments = [{
'filename': filename,
'contents': data
}];
var email = {
'from': from,
'to': to,
'subject': subject,
'body': message
};
console.log("email: ", email);
pack(email, attachments, function(err, mime) {
if (err) {
res.statusCode = 500;
res.send(err);
} else {
//send email
send(config.abelian, mime, function(err) {
if (err) {
res.statusCode = 500;
res.send(err);
} else {
console.log(mime.substring(0, 1000));
console.log("...skipping rest of mime envelope");
console.log("everything is ok");
res.send('OK');
}
});
}
});
});
//get list of messages
app.get('/api/v1/inbox', function(req, res) {
//takes query param memberId /doctor e.g. username/email address
//var memberId = req.query.memberId || "STAN01";
inbox(config.abelian, false, function(err, response) {
if (err) {
res.statusCode = 500;
res.send(err);
} else {
console.log(response);
console.log("everything is ok");
res.send(response);
}
})
//res.status(200).end();
});
var server = app.listen(3001, function() {
var host = server.address().address
var port = server.address().port
console.log('Listening at http://%s:%s', host, port)
var mailListener = require('./lib/mail-listener');
function timerMail() {
mailListener(function(err, results) {
if (err) {
console.error(err);
} else {
console.log("got mail #", results.length);
//TODO: process each email into DRE
for (var j = 0; j < results.length; j++) {
console.log("processing email ", results[j]);
//console.log(results[j].attachments[0].content.toString());
//DRE Ingest call here
console.log("posting to ingest api: ", config['dre-ingest-api'] + '/api/v1/ingest');
var patKey = results[j].user;
if (results[j].attachments) {
var form = new FormData();
form.append('file', results[j].attachments[0].content, {filename: 'bluebutton.xml'});
form.append('patKey', patKey);
form.submit(config['dre-ingest-api'] + '/api/v1/ingest', function(err, res) {
//res.resume(); // for node-0.10.x
});
}
}
}
});
}
//mail listener (every 30 seconds)
console.log("listening for mail every 15 seconds");
setInterval(timerMail, 15000);
})
|
/**
* Created by Bane.Shi.
* Copyright MoenSun
* User: Bane.Shi
* Blog: http://blog.fengxiaotx.com
* Date: 2017/2/4
* Time: 17:04
*/
'use strict';
import Datepicker from "./src/date/datepicker.vue";
module.exports = {
Datepicker
}
|
import React from 'react';
import Icon from '@ichef/gypcrete/src/Icon';
import iconMap from '@ichef/gypcrete/src/icons/components';
export default {
title: '@ichef/gypcrete|Icon',
component: Icon,
};
export function BasicUsage() {
/**
* Show all icons, ordering from a to z.
*/
return (
<>
{
Object.keys(iconMap).sort().map(iconType => (
<Icon
type={iconType}
spinning={iconType.includes('loading')}
/>
))
}
</>
);
}
BasicUsage.story = {
name: 'Basic Icons Set',
};
export function CRMIconsSet() {
return (
<div>
<Icon type="crm-address" />
<Icon type="crm-age" />
<Icon type="crm-birthday" />
<Icon type="crm-email" />
<Icon type="crm-gender" />
<Icon type="crm-member-name" />
<Icon type="crm-member-note" />
<Icon type="crm-phone-land" />
<Icon type="crm-phone-mobile" />
</div>
);
}
export function ColorOptions() {
return (
<div>
<Icon type="drag" color="gray" />
<Icon type="edit" color="blue" />
<Icon type="trashcan" color="red" />
<Icon type="add" style={{ color: '#78c878' }} />
</div>
);
}
export function InlineIconsSet() {
return (
<div>
<Icon type="inline-loading" />
<Icon type="inline-success" />
<Icon type="inline-error" />
<Icon type="inline-question" />
</div>
);
}
InlineIconsSet.story = {
name: 'Inline-sized Icons Set',
};
export function InventoryIconsSet() {
return (
<div>
<Icon type="inventory-category" />
<Icon type="inventory-item" />
</div>
);
}
export function LargeSizeOptions() {
return (
<div>
<Icon type="loading" large spinning />
<Icon type="success" large color="blue" />
<Icon type="error" large color="red" />
</div>
);
}
export function MenuPageIconsSet() {
return (
<div>
<Icon type="add-item" />
<Icon type="add-multi-items" />
<Icon type="clear-item" />
</div>
);
}
export function PaginationIconsSet() {
return (
<div>
<Icon type="first-page" />
<Icon type="prev-page" />
<Icon type="next-page" />
<Icon type="last-page" />
</div>
);
}
export function PaymentIconsSet() {
return (
<div>
<Icon type="cash" />
<Icon type="credit-card" />
<Icon type="ctbc-direct" />
<Icon type="ctbc-mpos" />
<Icon type="custom-pay" />
</div>
);
}
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import Lozenge from './';
storiesOf('Lozenge', module)
.add('Base', () => {
return <Lozenge>Foo</Lozenge>;
})
.add('With Custom Background Colors', () => {
return (
<div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="#E91E63">foo</Lozenge>
</div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="#009688">bar</Lozenge>
</div>
<div>
<Lozenge backgroundColor="red">baz</Lozenge>
</div>
</div>
);
})
.add('With Custom Text Colors', () => {
return (
<div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="lightgrey" textColor="#E91E63">
foo
</Lozenge>
</div>
<div style={{ marginBottom: '10px' }}>
<Lozenge backgroundColor="lightgrey" textColor="#009688">
bar
</Lozenge>
</div>
<div>
<Lozenge backgroundColor="lightgrey" textColor="red">
baz
</Lozenge>
</div>
</div>
);
})
.add('With Icons', () => {
return (
<div>
<div style={{ marginBottom: '10px' }}>
<Lozenge iconClassName="icon-gps">foo</Lozenge>
</div>
<div style={{ marginBottom: '10px' }}>
<Lozenge iconClassName="icon-face">bar</Lozenge>
</div>
<div>
<Lozenge iconClassName="icon-ocr">baz</Lozenge>
</div>
</div>
);
});
|
'use strict';
import React,{ Component } from 'react';
import { StyleSheet, AppState, Dimensions, Image } from 'react-native';
import CodePush from 'react-native-code-push';
import { Container, Text, View, InputGroup, Input, Icon } from 'native-base';
import Modal from 'react-native-modalbox';
import AppNavigator from './AppNavigator';
import ProgressBar from './components/loaders/ProgressBar';
import theme from './themes/base-theme';
var height = Dimensions.get('window').height;
let styles = StyleSheet.create({
container: {
flex: 1,
width: null,
height: null
},
box: {
padding: 10,
backgroundColor: 'transparent',
flex: 1,
height: height-70
},
space: {
marginTop: 10,
marginBottom: 10,
justifyContent: 'center'
},
modal: {
justifyContent: 'center',
alignItems: 'center'
},
modal1: {
height: 300,
width: 300
}
});
class App extends Component {
constructor(props) {
super(props);
this.state = {
showDownloadingModal: false,
showInstalling: false,
downloadProgress: 0
}
}
componentDidMount() {
CodePush.sync({ updateDialog: true, installMode: CodePush.InstallMode.IMMEDIATE },
(status) => {
switch (status) {
case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
this.setState({showDownloadingModal: true});
this.refs.modal.open();
break;
case CodePush.SyncStatus.INSTALLING_UPDATE:
this.setState({showInstalling: true});
break;
case CodePush.SyncStatus.UPDATE_INSTALLED:
this.refs.modal.close();
this.setState({showDownloadingModal: false});
break;
}
},
({ receivedBytes, totalBytes, }) => {
this.setState({downloadProgress: receivedBytes / totalBytes * 100});
}
);
}
render() {
if(this.state.showDownloadingModal)
return (
<View style={{backgroundColor: theme.brandSecondary}}>
<InputGroup
borderType='rounded'
>
<Icon name='ios-person-outline' />
<Input placeholder='Username' />
</InputGroup>
<InputGroup
borderType='rounded'
>
<Icon name='ios-unlock-outline' />
<Input
placeholder='Password'
secureTextEntry={true}
/>
</InputGroup>
</View>
);
else
return(
<AppNavigator store={this.props.store} />
);
}
}
export default App
|
'use strict';
module.exports = {
ClientRequest: function () {}
};
|
const path = require('path');
const express = require('express');
const open = require('open');
const serveIndex = require('serve-index');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const product = process.argv[2];
var dirname = product === 'openlayers' ? 'ol' : product
const app = (module.exports = express());
if (product) {
const config = require(`./webpack.config.${product}.js`);
const configBase = require(`./webpack.config.base.js`);
const entry = [`./src/${product}/${product === 'openlayers' ? 'namespace.js' : 'index.js'}`];
const filename = `iclient-${dirname}`;
config.output.filename = `${filename}-es6.min.js`;
config.output.path = path.resolve(`${__dirname}/../dist/${dirname}`);
if (['leaflet', 'openlayers'].includes(product)) {
entry.push(`./src/${product}/css/index.js`);
config.plugins = configBase.plugins(product, `${filename}.min`);
}
config.mode = 'development';
config.entry = entry;
config.devtool = 'inline-cheap-module-source-map';
const compiler = webpack(config);
const instance = webpackDevMiddleware(compiler, {
publicPath: `/dist/${dirname}`,
stats: {
colors: true
}
});
app.use(instance);
instance.waitUntilValid(() => {
open(`http://localhost:8082/examples/${product}`);
});
}
const server = app.listen(8082, () => {
const host = server.address().address;
const port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
app.use(express.static('web'));
app.use('/examples/template/header.html', express.static('web/template/header.html'));
app.use('/examples', express.static('examples'), serveIndex('examples'));
app.use('/examples-bug', express.static('examples-bug'), serveIndex('examples-bug'));
app.use('/dist', express.static('dist'), serveIndex('dist'));
app.use('/build', express.static('build'), serveIndex('build'));
app.use('/docs', express.static('docs'), serveIndex('docs'));
app.use('/web', express.static('web'), serveIndex('web'));
app.use('/en/examples/template/header.html', express.static('web/en/web/template/header.html'));
app.use('/en/examples', express.static('examples'), serveIndex('examples'));
app.use('/en/docs', express.static('docs'), serveIndex('docs'));
app.use('/en/dist', express.static('dist'), serveIndex('dist'));
app.use('/en/build', express.static('build'), serveIndex('build'));
app.use('/en', express.static('web/en'), serveIndex('web/en'));
if (!product) {
open(`http://localhost:8082`);
}
|
/**
* A function to be invoked after completing an asynchronous task.
*
* @typedef {Function} Callback
*/
/**
* A callback whose first argument is either an `Error` or `null`.
*
* @typedef {Callback} Errback
*/
|
/**
* Created by liyadan01_bj on 2016/4/26.
*/
function addLoadEvent(func){
var oldonload=window.onload;
if(typeof window.onload != 'function'){
window.onload=func;
}else{
window.onload=function(){
oldonload();
func();
}
}
}
|
angular.module('Angular').config([ '$routeProvider',
function ($routeProvider) {
$routeProvider.when('/exampleRoute', {
templateUrl: 'app/exampleRoute/exampleRoute.html',
controller: 'exampleRoute',
controllerAs: 'exampleRoute'
});
}]);
|
import slayer from "./s_layer";
let params;
export function jsApiCall(callback) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
params,
function (res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
slayer.alert('支付成功');
if (callback) {
callback();
}
} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
slayer.alert('用户取消支付');
}
}
);
}
export function callpay(callback) {
if (typeof('WeixinJSBridge') == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
} else {
jsApiCall(callback);
}
}
export default {
pay(jsApiParams, callback) {
params = jsApiParams;
callpay(callback);
}
}
|
/**
* cms 新增js
*/
$(document).ready(function(){
// 数据回显
if(bzptCmsId){
intaddBzptCms(bzptCmsId);
}
//保存
$("#btn_save").on("click",function(){
addBzptCms.saveData();
});
// //确认
// $("#btn_affirm").on("click",function(){
// addArchives.affirmData();
// });
//返回
$("#btn_back").on("click",function(){
window.history.go(-1);
});
});
/**
* 数据回显
* @param id
*/
function intaddBzptCms(id){
$.ajax({
url:ctxManager+"/bzptCms/getDetail",
data:{id : id},
dataType:"json",
type:"post",
success:function(res){
if(res.flag){
if(res.bzptCms){
var bzptCms = res.bzptCms;
var content = bzptCms.content;
$('.summernote').code(content);
$('#cms_type').val(bzptCms.cmsType);
$('#title').val(bzptCms.title);
}
} else {
console.log("获取失败");
}
},
error:function(){
console.log("获取失败");
}
})
}
var addBzptCms = {
/**
* 表单校验
*/
check : function(){
if($("#cms_type").val() == null || $("#cms_type").val() == "" || $("#cms_type").val() == undefined){
layer.alert("请选择信息类型");
return false;
}
if($("#title").val() == null || $("#title").val() == "" || $("#title").val() == undefined){
layer.alert("请录入标题");
return false;
} else if($("#title").val().length > 30){
layer.alert("标题不得超过30个字符");
return false;
}
var content= $('.summernote').code();
if(content == null || content == "" || content == undefined){
layer.alert("请录入内容");
return false;
}
return true;
},
/**
* 保存表单数据
*/
saveData:function(){
//校验
if(!addBzptCms.check()){
return;
}
var content= $('.summernote').code();
var cmsType = $('#cms_type').val();
var title = $('#title').val();
$.ajax({
url:ctxManager+"/bzptCms/addOrUpdateBzptCms",
data:{
id : bzptCmsId,
content : content,
cmsType : cmsType,
title : title
},
dataType:"json",
type:"post",
success:function(res){
if(res.flag){
layer.alert("保存成功!",function(){
// window.history.go(-1);
//location.href = ctxManager + '/bzptCms/listBzptCms';
window.parent.OptApi.closeNowTab();
});
}else{
layer.msg("保存失败:"+res.msg);
}
},
error:function(){
layer.msg("信息保存失败。");
}
})
},
/**
* 取消、返回上一页
*/
cancel:function(){
//location.href = ctxManager + '/bzptCms/listBzptCms';
window.parent.OptApi.closeNowTab();
}
};
|
/**
* Created by kev on 15-08-14.
*/
define(['underscore',
'base_sketch',
'snow_2/noiseBuffer'],
function (_,
BaseSketch,
NoiseBuffer) {
Number.prototype.mod = function (n) {
return ((this % n) + n) % n;
};
var HALF_PI = Math.PI / 2;
var QUART_PI = Math.PI / 4;
var DBL_PI = Math.PI * 2;
var ParticleBuffer = function (buffer,img) {
buffer.length = 50;
buffer.numAngles = 30;
buffer.resize(100,buffer.numAngles * 100);
var inc = DBL_PI / buffer.numAngles;
buffer.ctx.globalAlpha = 0.7;
for (var i = 0; i < buffer.numAngles; i++) {
buffer.ctx.save();
buffer.ctx.translate(0,i * 100);
buffer.ctx.translate(buffer.width >> 1,buffer.width >> 1);
buffer.ctx.rotate(i * inc);
buffer.ctx.drawImage(img,-buffer.width >> 1,-img.naturalHeight >> 1,buffer.length,img.naturalHeight);
buffer.ctx.restore();
}
return buffer;
};
var Particle = function (noiseBuffer,particleBuffer) {
this.noiseBuffer = noiseBuffer;
this.particleBuffer = particleBuffer;
};
_.extend(Particle.prototype,{
length:Math.random() * 10 + 10,
pos :{x:0,y:0},
angle :QUART_PI,
count :0,
resize:function (w,h) {
this.pos = {
x:Math.random() * w,
y:Math.random() * h
};
},
update:function (bounds) {
var noiseAmt = this.noiseBuffer.getNoiseByRatio(this.pos.x / (bounds.right - bounds.left),this.pos.y / (bounds.bottom - bounds.top)) * 0.4;
this.angle = noiseAmt * HALF_PI;//- QUART_PI/10;
var speed = ((noiseAmt + 1) / 2) * 400;
var x = this.pos.x - Math.sin(this.angle) * speed;
var y = this.pos.y + Math.cos(this.angle) * speed;
if (x > bounds.right || x < bounds.left || y > bounds.bottom) {
x = Math.random() * (bounds.right - bounds.left) + bounds.left;
y = Math.random() * -speed - speed;
}
this.pos = {
x:x,
y:y
};
},
draw:function (ctx) {
var angle = (this.angle + HALF_PI).mod(DBL_PI);
var ratio = (angle / DBL_PI);
var angleIndex = Math.floor(ratio * this.particleBuffer.numAngles);
ctx.drawImage(this.particleBuffer.canvas,0,angleIndex * 100,100,100,
this.pos.x,this.pos.y,100,100);
}
});
return BaseSketch.extend({
particleBuffer:null,
noiseBuffer :null,
mainBuffer :null,
numParticles :1000,
frameRate :30,
lastUpdate :-1,
initialize:function () {
this.particles = [];
this.snowImg = [];
this.mainBuffer = this.createBuffer();
this.ctx = this.mainBuffer.ctx;
this.el.appendChild(this.mainBuffer.canvas);
var _this = this;
this.loadImages(["img/snow.png","img/snow10x10.png","img/LANDING_SECTION.png"]).then(function (imgs) {
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].src.indexOf("img/LANDING_SECTION.png") !== -1) {
_this.bgImage = imgs.splice(i,1)[0];
}
}
_this.noiseBuffer = new NoiseBuffer({w:100,h:100});
//_this.particle = new Particle(imgs[1],_this.noiseBuffer,_this.createBuffer());
_this.snowImg = imgs;
_this.createParticles();
_this.loaded = true;
_this.invalidated = true;
_this.resize(_this.mainBuffer.width,_this.mainBuffer.height);
}).catch(function (e) {
console.error(e);
})
}
,
createParticles:function () {
this.particleBuffer = new ParticleBuffer(this.createBuffer(),this.snowImg[1]);
for (var i = 0; i < this.numParticles; i++) {
var particle = new Particle(this.noiseBuffer,this.particleBuffer);
particle.resize(this.mainBuffer.width,this.mainBuffer.height);
this.particles.push(particle);
}
},
resize:function (w,h) {
//this causes redraw!
this.mainBuffer.resize(w,h);
if (this.loaded) {
}
}
,
draw :function (time) {
if (!this.loaded) {
return;
}
if (time - this.lastUpdate > 50) {
this.lastUpdate = time;
this.noiseBuffer.renderNoise();
this.ctx.fillStyle = "#000";
this.ctx.fillRect(0,0,this.mainBuffer.width,this.mainBuffer.height);
// this.ctx.drawImage(this.particleBuffer.canvas,0,0);
for (var i = 0; i < this.numParticles; i++) {
var particle = this.particles[i];//new Particle(imgs[1],this.noiseBuffer,this.createBuffer());
particle.draw(this.ctx);
particle.update({left:-400, top : 0, right:this.mainBuffer.width + 400,bottom:this.mainBuffer.height});
}
}
}
})
});
|
var angular = require('angular');
angular.module('example.photos.controllers', ['example.api.services'])
.controller('PhotosController', ['$scope', 'postService', 'postPhotoService', function ($scope, postService, postPhotoService) {
$scope.photos = {};
$scope.posts = postService.query(); // Obtiene todos los posts
$scope.posts.$promise.then(function (results) {
// Esto se realiza por cada post
results.forEach(function (post) {
// Esto obtendra todas las fotos por cada post
postPhotoService.query({post_id: post.id}, function (data) {
$scope.photos[post.id] = data;
});
});
});
}]);
|
angular.module("Thesaurus")
.service("NodeHandler", ['$http', 'PagingSet',
function($http, PagingSet) {
var nr_of_displayed_pages = 5;
var items_per_page = 25;
function mapData(data) {
data.items.forEach(function(child) {
child.loadingChildren = false;
child.currentPage = 1;
child.expanded = false;
child.children = null;
child.pages = null;
child.selected = false;
});
}
function findChild(children, uri) {
for (var i = 0; i < children.length; i++) {
if (children[i].value.link === uri) {
return children[i];
}
}
return null;
}
function configureNodePagingSet(node, start, totalResults) {
node.pagingSet = new PagingSet(nr_of_displayed_pages);
node.currentPage = Math.floor(start / items_per_page) + 1;
node.numberOfPages = Math.ceil(totalResults / items_per_page);
var pages = node.pagingSet.assemblePagingSet(node.currentPage, node.numberOfPages);
if (pages.length > 3) {
node.pages = pages;
} else {
node.pages = null;
}
}
this.expand = function expand(node, itemPath) {
console.log('expanding node ' + node.value.link);
if (!node.hasChildren) {
// ignore
return;
}
if (!node.expanded) {
// when the root is selected further nodes will be missing
if (itemPath && itemPath.nodes.length) {
var childRow = itemPath.nodes[0].row - 1;
var onPageNumber = Math.floor(childRow / items_per_page) + 1;
node.currentPage = onPageNumber;
this.loadChildren(node, itemPath);
} else {
this.loadChildren(node);
node.selected = true;
}
}
};
this.loadChildren = function(node, itemPath) {
node.loadingChildren = true;
var start = (node.currentPage - 1) * items_per_page;
var that = this;
$http.get('/item/children', {
params: {
uri: node.value.link,
start: start,
count: items_per_page
}
})
.success(function(data) {
console.log('setting loaded children for node ' + node.value.link);
mapData(data);
node.children = data.items;
configureNodePagingSet(node, data.start, data.totalResults);
node.loadingChildren = false;
node.expanded = true;
// itemPath is passed in when we are part of path
if (itemPath) {
// find the relevant child
var children = node.children;
var childPathNode = itemPath.nodes.shift();
var childNode = findChild(children, childPathNode.uri);
if (itemPath.nodes.length > 0) {
that.expand(childNode, itemPath);
} else {
// leaf
if (childNode) {
childNode.selected = true;
// when showing leaf with further children, expand node
if (childNode.hasChildren) {
that.expand(childNode);
}
}
}
}
});
};
this.fold = function(node) {
console.log('folding on node ' + node.value.link + ' from ' + node.expanded);
if (!node.hasChildren) {
// ignore
return;
}
if (node.expanded) {
// clean the children
node.expanded = false;
node.children = null;
} else {
this.loadChildren(node);
}
};
this.gotoPage = function(node, link) {
if (!link) {
return false;
}
console.log('paging to page ' + link);
node.currentPage = link;
this.loadChildren(node);
return false;
};
}
]);
|
/**
* Created by Ali on 4/08/2015.
*/
"use strict";
const Hoek = require("hoek"),
Joi = require("joi"),
_get = require("lodash/get"),
_set = require("lodash/set"),
model_factory = require("../../../model");
const options_schema = Joi
.object({
enabled: Joi
.boolean()
.default(false)
})
.required();
/**
*
* @param server
* @param options
* @param next
*/
const resource_set_plugin = async (server, options) => {
return new Promise(async (resolve, reject) => {
let results = Joi.validate(options, options_schema);
try {
Hoek.assert(!results.error, results.error);
} catch (err) {
return reject(err);
}
let resource_set_settings = results.value;
server.ext("onPreHandler", async (request, h) => {
let routeEnabled = _get(request, "route.settings.plugins.resource_set.enabled", resource_set_settings.enabled || false);
request.plugins.valde_resource_set = {};
if (routeEnabled === true) {
try {
let resource_set = await model_factory.create_model_for_rest_request(request, h);
_set(request, "plugins.valde_resource_set", resource_set);
return h.continue;
} catch (err) {
_set(request, "plugins.valde_resource_set", {});
return h.continue;
}
} else {
return h.continue;
}
});
return resolve();
});
};
module.exports.plugin = {
register: resource_set_plugin,
pkg: require("./package.json")
};
|
var models = require('../models/models.js');
exports.ownershipRequired = function (req, res, next) {
models.Quiz.find({
where: {
id: Number(req.comment.QuizId)
}
}).then(function (quiz) {
if (quiz) {
var objQuizOwner = quiz.UserId;
var logUser = req.session.user.id;
var isAdmin = req.session.user.isAdmin;
console.log(objQuizOwner, logUser, isAdmin);
if (isAdmin || objQuizOwner === logUser) {
next();
} else {
res.redirect('/');
}
} else { next(new Error('No existe quizId=' + quizId)) }
}).catch(function(error){next(error)});
};
exports.load = function (req, res, next, commentId) {
models.Comment.find({
where: {
id: Number(commentId)
}
}).then(function (comment) {
if (comment) {
req.comment = comment;
next();
} else {
next(new Error('No existe commentId=' + commentId));
}
});
};
exports.new = function (req, res) {
res.render('comments/new.ejs', { quizId: req.params.quizId, errors: [] });
};
exports.create = function (req, res) {
var comment = models.Comment.build({
texto: req.body.comment.texto,
QuizId: req.params.quizId
});
comment.validate().then(
function (err) {
if (err) {
res.render('comments/new.ejs', { comment: comment, errors: err.errors });
} else {
comment.save().then(
function () { res.redirect('/quizes/' + req.params.quizId); });
}
}
).catch(function (error) { next(error); });
};
exports.publish = function (req, res) {
req.comment.publicado = true;
req.comment.save({ fields: ["publicado"] }).then(function () {
res.redirect('/quizes/' + req.params.quizId);
}).catch(function (error) { next(error) });
};
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 ApplicationOptions = {
colors: {
states: {
NORMAL: 'blue',
WARNING: 'blue',
OFFLINE: 'grey',
ALERTED: 'red',
UNKNOWN: 'black' // TODO: previous color #19FFFF , change this if black is not user friendly ;)
},
application: {
header: 'grey'
}
},
constance:{
CEP_WEB_SOCKET_OUTPUT_ADAPTOR_NAME: 'geo_publisher_websocket_localfusedspacialevent',
// CEP_ON_ALERT_WEB_SOCKET_OUTPUT_ADAPTOR_NAME: 'Geo-Publisher-WebSocketLocal-GeoAlertNotifications',
CEP_Traffic_STREAM_WEB_SOCKET_OUTPUT_ADAPTOR_NAME: 'DefaultWebsocketOutputAdaptorOnTrafficStream',
CEP_WEB_SOCKET_OUTPUT_ADAPTOR_WEBAPP_NAME: 'outputwebsocket',
TENANT_INDEX: 't',
COLON : ':',
PATH_SEPARATOR : '/',
SPEED_HISTORY_COUNT: 20,
NOTIFY_INFO_TIMEOUT: 1000,
NOTIFY_SUCCESS_TIMEOUT: 1000,
NOTIFY_WARNING_TIMEOUT: 3000,
NOTIFY_DANGER_TIMEOUT: 5000
},
messages:{
app:{
}
},
leaflet: {
iconUrls: {
normalMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/object-types/default/moving/alerted.png',
alertedMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/moving/arrow_alerted.png',
offlineMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/moving/arrow_offline.png',
warningMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/moving/arrow_warning.png',
defaultMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/moving/arrow_normal.png',
normalNonMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/non_moving/dot_normal.png',
alertedNonMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/non_moving/dot_alerted.png',
offlineNonMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/non_moving/dot_offline.png',
warningNonMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/non_moving/dot_warning.png',
defaultNonMovingIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/non_moving/dot_normal.png',
normalPlaceIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/places/marker-icon.png',
alertedPlaceIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/places/redMarker.png',
offlinePlaceIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/places/ashMarker.png',
warningPlaceIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/places/pinkMarker.png',
defaultPlaceIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/places/marker-icon.png',
defaultIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/moving/default_icons/marker-icon.png',
resizeIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/resize.png',
stopIcon: '/portal/store/carbon.super/fs/gadget/motor-rally/img/markers/stopIcon.png'
}
}
};
|
export const schema = {}
export const jsonDict = {}
export const columns1 = [
{
items: [
{
errors: [],
key: 'a',
reactId: '/a+{"b":{"123":123,"c":"ccc","d":"ddd"}}',
sortIndex: 1,
value: { b: { 123: 123, c: 'ccc', d: 'ddd' } },
},
{ errors: [], key: '123', reactId: '/123+123', sortIndex: 2, value: 123 },
{ errors: [], key: 'b', reactId: '/b+"bbb"', sortIndex: 3, value: 'bbb' },
],
parent: { 123: 123, a: { b: { 123: 123, c: 'ccc', d: 'ddd' } }, b: 'bbb' },
},
]
export const columns2 = [
{
items: [
{
errors: [],
key: 'a',
reactId: '/a+{"b":{"123":123,"c":"ccc","d":"ddd"}}',
sortIndex: 0,
value: { b: { 123: 123, c: 'ccc', d: 'ddd' } },
},
{ errors: [], key: 'b', reactId: '/b+"bbb"', sortIndex: 0, value: 'bbb' },
{ errors: [], key: '123', reactId: '/123+123', sortIndex: 1, value: 123 },
],
parent: { 123: 123, a: { b: { 123: 123, c: 'ccc', d: 'ddd' } }, b: 'bbb' },
},
{
items: [
{
errors: [],
key: 'b',
reactId: '/a/b+{"123":123,"c":"ccc","d":"ddd"}',
sortIndex: 0,
value: {
123: 123,
c: 'ccc',
d: 'ddd',
},
},
],
parent: {
b: {
123: 123,
c: 'ccc',
d: 'ddd',
},
},
},
{
items: [
{
errors: [],
key: '123',
reactId: '/a/b/123+123',
sortIndex: 0,
value: 123,
},
{
errors: [],
key: 'd',
reactId: '/a/b/d+"ddd"',
sortIndex: 2,
value: 'ddd',
},
{
errors: [],
key: 'c',
reactId: '/a/b/c+"ccc"',
sortIndex: 3,
value: 'ccc',
},
],
parent: {
123: 123,
c: 'ccc',
d: 'ddd',
},
},
]
export const sortOrder1 = { '/a': 1, '/123': 2, '/b': 3 }
export const sortOrder2 = { '/123': 1, '/a/b/c': 3, '/a/b/d': 2 }
export const object = { a: { b: { c: 'ccc', d: 'ddd', 123: 123 } }, b: 'bbb', 123: 123 }
|
const tsconfig = require('./tsconfig');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'karma-typescript'],
files: ['node_modules/tslib/tslib.js']
.concat(tsconfig.files)
.concat(['test/setup.ts', 'test/**/*.ts']),
exclude: [],
preprocessors: {
'**/*.ts': ['karma-typescript']
},
karmaTypescriptConfig: {
compilerOptions: {
noEmitHelpers: true,
},
coverageOptions: {
exclude: [
/(lib\/templates\.ts)/i,
/(test\/.*\.ts)/i,
],
}
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: false,
concurrency: Infinity,
coverageReporter: {
dir: 'coverage/',
reporters: [{
type: 'lcov',
subdir: 'report-lcov'
}, {
type: 'lcovonly',
subdir: '.',
file: 'lcov.info'
}]
}
});
}
|
// 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.
import module from 'config/module';
import {resolveResource} from 'config/stateconfig';
describe('StateConfig for config list', () => {
/** @type {!common/dataselect/dataselect_service.DataSelectService} */
let kdDataSelectService;
beforeEach(() => {
angular.mock.module(module.name);
angular.mock.inject((_kdDataSelectService_) => {
kdDataSelectService = _kdDataSelectService_;
});
});
it('should resolve config', angular.mock.inject(($q) => {
let promise = $q.defer().promise;
let resource = jasmine.createSpyObj('$resource', ['get']);
resource.get.and.callFake(function() {
return {$promise: promise};
});
let actual = resolveResource(resource, {namespace: 'foo-ns'}, kdDataSelectService);
expect(resource.get)
.toHaveBeenCalledWith(kdDataSelectService.getDefaultResourceQuery('foo-ns'));
expect(actual).toBe(promise);
}));
});
|
// https://snazzymaps.com/style/25/blue-water
module.exports = [
{
featureType: 'administrative',
elementType: 'labels.text.fill',
stylers: [{ color: '#444444' }],
},
{ featureType: 'landscape', elementType: 'all', stylers: [{ color: '#f2f2f2' }] },
{ featureType: 'poi', elementType: 'all', stylers: [{ visibility: 'off' }] },
{ featureType: 'road', elementType: 'all', stylers: [{ saturation: -100 }, { lightness: 45 }] },
{ featureType: 'road.highway', elementType: 'all', stylers: [{ visibility: 'simplified' }] },
{ featureType: 'road.arterial', elementType: 'labels.icon', stylers: [{ visibility: 'off' }] },
{ featureType: 'transit', elementType: 'all', stylers: [{ visibility: 'off' }] },
{
featureType: 'water',
elementType: 'all',
stylers: [{ color: '#46bcec' }, { visibility: 'on' }],
},
];
|
// Copyright 2017 The TIE 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 Factory for creating a snapshot of a student's code
* and performance at a given time.
*/
tie.factory('SnapshotObjectFactory', [
function() {
var Snapshot = function(codePrereqCheckResult, codeEvalResult, feedback) {
this._codePrereqCheckResult = codePrereqCheckResult;
this._codeEvalResult = codeEvalResult;
this._feedback = feedback;
this._timestamp = '';
};
// Instance methods.
Snapshot.prototype.getCodePrereqCheckResult = function() {
return this._codePrereqCheckResult;
};
Snapshot.prototype.setCodePrereqCheckResult = function(
codePrereqCheckResult) {
this._codePrereqCheckResult = codePrereqCheckResult;
};
Snapshot.prototype.getCodeEvalResult = function() {
return this._codeEvalResult;
};
Snapshot.prototype.setCodeEvalResult = function(codeEvalResult) {
this._codeEvalResult = codeEvalResult;
};
Snapshot.prototype.getFeedback = function() {
return this._feedback;
};
Snapshot.prototype.setFeedback = function(feedback) {
this._feedback = feedback;
};
// Static class methods.
Snapshot.create = function(codePrereqCheckResult, codeEvalResult,
feedback) {
return new Snapshot(codePrereqCheckResult, codeEvalResult, feedback);
};
return Snapshot;
}
]);
|
/*!
* CBBL®
* ______________________________________________________________
* Architecture and Code Handcrafted by Prabhat Kumar.
* Architectuur en Code handgemaakt door Prabhat Kumar.
* @author : Prabhat Kumar [http://prabhatkumar.org/]
* @copyright : Sequømics Corporation [http://sequomics.com/]
* ______________________________________________________________
* @date : 09-May-2016
* @license : Apache, version 2.0
* ______________________________________________________________
*/
|
/**
* Copyright 2014 Shape Security, Inc.
*
* 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.
*/
// FIXME: the code generated by 6to5 should not have to require ES6 shims.
if (typeof Map === "undefined")
require('es6-map/implement');
if (typeof Symbol === "undefined")
require('es6-symbol/implement');
import ScopeAnalyzer from "./scope-analyzer";
export {ScopeType} from "./scope";
export {DeclarationType} from "./declaration";
export {Accessibility} from "./reference";
export default function analyze(script) {
return ScopeAnalyzer.analyze(script);
}
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --expose-wasm
load('test/mjsunit/wasm/wasm-constants.js');
load('test/mjsunit/wasm/wasm-module-builder.js');
let k1MiB = 1 * 1024 * 1024;
let k1GiB = 1 * 1024 * 1024 * 1024;
let k4GiB = 4 * k1GiB;
let kMaxMemory = 2 * k1GiB - kPageSize; // TODO(titzer): raise this to 4GiB
(function Test() {
var memory;
function BuildAccessors(type, load_opcode, store_opcode) {
builder = new WasmModuleBuilder();
builder.addImportedMemory("i", "mem");
builder.addFunction("load", makeSig([kWasmI32], [type]))
.addBody([ // --
kExprGetLocal, 0, // --
load_opcode, 0, 0, // --
]) // --
.exportFunc();
builder.addFunction("store", makeSig([kWasmI32, type], []))
.addBody([ // --
kExprGetLocal, 0, // --
kExprGetLocal, 1, // --
store_opcode, 0, 0, // --
]) // --
.exportFunc();
let i = builder.instantiate({i: {mem: memory}});
return {load: i.exports.load, store: i.exports.store};
}
function probe(a, f) {
print("------------------------");
let stride = kPageSize;
let max = kMaxMemory;
for (let i = 0; i < max; i += stride) {
a.store(i, f(i));
}
for (let i = 0; i < max; i += stride) {
// print(`${i} = ${f(i)}`);
assertEquals(f(i), a.load(i));
}
}
try {
let kPages = kMaxMemory / kPageSize;
memory = new WebAssembly.Memory({initial: kPages, maximum: kPages});
} catch (e) {
print("OOM: sorry, best effort max memory size test.");
return;
}
assertEquals(kMaxMemory, memory.buffer.byteLength);
{
let a = BuildAccessors(kWasmI32, kExprI32LoadMem, kExprI32StoreMem);
probe(a, i => (0xaabbccee ^ ((i >> 11) * 0x110005)) | 0);
}
{
let a = BuildAccessors(kWasmI32, kExprI32LoadMem16U, kExprI32StoreMem16);
probe(a, i => (0xccee ^ ((i >> 11) * 0x110005)) & 0xFFFF);
}
{
let a = BuildAccessors(kWasmI32, kExprI32LoadMem8U, kExprI32StoreMem8);
probe(a, i => (0xee ^ ((i >> 11) * 0x05)) & 0xFF);
}
{
let a = BuildAccessors(kWasmF64, kExprF64LoadMem, kExprF64StoreMem);
probe(a, i => 0xaabbccee ^ ((i >> 11) * 0x110005));
}
{
let a = BuildAccessors(kWasmF32, kExprF32LoadMem, kExprF32StoreMem);
probe(a, i => Math.fround(0xaabbccee ^ ((i >> 11) * 0x110005)));
}
})();
|
/*
* Copyright 2019 EPAM Systems
*
* 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.
*/
export { InputCheckbox } from './inputCheckbox';
|
'use strict';
const nock = require('nock');
const watson = require('../../index');
const authHelper = require('./auth_helper.js');
const auth = authHelper.auth;
const describe = authHelper.describe; // this runs describe.skip if there is no auth.js file :)
const TWENTY_SECONDS = 20000;
const TWO_SECONDS = 2000;
describe('language_translator_integration', function() {
this.timeout(TWENTY_SECONDS * 2);
this.slow(TWO_SECONDS); // this controls when the tests get a colored warning for taking too long
this.retries(1);
let language_translator;
before(function() {
language_translator = watson.language_translator(auth.language_translator);
nock.enableNetConnect();
});
after(function() {
nock.disableNetConnect();
});
it('getModels()', function(done) {
language_translator.getModels(null, done);
});
it('translate()', function(done) {
const params = {
text: 'this is a test',
source: 'en',
target: 'es'
};
language_translator.translate(params, done);
});
it('getIdentifiableLanguages()', function(done) {
language_translator.getIdentifiableLanguages(null, done);
});
it('identify()', function(done) {
const params = {
text: 'this is an important test that needs to work'
};
language_translator.identify(params, done);
});
});
|
import React from 'react'
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import Card from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import Typography from 'material-ui/Typography'
import Api from '../../../data/api'
import {CircularProgress} from "material-ui/Progress";
import {withStyles} from 'material-ui/styles';
import PropTypes from 'prop-types';
import List, { ListItem, ListItemText } from 'material-ui/List';
import Avatar from 'material-ui/Avatar';
import ImageIcon from 'material-ui-icons/Image';
// TODO: need to add alert library to store as well
// import Alert from '../../Shared/alert'
const styles = theme => ({
titleBar: {
display: 'flex',
justifyContent: 'space-between',
borderBottomWidth: '1px',
borderBottomStyle: 'solid',
borderColor: theme.palette.text.secondary,
marginBottom: 20,
}
});
class Forum extends React.Component {
constructor(props) {
super(props);
this.state = {
commentList: null,
comment: '',
api: {}
};
this.api_uuid = this.props.match.params.api_uuid;
this.updateCommentString = this.updateCommentString.bind(this);
this.handleAddComment = this.handleAddComment.bind(this);
this.getAllComments();
}
getAllComments() {
let api = new Api();
let promise_get = api.getAllComments(this.api_uuid);
promise_get.then(
response => {
this.setState({commentList: response.obj.list});
}).catch(
error => {
console.error(error);
/* TODO: Uncomment below line when Alert library is added to store */
// Alert.error("Error occurred while retrieving comments!");
}
);
}
updateCommentString(event) {
this.setState({comment: event.target.value});
}
handleAddComment() {
let api = new Api();
let commentInfo = {"commentText": this.state.comment};
let promise = api.addComment(this.api_uuid, commentInfo);
promise.then(
response => {
this.getAllComments();
this.setState({comment: ''});
// TODO: uncomment below once the alert library is added to store
// Alert.success("Comment added successfully");
}).catch(
error => {
// TODO: uncomment below once the alert library is added to store ~tmkb
// Alert.error("Error occurred while adding comments!");
}
);
}
render() {
const {commentList, comment, api} = this.state;
const { classes } = this.props;
return (
<Grid container>
<Grid item xs={12} sm={12} md={12} lg={11} xl={10} >
<TextField
label="Comment"
InputLabelProps={{
shrink: true,
}}
helperText="Please proved your comments on this API "
fullWidth
name="name"
multiline
rows="4"
onChange={this.updateCommentString}
placeholder="Type your comments here"
autoFocus={true}
className={classes.inputText}
/>
</Grid>
<Grid item xs={12} sm={12} md={12} lg={11} xl={10} >
<Button variant="raised" color="primary" onClick={this.handleAddComment}>
Add New Comment
</Button>
</Grid>
<Grid item xs={12}>
<Paper>
<List>
{commentList ? commentList.map((comment,index) => (
<ListItem key={index}>
<Avatar>
<ImageIcon />
</Avatar>
<ListItemText primary={comment.commentText}
secondary={ "Posted By " + comment.createdBy + " at " + comment.createdTime } />
</ListItem>))
:
<CircularProgress/>
}
</List>
</Paper>
</Grid>
</Grid>
);
}
}
Forum.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Forum);
|
/*
* Copyright (c) 2011-2016 Pivotal Software 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.
*/
import React from 'react';
class Metric extends React.Component {
render() {
return (
<div>
<div className="heading">
<strong>Metrics</strong>
</div>
</div>
);
}
}
export default Metric;
|
/* @flow */
export default {
id: 'import-syntax',
title: 'Import Syntax',
description: `\`\`\`
import Menu, { MenuGroup } from 'mineral-ui/Menu';
\`\`\``
};
|
(function(){
function AlbumCtrl(Fixtures, SongPlayer) {
this.albumData = Fixtures.getAlbum();
this.songPlayer = SongPlayer;
}
angular
.module('blocJams')
.controller('AlbumCtrl', ['Fixtures', 'SongPlayer', AlbumCtrl]);
})();
|
(function() {
angular
.module("zenigmesApp")
.controller("resetCtrl", resetCtrl);
resetCtrl.$inject = ["$location", "$uibModal","$routeParams", "authentication"];
function resetCtrl($location, $uibModal, $routeParams, authentication) {
var vm = this;
vm.pageHeader = {
title: "Réinitialisation du mot de passe"
};
var resetToken = $routeParams.resetToken;
vm.onSubmit = function() {
vm.formError = "";
if (!vm.newPassword || !vm.passwordCheck) {
vm.formError = "Tous les champs sont requis, veuillez réessayer";
return false;
} else if (vm.newPassword !== vm.passwordCheck){
vm.formError = "Les deux mots de passe ne correspondent pas";
return false;
} else {
_resetPassword();
}
};
var _resetPassword = function() {
vm.formError = "";
authentication
.resetPassword(resetToken, vm.newPassword)
.then(function() {
var modalInstance = $uibModal.open({
templateUrl: "app/auth/reset/resetModal.template.html",
controller: "answerModalCtrl as vm"
});
modalInstance.result.then(function(data) {
$location.path("/");
});
}, function(err) {
vm.formError = err.data.message;
});
};
}
})();
|
'use strict';
// Benchmark comparing performance of event emit for single listener
// To run it, do following in memoizee package path:
//
// $ npm install eventemitter2 signals
// $ node benchmark/single-on.js
var forEach = require('es5-ext/lib/Object/for-each')
, pad = require('es5-ext/lib/String/prototype/pad')
, now = Date.now
, time, count = 1000000, i, data = {}
, ee, native, ee2, signals, a = {}, b = {};
ee = (function () {
var ee = require('../lib/core');
return ee().on('test', function () {
return arguments;
});
}());
native = (function () {
var ee = require('events');
return (new ee.EventEmitter()).on('test', function () {
return arguments;
});
}());
ee2 = (function () {
var ee = require('eventemitter2');
return (new ee.EventEmitter2()).on('test', function () {
return arguments;
});
}());
signals = (function () {
var Signal = require('signals')
, ee = {test: new Signal()};
ee.test.add(function () {
return arguments;
});
return ee;
}());
console.log("Emit for single listener", "x" + count + ":\n");
i = count;
time = now();
while (i--) {
ee.emit('test', a, b);
}
data["event-emitter (this implementation)"] = now() - time;
i = count;
time = now();
while (i--) {
native.emit('test', a, b);
}
data["EventEmitter (Node.js native)"] = now() - time;
i = count;
time = now();
while (i--) {
ee2.emit('test', a, b);
}
data.EventEmitter2 = now() - time;
i = count;
time = now();
while (i--) {
signals.test.dispatch(a, b);
}
data.Signals = now() - time;
forEach(data, function (value, name, obj, index) {
console.log(index + 1 + ":", pad.call(value, " ", 5), name);
}, null, function (a, b) {
return this[a] - this[b];
});
|
$(function() {
var resposta = $.ajax({
url:"http://localhost:8080/estados",
method: "GET",
dataType: "jsonp"//usado por estar em domínios diferentes
});
//A requisição Ajax pode demorar a retornar uma resposta
//com Promises é possível utilizar o método done() que executa
//assim que a requisição retornar uma resposta. Pode-se utilizar mais
//de uma vez.
resposta.done(function(estados) {
var comboEstado = $("#combo-estado");
//comboEstado.empty();
comboEstado.html("<option>Selecione o estado</option>")
estados.forEach(function(estado) {
//cria uma elemento 'option' e adiciona no select
var optionEstado = $("<option>").val(estado.uf).text(estado.nome);
comboEstado.append(optionEstado);
});
});
resposta.fail(function() {
alert("Erro carregando dados do servidor.");
});
});
|
var Redirects = function () {
this.respondsWith = ['html', 'json', 'xml', 'js', 'txt'];
this.index = function (req, resp, params) {
var self = this;
geddy.model.Redirect.all(function(err, redirects) {
self.respondWith(redirects, {type:'Redirect'});
});
};
this.add = function (req, resp, params) {
this.respond({params: params});
};
this.create = function (req, resp, params) {
var self = this
, redirect = geddy.model.Redirect.create(params);
if (!redirect.isValid()) {
this.respondWith(redirect);
}
else {
redirect.save(function(err, data) {
if (err) {
throw err;
}
if(err)
return self.respondWith(redirect, {status: err});
self.redirect({controller: 'redirects'});
});
}
};
this.show = function (req, resp, params) {
var self = this;
geddy.model.Redirect.first(params.id, function(err, redirect) {
if (err) {
throw err;
}
if (!redirect) {
throw new geddy.errors.NotFoundError();
}
else {
self.respondWith(redirect);
}
});
};
this.edit = function (req, resp, params) {
var self = this;
geddy.model.Redirect.first(params.id, function(err, redirect) {
if (err) {
throw err;
}
if (!redirect) {
throw new geddy.errors.BadRequestError();
}
else {
self.respondWith(redirect);
}
});
};
this.update = function (req, resp, params) {
var self = this;
geddy.model.Redirect.first(params.id, function(err, redirect) {
if (err) {
throw err;
}
redirect.updateProperties(params);
if (!redirect.isValid()) {
self.respondWith(redirect);
}
else {
redirect.save(function(err, data) {
if (err) {
throw err;
}
self.respondWith(redirect, {status: err});
});
}
});
};
this.remove = function (req, resp, params) {
var self = this;
geddy.model.Redirect.first(params.id, function(err, redirect) {
if (err) {
throw err;
}
if (!redirect) {
throw new geddy.errors.BadRequestError();
}
else {
geddy.model.Redirect.remove(params.id, function(err) {
if (err) {
throw err;
}
self.respondWith(redirect);
});
}
});
};
};
exports.Redirects = Redirects;
|
/* @flow */
import { bool, node, number, oneOfType, string } from 'prop-types';
export const iconPropTypes = {
children: node,
color: string,
rtl: bool,
size: oneOfType([number, string]),
title: string
};
|
/*!
* Bootstrap-select v1.6.4 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2015 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Nu a fost selectat nimic',
noneResultsText: 'Nu exista niciun rezultat {0}',
countSelectedText: '{0} din {1} selectat(e)',
maxOptionsText: ['Limita a fost atinsa ({n} {var} max)', 'Limita de grup a fost atinsa ({n} {var} max)', ['iteme', 'item']],
multipleSeparator: ', '
};
})(jQuery);
|
// Задание 11
// Войти на главную страницу http://localhost/litecart
// Зарегистрировать нового пользователя
// Выйти - Logout
// Авторизоваться пользователем и выйти
var webdriver = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var By = webdriver.By;
var until = webdriver.until;
var test = require('selenium-webdriver/testing');
var assert = require('assert');
var Key = webdriver.Key;
var $q=require('q');
test.describe('Регистрация пользователя', function() {
var driver; var email; var password;
var getRandomNumber = function () {
var n=100; var m=1000;
return Math.floor(Math.random( ) * (n - m + 1)) + m
};
test.before(function() {
driver = new webdriver.Builder()
.withCapabilities({'unexpectedAlertBehaviour': 'dismiss'})
.forBrowser('chrome')
.build();
driver.get('http://localhost/litecart/');
driver.manage().timeouts().implicitlyWait(10000/*ms*/);
});
test.after(function() {
driver.quit();
});
test.it('Регистрируемся', function() {
var inputField;
var number =getRandomNumber();
var firstname = "Marina";
var lastname = "Tolmacheva" + number;
email = "emailUser"+number+"@list.ru";
password = lastname;
driver.findElement(By.linkText("New customers click here")).click().then(
(click)=> {
driver.findElement(By.name("firstname")).sendKeys(firstname + Key.TAB
+ lastname + Key.TAB + "100 let Vladivostoky" + Key.TAB + "Davydova" + Key.TAB
+ "69006" + Key.TAB + "Vladivostok" + Key.TAB + "United States"
+ Key.TAB + email + Key.TAB + "+7 914 123 98 70" + Key.TAB
+ password + Key.TAB + password).then(()=>
driver.findElement(By.css("select[name = 'country_code']")).getAttribute("value")
.then((text) =>{
if (text == "US") {
var selectElem = driver.findElement(By.css("select[name = 'zone_code']"));
selectElem.click();
selectElem.findElement(By.css("option[value='AK']")).click();
}
})).then(()=>
driver.findElement(By.css("input[name='newsletter']")).getAttribute("value")
.then((text) =>{
if (text == "1") {
driver.findElement(By.css("input[name='newsletter']")).click();
}
})).then(()=>
driver.findElement(By.css("button[name='create_account']")).click()).then(()=>
driver.wait(driver.findElement(By.linkText("Logout")).click(),1000));
}
);
});
test.it('Авторизация', function () {
driver.findElement(By.name("email")).sendKeys(email).then(()=>
driver.findElement(By.name("password")).sendKeys(password)).then(()=>
driver.wait(driver.findElement(By.css("button[name = 'login'")).click(), 1000)).then(()=>
driver.wait(driver.findElement(By.linkText("Logout")).click(), 1000));
});
});
|
const fs = require('fs');
const path = require('path');
const { COPYFILE_EXCL } = fs.constants;
function isConflict(origStat, stat)
{
return stat != null && origStat != null && stat.mtimeMs != origStat.mtimeMs;
};
function saveFile(fileObject, data, origStat, overwrite, defEnc, reqId)
{
var retryCount = 0;
var backupCreated = false;
var writeFile = function()
{
if (data == null || data.length == 0)
{
postMessage({error: true, msg: 'empty data', reqId: reqId});
}
else
{
var writeEnc = defEnc || fileObject.encoding;
fs.writeFile(fileObject.path, data, writeEnc,
function (e)
{
if (e)
{
postMessage({error: true, msg: 'saving failed', e: e, reqId: reqId});
}
else
{
fs.stat(fileObject.path, function(e2, stat2)
{
if (e2)
{
postMessage({error: true, msg: 'stat failed', e: e2, reqId: reqId});
}
else
{
// Workaround for possible writing errors is to check the written
// contents of the file and retry 3 times before showing an error
fs.readFile(fileObject.path, writeEnc, (err, writtenData) =>
{
if (data != writtenData)
{
retryCount++;
if (retryCount < 3)
{
writeFile();
}
else
{
postMessage({error: true, msg: 'all saving trials failed', e: e, reqId: reqId});
}
}
else
{
postMessage({success: true, data: {stat: stat2}, reqId: reqId});
if (backupCreated)
{
fs.unlink(fileObject.bkpPath, (err) => {}); //Ignore errors!
}
}
});
}
});
}
});
}
};
function doSaveFile()
{
//Copy file to backup file (after conflict and stat is checked)
fs.copyFile(fileObject.path, fileObject.bkpPath, COPYFILE_EXCL, (err) =>
{
if (!err)
{
backupCreated = true;
}
writeFile();
});
};
if (overwrite)
{
doSaveFile();
}
else
{
//TODO Using stat before write is not recommended, we can check the error code from writeFile
fs.stat(fileObject.path, function(err, stat)
{
if (isConflict(origStat, stat))
{
postMessage({error: true, msg: 'conflict', e: {isConflicted: true}, reqId: reqId});
}
else if (err != null && err.code !== 'ENOENT')
{
postMessage({error: true, msg: 'stat failed', e: err, reqId: reqId});
}
else
{
doSaveFile();
}
});
}
};
//TODO handle reqId better
onmessage = function(e)
{
switch(e.data.action)
{
case 'saveFile':
saveFile(e.data.fileObject, e.data.data, e.data.origStat, e.data.overwrite, e.data.defEnc, e.data.reqId);
break;
};
};
|
define(function (require) {
"use strict";
var fixtures = require("fixtures");
var net = require("net");
QUnit.module("Unit test: net/http/header");
QUnit.test("Can parse HTTP request headers with line break '\\n'", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withLineEndings("\n")
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "Valid header value is parsed.");
});
QUnit.test("Can parse a HTTP request with line break '\\r\\n'", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withLineEndings("\r\n")
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "Valid header value is parsed.");
});
QUnit.test("Request header is either separated from body with empty line or the whole payload is header.", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withLineEndings("\n")
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.build();
// Act
var httpHeader = net.http.header.fromData(testData + "\n\nIGNORE: THIS");
// Assert
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "Valid header value is parsed.");
QUnit.strictEqual(httpHeader.getHeaderValue("IGNORE"), null, "Ignoring things after empty line.");
});
QUnit.test("Can read valid request header values and they are case insensitive", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withRequestLine("POST /foo/bar HTTP/1.1")
.withKeyValuePair("HOST", "192.168.1.1:58008")
.withKeyValuePair("CONTENT-TYPE", "text/xml")
.withKeyValuePair("CONTENT-LENGTH", "1234")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.action, "POST", "The request action could be read.");
QUnit.strictEqual(httpHeader.requestPath, "/foo/bar", "The request path could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("HOST"), "192.168.1.1:58008", "HOST value is correct.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-type"), "text/xml", "CONTENT-TYPE value is correct.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-LENGTH"), "1234", "CONTENT-LENGTH value is correct.");
});
QUnit.test("Can read response header values and they are case insensitive", function () {
// Arrange
var testData = fixtures.builders.httpHeaderBuilder()
.withRequestLine("HTTP/1.1 418 I'm a teapot")
.withKeyValuePair("CONTENT-TYPE", "coffee")
.withKeyValuePair("CONTENT-LENGTH", "0")
.build();
// Act
var httpHeader = net.http.header.fromData(testData);
// Assert
QUnit.strictEqual(httpHeader.code, 418, "The response code could be read.");
QUnit.strictEqual(httpHeader.statusMessage, "I'm a teapot", "The response status message could be read.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-type"), "coffee", "CONTENT-TYPE value is correct.");
QUnit.strictEqual(httpHeader.getHeaderValue("content-LENGTH"), "0", "CONTENT-LENGTH value is correct.");
});
}
);
|
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.route('resume');
this.route('wip');
});
export default Router;
|
// .po file like language pack
plupload.addI18n({
'Select files' : 'Vyberte soubory',
'Add files to the upload queue and click the start button.' : 'Přidejte soubory do fronty a pak spusťte nahrávání.',
'Filename' : 'Název souboru',
'Status' : 'Status',
'Size' : 'Velikost',
'Add Files' : 'Přidat soubory',
'Stop current upload' : 'Zastavit nahrávání',
'Start uploading queue' : 'Spustit frontu nahrávání',
'Drag files here.' : 'Sem přetáhněte soubory.',
'Start Upload': 'Spustit nahrávání',
'Uploaded %d/%d files': 'Nahráno %d/%d souborů'
});
|
export const template = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><script>//inject_title</script></title>
<base target="_self">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<script>//inject_meta</script>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,minimal-ui">
<meta name="format-detection" content="telephone=no,email=no,address=no">
<meta name="format-detection" content="email=no">
<meta name="format-detection" content="address=no">
<meta name="format-detection" content="telephone=no">
<meta name="HandheldFriendly" content="true">
<meta name="mobile-web-app-capable" content="yes">
<!-- IE/Edge -->
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!-- iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- for Facebook -->
<meta property="og:title" content="xxx">
<meta property="og:type" content="website">
<meta property="og:description" content="xxx">
<meta property="og:image" content="xxx">
<meta name="copyright" content="Copyright (c) xxx">
<meta name="theme-color" content="#371273" />
<link href="//cdn.bootcss.com/meyer-reset/2.0/reset.min.css" rel="stylesheet">
<script>//inject_component_styles</script>
</head>
<body>
<div id="root">
<div><script>//inject_html</script></div>
</div>
<script>//inject_redux_state</script>
<script>//inject_js</script>
</body>
</html>
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?e76ecaf50bab944f2c62edf3f6588a9d";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
`
|
var EPG = {
pressLeft : function() {
},
pressRight : function() {
},
pressUp : function() {
var element = document.getElementsByClassName("selected")[0];
var previousSiblingElement = element.previousElementSibling;
if (null != previousSiblingElement) {
classList(element).remove("selected");
classList(previousSiblingElement).add("selected");
}
},
pressDown : function() {
var element = document.getElementsByClassName("selected")[0];
var nextSiblingElement = element.nextElementSibling;
if (null != nextSiblingElement) {
classList(element).remove("selected");
classList(nextSiblingElement).add("selected");
}
},
pressEnter : function() {
var gameId = document.getElementsByClassName("selected")[0].id;
window.location.href = "http://39.98.243.254:8080/lobby/game.jsp?gamename="
+ gameId;
}
};
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var pow = require( '@stdlib/math/base/special/pow' );
// MAIN //
/**
* Computes an exponential delay.
*
* @private
* @param {NonNegativeInteger} retries - number of retries
* @param {number} max - maximum delay
* @returns {NonNegativeInteger} exponential delay
*/
function delay( retries, max ) {
var d = pow( 2, retries ) - 1;
if ( d > max ) {
d = max;
}
return d;
}
// EXPORTS //
module.exports = delay;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
var _createShareButton = require('./utils/createShareButton');
var _createShareButton2 = _interopRequireDefault(_createShareButton);
var _objectToGetParams = require('./utils/objectToGetParams');
var _objectToGetParams2 = _interopRequireDefault(_objectToGetParams);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function instapaperLink(url, _ref) {
var title = _ref.title,
description = _ref.description;
(0, _assert2.default)(url, 'instapaper.url');
return 'http://www.instapaper.com/hello2' + (0, _objectToGetParams2.default)({
url: url,
title: title,
description: description
});
}
var InstapaperShareButton = (0, _createShareButton2.default)('instapaper', instapaperLink, function (props) {
return {
title: props.title,
description: props.description
};
}, {
title: _propTypes2.default.string,
description: _propTypes2.default.string
}, {
windowWidth: 500,
windowHeight: 500
});
exports.default = InstapaperShareButton;
|
sap.ui.define([
"sap/ui/core/Control",
"sap/ui/core/HTML",
"sap/ui/core/ResizeHandler",
"sap/ui/dom/jquery/rect" // provides jQuery.fn.rect
], function(Control, HTML, ResizeHandler) {
"use strict";
return Control.extend("sap.ui.demo.toolpageapp.control.D3Chart", {
metadata: {
properties: {
type: {type: "string", defaultValue: "Radial"}
},
aggregations: {
_html: {
type: "sap.ui.core.HTML",
multiple: false,
visibility: "hidden"
},
data: {
type: "sap.ui.base.ManagedObject",
multiple: true
}
},
defaultAggregation: "data"
},
_iHeight: null,
_sContainerId: null,
_sResizeHandlerId: null,
/**
* Initialize hidden html aggregation
*/
init: function () {
this._sContainerId = this.getId() + "--container";
this._iHeight = 130;
this.setAggregation("_html", new HTML(this._sContainerId, {
content: "<svg id=\"" + this._sContainerId + "\" width=\"100%\" height=\"130px\"></svg>"
}));
},
_onResize: function (oEvent) {
this._updateSVG(oEvent.size.width);
},
onBeforeRendering: function () {
ResizeHandler.deregister(this._sResizeHandlerId);
},
onAfterRendering: function () {
this._sResizeHandlerId = ResizeHandler.register(
this,
this._onResize.bind(this));
var $control = this.$();
if ($control.length > 0) {
// jQuery Plugin "rect"
this._updateSVG($control.rect().width);
}
},
renderer: {
apiVersion: 2,
/**
* Renders the root div and the HTML aggregation
* @param {sap.ui.core.RenderManger} oRM the render manager
* @param {sap.ui.demo.toolpageapp.control.D3Chart} oControl the control to be rendered
*/
render: function (oRM, oControl) {
oRM.openStart("div", oControl);
oRM.class("customD3Chart");
oRM.openEnd();
oRM.renderControl(oControl.getAggregation("_html"));
oRM.close("div");
}
}
});
});
|
/*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* 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.
*/
var _ = require('lodash');
function appListModel() {
'use strict';
function init() {
return {
'apps': [],
'detail': {}
};
}
return {
// State
state: init(),
handlers: {
'appDetail': 'detail',
'appList': 'list'
},
detail: function (r) {
// Sort in descending by deploy id
this.state.detail[r.id.toString()] = _.sortByOrder(r.data, ['Id'], [false]);
this.emitChange();
},
list: function (r) {
this.state.apps = r.data;
this.emitChange();
},
exports: {
apps: function () {
return this.state.apps;
},
detail: function (id) {
if (id === undefined) {
return this.state.detail;
}
var ret = this.state.detail[id.toString()];
return ret ? ret : {};
}
}
};
}
module.exports = appListModel;
|
angular.module( 'qkstrt', [
'templates-app',
'templates-common',
'qkstrt.home',
'ui.router'
])
.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) {
$urlRouterProvider.otherwise( '/home' );
})
.run( function run () {
})
.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
if ( angular.isDefined( toState.data.pageTitle ) ) {
$scope.pageTitle = toState.data.pageTitle + ' | qkstrt' ;
}
});
})
;
|
{
graphitePort: 2003
, graphiteHost: "{{ inventory_hostname }}"
, port: 8125
, backends: [ "./backends/graphite" ]
, graphite: {
legacyNamespace: false
}
}
|
'use strict';
var mongodb = require ('@onehilltech/blueprint-mongodb')
, StatPlugin = mongodb.plugins.StatPlugin
;
var schema = new mongodb.Schema ({
name: {type: String, required: true, trim: true},
location: {type: String, required: true, trim: true},
website: {type: String, required: true, trim: true},
industry: {type: String, required: true, trim: true}
});
// register stat plugin with schema
schema.plugin (StatPlugin);
const MODEL_NAME = 'organization';
const COLLECTION_NAME = 'organizations';
module.exports = mongodb.resource (MODEL_NAME, schema, COLLECTION_NAME);
|
require('chai').should();
var viewTestUtils = require('./utils/view-test-utils');
var test_date = new Date();
describe('Pie Sink View', function () {
var PieView = require('../../src/views/piechart');
describe('invalid params', function() {
it('unknown top level field', function() {
viewTestUtils.verifyValidationError({
viewConstructor : PieView,
params : {
columnOrder : 'asdf'
},
errorPath : 'columnOrder',
error : {
'code' : 'UNKNOWN',
'info' : {}
}
});
});
it('non-string sliceLabels.valueFormat', function() {
viewTestUtils.verifyValidationError({
viewConstructor : PieView,
params : {
sliceLabels : {
valueFormat : 1
}
},
errorPath : 'sliceLabels.valueFormat',
error : {
'code' : 'INVALID_TYPE',
'info' : {
'type' : 'STRING'
}
}
});
});
it('non-string valueField', function() {
viewTestUtils.verifyValidationError({
viewConstructor : PieView,
params : {
valueField : []
},
errorPath : 'valueField',
error : {
'code' : 'INVALID_TYPE',
'info' : {
'type' : 'STRING'
}
}
});
});
it('non-string categoryField', function() {
viewTestUtils.verifyValidationError({
viewConstructor : PieView,
params : {
categoryField : {}
},
errorPath : 'categoryField',
error : {
'code' : 'INVALID_TYPE',
'info' : {
'type' : 'STRING'
}
}
});
});
it('radiusInner too big', function() {
viewTestUtils.verifyValidationError({
viewConstructor : PieView,
params : {
radiusInner : 150
},
errorPath : 'radiusInner',
error : {
'code' : 'OUT_OF_RANGE',
'info' : {
'threshold' : 100,
'type' : 'LESS_THAN_OR_EQUAL'
}
}
});
});
it('radiusInner too small', function() {
viewTestUtils.verifyValidationError({
viewConstructor : PieView,
params : {
radiusInner : -1
},
errorPath : 'radiusInner',
error : {
'code' : 'OUT_OF_RANGE',
'info' : {
'threshold' : 0,
'type' : 'GREATER_THAN_OR_EQUAL'
}
}
});
});
});
describe('Runtime Messages', function () {
it('waiting for data', function() {
var chart = new PieView({});
chart.setDimensions(null, 100, 100);
viewTestUtils.verifyRuntimeMessage(chart, 'WAITING_FOR_DATA');
chart.consume([
{ time : test_date, value : 1, pop : 'pop1' }
]);
viewTestUtils.verifyNoRuntimeMessages(chart);
});
it('all categories are 0', function() {
var chart = new PieView({});
chart.setDimensions(null, 100, 100);
chart.consume([
{ time : test_date, value : 0, pop : 'pop1' }
]);
viewTestUtils.verifyRuntimeMessage(chart, 'ALL_CATEGORIES_ARE_ZERO');
chart.consume([
{ time : test_date, value : 1, pop : 'pop2' }
]);
viewTestUtils.verifyNoRuntimeMessages(chart);
chart.consume([
{ time : test_date, value : 0, pop : 'pop3' }
]);
viewTestUtils.verifyNoRuntimeMessages(chart);
});
it('No Data Received', function() {
var chart = new PieView({});
chart.setDimensions(null, 100, 100);
chart.consume_eof();
viewTestUtils.verifyRuntimeMessage(chart, 'NO_DATA_RECEIVED');
});
it('Value field does not exist', function() {
var chart = new PieView({
params : {
valueField : 'v',
categoryField : 'host'
}
});
chart.setDimensions(null, 100, 100);
chart.consume([
{ time: test_date, host: 'host1', value: 1 },
{ time: test_date, host: 'host2', value: 1 },
{ time: test_date, host: 'host3', value: 1 },
{ time: test_date, host: 'host4', value: 1 },
{ time: test_date, host: 'host5', value: 1 }
]);
viewTestUtils.verifyRuntimeMessage(chart, 'VALUE_FIELD_NON_NUMERIC', {
valueField : 'v'
});
});
it('doesn\'t complain about timeless points', function() {
var chart = new PieView({});
chart.setDimensions(null, 200, 200);
chart.consume([
{
category: 'A',
value: 1
},
{
category: 'B',
value: 1
}
]);
viewTestUtils.verifyNoRuntimeMessages(chart);
});
});
});
|
import React, {Component} from 'react';
class Signup extends Component {
handleSignup(e) {
e.preventDefault();
if ($('#user').val() === '' || $('#pass').val() === '' || $('#pass2').val() === '') {
handleError('Please fill out all fields.');
return false;
}
if ($('#pass').val() !== $('#pass2').val()) {
handleError('Please make sure the passwords match.');
return false;
}
sendAjax('POST', $('#signupForm').attr('action'), $('#signupForm').serialize(), redirect);
return false;
}
render() {
return (
<form id="signupForm" name="signupForm" onSubmit={this.handleSignup} action="/signup" method="POST" className="mainForm">
<div className="ui input textField">
<input id="user" type="text" name="username" placeholder="Username"/>
</div>
<div className="ui input textField">
<input id="pass" type="password" name="pass" placeholder="Password"/>
</div>
<div className="ui input textField">
<input id="pass2" type="password" name="pass2" placeholder="Confirm Password"/>
</div>
<input type="hidden" name="_csrf" value={this.props.csrf}/>
<button className="large ui orange button loginButton" type="submit" form="signupForm" value="Sign Up">Sign Up</button>
<div className="signUpBlurb">
Already have an account?
<a className="signUpLink" onClick={this.props.onLogin}> Login </a>
here!
</div>
</form>
);
}
}
export default Signup;
|
// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Ti.UI.setBackgroundColor('#000');
Ti.UI.iPhone.statusBarStyle = Ti.UI.iPhone.StatusBar.OPAQUE_BLACK;
//Create main app namespace
var demo={};
//Create a few helpers
demo.myHelpers = {
isAndroid : function(){
return (Ti.Platform.name == 'android');
},
makeWindow : function(a){
a = a || {};
var win = Ti.UI.createWindow(a);
//Force the orientations
win.orientationModes = [
Ti.UI.PORTRAIT,
Ti.UI.UPSIDE_PORTRAIT
];
return win;
}
};
//Bring in the child windows
Ti.include('main.js','picker.js');
//Bring in the color picker functions (CommonJS format)
demo.colorHelper = require('colorhelper');
//Create our configs
var winConfig = {
title:Ti.Locale.getString('sample_win_title'),
barColor:'#000',
backgroundColor:'#fff',
tabBarHidden:true,
fullscreen:false,
navBarHidden : (Ti.Platform.name == 'android')
};
//Create the main launch window
demo.mainWindow = demo.launchMainWindow(winConfig);
//Check if we didn't return the window correctly
if(demo.mainWindow===null){
alert(Ti.Locale.getString('forgot_return'));
}
//Add an app listener for the event sample
Ti.App.addEventListener('color:update_color', function(e){
demo.mainWindow.backgroundColor=e.selectedColor;
});
//Based on platfomr launch the App in a specific way
if(Ti.Platform.name!=='android'){
var tabGroup = Ti.UI.createTabGroup();
var tab1 = Ti.UI.createTab({window:demo.mainWindow});
tabGroup.addTab(tab1);
// open tab group
tabGroup.open();
}else{
demo.mainWindow.open();
}
|
Clazz.declarePackage ("J.util");
c$ = Clazz.decorateAsClass (function () {
this.entryCount = 0;
this.entries = null;
Clazz.instantialize (this, arguments);
}, J.util, "Int2IntHash");
Clazz.makeConstructor (c$,
function (initialCapacity) {
this.entries = new Array (initialCapacity);
}, "~N");
$_M(c$, "get",
function (key) {
var entries = this.entries;
var hash = (key & 0x7FFFFFFF) % entries.length;
for (var e = entries[hash]; e != null; e = e.next) if (e.key == key) return e.value;
return -2147483648;
}, "~N");
$_M(c$, "put",
function (key, value) {
var entries = this.entries;
var hash = (key & 0x7FFFFFFF) % entries.length;
for (var e = entries[hash]; e != null; e = e.next) if (e.key == key) {
e.value = value;
return;
}
if (this.entryCount > entries.length) this.rehash ();
entries = this.entries;
hash = (key & 0x7FFFFFFF) % entries.length;
entries[hash] = new J.util.Int2IntHash.Entry (key, value, entries[hash]);
++this.entryCount;
}, "~N,~N");
$_M(c$, "rehash",
($fz = function () {
var oldEntries = this.entries;
var oldSize = oldEntries.length;
var newSize = oldSize * 2 + 1;
var newEntries = new Array (newSize);
for (var i = oldSize; --i >= 0; ) {
for (var e = oldEntries[i]; e != null; ) {
var t = e;
e = e.next;
var hash = (t.key & 0x7FFFFFFF) % newSize;
t.next = newEntries[hash];
newEntries[hash] = t;
}
}
this.entries = newEntries;
}, $fz.isPrivate = true, $fz));
Clazz.pu$h ();
c$ = Clazz.decorateAsClass (function () {
this.key = 0;
this.value = 0;
this.next = null;
Clazz.instantialize (this, arguments);
}, J.util.Int2IntHash, "Entry");
Clazz.makeConstructor (c$,
function (a, b, c) {
this.key = a;
this.value = b;
this.next = c;
}, "~N,~N,J.util.Int2IntHash.Entry");
c$ = Clazz.p0p ();
|
var dir_868198085b236c6136218653797759d1 =
[
[ "ComponentConfigCommand.java", "ComponentConfigCommand_8java.html", [
[ "ComponentConfigCommand", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentConfigCommand.html", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentConfigCommand" ]
] ],
[ "ComponentConfigCommandCompleter.java", "ComponentConfigCommandCompleter_8java.html", [
[ "ComponentConfigCommandCompleter", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentConfigCommandCompleter.html", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentConfigCommandCompleter" ]
] ],
[ "ComponentNameCompleter.java", "ComponentNameCompleter_8java.html", [
[ "ComponentNameCompleter", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentNameCompleter.html", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentNameCompleter" ]
] ],
[ "ComponentPropertyNameCompleter.java", "ComponentPropertyNameCompleter_8java.html", [
[ "ComponentPropertyNameCompleter", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentPropertyNameCompleter.html", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1ComponentPropertyNameCompleter" ]
] ],
[ "NetworkConfigCommand.java", "NetworkConfigCommand_8java.html", [
[ "NetworkConfigCommand", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1NetworkConfigCommand.html", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1NetworkConfigCommand" ]
] ],
[ "NetworkConfigRegistryCommand.java", "NetworkConfigRegistryCommand_8java.html", [
[ "NetworkConfigRegistryCommand", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1NetworkConfigRegistryCommand.html", "classorg_1_1onosproject_1_1cli_1_1cfg_1_1NetworkConfigRegistryCommand" ]
] ],
[ "package-info.java", "cli_2src_2main_2java_2org_2onosproject_2cli_2cfg_2package-info_8java.html", null ]
];
|
module.exports = function(w)
{
var global = require('ui/common/globals');
w.barImage='images/iPhone_Nav_Bar_Bkgrd_With_Black.png';
// This is where I am going put the with all the results.
var overview = Ti.UI.createView({
width: Ti.UI.FILL,
height: Ti.UI.SIZE,
layout: 'vertical',
top: 0
});
// Creates back button
var back = Ti.UI.createButton({ title: "Back" });
back.addEventListener("click", function()
{
w.close({animated:true});
});
w.setLeftNavButton(back);
// Creates top label
var top_label = Ti.UI.createLabel({
text: 'Settings',
color: 'white',
font:{
fontFamily:'Helvetica Neue',
fontSize:18,
fontWeight:'Bold'
},
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
width: Ti.UI.FILL,
height: 40,
top:0,
backgroundColor: global.colors.dark,
});
w.add(top_label)
var logout_button = Ti.UI.createButton({
top: 60,
width: Ti.UI.FILL,
height: 42,
left: 10,
right: 10,
backgroundColor: global.colors.dark,
backgroundImage:'none',
color: 'white',
font:{
fontFamily:'Helvetica Neue',
fontSize:18,
},
borderRadius: 5,
title: 'Logout'
});
overview.add(logout_button);
logout_button.addEventListener('click', function(e){
global.api.logout(function(data){
Ti.App.fireEvent('user_logout', {});
});
//alert('You have successfully logged out');
});
// add overview to the window.
w.add(overview);
}
//*/
|
jQuery(document).ready(function($) {
$('#addmoreitem').click(function() {
var lastid = $('.uploadevent').last().attr('id');
for(var i = 1; i < 5; i++){
var addId = Number(lastid)+Number(i);
var addHtml = '<div class="panel-group" id="accordion"><div class="panel panel-default"><div class="panel-heading"><div class="input-group"><input type="text" name="vote_item_name['+addId+']" class="form-control" placeholder="选项'+addId+'"><div class="input-group-btn"><a type="button" class="btn btn-default uploadevent" data-toggle="collapse" data-parent="#accordion" href="#add_info_'+addId+'">添加详情</a></div></div></div><div id="add_info_'+addId+'" class="panel-collapse collapse"><div class="panel-body"><input type="hidden" name="vote_item_attach['+addId+']" id="vote_item_attach_'+addId+'"><button type="button" class="btn btn-info uploadevent" tabindex="-1" data-toggle="modal" data-target="#model_upload" id="'+addId+'">上传附件</button><br><br><textarea class="form-control" rows="2" name="vote_item_description['+addId+']" placeholder="选项描述"></textarea></div></div></div></div>';
$('#vote-item').append(addHtml);
if(addId == 20){
$('#addmoreitem').css({
display: 'none'
});
}
}
});
$('.date').datepicker({
format: "yyyy-mm-dd"
});
$('#vote_type1').click(function(){
$('#vote_limit_number_div').remove();
});
$('#vote_type2').click(function(){
var divnum = $('#vote_limit_number_div');
if(!divnum.length){
var addHtml = '<div class="form-group" id="vote_limit_number_div"><br><label for="vote-topic">限投票数:</label><input type="text" name="vote_limit_number" class="form-control" placeholder="限投票数"></div>';
$('#vote_num_more').append(addHtml);
}
});
$('.vote-item-more-info').click(function() {
alert('ss');
});
});
$(document).ready(function(){
$("#votepostuploader").uploadFile({
url:"/herald_vote/index.php/Admin/Index/addVotePost/",
allowedTypes:"jpg,png,gif,jpeg,mp4",
fileName:"vote_post",
showAbort:true,
uploadButtonClass:"btn btn-success",
onSuccess:function(files,data,xhr){
var uploadid = $('#uploadid').val();
var inputid = '#vote_item_attach_'+uploadid;
var btnid = '#'+uploadid;
$(inputid).val(data);
$(btnid).html('添加成功').removeClass('btn-info').removeAttr('data-target').addClass('btn-success').attr('disabled', 'disabled');;
}
});
$('#vote_post_name').click(function() {
$('#uploadid').val(0);
});
$('body').on('click','.uploadevent', function() {
var upid = $(this).attr('id');
$('#uploadid').val(upid);
});
// $('.uploadevent').click(function() {
// var upid = $(this).attr('id');
// $('#uploadid').val(upid);
// });
$('.delete_vote').click(function() {
var delid = $(this).attr('id');
$.ajax({
url: '/herald_vote/index.php/Admin/Index/deleteVote/',
type: 'post',
data: {'vote_id': delid},
success:function(data){
$('#vote_info_tr_'+delid).hide("slow");
},
})
});
});
|
export default function reducer(google = {}, action) {
switch (action.type) {
case 'GOOGLE_SET':
return { ...google, ...action.data };
default:
return google;
}
}
|
// Copyright 2016 The HongJiang Library Project Authors. All right reserved.
// Use of this source code is governed by a Apache-style
// license that can be found in the LICENSE file.
//
// Administrator服務之簡體中文語言包
//
// @authors hjboss <hongjiangproject@gmail.com> 2016-07-05 13:45:04 CST $$
// @version 0.1.0
module.exports = {
error: {
apiKey: '客户端版本过低,请及时升级!',
notExists: '当前管理账号不存在',
password: '管理账号或密码出现错误',
noPermissions: '当前设备无权限访问',
timeout: '登录会话已过期,请点击注销重新登录'
},
'siteTitle': 'Collavis China',
'homeTitle': '康萊美姿 ',
'siteKeyword': '康萊美姿 collavis.com.cn',
'siteDescription': '康萊美姿 化妝品國際著名品牌',
'siteAuthor': 'collavis.com.cn',
'siteCopyright': 'collavis.com.cn, 2016 co.ltd',
'footerCompany': '濟南康婷生物科技有限公司 JINAN CO.LTD',
'footerCopyright': '聯繫我們:400-636-9331 聯系時間:週一至週五 09:00-18:00(法定節假日除外)',
}
|
var config = {
defaultPort: process.env.WEB_PORT || 3000,
defaultLogLength: process.env.LOGLENGTH || 64,
defaultLogLines: process.env.LOGLINES || 10,
defaultSpacer: process.env.SPACER || ' | ',
defaultIdentifier: process.env.IDENTIFIER || '',
defaultLineCount: process.env.LINECOUNT || 1,
defaultLineDated: process.env.LINEDATED || 0,
defaultRepeatDelay: process.env.REPEATDELAY || 2
};
module.exports = config;
|
var searchData=
[
['ratecomment',['rateComment',['../namespace_meanco_app_1_1views_1_1_api_comment.html#a3126e77b21099a4dd4dea0c7d5370b50',1,'MeancoApp::views::ApiComment']]],
['raterelation',['rateRelation',['../namespace_meanco_app_1_1views_1_1_api_relation.html#a024057c446726ba7e55cba45c6ce116c',1,'MeancoApp::views::ApiRelation']]],
['register',['register',['../namespace_meanco_app_1_1views_1_1_api_authentication.html#af77e576094ba5aac7cb8bb6ec321aecc',1,'MeancoApp::views::ApiAuthentication']]]
];
|
/**
* angularjs-jspm-seed
* Created by kdavin on 19/11/2015.
*/
import {Service, Module} from '../../decorators';
@Module({
name : "app.common.services"
})
@Service("CustomLogService")
class CustomLogService {
constructor ($log) {
"ngInject";
this.$log = $log;
}
print(message = "Hello World !!") {
this.$log.info(message);
}
}
export default CustomLogService;
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var objectKeys = require( '@stdlib/utils/keys' );
var isPlainObject = require( '@stdlib/assert/is-plain-object' );
var table = require( './../' ).EMOJI_CODE_PICTO;
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof table, 'function', 'main export is a function' );
t.end();
});
tape( 'the function returns an object', function test( t ) {
var tbl = table();
t.equal( isPlainObject( tbl ), true, 'returns an object' );
t.end();
});
tape( 'the returned object has keys', function test( t ) {
var tbl = table();
t.equal( objectKeys( tbl ).length > 0, true, 'has keys' );
t.end();
});
tape( 'the returned object maps emoji codes to pictographs', function test( t ) {
var tbl = table();
t.equal( tbl[ ':smile:' ], '😄', 'returns expected value' );
t.equal( tbl[ ':unicorn:' ], '🦄', 'returns expected value' );
t.end();
});
|
function MouseTimer(){
timers = {};
listenersWait = {};
function init(){
setMouseMoveHandler();
}
function setMouseMoveHandler(){
$(document).mousemove(function(event) {
for (var time in timers){
var timer = timers[time];
clearTimeout(timer);
delete timers[time];
addTimer(time);
}
});
}
function addTimer(time){
if (!timers[time]) {
timers[time] = setTimeout(function(){
for (var i in listenersWait[time]){
var handler = listenersWait[time][i];
handler();
}
}, time);
}
}
function mousewait(time, handler){
if (!listenersWait[time]){
listenersWait[time] = [];
}
listenersWait[time].push(handler);
addTimer(time);
}
this.on = function(event, time, handler){
if (event.toLowerCase() == "mousewait"){
mousewait(time, handler);
}
};
this.off = function(event, time, handler){
if (event.toLowerCase() == "mousewait"){
if (!listenersWait[time]) return;
var pos = listenersWait[time].indexOf(handler);
if (pos >= 0){
listenersWait[time].splice(pos, 1);
}
}
};
init();
}
var MouseTimer = new MouseTimer();
|
import tests from "../../support/accessibility/a11y-utils";
tests(0, 150);
|
'use strict';
const common = require('../common');
const assert = require('assert');
const cluster = require('cluster');
const net = require('net');
if (cluster.isMaster) {
cluster.fork().on('message', function(msg) {
if (msg === 'done') this.kill();
});
} else {
const server = net.createServer(common.fail);
server.listen(common.PORT, function() {
server.unref();
server.ref();
server.close(function() {
process.send('done');
});
});
}
|
/**
* Copyright 2020 Google LLC
*
* 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 './node_modules/@google-pay/save-button-element/dist/index.js';
const button = document.querySelector('save-to-google-pay-button');
[...document.querySelectorAll('select')].forEach(select => {
select.addEventListener('change', event => {
const { name, value } = event.target;
button.setAttribute(name, value);
});
});
button.addEventListener('success', () => {
console.log('success');
});
button.addEventListener('failure', event => {
console.log('failure', event.detail);
});
// button.onProvideJwt = () => {
// console.log('provide jwt');
// return button.jwt;
// };
|
function loadNavBar() {'use strict';
var navBarView = Ti.UI.createView({
backgroundImage : '/assets/navBar/backgroundGrey.png',
backgroundColor : '#ffffff',
height : '44dp',
width : '100%',
top : 0
});
// The title
var navBarTitle = Ti.UI.createLabel({
left : 10,
right : 10,
height : 'auto',
textAlign : 'center',
color : '#ffffff',
font : {
fontSize : '22dp',
fontWeight : 'bold'
},
text : "navBarTitle"
});
navBarView.add(navBarTitle);
// The back button
var navBarBack = Ti.UI.createView({
left : '10dp',
height : '28dp',
width : '57dp',
backgroundImage : '/assets/buttons/backButtonGreyOff.png',
zIndex:2
});
navBarBack.addEventListener('click', function() {
navBarView.fireEvent('ratingChanged',{
currentValue:"back"
});
});
var navBarBackText = Ti.UI.createLabel({
top : 0,
left : 10,
right : 0,
bottom : 0,
text : "Back",
textAlign : 'center',
color : '#ffffff',
font : {
fontSize : '16dp',
fontWeight : 'bold'
}
});
// Same trick as the menu to identify the area with a plain view over the top
var navBarButtonView = Ti.UI.createView({
top : 0,
left : 0,
right : 0,
bottom : 0,
backgroundColor : 'transparent',
//OPTION : settingsGlobal.value.OPTIONS.BACK,
TEXT : navBarBackText,
IMAGE : navBarBack
});
var navBarMenu = Ti.UI.createView({
right : '10dp',
height : '28dp',
width : '57dp',
backgroundImage : '/assets/menuBar/menuIconOffGrey.png',
zIndex:2
});
// working ok
navBarMenu.addEventListener('click', function() {
navBarView.fireEvent('ratingChanged',{
currentValue:"home"
});
});
var navBarMenuText = Ti.UI.createLabel({
top : 0,
left : 10,
right : 0,
bottom : 0,
text : "Menu",
textAlign : 'center',
color : '#ffffff',
font : {
fontSize : '16dp',
fontWeight : 'bold'
}
});
var navBarMenuView = Ti.UI.createView({
top : 0,
left : 0,
right : 0,
bottom : 0,
backgroundColor : 'transparent',
TEXT : navBarMenuText,
IMAGE : navBarMenu
});
navBarBack.add(navBarBackText);
navBarView.add(navBarBack);
navBarView.add(navBarButtonView);
navBarMenu.add(navBarMenuText);
navBarView.add(navBarMenu);
navBarView.add(navBarMenuView);
// Always return the view object to the calling window
return navBarView;
}
/*
* EXPORTS SECTION
*/
exports.loadNavBar= loadNavBar;
/*
* END OF FILE
*/
|
sap.ui.define(['sap/ui/core/UIComponent'],
function(UIComponent) {
"use strict";
var Component = UIComponent.extend("sap.m.sample.ListDeletion.Component", {
metadata : {
manifest: "json"
}
});
return Component;
});
|
/**
* Copyright 2012 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.
*/
/**
* @author benvanik@google.com (Ben Vanik)
*/
goog.provide('blk.sim.Inventory');
goog.require('blk.sim');
goog.require('blk.sim.EntityType');
goog.require('blk.sim.commands.SetHeldToolCommand');
goog.require('gf');
goog.require('gf.sim');
goog.require('gf.sim.Entity');
goog.require('goog.events.KeyCodes');
goog.require('goog.math');
/**
* Abstract actor controller entity.
* Can be parented to an actor and assigned as a controller.
*
* @constructor
* @extends {gf.sim.Entity}
* @param {!gf.sim.Simulator} simulator Owning simulator.
* @param {!gf.sim.EntityFactory} entityFactory Entity factory.
* @param {number} entityId Entity ID.
* @param {number} entityFlags Bitmask of {@see gf.sim.EntityFlag} values.
*/
blk.sim.Inventory = function(
simulator, entityFactory, entityId, entityFlags) {
goog.base(this, simulator, entityFactory, entityId, entityFlags);
if (goog.DEBUG) {
this.debugName = 'Inventory';
}
};
goog.inherits(blk.sim.Inventory, gf.sim.Entity);
/**
* Entity ID.
* @const
* @type {number}
*/
blk.sim.Inventory.ID = gf.sim.createTypeId(
blk.sim.BLK_MODULE_ID, blk.sim.EntityType.INVENTORY);
/**
* Gets the target actor of the controller, if any.
* @return {blk.sim.Actor} Target actor.
*/
blk.sim.Inventory.prototype.getTarget = function() {
return /** @type {blk.sim.Actor} */ (this.getParent());
};
/**
* @override
*/
blk.sim.Inventory.prototype.childAdded = function(entity) {
goog.base(this, 'childAdded', entity);
// Item was added to the inventory
};
/**
* @override
*/
blk.sim.Inventory.prototype.childRemoved = function(entity) {
goog.base(this, 'childRemoved', entity);
// Item was removed from the inventory
};
/**
* @override
*/
blk.sim.Inventory.prototype.executeCommand = function(command) {
goog.base(this, 'executeCommand', command);
if (command instanceof blk.sim.commands.SetHeldToolCommand) {
var target = this.getTarget();
var newTool = this.getChild(command.toolId);
if (newTool) {
target.setHeldTool(newTool);
}
}
};
if (gf.CLIENT) {
/**
* Processes the input control for a single frame.
* @param {!gf.RenderFrame} frame Current frame.
* @param {!gf.input.Data} inputData Current input data.
* @return {boolean} True if input is valid, false if input has failed.
*/
blk.sim.Inventory.prototype.processInput = function(frame, inputData) {
var keyboardData = inputData.keyboard;
var mouseData = inputData.mouse;
var target = this.getTarget();
var heldTool = target.getHeldTool();
var count = this.getChildCount();
var oldHeldIndex = heldTool ? this.getIndexOfChild(heldTool) : 0;
var newHeldIndex = oldHeldIndex;
if (mouseData.dz) {
// TODO(benvanik): mac touchpad scroll
var dz = mouseData.dz > 0 ? 1 : -1;
newHeldIndex = (oldHeldIndex + dz) % count;
if (newHeldIndex < 0) {
newHeldIndex = count - 1;
}
}
if (keyboardData.didKeyGoDown(goog.events.KeyCodes.ONE)) {
newHeldIndex = 0;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.TWO)) {
newHeldIndex = 1;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.THREE)) {
newHeldIndex = 2;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.FOUR)) {
newHeldIndex = 3;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.FIVE)) {
newHeldIndex = 4;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.SIX)) {
newHeldIndex = 5;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.SEVEN)) {
newHeldIndex = 6;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.EIGHT)) {
newHeldIndex = 7;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.NINE)) {
newHeldIndex = 8;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.ZERO)) {
newHeldIndex = 9;
}
newHeldIndex = goog.math.clamp(newHeldIndex, 0, count - 1);
if (newHeldIndex != oldHeldIndex) {
// Create command
var cmd = /** @type {!blk.sim.commands.SetHeldToolCommand} */ (
this.createCommand(blk.sim.commands.SetHeldToolCommand.ID));
var newTool = this.getChildAtIndex(newHeldIndex);
cmd.toolId = newTool.getId();
this.simulator.sendCommand(cmd);
if (gf.CLIENT) {
var controller = blk.sim.getClientController(this);
controller.playClick();
}
}
return true;
};
}
|
/**
* Users collection.
* Initializes Users collection and provides methods
* for accessing the collection.
* */
users = "Users";
Users = new Mongo.Collection(users);
/**
* Schema for Users
*/
Users.attachSchema(new SimpleSchema({
userName:{
label: "Username",
type: String,
optional: false,
autoform:{
group: users,
placeholder: "Username"
}
},
firstName:{
label: "First Name",
type: String,
optional: true,
autoform:{
group: users,
placeholder: "First Name"
}
},
lastName:{
label: "Last Name",
type: String,
optional: true,
autoform:{
group: users,
placeholder: "Last Name"
}
},
email:{
label: "Email",
type: String,
optional: false,
unique: true,
autoform:{
group: users,
placeholder: "Email"
}
},
roles: {
type: Object,
optional: true,
blackbox: true
}
}));
|
if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.perform("Image Entity keepAspectRatio", Script.resolvePath("."), "secondary", undefined, function(testType) {
Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
var LIFETIME = 200;
// Add the test Cases
var initData = {
flags: {
hasKeyLight: true,
hasAmbientLight: true
},
lifetime: LIFETIME,
originFrame: nitpick.getOriginFrame()
};
var createdEntities = setupStage(initData);
var posOri = getStagePosOriAt(0, 0, 0);
var assetsRootPath = nitpick.getAssetsRootPath();
function getPos(col, row) {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
}
createdEntities.push(Entities.addEntity({
type: "Image",
imageURL: assetsRootPath + "textures/redArrow.jpg",
position: getPos(-0.5, 1),
dimensions: 1.0,
keepAspectRatio: false,
lifetime: LIFETIME
}));
createdEntities.push(Entities.addEntity({
type: "Image",
imageURL: assetsRootPath + "textures/redArrow.jpg",
position: getPos(0.5, 1),
dimensions: 1.0,
keepAspectRatio: true,
lifetime: LIFETIME
}));
nitpick.addStepSnapshot("Take snapshot");
nitpick.addStep("Clean up after test", function () {
for (var i = 0; i < createdEntities.length; i++) {
Entities.deleteEntity(createdEntities[i]);
}
});
var result = nitpick.runTest(testType);
});
|
/*jshint expr: true*/
describe('selectBy', function() {
before(h.setup());
describe('VisibleText', function() {
it('should find element without special conditions', function() {
return this.client.selectByVisibleText('#selectTest', 'seis').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue6');
});
});
it('should find element with spaces before and after the text', function() {
return this.client.selectByVisibleText('#selectTest', 'dos').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue2');
});
});
it('should find element with spaces before and after the text parameter', function() {
return this.client.selectByVisibleText('#selectTest', ' cinco ').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue5');
});
});
it('should find element with quotes around the text', function() {
return this.client.selectByVisibleText('#selectTest', '"siete"').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue7');
});
});
it('should find element with quotes in the text', function() {
return this.client.selectByVisibleText('#selectTest', 'ocho "huit" (otto)').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue8');
});
});
it('should find element with a quote in the text', function() {
return this.client.selectByVisibleText('#selectTest', 'nu"eve').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue9');
});
});
it('should find element with a quote at the end of the text', function() {
return this.client.selectByVisibleText('#selectTest', 'diez"').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue10');
});
});
});
describe('Index', function() {
it('should find element without special conditions', function() {
return this.client.selectByIndex('#selectTest', 3).getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue4');
});
});
it('should throw error if index is negative', function() {
return this.client.selectByIndex('#selectTest', -2).catch(function(err) {
assert.ifError(!!!err);
});
});
it('should throw error if index is higher than number of options', function() {
return this.client.selectByIndex('#selectTest', 99).catch(function(err) {
assert.ifError(!!!err);
});
});
});
describe('Name', function() {
it('should find element without special conditions', function() {
return this.client.selectByName('#selectTest', 'someName7').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue7');
});
});
it('should find element with spaces before and after the name', function() {
return this.client.selectByName('#selectTest', 'someName9').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue9');
});
});
it('should find element with spaces before and after the name parameter', function() {
return this.client.selectByName('#selectTest', ' someName8 ').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue8');
});
});
});
describe('Value', function() {
it('should find element without special conditions', function() {
return this.client.selectByValue('#selectTest', 'someValue1').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue1');
});
});
it('should find element with spaces before and after the value', function() {
return this.client.selectByValue('#selectTest', 'someValue3').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue3');
});
});
it('should find element with spaces before and after the value parameter', function() {
return this.client.selectByValue('#selectTest', ' someValue5 ').getValue('#selectTest').then(function (value) {
value.should.be.exactly('someValue5');
});
});
});
});
|
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis.
*
* @returns {RegExp} regular expression
*
* @example
* var RE_NATIVE_FUNCTION = reNativeFunction();
* var bool = RE_NATIVE_FUNCTION.test( Date.toString() );
* // returns true
*/
function reNativeFunction() {
var str = '';
// Use a native function as a template:
str += Function.prototype.toString.call( Function );
// Escape special RegExp characters:
str = str.replace( /([.*+?^=!:$(){}|[\]\/\\])/g, '\\$1' ); // eslint-disable-line no-useless-escape
// Replace any mentions of `Function` to make template generic and replace `for ...` and additional info provided in other environments, such as Rhino.
str = str.replace( /Function|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?' );
// Bracket the regular expression:
str = '^' + str + '$';
// Create the regular expression:
return new RegExp( str );
}
// EXPORTS //
module.exports = reNativeFunction;
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
var isPositiveInteger = require( './../lib' );
console.log( isPositiveInteger( 5.0 ) );
// => true
console.log( isPositiveInteger( 0.0 ) );
// => false
console.log( isPositiveInteger( -1.0 ) );
// => false
console.log( isPositiveInteger( 3.14 ) );
// => false
console.log( isPositiveInteger( NaN ) );
// => false
|
var http = require('http');
if (null == process.env.WORKER_ID)
throw new Error("env.WORKER_ID not set!");
var s = http.createServer(function(req, res) {
var params = req.url.split('/').slice(1);
setTimeout(function() {
res.writeHead(200);
res.end("hello world\n");
}, params[0] || 1);
});
s.listen(8000);
setTimeout(function() {
// Don't exit - to test termination timeout.
setTimeout(function() {
console.log('Finally cleaned up');
}, 5000);
require('cluster').worker.disconnect();
}, 500);
|
'use strict';
angular.module('gigsecApp')
.controller('GigResignupController', function($scope, $uibModalInstance, entity, GigSignup) {
$scope.gig = entity.gig;
$scope.gigSignup = entity.signup;
$scope.clear = function() {
$uibModalInstance.dismiss('cancel');
};
var onSaveSuccess = function (result) {
$scope.$emit('gigsecApp:gigUpdate', result);
$uibModalInstance.close(result);
$scope.isSaving = false;
};
var onSaveError = function (result) {
$scope.isSaving = false;
};
$scope.confirmUpdate = function (id) {
$scope.isSaving = true;
$scope.gigSignup.performing = true;
GigSignup.signup().update($scope.gigSignup, onSaveSuccess, onSaveError);
};
});
|
/**
* DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler.
* @link https://github.com/gdbots/pbjc-php
*
* Returns an array of curies using mixin "triniti:boost:mixin:search-sponsors-request:v1"
* @link http://schemas.triniti.io/json-schema/triniti/boost/mixin/search-sponsors-request/1-0-0.json#
*/
export default [
];
|
//// [classImplementsClass6.ts]
class A {
static bar(): string {
return "";
}
foo(): number { return 1; }
}
class C implements A {
foo() {
return 1;
}
}
class C2 extends A {}
var c: C;
var c2: C2;
c = c2;
c2 = c;
c.bar(); // error
c2.bar(); // should error
//// [classImplementsClass6.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var A = (function () {
function A() {
}
A.bar = function () {
return "";
};
A.prototype.foo = function () { return 1; };
return A;
})();
var C = (function () {
function C() {
}
C.prototype.foo = function () {
return 1;
};
return C;
})();
var C2 = (function (_super) {
__extends(C2, _super);
function C2() {
_super.apply(this, arguments);
}
return C2;
})(A);
var c;
var c2;
c = c2;
c2 = c;
c.bar(); // error
c2.bar(); // should error
|
/**
* myCarousel
*/
angular.module(PKG.name+'.directives').directive('myCarousel',
function myCarouselDirective ($interval) {
return {
restrict: 'AC',
link: function (scope, element, attrs) {
element.addClass('my-carousel');
var currentSlide = 1,
allSlides = element.find('section'),
slideCount = allSlides.length;
function boundaries() {
if(currentSlide > slideCount) {
currentSlide = 1;
}
else if(currentSlide <= 0) {
currentSlide = slideCount;
}
}
var tick = $interval(function() {
console.log('carousel tick');
scope.nextSlide();
}, 5000);
function cancelInterval() {
$interval.cancel(tick);
}
scope.$on('$destroy', cancelInterval);
function setAnimationClass (d) {
var am = 'am-slide-';
allSlides
.removeClass(am+'right '+am+'left')
.addClass(am+d);
}
scope.slideIsVisible = function(n) {
return n == currentSlide;
}
scope.nextSlide = function (event) {
if(event) {
cancelInterval();
}
setAnimationClass('right');
boundaries(currentSlide++);
}
scope.prevSlide = function (event) {
if(event) {
cancelInterval();
}
setAnimationClass('left');
boundaries(currentSlide--);
}
}
};
});
|
TornadoFaces.declareWidget('List', function() {
var widget;
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
this.init = function() {
widget = this;
widget.items = widget.elem.find('ul li');
widget.bindEvents();
};
this.getFilterFn = function() {
var filterFn = widget.conf.filterFn;
if (!filterFn) {
filterFn = function(item, query) {
return item.text().toUpperCase().indexOf(query.toUpperCase()) > -1;
};
widget.conf.filterFn = filterFn;
}
return filterFn;
};
this.setFilterFn = function(filterFn) {
widget.conf.filterFn = filterFn;
};
this.filter = function(query) {
var doHighlight = widget.conf.highlightFilter;
if (!query || query.length == 0 || query === '') {
widget.items.show();
if (doHighlight)
widget.items.unhighlight();
} else {
var filterFn = widget.getFilterFn();
for (var idx = 0; idx < widget.items.length; idx++) {
var item = $(widget.items[idx]);
if (doHighlight)
item.unhighlight();
if (filterFn(item, query, idx)) {
item.show();
if (doHighlight)
item.highlight(query);
} else {
item.hide();
}
}
}
};
this.bindEvents = function() {
widget.items.children('.accordion-title').click(function(event) {
var item = $(this).parent();
var itemIndex = item.index();
widget.select(itemIndex);
event.preventDefault();
return false;
});
}
});
|
/*
* Copyright 2015 OpenCB
*
* 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.
*/
db.getCollection('user').createIndex({"name": 1})
db.getCollection('user').createIndex({"sessions.id": 1})
db.getCollection('study').createIndex({"alias": 1})
db.getCollection('study').createIndex({"_projectId": 1})
db.getCollection('sample').createIndex({"name": 1})
db.getCollection('sample').createIndex({"annotationSets.variableSetId": 1})
db.getCollection('sample').createIndex({"annotationSets.annotations.id": 1})
db.getCollection('sample').createIndex({"annotationSets.annotations.value": 1})
db.getCollection('sample').createIndex({"_studyId": 1})
db.getCollection('file').createIndex({"name": 1})
db.getCollection('file').createIndex({"path": 1})
db.getCollection('file').createIndex({"jobId": 1})
db.getCollection('file').createIndex({"_studyId": 1})
|
emailForm = function() {
var remite = prompt("Introduzca correo de contacto: ");
document.getElementById("remite").value;
if (remite != '' && remite != null && nombre != '' && nombre != null && telefono != '' && telefono != null) {
itemsString = "";
esubtotal = 0;
egastos = 0;
etotal = 0;
for( var current in this.items ){
var item = this.items[current];
esubtotal = item.quantity * item.price;
itemsString += item.name;
if (item.size) itemsString += " " + item.size + "\n";
itemsString += item.quantity + " x " + item.price + " = " + String(esubtotal) + " " + me.currency + "\n";
etotal += esubtotal;
};
itemsString += "\nSubtotal = " + etotal + " " + me.currency +"\n";
var gastos = me.shippingCost;
if (formapago == "Contra-reembolso") {
gastos += 8;
etotal += 8;
}
if (gastos){
itemsString += "Gastos de envio = " + gastos + " " + me.currency +"\n";
etotal += me.shippingCost;
} else {itemsString += "Gastos de envio = GRATIS\n";}
itemsString +="\nTOTAL: " + String(etotal) + me.currency + "\n\n" + "Remitente: " + remite;
itemsString +="\n\nNOMBRE: " + nombre + "\nTelefono: " + telefono;
itemsString +="\nDIRECCION: " + direccion;
itemsString +="\nCIUDAD/PAIS: " + codigo + " " + ciudad + " - " + provincia + " (" + pais + ")";
itemsString +="\n\nOBSERVACIONES: " + observaciones;
itemsString +="\n\nFORMA DE PAGO: " + formapago;
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "http://kamillustore.16mb.com/emailform.php";
form.acceptCharset = "utf-8";
form.appendChild(this.createHiddenElement("jcitems", itemsString));
form.appendChild(this.createHiddenElement("jcremite", remite));
document.body.appendChild(form);
me.empty();
form.submit();
document.body.removeChild(form);
if (p == null || p=='');
}
return;
};
|
var app = {
initialize: function() {
this.bind();
this.run();
},
bind: function() {
var self = this;
document.getElementById("page-request-form").addEventListener('submit', function(e) {
var address = document.getElementById("page-request-address");
self.loadPageRequest(address.value);
return false;
});
},
run: function() {
this.showLoading(true);
this.load();
this.showLoading(false);
},
load: function() {
if (this.hasWarnings()) {
this.loadWarnings();
}
else if (this.hasApiRequest()) {
this.loadApiRequest();
}
else {
this.loadPageRequest();
}
},
hasWarnings: function() {
return !(this.isBrowserSupported() && this.hasRipplez());
},
loadWarnings: function() {
if (!this.isBrowserSupported()) {
this.show('browser-warning');
}
else if (!this.hasRipplez()) {
this.show('ripple-warning');
}
},
isBrowserSupported: function() {
return !!window.chrome;
},
hasRipplez: function () {
// we do not use window.chrome.isInstalled(id)
// because Ripple has two IDs (hosted and Chrome Store)
// and local dev installations have unique IDs.
return !!document.getElementById("tinyhippos-injected");
},
hasApiRequest: function() {
return !!this.queryString().match(/url=/);
},
loadApiRequest: function() {
var uri = this.queryString().match(/url=([^&]*)/)[1];
uri = decodeURIComponent(uri);
this.goto(uri);
},
loadPageRequest: function(uri) {
if (uri) {
this.goto(uri);
}
else {
this.show('content');
}
},
goto: function (uri) {
uri = uri.replace('platform=', 'enableripple=');
if (!uri.match(/enableripple=/)) {
uri += uri.match(/\?/) ? "&" : "?";
uri += 'enableripple=cordova';
}
if (!uri.match(/^http[s]?:\/\//)) {
uri = "http://" + uri;
}
this.redirect(uri);
},
redirect: function(uri) {
window.location.href = uri;
},
show: function (id) {
document.getElementById(id).setAttribute("style", "");
},
hide: function (id) {
document.getElementById(id).setAttribute("style", "display: none");
},
visible: function(id) {
return (document.getElementById(id).style.display === '');
},
queryString: function() {
return window.location.search;
},
showLoading: function(loading) {
if (loading) {
this.show('loading');
}
else {
this.hide('loading');
}
}
};
var page = {
initialize: function() {
document.body.addEventListener('click', function(e) {
var el = e.target;
if (el.href && el.href.match(/#$/)) {
e.preventDefault();
if (el.text.match(/^emulate\./)) {
app.redirect(el.text);
}
else {
app.goto(el.text);
}
}
});
}
};
|
/*
* #%L
* %%
* Copyright (C) 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
'use strict';
import test from 'ava';
const cartesianProduct = require('cartesian-product');
const Setup = require('./setup.helper.js');
function runEchoTest(config) {
const setup = config[0];
const message = config[1];
const testName = 'message is sent to server and received again; connection: ' + setup.name +
', datatype: ' + typeof message;
test.cb(testName, t => {
setup.init().then((setup) => {
setup.server.on('connection', (ws) => {
ws.on('message', (message) => {
ws.send(message);
});
});
setup.client.onerror = (e) => {
t.fail('onerror callback invoked with ' + JSON.stringify(e));
};
setup.client.onclose = () => {
t.end();
};
setup.client.onopen = () => {
setup.client.send(config[1]);
};
setup.client.onmessage = (msg) => {
t.deepEqual(msg.data, message);
setup.client.close();
}
});
});
}
function sequentialNumberArray(count) {
return Array.from(Array(count).keys());
}
function flattenArray(array) {
return [].concat.apply([], array)
}
const shortNumberArray = sequentialNumberArray(10);
const longNumberArray = sequentialNumberArray(1000);
const inputList = [shortNumberArray, longNumberArray];
const inputPreprocessorFunctions = [JSON.stringify, Buffer.from];
const preprocessedInput = inputList.map((input) => {
return inputPreprocessorFunctions.map((fun) => {
return fun(input);
});
});
const messages = flattenArray(preprocessedInput);
function initTlsCommunicationEncrypted() {
const serverSuffix = '1';
const clientSuffix = '1';
return Setup.initTlsCommunicationEncrypted(serverSuffix, clientSuffix);
}
function initTlsCommunicationUnencrypted() {
const serverSuffix = '1';
const clientSuffix = '1';
return Setup.initTlsCommunicationUnencrypted(serverSuffix, clientSuffix);
}
const nonTlsConfig = {
name: 'non TLS',
init: Setup.initNonTlsCommunication
};
const tlsConfigEncrypted = {
name: 'TLSEncrypted',
init: initTlsCommunicationEncrypted
};
const tlsConfigUnencrypted = {
name: 'TLSUnencrypted',
init: initTlsCommunicationUnencrypted
};
const configs = [nonTlsConfig, tlsConfigEncrypted, tlsConfigUnencrypted];
const allTestCases = cartesianProduct([configs, messages]);
allTestCases.forEach(testCase => runEchoTest(testCase));
|
/**
* List Component: Basic Usage
*/
import React from 'react';
import NavList from '../NavList';
import NavListSection from '../../NavListSection';
import NavListItem from '../../NavListItem';
export default () => (
<div>
<NavList>
<NavListSection label="Settings" activeLink="#organization">
<NavListItem>Users</NavListItem>
<NavListItem>Items</NavListItem>
<NavListItem>Check out</NavListItem>
<NavListItem href="#organization">Organization</NavListItem>
<NavListItem>Circulation</NavListItem>
</NavListSection>
</NavList>
<br />
<br />
<NavList>
<NavListSection activeLink="#organization" label="Using striped style" striped>
<NavListItem>Users</NavListItem>
<NavListItem>Items</NavListItem>
<NavListItem>Check out</NavListItem>
<NavListItem href="#organization">Organization</NavListItem>
<NavListItem>Circulation</NavListItem>
</NavListSection>
</NavList>
<br />
<br />
<NavList aria-label="example navigation list">
<NavListSection activeLink="#organization" label="Using aria-label">
<NavListItem>Users</NavListItem>
<NavListItem>Items</NavListItem>
</NavListSection>
</NavList>
</div>
);
|
/**
* Copyright 2016 Henning Treu
*
* 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 debug from 'debug'; let logger = debug('SitemapParser');
class SitemapParser {
constructor() {
// nop
}
parseSitemap(sitemap) {
let widgets = [].concat(sitemap.homepage.widget);
let result = [];
for (let i = 0; i < widgets.length; i++) {
let widget = widgets[i];
// parse Frames (Outlets)
if (this.looksLikeOutletFrame(widget)) {
let outlets = this.parseOutlets([].concat(widget.widget));
result = result.concat(outlets);
continue;
}
let parsedWidget = this.parseWidget(widget);
if (parsedWidget) {
result.push(parsedWidget);
}
}
return result;
}
parseOutlets(widgets) {
let result = [];
for (let i = 0; i < widgets.length; i++) {
let parsedWidget = this.parseWidget(widgets[i]);
if (parsedWidget) {
parsedWidget.itemType = 'OutletItem';
result.push(parsedWidget);
}
}
return result;
}
parseWidget(widget) {
if (!widget.item) {
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'test') {
logger("WARN: The widget '" + widget.label + "' does not reference an item.");
}
return;
}
return {
type: widget.type,
itemType: widget.item.type,
name: widget.label,
link: widget.item.link,
state: widget.item.state
}
}
looksLikeOutletFrame(widget) {
return widget.type === 'Frame'
&& (widget.icon === 'outlet' || widget.label === 'outlet');
}
};
export { SitemapParser };
|
var _ = require("underscore"),
Util = require("../lib/util.js"),
rethinkdb = require("rethinkdb");
var defaultOptions = {
host : "localhost",
port : 28015,
dbName : "test",
tableName : "user"
}
var initializeOptions = function( options ){
if(!_.isNull(options) && _.isObject(options)){
return _.extend(defaultOptions, options);
}
return defaultOptions;
}
// Constructor
var User = function( options, callback ){
var self = this;
var optionals = initializeOptions( options );
// TODO - implement connection etc in user-db.js
rethinkdb.connect( {host : optionals.host, port : optionals.port}, function(err, conn) {
if (err){
throw new Error("Unable to connect to database. " + err.stack());
}
self.connection = conn;
self.dbName = optionals.dbName;
self.tableName = optionals.tableName;
Util.executeSafely(callback);
});
};
User.prototype.registerUser = function( user, callBack, options ){
Util.checkIsObject( user, "Cannot save an empty user." );
Util.checkIsFunction( callBack, "Must supply a valid callback.");
var optionals = options == undefined ? {upsert: true, return_vals: true} : options;
Util.setId( user );
rethinkdb
.db(this.dbName)
.table(this.tableName)
.insert( user, optionals )
.run(this.connection, function(err, result){
callBack(err, result);
});
};
User.prototype.updateUser = function( id, changes, callBack, options ){
Util.checkNotEmpty( id, "Cannot update a user without a valid userId." );
Util.checkIsObject( changes, "Cannot update an empty user." );
Util.checkIsFunction( callBack, "Must supply a valid callback." );
var optionals = options != null ? options : {return_vals : true};
rethinkdb
.db(this.dbName)
.table(this.tableName)
.get( id )
.update( changes, optionals )
.run(this.connection, function(err, result){
callBack(err, result);
});
};
User.prototype.getUserById = function( id, callBack ){
Util.checkNotEmpty( id, "Cannot retrieve a user without a valid userId.");
Util.checkIsFunction( callBack, "Must supply a valid callback.");
rethinkdb
.db(this.dbName)
.table(this.tableName)
.get( id )
.run(this.connection, function(err, result){
callBack(err, result);
});
};
User.prototype.deleteUser = function( id, callBack ){
Util.checkNotEmpty( id, "Cannot delete a user without a valid userId.");
Util.checkIsFunction( callBack, "Must supply a valid callback.");
rethinkdb
.db(this.dbName)
.table(this.tableName)
.get( id )
.delete({durability: 'hard'})
.run(this.connection, function(err, result){
callBack(err, result);
});
};
module.exports.createInstance = function( options, callback ){
return new User( options, callback );
};
|
/**
* Copyright (c) 2016 Intel Corporation
*
* 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.
*/
(function () {
'use strict';
App.factory('ApplicationRegisterHelpers', function(ApplicationRegisterResource, NotificationService) {
return {
getOfferingsOfApp: function(appGuid) {
return ApplicationRegisterResource
.withErrorMessage('Failed to retrieve service offerings from catalog')
.getClonedApplication(appGuid)
.then(function (response) {
return response.plain();
});
},
registerApp: function(request) {
return ApplicationRegisterResource
.withErrorMessage('Failed to register application in marketplace')
.registerApplication(request)
.then(function (response) {
NotificationService.success('Application has been registered in marketplace');
return response.plain();
});
}
};
});
})();
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var abs = require( '@stdlib/math/base/special/abs' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var EPS = require( '@stdlib/constants/float64/eps' );
var variance = require( './../lib' );
// FIXTURES //
var data = require( './fixtures/julia/data.json' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof variance, 'function', 'main export is a function' );
t.end();
});
tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
var v = variance( NaN, 0.5 );
t.equal( isnan( v ), true, 'returns NaN' );
v = variance( 10.0, NaN );
t.equal( isnan( v ), true, 'returns NaN' );
t.end();
});
tape( 'if provided `k <= 0`, the function returns `NaN`', function test( t ) {
var y;
y = variance( -1.0, 2.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( NINF, 1.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( NINF, PINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( NINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( NINF, NaN );
t.equal( isnan( y ), true, 'returns NaN' );
t.end();
});
tape( 'if provided `lambda <= 0`, the function returns `NaN`', function test( t ) {
var y;
y = variance( 2.0, -1.0 );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( 1.0, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( PINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( NINF, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
y = variance( NaN, NINF );
t.equal( isnan( y ), true, 'returns NaN' );
t.end();
});
tape( 'the function returns the variance of a Weibull distribution', function test( t ) {
var expected;
var lambda;
var delta;
var tol;
var k;
var i;
var y;
expected = data.expected;
k = data.k;
lambda = data.lambda;
for ( i = 0; i < expected.length; i++ ) {
y = variance( k[i], lambda[i] );
if ( y === expected[i] ) {
t.equal( y, expected[i], 'k: '+k[i]+', lambda: '+lambda[i]+', y: '+y+', expected: '+expected[i] );
} else {
delta = abs( y - expected[ i ] );
tol = 300.0 * EPS * abs( expected[ i ] );
t.ok( delta <= tol, 'within tolerance. k: '+k[i]+'. lambda: '+lambda[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' );
}
}
t.end();
});
|
/*
Copyright 2015, 2016 OpenMarket Ltd
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.
*/
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { _t } from '../../../languageHandler';
const DIV_ID = 'mx_recaptcha';
/**
* A pure UI component which displays a captcha form.
*/
module.exports = React.createClass({
displayName: 'CaptchaForm',
propTypes: {
sitePublicKey: PropTypes.string,
// called with the captcha response
onCaptchaResponse: PropTypes.func,
},
getDefaultProps: function() {
return {
onCaptchaResponse: () => {},
};
},
getInitialState: function() {
return {
errorText: null,
};
},
componentWillMount: function() {
this._captchaWidgetId = null;
},
componentDidMount: function() {
// Just putting a script tag into the returned jsx doesn't work, annoyingly,
// so we do this instead.
if (global.grecaptcha) {
// already loaded
this._onCaptchaLoaded();
} else {
console.log("Loading recaptcha script...");
window.mx_on_recaptcha_loaded = () => {this._onCaptchaLoaded();};
const protocol = global.location.protocol;
if (protocol === "file:") {
const warning = document.createElement('div');
// XXX: fix hardcoded app URL. Better solutions include:
// * jumping straight to a hosted captcha page (but we don't support that yet)
// * embedding the captcha in an iframe (if that works)
// * using a better captcha lib
ReactDOM.render(_t(
"Robot check is currently unavailable on desktop - please use a <a>web browser</a>",
{},
{ 'a': (sub) => { return <a href='https://riot.im/app'>{ sub }</a>; }}), warning);
this.refs.recaptchaContainer.appendChild(warning);
} else {
const scriptTag = document.createElement('script');
scriptTag.setAttribute(
'src', protocol+"//www.google.com/recaptcha/api.js?onload=mx_on_recaptcha_loaded&render=explicit",
);
this.refs.recaptchaContainer.appendChild(scriptTag);
}
}
},
componentWillUnmount: function() {
this._resetRecaptcha();
},
_renderRecaptcha: function(divId) {
if (!global.grecaptcha) {
console.error("grecaptcha not loaded!");
throw new Error("Recaptcha did not load successfully");
}
const publicKey = this.props.sitePublicKey;
if (!publicKey) {
console.error("No public key for recaptcha!");
throw new Error(
"This server has not supplied enough information for Recaptcha "
+ "authentication");
}
console.log("Rendering to %s", divId);
this._captchaWidgetId = global.grecaptcha.render(divId, {
sitekey: publicKey,
callback: this.props.onCaptchaResponse,
});
},
_resetRecaptcha: function() {
if (this._captchaWidgetId !== null) {
global.grecaptcha.reset(this._captchaWidgetId);
}
},
_onCaptchaLoaded: function() {
console.log("Loaded recaptcha script.");
try {
this._renderRecaptcha(DIV_ID);
} catch (e) {
this.setState({
errorText: e.toString(),
});
}
},
render: function() {
let error = null;
if (this.state.errorText) {
error = (
<div className="error">
{ this.state.errorText }
</div>
);
}
return (
<div ref="recaptchaContainer">
{ _t("This Home Server would like to make sure you are not a robot") }
<br />
<div id={DIV_ID}></div>
{ error }
</div>
);
},
});
|
import './scss/root-theme.scss';
|
// This file is part of BenchExec, a framework for reliable benchmarking:
// https://github.com/sosy-lab/benchexec
//
// SPDX-FileCopyrightText: 2019-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
const path = require("path");
module.exports = {
webpack: function override(config, webpackEnv) {
const isEnvDevelopment = webpackEnv === "development";
// main configuration of output files:
// two bundles, one for our code, one for dependencies
config.output.filename = "bundle.min.js";
config.output.chunkFilename = "[name].min.js";
config.optimization.runtimeChunk = false;
config.optimization.splitChunks = {
chunks: "all",
cacheGroups: {
vendors: {
chunks: "all",
name: "vendors",
test: /(node_modules|src\/data\/dependencies\.json)/,
},
},
};
// same for CSS files
const cssConfig = config.plugins.find(
(p) => p.constructor.name === "MiniCssExtractPlugin",
);
if (cssConfig) {
cssConfig.options.filename = "bundle.min.css";
cssConfig.options.chunkFilename = "[name].min.css";
}
// Don't extract license comments, we bundle them separately
config.optimization.minimizer.find(
(m) => m.constructor.name === "TerserPlugin",
).options.extractComments = false;
// Make vendor bundle change less often even if our own code changes.
config.optimization.occurrenceOrder = false;
// For consistency with previous configs
delete config.output.jsonpFunction;
if (isEnvDevelopment) {
// Make @data resolve to our dummy data
const dataPath = process.env.DATA || "src/data/data.json";
config.resolve.alias["@data"] = path.resolve(__dirname, dataPath);
}
return config;
},
};
|
/**
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 path = require('path');
var util = require('../cordova/util');
var platforms = require('./platformsConfig.json');
var events = require('weexpack-common').events;
// Avoid loading the same platform projects more than once (identified by path)
var cachedApis = {};
// getPlatformApi() should be the only method of instantiating the
// PlatformProject classes for now.
function getPlatformApi(platform, platformRootDir) {
// if platformRootDir is not specified, try to detect it first
if (!platformRootDir) {
var projectRootDir = util.isCordova();
platformRootDir = projectRootDir && path.join(projectRootDir, 'platforms', platform);
}
if (!platformRootDir) {
// If platformRootDir is still undefined, then we're probably is not inside of cordova project
throw new Error('Current location is not a weexpack project');
}
// CB-11174 Resolve symlinks first before working with root directory
platformRootDir = util.convertToRealPathSafe(platformRootDir);
var cached = cachedApis[platformRootDir];
if (cached && cached.platform == platform) return cached;
if (!platforms[platform]) throw new Error('Unknown platform ' + platform);
var PlatformApi;
//WEEK_HOOK
// try {
// // First we need to find whether platform exposes its' API via js module
// // If it does, then we require and instantiate it.
// var platformApiModule = path.join(platformRootDir, 'cordova', 'Api.js');
// PlatformApi = require(platformApiModule);
// } catch (err) {
// // Check if platform already compatible w/ PlatformApi and show deprecation warning
// if (err && err.code === 'MODULE_NOT_FOUND' && platforms[platform].apiCompatibleSince) {
// events.emit('warn', ' Using this version of weexpack with older version of weexpack-' + platform +
// ' is being deprecated. Consider upgrading to weexpack-' + platform + '@' +
// platforms[platform].apiCompatibleSince + ' or newer.');
// } else {
// events.emit('warn', 'Error loading weexpack-'+platform);
// }
//
// PlatformApi = require('./PlatformApiPoly');
// }
var platformPath = platform + '_' + 'pack';
var platformApiPath = path.join(__dirname, platformPath, 'Api.js');
PlatformApi = require(platformApiPath);
var platformApi = new PlatformApi(platform, platformRootDir, events);
cachedApis[platformRootDir] = platformApi;
return platformApi;
}
function getRealPlatformApi(platform, platformRootDir) {
var cached; //= cachedApis[__dirname];
if (cached && cached.platform == platform) return cached;
if (!platforms[platform]) throw new Error('Unknown platform ' + platform);
var PlatformApi;
try {
// First we need to find whether platform exposes its' API via js module
// If it does, then we require and instantiate it.
var platformPath = platform + '_' + 'pack';
var platformApiPath = path.join(__dirname, platformPath, 'Api.js');
PlatformApi = require(platformApiPath);
} catch (err) {
// Check if platform already compatible w/ PlatformApi and show deprecation warning
if (err && err.code === 'MODULE_NOT_FOUND' && platforms[platform].apiCompatibleSince) {
events.emit('warn', ' Using this version of weexpack with older version of weexpack-' + platform +
' is being deprecated. Consider upgrading to weexpack-' + platform + '@' +
platforms[platform].apiCompatibleSince + ' or newer.');
} else {
events.emit('warn', 'Error loading weexpack-'+platform);
}
PlatformApi = require('./PlatformApiPoly');
}
var platformApi = new PlatformApi(platform, platformRootDir, events);
// cachedApis[__dirname] = platformApi;
return platformApi;
}
module.exports = platforms;
// We don't want these methods to be enumerable on the platforms object, because we expect enumerable properties of the
// platforms object to be platforms.
Object.defineProperties(module.exports, {
'getPlatformApi': {value: getPlatformApi, configurable: true, writable: true},
'getRealPlatformApi':{value: getRealPlatformApi, configurable: true, writable: true}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.