code
stringlengths 2
1.05M
|
---|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Winston = require("winston");
var request = require("request");
var moment = require("moment");
var path = require("path");
var fs = require("fs-extra");
var _ = require("underscore");
var GeoJSONHelper = require("../helpers/GeoJSON");
var Api = require("../api/ApiManager");
/** REST datasource
* Provides an endpoint for obtaining features from a REST source. The features can be provided in many forms,
* as they will be converted by a specific converter-JavaScript file. The converter takes care of the conversion
* from the format used by the REST source to GeoJSON.
* Furthermore the datasource will request the GeoJSON features on a certain interval. Only the features that have
* been updated in the interval period will be pushed to the client. Next to the polling interval, a prune period
* can be configured. When features have not been updated within the prune period, they will be deleted.
*/
var RestDataSource = (function () {
function RestDataSource(server, apiManager, layerId, url) {
if (url === void 0) { url = '/restdatasource'; }
this.server = server;
this.apiManager = apiManager;
this.layerId = layerId;
this.url = url;
/** Features that should be added on the client */
this.featuresUpdates = [];
this.restDataSourceOpts = {};
this.enableLogging = false;
this.restDataSourceUrl = url;
this.layerId = layerId;
}
RestDataSource.prototype.init = function (options, callback) {
var _this = this;
if (!options || !options.converterFile) {
callback('Rest datasource not started: No converterfile provided.');
return;
}
Winston.info('Init Rest datasource on port ' + this.server.get('port') + '. Base path is ' + this.url);
this.counter = 1;
this.restDataSourceOpts.converterFile = options.converterFile;
this.restDataSourceOpts.url = options.url;
this.restDataSourceOpts.urlParams = options.urlParams || {};
this.restDataSourceOpts.pollIntervalSeconds = options.pollIntervalSeconds || 60;
this.restDataSourceOpts.pruneIntervalSeconds = options.pruneIntervalSeconds || 300;
this.restDataSourceOpts.diffIgnoreGeometry = (options.hasOwnProperty('diffIgnoreGeometry')) ? false : options['diffIgnoreGeometry'];
this.restDataSourceOpts.diffPropertiesBlacklist = options.diffPropertiesBlacklist || [];
this.restDataSourceOpts.diffPropertiesWhitelist = options.diffPropertiesWhitelist || [];
this.restDataSourceOpts.dateProperty = options.dateProperty || '';
this.restDataSourceOpts.timeProperty = options.timeProperty || '';
this.restDataSourceOpts.dateFormat = options.dateFormat || '';
this.restDataSourceOpts.timeFormat = options.timeFormat || '';
this.restDataSourceOpts.maxFeatureAgeMinutes = options.maxFeatureAgeMinutes || Number.MAX_VALUE;
this.restDataSourceOpts.logFile = options.logFile || null;
if (this.restDataSourceOpts.diffPropertiesBlacklist.length > 0 && this.restDataSourceOpts.diffPropertiesWhitelist.length > 0) {
Winston.info('Both whitelist and blacklist properties provided, ignoring the blacklist.');
this.restDataSourceOpts.diffPropertiesBlacklist.length = 0;
}
if (!fs.existsSync(this.restDataSourceOpts.converterFile)) {
callback("Provided converterfile not found. (" + this.restDataSourceOpts.converterFile + ")");
return;
}
this.converter = require(this.restDataSourceOpts.converterFile);
if (!this.isConverterValid()) {
callback("Provided converterfile not valid. (" + path.basename(this.restDataSourceOpts.converterFile) + ")");
return;
}
if (!!this.restDataSourceOpts.logFile) {
fs.createFile(this.restDataSourceOpts.logFile, function (err) {
if (!err) {
Winston.info('Log Rest data to ' + _this.restDataSourceOpts.logFile);
_this.enableLogging = true;
}
else {
Winston.warn('Error creating log ' + _this.restDataSourceOpts.logFile);
_this.enableLogging = false;
}
});
}
var urlDataParams = this.restDataSourceOpts.urlParams;
urlDataParams['url'] = this.restDataSourceOpts.url;
this.startRestPolling(urlDataParams);
this.server.get(this.restDataSourceUrl, function (req, res) {
Winston.info('Restdatasource got request');
var layerDef = req.body;
if (!layerDef || !_this.converter || !_this.features) {
res.sendStatus(404);
return;
}
layerDef.features = _.map(_this.features, function (val, key) { return val.f; });
res.send(layerDef);
});
callback('Loaded successfully!');
};
RestDataSource.prototype.startRestPolling = function (dataParameters) {
var _this = this;
dataParameters['counter'] = this.counter++;
this.converter.getData(request, dataParameters, { apiManager: this.apiManager, fs: fs }, function (result) {
Winston.info('RestDataSource received ' + result.length || 0 + ' features');
var featureCollection = GeoJSONHelper.GeoJSONFactory.Create(result);
_this.filterOldEntries(featureCollection);
if (!_this.features || Object.keys(_this.features).length === 0) {
_this.initFeatures(featureCollection, Date.now());
}
else {
_this.findFeatureDiff(featureCollection, Date.now());
}
if (_this.enableLogging) {
var toWrite = 'Time: ' + (new Date()).toISOString() + '\n';
toWrite += JSON.stringify(result, null, 2) + '\n';
fs.appendFile(_this.restDataSourceOpts.logFile, toWrite, 'utf8', function (err) {
if (!err) {
Winston.debug('Logged REST datasource result');
}
else {
Winston.warn('Error while logging REST datasource result: ' + err);
}
});
}
});
setTimeout(function () { _this.startRestPolling(dataParameters); }, this.restDataSourceOpts.pollIntervalSeconds * 1000);
};
RestDataSource.prototype.filterOldEntries = function (fcoll) {
if (!fcoll || !fcoll.features || fcoll.features.length === 0)
return;
console.log("Before filtering: " + fcoll.features.length);
var dProp = this.restDataSourceOpts.dateProperty;
var tProp = this.restDataSourceOpts.timeProperty;
var dFormat = this.restDataSourceOpts.dateFormat;
var tFormat = this.restDataSourceOpts.timeFormat;
var age = this.restDataSourceOpts.maxFeatureAgeMinutes;
fcoll.features = fcoll.features.filter(function (f) {
if (f.properties.hasOwnProperty(dProp) && f.properties.hasOwnProperty(dProp)) {
var time = f.properties[tProp].toString();
if (time.length === 5)
time = '0' + time;
var propDate = moment(''.concat(f.properties[dProp], time), ''.concat(dFormat, tFormat));
var now = moment();
if (Math.abs(now.diff(propDate, 'minutes', true)) > age) {
// console.log("Remove feature: " + propDate.toISOString());
return false;
}
else {
f.properties['ParsedDate'] = propDate.toDate().getTime();
}
}
return true;
});
console.log("After filtering: " + fcoll.features.length);
};
RestDataSource.prototype.initFeatures = function (fCollection, updateTime) {
var _this = this;
if (!fCollection || !fCollection.features)
return;
if (!this.features)
this.features = {};
if (_.isArray(fCollection.features)) {
fCollection.features.forEach(function (f, ind) {
_this.features[f.id] = { f: f, updated: updateTime };
if (ind === fCollection.features.length - 1) {
Winston.info('RestDataSource initialized ' + fCollection.features.length + ' features.');
}
});
}
};
RestDataSource.prototype.findFeatureDiff = function (fCollection, updateTime) {
var _this = this;
if (!fCollection || !fCollection.features)
return;
this.featuresUpdates.length = 0;
var notUpdated = 0, updated = 0, added = 0, removed = 0;
var fts = fCollection.features;
var fCollectionIds = [];
if (_.isArray(fts)) {
fts.forEach(function (f) {
fCollectionIds.push(f.id);
if (!_this.features.hasOwnProperty(f.id)) {
// ADD FEATURE
_this.features[f.id] = { f: f, updated: updateTime };
_this.featuresUpdates.push({ value: f, type: Api.ChangeType.Create, id: f.id });
added += 1;
}
else if (!_this.isFeatureUpdated(f)) {
// NO UPDATE
notUpdated += 1;
}
else {
// UPDATE
_this.features[f.id] = { f: f, updated: updateTime };
_this.featuresUpdates.push({ value: f, type: Api.ChangeType.Update, id: f.id });
updated += 1;
}
});
}
// CHECK INACTIVE FEATURES
var inactiveFeatures = _.difference(Object.keys(this.features), fCollectionIds);
if (inactiveFeatures && inactiveFeatures.length > 0) {
inactiveFeatures.forEach(function (fId) {
if ((updateTime - _this.features[fId].updated) >= (_this.restDataSourceOpts.pruneIntervalSeconds * 1000)) {
// REMOVE
_this.featuresUpdates.push({ value: _this.features[fId].f, type: Api.ChangeType.Delete, id: _this.features[fId].f.id });
delete _this.features[_this.features[fId].f.id];
removed += 1;
}
});
}
this.apiManager.addUpdateFeatureBatch(this.layerId, this.featuresUpdates, {}, function (r) { });
Winston.info("Feature diff complete. " + updated + " updated \t" + added + " added \t" + notUpdated + " not updated \t" + removed + " removed. (" + this.counter + ")");
};
RestDataSource.prototype.isFeatureUpdated = function (f) {
if (!f)
return false;
// Check geometry
if (!this.restDataSourceOpts.diffIgnoreGeometry && !_.isEqual(f.geometry, this.features[f.id].f.geometry)) {
return true;
}
if (!f.properties)
return false;
// Check for blacklisted properties
if (this.restDataSourceOpts.diffPropertiesBlacklist.length > 0) {
var blacklist = this.restDataSourceOpts.diffPropertiesBlacklist;
if (_.isEqual(_.omit(f.properties, blacklist), _.omit(this.features[f.id].f.properties, blacklist))) {
return false;
}
}
// Check for whitelisted properties
if (this.restDataSourceOpts.diffPropertiesWhitelist.length > 0) {
var whitelist = this.restDataSourceOpts.diffPropertiesWhitelist;
if (_.isEqual(_.pick(f.properties, whitelist), _.pick(this.features[f.id].f.properties, whitelist))) {
return false;
}
}
// Check all properties
if (_.isEqual(f.properties, this.features[f.id].f.properties)) {
return false;
}
return true;
};
RestDataSource.prototype.isConverterValid = function () {
var valid = true;
Winston.info("" + Object.keys(this.converter));
valid = (this.converter.getData && typeof this.converter.getData === 'function');
return valid;
};
return RestDataSource;
}());
exports.RestDataSource = RestDataSource;
//# sourceMappingURL=RestDataService.js.map
|
module.exports = function(grunt, options) {
return {
src: {
dir: './tests'
},
options: {
bin: 'vendor/bin/phpunit',
bootstrap: 'bootstrap/autoload.php',
color: true
}
};
};
|
$(document).ready(function() {
/* ------- main_template ------- */
$("#adapter").change(function() {
var adp = $("#adapter").val();
var adp_tmp = available_tests[adp];
if (adp == '-') {
$('#tests').html('');
$('#button_show_resulsts').hide();
} else {
if (typeof adp_tmp == 'string' || adp_tmp instanceof String) {
$('#tests').html(adp_tmp);
$('#button_show_resulsts').hide();
} else {
var s = $("<select id=\"available_tests\" name=\"available_tests\" />");
for (var i in adp_tmp) {
$("<option />", {value: adp_tmp[i].id, text: adp_tmp[i].name}).appendTo(s);
}
$('#tests').html(s);
$('#button_show_resulsts').show();
}
}
});
$("#show_graphics").click(function() {
location.href = '/result/' + $("#adapter").val() + '/' + $("#available_tests").val();
});
$("#compare").click(function() {
var url = '/compare/0?';
var url_params = [];
var i = 0;
$('select.compare').each(function() {
url_params.push('compare[' + i + ']=' + $(this).val());
i = i + 1;
});
location.href = url + url_params.join('&');
});
/* ------- compare_template ------- */
$("#proc").change(function () {
location.href = '/compare/' + $(this).val() + location.search;
});
/* ------- graphics ------- */
if($('#chartdiv').length > 0) {
$('#chartdiv').width($(window).width());
$.jqplot('chartdiv', graph_json_data, {
series: [],
seriesDefaults: {showMarker: true, showLine: false},
title: graph_title,
axes: {
xaxis: {
label: 'request № (first, second, etc.)',
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
min: 0
},
yaxis: {
label: 'time (sec)',
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
min: 0
}
},
legend: {
show: true,
labels: graph_labels
}
});
}
});
|
// Jquery with no conflict
jQuery(document).ready(function($) {
// nivo slider ------------------------------------------------------ //
$('#slider').nivoSlider({
effect:'random', //Specify sets like: 'fold,fade,sliceDown'
slices:15,
animSpeed:500, //Slide transition speed
pauseTime:3000,
startSlide:0, //Set starting Slide (0 index)
directionNav:true, //Next & Prev
directionNavHide:true, //Only show on hover
controlNav:true, //1,2,3...
controlNavThumbs:false, //Use thumbnails for Control Nav
controlNavThumbsFromRel:false, //Use image rel for thumbs
controlNavThumbsSearch: '.jpg', //Replace this with...
controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
keyboardNav:true, //Use left & right arrows
pauseOnHover:true, //Stop animation while hovering
manualAdvance: false, //Force manual transitions
captionOpacity:0.7 //Universal caption opacity
});
// Poshytips ------------------------------------------------------ //
$('.poshytip').poshytip({
className: 'tip-twitter',
showTimeout: 1,
alignTo: 'target',
alignX: 'center',
offsetY: 5,
allowTipHover: false
});
// Poshytips Forms ------------------------------------------------------ //
$('.form-poshytip').poshytip({
className: 'tip-yellowsimple',
showOn: 'focus',
alignTo: 'target',
alignX: 'right',
alignY: 'center',
offsetX: 5
});
// Superfish menu ------------------------------------------------------ //
$("ul.sf-menu").superfish({
animation: {height:'show'}, // slide-down effect without fade-in
delay: 800 , // 1.2 second delay on mouseout
autoArrows: false
});
// Scroll to top ------------------------------------------------------ //
$('#to-top').click(function(){
$.scrollTo( {top:'0px', left:'0px'}, 300 );
});
// Submenu rollover --------------------------------------------- //
$("ul.sf-menu>li>ul li").hover(function() {
// on rollover
$(this).children('a').children('span').stop().animate({
marginLeft: "3"
}, "fast");
} , function() {
// on out
$(this).children('a').children('span').stop().animate({
marginLeft: "0"
}, "fast");
});
// Tweet Feed ------------------------------------------------------ //
$("#tweets").tweet({
count: 3,
username: "ansimuz",
callback: tweet_cycle
});
// Tweet arrows rollover --------------------------------------------- //
$("#twitter #prev-tweet").hover(function() {
// on rollover
$(this).stop().animate({
left: "27"
}, "fast");
} , function() {
// on out
$(this).stop().animate({
left: "30"
}, "fast");
});
$("#twitter #next-tweet").hover(function() {
// on rollover
$(this).stop().animate({
right: "27"
}, "fast");
} , function() {
// on out
$(this).stop().animate({
right: "30"
}, "fast");
});
// Tweet cycle --------------------------------------------- //
function tweet_cycle(){
$('#tweets .tweet_list').cycle({
fx: 'scrollHorz',
speed: 500,
timeout: 0,
pause: 1,
next: '#twitter #next-tweet',
prev: '#twitter #prev-tweet'
});
}
// tabs ------------------------------------------------------ //
$("ul.tabs").tabs("div.panes > div", {effect: 'fade'});
// Thumbs rollover --------------------------------------------- //
$('.thumbs-rollover li a img').hover(function(){
// on rollover
$(this).stop().animate({
opacity: "0.5"
}, "fast");
} , function() {
// on out
$(this).stop().animate({
opacity: "1"
}, "fast");
});
// Blog posts rollover --------------------------------------------- //
$('#posts .post').hover(function(){
// on rollover
$(this).children('.thumb-shadow').children('.post-thumbnail').children(".cover").stop().animate({
left: "312"
}, "fast");
} , function() {
// on out
$(this).children('.thumb-shadow').children('.post-thumbnail').children(".cover").stop().animate({
left: "0"
}, "fast");
});
// Portfolio projects rollover --------------------------------------------- //
$('#projects-list .project').hover(function(){
// on rollover
$(this).children('.project-shadow').children('.project-thumbnail').children(".cover").stop().animate({
top: "133"
}, "fast");
} , function() {
// on out
$(this).children('.project-shadow').children('.project-thumbnail').children(".cover").stop().animate({
top: "0"
}, "fast");
});
// Sidebar rollover --------------------------------------------------- //
$('#sidebar>li>ul>li').hover(function(){
// over
$(this).children('a').stop().animate({ marginLeft: "5" }, "fast");
} , function(){
// out
$(this).children('a').stop().animate({marginLeft: "0"}, "fast");
});
// Fancybox --------------------------------------------------- //
$("a.fancybox").fancybox({
'overlayColor': '#000'
});
// pretty photo ------------------------------------------------------ //
$("a[rel^='prettyPhoto']").prettyPhoto();
// Project gallery over --------------------------------------------- //
$('.project-gallery li a img').hover(function(){
// on rollover
$(this).stop().animate({
opacity: "0.5"
}, "fast");
} , function() {
// on out
$(this).stop().animate({
opacity: "1"
}, "fast");
});
// Thumbs functions ------------------------------------------------------ //
function thumbsFunctions(){
// prettyphoto
$("a[rel^='prettyPhoto']").prettyPhoto();
// Fancy box
$("a.fancybox").fancybox({
'overlayColor' : '#000'
});
// Gallery over
$('.gallery li a img').hover(function(){
// on rollover
$(this).stop().animate({
opacity: "0.5"
}, "fast");
} , function() {
// on out
$(this).stop().animate({
opacity: "1"
}, "fast");
});
// tips
$('.gallery a').poshytip({
className: 'tip-twitter',
showTimeout: 1,
alignTo: 'target',
alignX: 'center',
offsetY: -15,
allowTipHover: false
});
}
// init
thumbsFunctions();
// Filtering using isotope -----------------------------------------------------------//
var $container = $('#portfolio-list');
$container.imagesLoaded( function(){
$container.isotope({
itemSelector : 'li',
filter: '*',
animationEngine: 'jquery'
});
});
// filter buttons
$('#portfolio-filter a').click(function(){
// select current
var $optionSet = $(this).parents('#portfolio-filter');
$optionSet.find('.selected').removeClass('selected');
$(this).parent().addClass('selected');
var selector = $(this).attr('data-filter');
$container.isotope({ filter: selector });
return false;
});
// UI Accordion ------------------------------------------------------ //
$( ".accordion" ).accordion();
// Toggle box ------------------------------------------------------ //
$(".toggle-container").hide();
$(".toggle-trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
return false;
});
// Footer menu rollover --------------------------------------------------- //
$('#footer .col .page_item').hover(function(){
// over
$(this).children('a').stop().animate({ marginLeft: "5" }, "fast");
} , function(){
// out
$(this).children('a').stop().animate({marginLeft: "0"}, "fast");
});
//close
});
// search clearance
function defaultInput(target){
if((target).value == 'Search...'){(target).value=''}
}
function clearInput(target){
if((target).value == ''){(target).value='Search...'}
}
|
System.register(['angular2/core', './astronaut.component', './mission.service'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1, astronaut_component_1, mission_service_1;
var MissionControlComponent;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
},
function (astronaut_component_1_1) {
astronaut_component_1 = astronaut_component_1_1;
},
function (mission_service_1_1) {
mission_service_1 = mission_service_1_1;
}],
execute: function() {
MissionControlComponent = (function () {
function MissionControlComponent(missionService) {
var _this = this;
this.missionService = missionService;
this.astronauts = ['Lovell', 'Swigert', 'Haise'];
this.history = [];
this.missions = [
'Fly to the moon!',
'Fly to mars!',
'Fly to Vegas!'
];
this.nextMission = 0;
missionService.missionConfirmed$.subscribe(function (astronaut) {
_this.history.push(astronaut + " confirmed the mission");
});
}
MissionControlComponent.prototype.announce = function () {
var mission = this.missions[this.nextMission++];
this.missionService.announceMission(mission);
this.history.push("Mission \"" + mission + "\" announced");
if (this.nextMission >= this.missions.length) {
this.nextMission = 0;
}
};
MissionControlComponent = __decorate([
core_1.Component({
selector: 'mission-control',
template: "\n <h2>Mission Control</h2>\n <button (click)=\"announce()\">Announce mission</button>\n <my-astronaut *ngFor=\"#astronaut of astronauts\"\n [astronaut]=\"astronaut\">\n </my-astronaut>\n <h3>History</h3>\n <ul>\n <li *ngFor=\"#event of history\">{{event}}</li>\n </ul>\n ",
directives: [astronaut_component_1.AstronautComponent],
providers: [mission_service_1.MissionService]
}),
__metadata('design:paramtypes', [mission_service_1.MissionService])
], MissionControlComponent);
return MissionControlComponent;
}());
exports_1("MissionControlComponent", MissionControlComponent);
}
}
});
//# sourceMappingURL=mission-control.component.js.map
|
module.exports = {
siteTitle: "Steffis Krümelkiste",
siteSlogan: "Liebevolle Kindertagespflege \nin\u00A0Weißensee",
copyright: "© Copyright - Steffis Krümelkiste",
aboutCaption: "Über mich",
contractCaption: "Kosten & Vertrag",
contactCaption: "Kontakt",
serviceCaption: "Mein Angebot",
siteNoticeCaption: "Impressum & Datenschutz",
emailAddress: "steffis.kruemelkiste@gmail.com",
}
|
'use strict';
import PostEditCtrl from './edit.controller';
let PostEditModule = angular
.module('hey.post.edit', [])
.controller('PostEditCtrl', PostEditCtrl)
.config(($stateProvider) => {
$stateProvider
.state('post.create', {
url: '/create/new',
parent: 'post',
templateUrl: 'app/post/edit/edit.html',
controller: 'PostEditCtrl',
controllerAs: 'vm'
})
.state('post.edit', {
url: '/:slug/edit',
parent: 'post',
templateUrl: 'app/post/edit/edit.html',
controller: 'PostEditCtrl',
controllerAs: 'vm'
});
});
export default PostEditModule;
|
adminApp.controller('resurserCategoryCtrl',function($scope, $http, $rootScope, $location,$timeout){
//get all branch list
$scope.resurserCategory=function(){
$http.get(baseUrl+'admin/resurser_category').success(function(response){
$scope.resurserCategoryList=response;
$('#resurserCatList').dataTable().fnDestroy();
$timeout(function() {
$('#resurserCatList').DataTable({
responsive: {
details: false
},
dom: 'Bfrtip',
buttons: [
'csv', 'excel', 'pdf', 'copy'
]
});
}, 1000);
}).error(function(error){
alertify.error('Error'+ error);
});
}
$scope.allChecked='0';
$scope.selectedResurserCategory = [];
$scope.takeAction = function () {
//console.log('here ' , $scope.selectedResurserCategory);
if($scope.markAction) {
var postData = {};
postData.users = $scope.selectedResurserCategory;
postData.action = $scope.markAction;
postData.reason = $scope.actionReason;
$http.post(baseUrl + 'admin/change_user_status', postData).success(function (response) {
if(response && response.success) {
$scope.resurserCategory();
alertify.success('Success' + response.message);
}else {
alertify.error('Error' + response.message);
}
}).error(function (error) {
alertify.error('Error' + error);
});
}
}
$scope.toggleCheckAll=function(){
if($scope.allChecked=='0'){
$scope.allChecked='1';
}
else{
$scope.allChecked='0';
}
if($scope.allChecked=='1'){
$scope.selectedResurserCategory=[];
angular.forEach($scope.resurserCategoryList,function(value){
$scope.selectedResurserCategory.push(value.id);
});
$('input:checkbox').prop('checked', true);
}
else{
$scope.selectedResurserCategory=[];
$('input:checkbox').removeAttr('checked');
}
}
/*values already filled during edit*/
$scope.selectRow=function(category){
$scope.selectedRow = category;
}
/*update fields*/
$scope.submitData=function(){
$http.post(baseUrl +'admin/update_resurser_category',$scope.selectedRow).success(function(response){
$scope.resurserCategory();
$('#editModal').modal('hide');
alertify.success('Success: Data has been updated successfully.');
}).error(function(error){
console.log('error',error);
});
}
/*Remove fields*/
$scope.removeResurserCategory=function(category){
// console.log('it is working', category);
alertify.confirm("Are you sure", "You are about to delete resurser category"+category.name,
function(){
$http.delete(baseUrl+'admin/delete_resurser_category/'+category.id).success(function(response){
alertify.success("Success: Page "+ category.name +" has been delete successfully");
//$scope.resurserCategory();
}).error(function(error){
alertify.error('Error: '+error);
});
},
function(){
});
}
/*Add reurser category*/
$scope.reurser={};
$scope.addReurserData=function(){
//console.log('the values are here',$scope.reurser);
$http.post(baseUrl +'Admin/post_reurser_category',$scope.reurser).success(function(response){
if (response && response.success) {
$('#addModal').modal('hide');
alertify.success('Success: Your project category has been posted successfully');
}
else {
alertify.error('Error: ' + response.message);
}
}).error(function(error){
console.log("error", error);
alertify.error('Error: ' + error);
});
}
});
|
"use strict";
const evaluate = require("babel-helper-evaluate-path");
function isPureAndUndefined(
rval,
{ tdz, scope = { hasBinding: () => false } } = {}
) {
if (rval.isIdentifier() && rval.node.name === "undefined") {
// deopt right away if undefined is a local binding
if (scope.hasBinding(rval.node.name, true /* no globals */)) {
return false;
}
return true;
}
if (!rval.isPure()) {
return false;
}
const evaluation = evaluate(rval, { tdz });
return evaluation.confident === true && evaluation.value === undefined;
}
function getLoopParent(path, scopeParent) {
const parent = path.findParent(p => p.isLoop() || p === scopeParent);
// don't traverse higher than the function the var is defined in.
return parent === scopeParent ? null : parent;
}
function getFunctionParent(path, scopeParent) {
const parent = path.findParent(p => p.isFunction());
// don't traverse higher than the function the var is defined in.
return parent === scopeParent ? null : parent;
}
function getFunctionReferences(path, scopeParent, references = new Set()) {
for (
let func = getFunctionParent(path, scopeParent);
func;
func = getFunctionParent(func, scopeParent)
) {
const id = func.node.id;
const binding = id && func.scope.getBinding(id.name);
if (!binding) {
continue;
}
binding.referencePaths.forEach(path => {
if (!references.has(path)) {
references.add(path);
getFunctionReferences(path, scopeParent, references);
}
});
}
return references;
}
function hasViolation(declarator, scope, start) {
const binding = scope.getBinding(declarator.node.id.name);
if (!binding) {
return true;
}
const scopeParent = declarator.getFunctionParent();
const violation = binding.constantViolations.some(v => {
// https://github.com/babel/minify/issues/630
if (!v.node) {
return false;
}
// return 'true' if we cannot guarantee the violation references
// the initialized identifier after
const violationStart = v.node.start;
if (violationStart === undefined || violationStart < start) {
return true;
}
const references = getFunctionReferences(v, scopeParent);
for (const ref of references) {
if (ref.node.start === undefined || ref.node.start < start) {
return true;
}
}
for (
let loop = getLoopParent(declarator, scopeParent);
loop;
loop = getLoopParent(loop, scopeParent)
) {
if (loop.node.end === undefined || loop.node.end > violationStart) {
return true;
}
}
});
return violation;
}
module.exports = function() {
return {
name: "transform-remove-undefined",
visitor: {
SequenceExpression(path, { opts: { tdz } = {} }) {
const expressions = path.get("expressions");
for (let i = 0; i < expressions.length; i++) {
const expr = expressions[i];
if (!isPureAndUndefined(expr, { tdz, scope: path.scope })) continue;
// last value
if (i === expressions.length - 1) {
if (path.parentPath.isExpressionStatement()) {
expr.remove();
}
} else {
expr.remove();
}
}
},
ReturnStatement(path, { opts: { tdz } = {} }) {
if (path.node.argument !== null) {
if (
isPureAndUndefined(path.get("argument"), {
tdz,
scope: path.scope
})
) {
path.node.argument = null;
}
}
},
VariableDeclaration(path, { opts: { tdz } = {} }) {
switch (path.node.kind) {
case "const":
break;
case "let":
for (const declarator of path.get("declarations")) {
if (isPureAndUndefined(declarator.get("init"), { tdz })) {
declarator.node.init = null;
}
}
break;
case "var":
const start = path.node.start;
if (start === undefined) {
// This is common for plugin-generated nodes
break;
}
const scope = path.scope;
for (const declarator of path.get("declarations")) {
if (
isPureAndUndefined(declarator.get("init")) &&
!hasViolation(declarator, scope, start)
) {
declarator.node.init = null;
}
}
break;
}
}
}
};
};
|
__report = {
"reports": [
{
"info": {
"file": "lib/WMIframeInserter.js",
"fileShort": "lib/WMIframeInserter.js",
"fileSafe": "lib_WMIframeInserter_js",
"link": "files/lib_WMIframeInserter_js/index.html"
},
"jshint": {
"messages": 0
},
"complexity": {
"aggregate": {
"line": 1,
"complexity": {
"sloc": {
"physical": 97,
"logical": 46
},
"cyclomatic": 9,
"halstead": {
"operators": {
"distinct": 15,
"total": 112,
"identifiers": [
"__stripped__"
]
},
"operands": {
"distinct": 64,
"total": 163,
"identifiers": [
"__stripped__"
]
},
"length": 275,
"vocabulary": 79,
"difficulty": 19.1015625,
"volume": 1733.5397057487035,
"effort": 33113.317035590466,
"bugs": 0.5778465685829012,
"time": 1839.6287241994703
},
"params": 12
}
},
"module": "lib/WMIframeInserter.js",
"maintainability": 73.19078716177786
}
}
],
"summary": {
"total": {
"sloc": 97,
"maintainability": 73.19078716177786
},
"average": {
"sloc": 97,
"maintainability": "73.19"
}
}
}
|
'use strict';
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _mkdirp = require('mkdirp');
var _mkdirp2 = _interopRequireDefault(_mkdirp);
var _bluebird = require('bluebird');
var _bluebird2 = _interopRequireDefault(_bluebird);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mkdirpAsync = _bluebird2.default.promisify(_mkdirp2.default);
_fs2.default.mkdirp = _mkdirp2.default;
_fs2.default._writeFile = _fs2.default.writeFile;
_fs2.default.writeFile = function (filePath, data) {
var options = arguments.length <= 2 || arguments[2] === undefined ? 'utf8' : arguments[2];
var cb = arguments[3];
var dirname = _path2.default.dirname(filePath);
(0, _mkdirp2.default)(dirname, function (err) {
if (err) return cb(err);
_fs2.default._writeFile(filePath, data, options, cb);
});
};
_fs2.default._appendFile = _fs2.default.appendFile;
_fs2.default.appendFile = function (filePath, data) {
var options = arguments.length <= 2 || arguments[2] === undefined ? 'utf8' : arguments[2];
var cb = arguments[3];
var dirname = _path2.default.dirname(filePath);
(0, _mkdirp2.default)(dirname, function (err) {
if (err) return cb(err);
_fs2.default._appendFile(filePath, data, options, cb);
});
};
_bluebird2.default.promisifyAll(_fs2.default);
module.exports = _fs2.default;
|
$(document).ready(function() {
//Resize plug-in
$(window).resize(function() { $('td').each(function(){$(this).css({"height":$(this).width()})});$('table').css({"margin": $('td').width()*(-1)}) })
//Tooltips active
$(function () {$('[data-toggle="tooltip"]').tooltip()})
//Global variables
var board = [];
var xaxis = 4;
var yaxis = 4;
var wallthickness = 1;
var foodvalue = 1;
var gameStatus = "idle";
var counter = 0;
var needGen = 1;
var head = [2,2];
var tail = [null,null];
var movement = [0,0,0,0]; //[left,right,up,down]
var recordingTime = false;
var time = 0;
var interval = 0;
var autoMoving = false;
var gridsCovered = 1;
var numberOfMoves = 0;
var playerNames = [];
var playerTimes = [0];
var gameMode;
var index = 0; //Use only in multiplayer mode (index of who is playing)
var level = 1; //Use only in arcade mode
var wallColor = 'transparent';
var headColor = 'black';
var snakeColor = 'brown';
var backgroundColor = 'white';
var foodColor = 'red';
var reverse = false;
//********** Functions **********
//Food generation
var foodGen = function() {
var i = Math.floor(Math.random() * xaxis) + wallthickness;
var j = Math.floor(Math.random() * yaxis) + wallthickness;
while (board[j][i] !== 0) {
i = Math.floor(Math.random() * xaxis + wallthickness);
j = Math.floor(Math.random() * yaxis + wallthickness);
}
board[j][i] = (-foodvalue);
};
//Input left
var goLeft = function() {
board[head[0]][head[1]-1] = 1;
head[1] -= 1;
};
//Input right
var goRight = function() {
board[head[0]][head[1]+1] = 2;
head[1]+=1;
};
//Input Up
var goUp = function() {
board[head[0]-1][head[1]] = 3;
head[0] -= 1;
};
//Input down
var goDown = function() {
board[head[0]+1][head[1]] = 4;
head[0]+=1;
};
//Chop tail
var chopTail = function() {
for (i = 0; i < xaxis+2*wallthickness; i+=1) {
for (j = 0; j < yaxis+2*wallthickness; j+=1) {
if (board[j][i] === 5) {
tail = [j,i];
console.log(tail)
}else if (board[j][i] === 1 && board[j][i+1] <= 0) {
tail = [j,i];
}else if (board[j][i] === 2 && board[j][i-1] <= 0) {
tail = [j,i];
}else if (board[j][i] === 3 && board[j+1][i] <= 0) {
tail = [j,i];
}else if (board[j][i] === 4 && board[j-1][i] <= 0) {
tail = [j,i];
}
}
}
if (counter > 0 && gameStatus == "inPlay" ) {
counter = counter - 1;
}else if (counter === 0) {
board[tail[0]][tail[1]] = 0;
}
};
//Check if food is nearby [left,right,up,down]
var checkStuff = function() {
var checkStuff = [0,0,0,0];
if (board[head[0]][head[1]-1] < 0) {checkStuff[0] = board[head[0]][head[1]-1]}
if (board[head[0]][head[1]+1] < 0) {checkStuff[1] = board[head[0]][head[1]+1]}
if (board[head[0]-1][head[1]] < 0) {checkStuff[2] = board[head[0]-1][head[1]]}
if (board[head[0]+1][head[1]] < 0) {checkStuff[3] = board[head[0]+1][head[1]]}
if (board[head[0]][head[1]-1] > 0) {checkStuff[0] = 1}
if (board[head[0]][head[1]+1] > 0) {checkStuff[1] = 1}
if (board[head[0]-1][head[1]] > 0) {checkStuff[2] = 1}
if (board[head[0]+1][head[1]] > 0) {checkStuff[3] = 1}
return checkStuff
};
//Opposite disable plug-in
var oppositeCheck = function(x,y) {
if (( x == 1 && y == 2 ) || ( x == 2 && y == 1) || ( x == 3 && y == 4 ) || ( x == 4 && y == 3)) {
return true;
}else {
return false;
}
}
//Check win
var checkWin = function () {
var win = true;
for (i=0; i < xaxis+2*wallthickness; i+=1) {
for (j=0; j < yaxis+2*wallthickness; j+=1) {
if (board[j][i] <= 0) {
win = false;
}
}
}
return win
}
//Timer
$(document).keydown(function (e) {
if([37, 38, 39, 40].indexOf(e.keyCode) > -1 && recordingTime === false && gameStatus === 'inPlay') {
var timer = setInterval(function(){
time += 1;
$('.stopWatch').text(time/100);
recordingTime = true;
if(gameStatus !== "inPlay") {
clearInterval(timer);
};
}, 10);
}
})
//Speed control system
var speedControl = function() {
if (interval === 0 && oppositeCheck((movement.indexOf(1) + 1) , board[head[0]][head[1]]) === false) {
running();
movement = [0,0,0,0];
}
else if (interval !== 0 && autoMoving === false) {
autoMoving = true;
var autoMove = setInterval(function(){
running();
if(gameStatus !== "inPlay") {
clearInterval(autoMove);
};
}, interval);
}
if (oppositeCheck((movement.indexOf(1) + 1) , board[head[0]][head[1]]) === true) {
movement = [0,0,0,0];
movement[board[head[0]][head[1]]-1] = 1;
}
}
//Running
var running = function() {
for (i = 0; i < 4; i+=1) {
if (movement[i] === 1 && checkStuff()[i] > 0) {
gameStatus = "crashed";
if (gameMode === 'Multiplayer') {
multiplayerAddOns();
}else if (gameMode === 'Arcade') {
arcadeAddOns();
}
alert("You Lost :((( Time taken: " + (time/100) + "s");
}else if (movement[i] === 1 && checkStuff()[i] < 0) {
counter = counter - checkStuff()[i];
needGen = 1;
}
}
if (gameStatus == "inPlay" ) {
chopTail();
if (movement[0] == 1) {
goLeft();
}else if (movement[1] == 1) {
goRight();
}else if (movement[2] == 1) {
goUp();
}else if (movement[3] == 1) {
goDown();
}
if (checkWin() === true) {
gameStatus = "Won";
alert("Perfect Snake! Well done!! Time taken: " + (time/100) + "s");
if (gameMode === 'Multiplayer') {
multiplayerAddOns();
}else if (gameMode === 'Arcade') {
arcadeAddOns();
}
}
if (needGen === 1 && gameStatus == "inPlay" ) {
foodGen();
needGen = 0;
}
}
colorTranslate();
numberOfMoves++;
$('.numberOfMoves').text(numberOfMoves);
}
//Translate into colors + Calculate grid covered
var colorTranslate = function () {
gridsCovered = 0;
for (i=0; i < xaxis+2*wallthickness; i+=1) {
for (j=0; j < yaxis+2*wallthickness; j+=1) {
if (board[j][i] === 8) {
$('.table tbody tr:nth-child(' + (j+1) + ') td:nth-child(' + (i+1) + ')').css({"background-color":'transparent'})
$('.table tbody tr:nth-child(' + (j+1) + ') td:nth-child(' + (i+1) + ')').css({"box-shadow":'none'})
}else if (board[j][i] > 0 ){
$('.table tbody tr:nth-child(' + (j+1) + ') td:nth-child(' + (i+1) + ')').css({"background-color":snakeColor}); gridsCovered++
}else if (board[j][i] < 0 ){
$('.table tbody tr:nth-child(' + (j+1) + ') td:nth-child(' + (i+1) + ')').css({"background-color":foodColor})
}else if (board[j][i] === 0 ){
$('.table tbody tr:nth-child(' + (j+1) + ') td:nth-child(' + (i+1) + ')').css({"background-color":backgroundColor})
}if (j === head[0] && i === head[1]) {
$('.table tbody tr:nth-child(' + (j+1) + ') td:nth-child(' + (i+1) + ')').css({"background-color":headColor});
}
}
}
$('.gridsCovered').text(((gridsCovered*100)/(xaxis*yaxis)).toFixed(2) + "% (" + gridsCovered + " out of " + (xaxis*yaxis) + ")")
}
//Reset
var reset = function () {
board = [];
xaxis = 4;
yaxis = 4;
wallthickness = 1;
foodvalue = 1;
gameStatus = "idle";
counter = 0;
needGen = 1;
head = [2,2];
tail = [null,null];
movement = [0,0,0,0]; //[left,right,up,down]
recordingTime = false;
time = 0;
interval = 0;
$('#buttonGroupOriginal button').removeClass('active'); $('#normal').addClass('active');
autoMoving = false;
gridsCovered = 1;
numberOfMoves = 0;
$('.table tbody').empty();
playerNames = [];
playerTimes = [0];
$('#timeRecords').empty();
$('#playerNames').empty();
$('#timeRecords').append('<li>Time</li>');
$('#playerNames').append('<li>Player</li>');
$('#levels').empty();
$('#levelsTime').empty();
$('#levels').append('<li>Levels</li>');
$('#levelsTime').append('<li>Time</li>');
$('#levelDisplay').text('Level 1');
$('#gridSize').text('2 x 2 grid');
index = 0;
level = 1;
wallColor = 'transparent';
headColor = 'black';
snakeColor = 'brown';
backgroundColor = 'white';
foodColor = 'red';
reverse = false;
$('#buttonGroupCustom button').removeClass('active'); $('#reverseFalse').addClass('active')
}
//Creating main board
var generateBoard = function () {
var x = xaxis + 2 * wallthickness;
var y = yaxis + 2 * wallthickness;
for (i = 1; i <= y; i +=1 ) {
$('.table tbody').append('<tr></tr>');
for (j = 1; j <= x; j += 1) {
$('.table tbody tr:nth-child(' + i + ')').append('<td></td>')
}
}
$('td').each(function(){$(this).css({"height":$(this).width()})})
$('table').css({"margin": $('td').width()*(-1)})
$('td').css({"border-color":'transparent'})
//Engine setup
for (i=0; i < yaxis+2*wallthickness; i+=1) {
board[i] = [];
for (j=0; j < xaxis+2*wallthickness; j+=1) {
board[i][j] = 0;
}
}
for (i=0; i < yaxis+2*wallthickness; i+=1) {
for (j=0; j < wallthickness; j+=1) {
board[i][j] = 8;
board[i][xaxis+2*wallthickness-1-j] = 8;
}
}
for (i=0; i < xaxis+2*wallthickness; i+=1) {
for (j=0; j < wallthickness; j+=1) {
board[j][i] = 8;
board[yaxis+2*wallthickness-1-j][i] = 8;
}
}
board[head[0]][head[1]] = 5;
colorTranslate();
}
//Arcade add-ons
var arcadeAddOns = function() {
if (gameStatus === "crashed") {
$('#levelsTime').append('<li>crashed</li>');
$('#levels').append('<li>Level ' + level + '</li>');
}else if (gameStatus === "Won") {
$('#levelsTime').append('<li>' + (time/100) + '</li>');
$('#levels').append('<li>Level ' + level + '</li>');
$('#nextLevelArcade').show();
}
}
//Multiplayer add-ons
var multiplayerAddOns = function() {
if (gameStatus === "crashed") {
playerTimes[index] = 'Lost';
$('#timeRecords li:nth-child(' + (index + 2) + ')').text('Lost')
}else if (gameStatus === "Won") {
playerTimes[index] = (time/100);
$('#timeRecords li:nth-child(' + (index + 2) + ')').text(time/100)
}
if ((index + 1) < $('.playerList input').length) {
$('#nextPlayerButton').show()
}
}
//********** Original mode **********
//Board Initialise
$('#startButtonOriginal').click(function() {
$('#startButtonOriginal').hide();
$('#buttonGroupOriginal').hide();
$('.intro').hide();
$('#scoreBoardOriginal').show();
gameMode = 'Original';
gameStatus = "inPlay";
if (interval === 0) {
interval = 150;
}
xaxis = 20;
yaxis = 15;
generateBoard();
$('.numberOfMoves').text(numberOfMoves);
$('.stopWatch').text(time);
})
//Speed choosing && determining reverse or not
$('#verySlow').click(function() { $('#buttonGroupOriginal button').removeClass('active'); $(this).addClass('active'); interval = 400})
$('#slow').click(function() { $('#buttonGroupOriginal button').removeClass('active'); $(this).addClass('active'); interval = 250})
$('#normal').click(function() { $('#buttonGroupOriginal button').removeClass('active'); $(this).addClass('active'); interval = 150})
$('#fast').click(function() { $('#buttonGroupOriginal button').removeClass('active'); $(this).addClass('active'); interval = 100})
$('#veryFast').click(function() { $('#buttonGroupOriginal button').removeClass('active'); $(this).addClass('active'); interval = 50})
$('#reverseTrue').click(function() { $('#buttonGroupCustom button').removeClass('active'); $(this).addClass('active'); reverse = true})
$('#reverseFalse').click(function() {$('#buttonGroupCustom button').removeClass('active'); $(this).addClass('active'); reverse = false})
//Reset button
$('#resetButtonOriginal').click(function() {
reset();
$('#startButtonOriginal').show();
$('#buttonGroupOriginal').show();
$('.intro').show();
$('#scoreBoardOriginal').hide();
})
//********** Arcade mode **********
//Board Initialise
$('#startButtonArcade').click(function() {
$('#scoreBoardArcade').show();
$('.intro').hide();
gameMode = 'Arcade';
gameStatus = "inPlay";
xaxis = 1 + level;
yaxis = 1 + level;
interval = 0;
generateBoard();
$('.numberOfMoves').text(numberOfMoves);
$('.stopWatch').text(time);
$('#startButtonArcade').hide();
$('#resetButtonArcade').show();
$('#nextLevelArcade').hide();
})
//Next level button
$('#nextLevelArcade').click(function() {
gameStatus = 'inPlay';
board = [];
$('.table tbody').empty();
counter = 0;
needGen = 1;
head = [2,2];
tail = [null,null];
movement = [0,0,0,0]; //[left,right,up,down]
recordingTime = false;
time = 0;
gridsCovered = 1;
numberOfMoves = 0;
level++;
xaxis = 1 + level;
yaxis = 1 + level;
generateBoard();
$('#levelDisplay').text('Level ' + level);
$('#gridSize').text(xaxis + ' x ' + yaxis + ' grid');
$('.numberOfMoves').text(numberOfMoves);
$('.stopWatch').text(time);
$('#nextLevelArcade').hide();
})
//Reset button
$('#resetButtonArcade').click(function() {
reset();
$('#startButtonArcade').show();
$('#resetButtonArcade').hide();
$('#scoreBoardArcade').hide();
$('.intro').show();
})
//********** Multiplayer mode **********
//Add new player
$('#addNewPlayerButton').click(function() {
$('.playerList').append('<input type="text" class="form-control" placeholder="Player ' + ($('.playerList input').length + 1) + '">')
})
//Preview board
$('#xaxisInputMulti, #yaxisInputMulti').keyup(function() {
reset();
if (parseInt($('#xaxisInputMulti').val()) >= 2) { xaxis = parseInt($('#xaxisInputMulti').val())};
if (parseInt($('#yaxisInputMulti').val()) >= 2) { yaxis = parseInt($('#yaxisInputMulti').val())};
generateBoard();
})
//Board Initialise
$('#startButtonMulti').click(function() {
$('#scoreBoardMulti').show();
$('#resetButtonMulti').show();
$('#multiplayer form').hide();
$('#addNewPlayerButton').hide();
$('.intro').hide();
interval = 0;
gameStatus = "inPlay";
gameMode = 'Multiplayer';
for (i = 0; i < $('.playerList input').length; i++) {
playerNames[i] = "Player " + (i+1);
playerTimes[i] = 0;
if ($('.playerList input:nth-child('+ (i+2) + ')').val() !== '') {
playerNames[i] = $('.playerList input:nth-child('+ (i+2) + ')').val();
}
$('#playerNames').append('<li>' + playerNames[i] + '</li>');
$('#timeRecords').append('<li>' + playerTimes[i] + '</li>')
}
$('#whosTurn').text(playerNames[0] + ' \'s turn')
})
//Next player button
$('#nextPlayerButton').click(function() {
index++;
$('#whosTurn').text(playerNames[index] + ' \'s turn');
gameStatus = 'inPlay';
board = [];
$('.table tbody').empty();
counter = 0;
needGen = 1;
head = [2,2];
tail = [null,null];
movement = [0,0,0,0]; //[left,right,up,down]
recordingTime = false;
time = 0;
gridsCovered = 1;
numberOfMoves = 0;
$('#nextPlayerButton').hide();
generateBoard();
$('.numberOfMoves').text(numberOfMoves);
$('.stopWatch').text(time);
})
//Reset button
$('#resetButtonMulti').click(function() {
reset();
generateBoard();
$('#scoreBoardMulti').hide();
$('#multiplayer form').show();
$('#addNewPlayerButton').show();
$('.intro').show();
$('input').val('');
$('.playerList').empty();
$('.playerList').append('<label class="intro">Player names</label><input type="text" class="form-control" placeholder="Player 1"><input type="text" class="form-control" placeholder="Player 2">')
})
//********** Custom mode **********
//Preview board
$('#custom form').keyup(function() {
reset();
if (parseInt($('#xaxisInputCustom').val()) >= 2) {xaxis = parseInt($('#xaxisInputCustom').val())};
if (parseInt($('#yaxisInputCustom').val()) >= 2) {yaxis = parseInt($('#yaxisInputCustom').val())};
if (parseInt($('#wallThicknessInput').val()) >= 1) { wallthickness = parseInt($('#wallThicknessInput').val())};
if ($('#wallColorInput').val() !== '') {wallColor = $('#wallColorInput').val()};
if ($('#headColorInput').val() !== '') {headColor = $('#headColorInput').val()};
if ($('#snakeColorInput').val() !== '') {snakeColor = $('#snakeColorInput').val()};
if ($('#backgroundColorInput').val() !== '') {backgroundColor = $('#backgroundColorInput').val()};
if ($('#foodColorInput').val() !== '') {foodColor = $('#foodColorInput').val()};
head[1] = 1 + wallthickness;
head[0] = 1 + wallthickness;
var headXaxis = parseInt($('#headXaxis').val());
var headYaxis = parseInt($('#headYaxis').val());
if (headXaxis >= 1 && headXaxis <= xaxis) { head[1] = headXaxis - 1 + wallthickness};
if (headYaxis >= 1 && headYaxis <= yaxis) { head[0] = headYaxis - 1 + wallthickness};
generateBoard();
})
//Board Initialise
$('#startButtonCustom').click(function() {
gameMode = 'Custom';
gameStatus = "inPlay";
if (parseInt($('#foodValueInput').val()) >=1) { foodvalue = parseInt($('#foodValueInput').val())};
if (parseInt($('#initialC').val()) >= 1) { counter = parseInt($('#initialC').val()) - 1};
if ($('#moveInterval').val() > 0) { interval = $('#moveInterval').val()*1000};
$('.numberOfMoves').text(numberOfMoves);
$('.stopWatch').text(time);
$('#scoreBoardCustom').show();
$('#custom form').hide();
$('.intro').hide();
})
//Reset button
$('#resetButtonCustom').click(function() {
reset();
generateBoard();
$('#scoreBoardCustom').hide();
$('#custom form').show();
$('.intro').show();
$('input').val('');
})
//********** Running / Key listening **********
$(document).keydown(function (e) {
if (reverse == false) {
if (e.keyCode == 37 && gameStatus === "inPlay") {movement = [1,0,0,0]; speedControl()};
if (e.keyCode == 39 && gameStatus === "inPlay") {movement = [0,1,0,0]; speedControl()};
if (e.keyCode == 38 && gameStatus === "inPlay") {movement = [0,0,1,0]; speedControl()};
if (e.keyCode == 40 && gameStatus === "inPlay") {movement = [0,0,0,1]; speedControl()};
}else if (reverse == true) {
if (e.keyCode == 37 && gameStatus === "inPlay") {movement = [0,1,0,0]; speedControl()};
if (e.keyCode == 39 && gameStatus === "inPlay") {movement = [1,0,0,0]; speedControl()};
if (e.keyCode == 38 && gameStatus === "inPlay") {movement = [0,0,0,1]; speedControl()};
if (e.keyCode == 40 && gameStatus === "inPlay") {movement = [0,0,1,0]; speedControl()};
}
});
//********** Reset when switch tabs **********
$('.nav-tabs li:nth-child(1), .nav-tabs li:nth-child(2)').click(function() {reset()})
//Multiplayer & custom default grid
$('.nav-tabs li:nth-child(3), .nav-tabs li:nth-child(4)').click(function() {reset(); generateBoard();})
//********** No Scroll plug-in **********//
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
})
|
// ==========================================================================
// Project: Ember Runtime
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
/*globals testBoth Global */
require('ember-metal/~tests/props_helper');
var willCount = 0 , didCount = 0,
willChange = Ember.propertyWillChange,
didChange = Ember.propertyDidChange;
module('Ember.watch', {
setup: function() {
willCount = didCount = 0;
Ember.propertyWillChange = function(cur, keyName) {
willCount++;
willChange.call(this, cur, keyName);
};
Ember.propertyDidChange = function(cur, keyName) {
didCount++;
didChange.call(this, cur, keyName);
};
},
teardown: function() {
Ember.propertyWillChange = willChange;
Ember.propertyDidChange = didChange;
}
});
testBoth('watching a computed property', function(get, set) {
var obj = {};
Ember.defineProperty(obj, 'foo', Ember.computed(function(keyName, value) {
if (value !== undefined) this.__foo = value;
return this.__foo;
}));
Ember.watch(obj, 'foo');
set(obj, 'foo', 'bar');
equals(willCount, 1, 'should have invoked willCount');
equals(didCount, 1, 'should have invoked didCount');
});
testBoth('watching a regular defined property', function(get, set) {
var obj = { foo: 'baz' };
Ember.watch(obj, 'foo');
equals(get(obj, 'foo'), 'baz', 'should have original prop');
set(obj, 'foo', 'bar');
equals(willCount, 1, 'should have invoked willCount');
equals(didCount, 1, 'should have invoked didCount');
});
testBoth('watches should inherit', function(get, set) {
var obj = { foo: 'baz' };
var objB = Ember.create(obj);
Ember.watch(obj, 'foo');
equals(get(obj, 'foo'), 'baz', 'should have original prop');
set(obj, 'foo', 'bar');
set(objB, 'foo', 'baz');
equals(willCount, 2, 'should have invoked willCount once only');
equals(didCount, 2, 'should have invoked didCount once only');
});
test("watching an object THEN defining it should work also", function() {
var obj = {};
Ember.watch(obj, 'foo');
Ember.defineProperty(obj, 'foo');
Ember.set(obj, 'foo', 'bar');
equals(Ember.get(obj, 'foo'), 'bar', 'should have set');
equals(willCount, 1, 'should have invoked willChange once');
equals(didCount, 1, 'should have invoked didChange once');
});
testBoth('watching an object value then unwatching should restore old value', function(get, set) {
var obj = { foo: { bar: { baz: { biff: 'BIFF' } } } };
Ember.watch(obj, 'foo.bar.baz.biff');
var foo = Ember.get(obj, 'foo');
equals(get(get(get(foo, 'bar'), 'baz'), 'biff'), 'BIFF', 'biff should exist');
Ember.unwatch(obj, 'foo.bar.baz.biff');
equals(get(get(get(foo, 'bar'), 'baz'), 'biff'), 'BIFF', 'biff should exist');
});
testBoth('watching a global object that does not yet exist should queue', function(get, set) {
Global = null;
var obj = {};
Ember.watch(obj, 'Global.foo'); // only works on global chained props
equals(willCount, 0, 'should not have fired yet');
equals(didCount, 0, 'should not have fired yet');
Global = { foo: 'bar' };
Ember.watch.flushPending(); // this will also be invoked automatically on ready
equals(willCount, 0, 'should not have fired yet');
equals(didCount, 0, 'should not have fired yet');
set(Global, 'foo', 'baz');
// should fire twice because this is a chained property (once on key, once
// on path)
equals(willCount, 2, 'should be watching');
equals(didCount, 2, 'should be watching');
Global = null; // reset
});
|
'use strict'
module.exports = app => {
return function* (next) {
this.socket.on('anEventNotRegisterInTheRouter',()=> {
})
yield* next
}
}
|
module.exports = require('./lib/fileman');
|
'use strict';
const assert = require('assert');
const HTMLBarsMinifier = require('../lib/htmlbars-minifier');
const minifier = new HTMLBarsMinifier('foo', {
removeSpacesAroundTags: true,
});
describe('removeSpacesAroundTags', () => {
it('should escape special chars', () => {
const input = '{{#foo}}{{/foo}}';
assert.strictEqual(minifier.processString(input), '{{~#foo}}{{~/foo}}');
});
it('should remove whitespaces after a DOM element', () => {
const input = '<a> foo';
assert.strictEqual(minifier.processString(input), '<a>foo');
});
it('should remove whitespaces before a DOM element', () => {
const input = 'foo <a>';
assert.strictEqual(minifier.processString(input), 'foo<a>');
});
it('should remove whitespaces between an HTMLBars node and a DOM element', () => {
const input = '{{foo}} <a>';
assert.strictEqual(minifier.processString(input), '{{foo}}<a>');
});
it('should remove whitespaces between a DOM element and an HTMLBars node', () => {
const input = '<a> {{foo}}';
assert.strictEqual(minifier.processString(input), '<a>{{foo}}');
});
});
|
var util = require('../test/utils');
var argv = require('optimist').argv;
var address = '127.0.0.1:8000';
var _host = address.substr(0, address.indexOf(':'));
var _port = Number(address.substr(address.indexOf(':') + 1));
var _app = argv.app || 'LINK:STALK_IO';
util.post(_host, _port, '/user/list/active', {A: _app}, function (err, data) {
if (data.status == 'ok') {
console.log(data);
} else {
console.error(data.status, data);
}
});
|
define([
'text!./templates/index.html',
'css!./styles/index.css'
], function (tpl) {
return function (options) {
var _ = options.sandbox._;
var $ = options.sandbox.$;
$(options.host).html(_.template(tpl, options));
return {};
};
});
|
{
importedFn();
localFn();
expect(importedFn.mock.calls.length).toBe(2);
expect(localFn.mock.calls.length).toBe(2);
}
|
const request = require('supertest')
const app = require('../app')
const assert = require('assert')
describe('login', () => {
describe('POST /login', () => {
const agent = request.agent(app)
it('success', function (done) {
agent
.post('/login')
.type('form')
.field({ username: 'admin', password: '1' })
.redirects()
.end(function (error, res) {
if (error) return done(error)
assert(res.text.match(/注册成功/))
done()
})
})
// it('should return the user', function (done) {
// agent
// .get('/users')
// .end(function (error, res) {
// if (error) return done(error)
// done()
// })
// })
})
})
|
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('condition', 'Unit | Serializer | Condition', {
needs: [
'serializer:condition',
'model:identifier',
'model:codeable-concept',
'model:reference',
'model:age',
'model:period',
'model:range',
'model:condition-stage',
'model:condition-evidence',
'model:annotation',
'model:meta',
'model:narrative',
'model:resource',
'model:extension'
]
});
test('it serializes records', function(assert) {
const record = this.subject(),
serializeRecord = record.serialize();
assert.ok(serializeRecord);
});
|
import DS from 'ember-data';
import BackboneElement from 'ember-fhir/models/backbone-element';
const { attr } = DS;
export default BackboneElement.extend({
code: attr('string'),
description: attr('string'),
operator: attr(),
value: attr('string')
});
|
/* global angular */
angular
.module('minimalist')
.directive('mnCheckbox', MnCheckboxDirective)
module.exports = MnCheckboxDirective
function MnCheckboxDirective() {
return {
restrict: 'C',
require: 'ngModel',
link(scope, element, attributes, ngModel) {
const component = element[0]
if (!attributes.name) {
const name = attributes.ngModel.split('.')[attributes.ngModel.split('.').length - 1]
component.setAttribute('name', name)
}
ngModel.$validators = {}
element.ready(() => {
component.ready = true
scope.$watch(attributes.ngModel, setComponentValue)
component.value = ngModel.$modelValue
component.input.addEventListener('change', setModelValue)
ngModel.$setViewValue(component.value)
})
scope.$on('$destroy', () => {
element.remove()
})
function setComponentValue(value, oldValue) {
if (!angular.equals(value, oldValue)) {
component.value = value
}
}
function setModelValue() {
const modelApplied = angular.equals(ngModel.$modelValue, component.value)
if (!modelApplied) {
ngModel.$setViewValue(component.value)
}
}
}
}
}
|
'use strict';
const assert = require('assert');
const path = require('path');
const fs = require('fs');
const Module = require('module');
const mock = require('mock-fs');
const noop = () => {};
function getDirTypedContentsSync(dir, forceType) {
// Return value can be fed to mock-fs
if (forceType !== 'dir' && forceType !== 'file') throw new Error("Not implemented");
return fs.readdirSync(dir).reduce(function (dict, elem) {
dict[elem] = forceType === 'dir' ? {} : '';
return dict;
}, {});
}
function init(callback) {
require('./../app.js');
// Run the battle engine in the main process to keep our sanity
let BattleEngine = global.BattleEngine = require('./../battle-engine.js');
for (let listener of process.listeners('message')) {
process.removeListener('message', listener);
}
// Turn IPC methods into no-op
BattleEngine.Battle.prototype.send = noop;
BattleEngine.Battle.prototype.receive = noop;
let Simulator = global.Simulator;
Simulator.Battle.prototype.send = noop;
Simulator.Battle.prototype.receive = noop;
for (let process of Simulator.SimulatorProcess.processes) {
// Don't crash -we don't care of battle child processes.
process.process.on('error', noop);
}
LoginServer.disabled = true;
// Deterministic tests
BattleEngine.Battle.prototype._init = BattleEngine.Battle.prototype.init;
BattleEngine.Battle.prototype.init = function (roomid, formatarg, rated) {
this._init(roomid, formatarg, rated);
this.seed = this.startingSeed = [0x09d56, 0x08642, 0x13656, 0x03653];
};
// Disable writing to modlog
require('./../command-parser.js').CommandContext.prototype.logModCommand = noop;
callback();
}
before('initialization', function (done) {
this.timeout(0); // Remove timeout limitation
// Load and override configuration before starting the server
let config;
try {
require.resolve('./../config/config.js');
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') throw err; // Should never happen
console.log("config.js doesn't exist - creating one with default settings...");
fs.writeFileSync(path.resolve(__dirname, '../config/config.js'),
fs.readFileSync(path.resolve(__dirname, '../config/config-example.js'))
);
} finally {
config = require('./../config/config.js');
}
try {
let chatRoomsPath = require.resolve('./../config/chatrooms.json');
let chatRoomsData = require.cache[chatRoomsPath] = new Module(chatRoomsPath, module);
chatRoomsData.filename = chatRoomsData.id;
chatRoomsData.exports = []; // empty chatrooms list
chatRoomsData.loaded = true;
} catch (e) {}
// Actually crash if we crash
config.crashguard = false;
// Don't try to write to file system
config.logladderip = false;
config.logchallenges = false;
config.logchat = false;
// Don't create a REPL
require('./../repl.js').start = noop;
// Sandbox file system: it's possible for a production server to be running in the same directory.
// And using a sandbox is safer anyway.
const fsSandbox = {
'config': {},
'chat-plugins': getDirTypedContentsSync('chat-plugins', 'file'),
'mods': getDirTypedContentsSync('mods', 'dir'),
'logs': {
'chat': {}, 'ladderip': {}, 'modlog': {}, 'repl': {},
'lastbattle.txt': '0',
},
};
// Node's module loading system should be backed up by the real file system.
Module.__resolveFilename__ = Module._resolveFilename;
Module._resolveFilename = function (request, parent) {
if (request === 'fs') return this.__resolveFilename__(request, parent);
mock.restore();
try {
return this.__resolveFilename__(request, parent);
} finally {
mock(fsSandbox);
}
};
for (let ext in Module._extensions) {
let defaultLoader = Module._extensions[ext];
Module._extensions[ext] = function (module, filename) {
mock.restore();
try {
return defaultLoader(module, filename);
} finally {
mock(fsSandbox);
}
};
}
Module.prototype.__compile__ = Module.prototype._compile;
Module.prototype._compile = function (content, filename) {
// Use the sandbox to evaluate the code in our modules.
mock(fsSandbox);
try {
return this.__compile__(content, filename);
} finally {
mock.restore();
}
};
// `watchFile` is unsupported and throws with mock-fs
Object.defineProperty(fs, 'watchFile', {
get: function () {return noop;},
set: noop,
});
mock(fsSandbox);
init(done);
});
describe('Native timer/event loop globals', function () {
let globalList = ['setTimeout', 'clearTimeout', 'setImmediate', 'clearImmediate'];
for (let elem of globalList) {
describe('`' + elem + '`', function () {
it('should be a global function', function () {
assert.strictEqual(typeof global[elem], 'function');
});
});
}
});
describe('Battle simulation', function () {
require('./simulator');
});
|
'use strict';
var startsWith = require('es5-ext/string/#/starts-with');
module.exports = function (key) {
if (key == null) return false;
return startsWith.call(key, 'n\0');
};
|
import getOptionalUrlParam from '../../src/get-optional-url-param'
describe('getOptionalUrlParam', () => {
it('should export a function', () => {
expect(getOptionalUrlParam).toBeInstanceOf(Function)
})
it("should return an empty string if there's no input", () => {
expect(getOptionalUrlParam()).toBe('')
})
it('should return an empty string if the input has any undefined values', () => {
expect(getOptionalUrlParam('key', ['hello', 'world', undefined])).toBe('')
})
it('should concatenate the array', () => {
expect(getOptionalUrlParam('key', ['hello', 'world'])).toBe(
'&key=helloworld'
)
})
it('should url escape any of the input values', () => {
expect(getOptionalUrlParam('key', ['hello', ' ', 'world & space!'])).toBe(
'&key=hello%20world%20%26%20space!'
)
})
})
|
import React from 'react';
import PropTypes from 'prop-types';
import * as globals from '../globals';
export default class RichTextBlockView extends React.Component {
constructor(props) {
super(props);
// Set initial React component state.
this.state = {
value: this.props.value,
};
// Bind this to non-React components.
this.setupEditor = this.setupEditor.bind(this);
this.handleClickableFAQ = this.handleClickableFAQ.bind(this);
}
componentDidMount() {
const $script = require('scriptjs');
if (this.context.editable) {
$script('ckeditor/ckeditor.js', this.setupEditor);
}
this.handleClickableFAQ();
}
/* eslint-disable camelcase */
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState({ value: nextProps.value });
}
/* eslint-enable camelcase */
shouldComponentUpdate(nextProps, nextState) {
return (!this.editor || nextState.value.body !== this.editor.getData());
}
// How to use the clickable FAQ function:
// There should be one <div> with the class name "faq" and it must contain all clickable questions and answers
// Every question container should have the class name "faq-question"
// Every answer container should have the class name "faq-answer"
// Each question container should have a unique id "faq#-question" where "#" is unique and an actual number, like "faq1-question"
// Each corresponding answer container must have a corresponding unique id "faq#-answer" where "#" is an actual number and matches the question container number, like "faq1-answer"
handleClickableFAQ() {
if (this.state.value.body.includes('faq')) {
const faqContainer = document.getElementsByClassName('faq')[0];
if (faqContainer) {
// Add caret icon before every question and check URL to see if we should expand one of the questions
const faqQuestions = faqContainer.querySelectorAll('.faq-question');
const currentURL = window.location.href;
faqQuestions.forEach((faqQuestion) => {
// If the URL contains a link to a question, that question should have its answer expanded and we append a caret pointing down
if (currentURL.indexOf(faqQuestion.id) !== -1) {
document.getElementById(faqQuestion.id.replace('question', 'answer')).classList.add('show');
faqQuestion.innerHTML = `<i class="icon icon-caret-down"></i>${faqQuestion.innerHTML}`;
// If the URL does not contain a link to a question, we append a caret pointing right
} else {
faqQuestion.innerHTML = `<i class="icon icon-caret-right"></i>${faqQuestion.innerHTML}`;
}
});
// One event listener on the 'faq' container handles all click events
faqContainer.addEventListener('click', (e) => {
// Determine which question the user clicked on
const target = e.target.closest('.faq-question');
if (target) {
// Toggle whether corresponding answer is displayed or hidden
const infoId = target.id.split('faq')[1].split('-question')[0];
const infoElement = document.getElementById(`faq${infoId}-answer`);
infoElement.classList.toggle('show');
// Toggle direction caret is pointing
const iconElement = target.getElementsByTagName('i')[0];
if (iconElement.className.indexOf('icon-caret-right') > -1) {
iconElement.classList.add('icon-caret-down');
iconElement.classList.remove('icon-caret-right');
} else {
iconElement.classList.remove('icon-caret-down');
iconElement.classList.add('icon-caret-right');
}
}
});
}
}
}
setupEditor() {
require('ckeditor4');
/* eslint-disable no-undef */
CKEDITOR.disableAutoInline = true;
this.editor = CKEDITOR.inline(this.domNode, {
/* eslint-enable no-undef */
language: 'en',
toolbar: [
{ name: 'basicstyles', groups: ['basicstyles', 'cleanup'], items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat'] },
{ name: 'styles', items: ['Format'] },
{ name: 'paragraph', groups: ['list', 'indent', 'align'], items: ['NumberedList', 'BulletedList'] },
{ name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
{ name: 'undo', groups: ['undo'], items: ['Undo', 'Redo'] },
{ name: 'document', groups: ['mode'], items: ['Source'] },
],
format_tags: 'p;h1;h2;h3;h4;h5;h6;pre;code;cite',
format_code: { name: 'Inline Code', element: 'code' },
format_cite: { name: 'Citation', element: 'cite' },
allowedContent: true,
});
this.editor.on('change', () => {
this.state.value.body = this.editor.getData();
this.setState((state) => ({ ...state }));
this.props.onChange(this.state.value);
});
}
render() {
return (
<div contentEditable={this.context.editable} dangerouslySetInnerHTML={{ __html: this.state.value.body }} ref={(comp) => { this.domNode = comp; }} />
);
}
}
RichTextBlockView.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.object,
};
RichTextBlockView.defaultProps = {
value: null,
};
RichTextBlockView.contextTypes = {
editable: PropTypes.bool,
};
globals.blocks.register({
label: 'rich text block',
icon: 'icon icon-file-text',
schema: {
type: 'object',
properties: {
body: {
title: 'HTML Source',
type: 'string',
formInput: <textarea rows="10" />,
},
className: {
title: 'CSS Class',
type: 'string',
},
},
},
view: RichTextBlockView,
initial: {
body: '<p>This is a new block.</p>',
},
}, 'richtextblock');
|
import PropTypes from 'prop-types'
import React from 'react'
import { findDOMNode } from 'react-dom'
import { Link } from 'react-router'
import GreenButton from '../Buttons/Green'
import OrangeButton from '../Buttons/Orange'
import RedButton from '../Buttons/Red'
export default class TableRow extends React.Component {
render() {
let tag = this.props.tag
return (
<tr key={ tag.id }>
<td>{ tag.id }</td>
<td>{ tag.title }</td>
<td>{ tag.slug }</td>
<td>{ tag.articles_count }</td>
<td>{ tag.projects_count }</td>
<td className='actions left'>
<Link className='button green' to={ `/tags/${tag.id}/edit` }>Edit</Link>
<RedButton title='Delete' onClick={ () => { this.props.deleteButtonClick(tag) }} />
</td>
</tr>
)
}
}
|
/**
* @fileOverview
* @author David Huynh
* @author <a href="mailto:ryanlee@zepheira.com">Ryan Lee</a>
*/
/**
*
*
* @class
* @constructor
*/
Exhibit.UIContext = function() {
this._parent = null;
this._exhibit = null;
this._collection = null;
this._lensRegistry = new Exhibit.LensRegistry();
this._settings = {};
this._formatters = {};
this._listFormatter = null;
this._editModeRegistry = {};
this._popupFunc = null;
};
/**
* @constant
*/
Exhibit.UIContext._settingSpecs = {
"bubbleWidth": { "type": "int", "defaultValue": 400 },
"bubbleHeight": { "type": "int", "defaultValue": 300 }
};
/**
* @param {Object} configuration
* @param {Exhibit} exhibit
* @returns {Exhibit.UIContext}
*/
Exhibit.UIContext.createRootContext = function(configuration, exhibit) {
var context, settings, n, formats;
context = new Exhibit.UIContext();
context._exhibit = exhibit;
settings = Exhibit.UIContext.initialSettings;
for (n in settings) {
if (settings.hasOwnProperty(n)) {
context._settings[n] = settings[n];
}
}
formats = Exhibit.getAttribute(document.body, "formats");
if (typeof formats !== "undefined" && formats !== null && formats.length > 0) {
Exhibit.FormatParser.parseSeveral(context, formats, 0, {});
}
Exhibit.SettingsUtilities.collectSettingsFromDOM(
document.body, Exhibit.UIContext._settingSpecs, context._settings);
Exhibit.UIContext._configure(context, configuration);
return context;
};
/**
* @param {Object} configuration
* @param {Exhibit.UIContext} parentUIContext
* @param {Boolean} ignoreLenses
* @returns {Exhibit.UIContext}
*/
Exhibit.UIContext.create = function(configuration, parentUIContext, ignoreLenses) {
var context = Exhibit.UIContext._createWithParent(parentUIContext);
Exhibit.UIContext._configure(context, configuration, ignoreLenses);
return context;
};
/**
* @param {Element} configElmt
* @param {Exhibit.UIContext} parentUIContext
* @param {Boolean} ignoreLenses
* @returns {Exhibit.UIContext}
*/
Exhibit.UIContext.createFromDOM = function(configElmt, parentUIContext, ignoreLenses) {
var context, id, formats;
context = Exhibit.UIContext._createWithParent(parentUIContext);
if (!(ignoreLenses)) {
Exhibit.UIContext.registerLensesFromDOM(configElmt, context.getLensRegistry());
}
id = Exhibit.getAttribute(configElmt, "collectionID");
if (typeof id !== "undefined" && id !== null && id.length > 0) {
context._collection = context._exhibit.getCollection(id);
}
formats = Exhibit.getAttribute(configElmt, "formats");
if (typeof formats !== "undefined" && formats !== null && formats.length > 0) {
Exhibit.FormatParser.parseSeveral(context, formats, 0, {});
}
Exhibit.SettingsUtilities.collectSettingsFromDOM(
configElmt, Exhibit.UIContext._settingSpecs, context._settings);
Exhibit.UIContext._configure(context, Exhibit.getConfigurationFromDOM(configElmt), ignoreLenses);
return context;
};
/**
*
*/
Exhibit.UIContext.prototype.dispose = function() {
};
/**
* @returns {Exhibit.UIContext}
*/
Exhibit.UIContext.prototype.getParentUIContext = function() {
return this._parent;
};
/**
* @returns {Exhibit}
*/
Exhibit.UIContext.prototype.getMain = function() {
return this._exhibit;
};
/**
* @returns {Exhibit.Database}
*/
Exhibit.UIContext.prototype.getDatabase = function() {
return this.getMain().getDatabase();
};
/**
* @returns {Exhibit.Collection}
*/
Exhibit.UIContext.prototype.getCollection = function() {
if (this._collection === null) {
if (this._parent !== null) {
this._collection = this._parent.getCollection();
} else {
this._collection = this._exhibit.getDefaultCollection();
}
}
return this._collection;
};
/**
* @returns {Exhibit.LensRegistry}
*/
Exhibit.UIContext.prototype.getLensRegistry = function() {
return this._lensRegistry;
};
/**
* @param {String} name
* @returns {String|Number|Boolean|Object}
*/
Exhibit.UIContext.prototype.getSetting = function(name) {
return typeof this._settings[name] !== "undefined" ?
this._settings[name] :
(this._parent !== null ? this._parent.getSetting(name) : undefined);
};
/**
* @param {String} name
* @param {Boolean} defaultValue
* @returns {Boolean}
*/
Exhibit.UIContext.prototype.getBooleanSetting = function(name, defaultValue) {
var v = this.getSetting(name);
return v === undefined || v === null ? defaultValue : v;
};
/**
* @param {String} name
* @param {String|Number|Boolean|Object} value
*/
Exhibit.UIContext.prototype.putSetting = function(name, value) {
this._settings[name] = value;
};
/**
* @param {String|Number|Boolean|Object} value
* @param {String} valueType
* @param {Function} appender
*/
Exhibit.UIContext.prototype.format = function(value, valueType, appender) {
var f;
if (typeof this._formatters[valueType] !== "undefined") {
f = this._formatters[valueType];
} else {
f = this._formatters[valueType] =
new Exhibit.Formatter._constructors[valueType](this);
}
f.format(value, appender);
};
/**
* @param {Exhibit.Set} iterator
* @param {Number} count
* @param {String} valueType
* @param {Function} appender
*/
Exhibit.UIContext.prototype.formatList = function(iterator, count, valueType, appender) {
if (this._listFormatter === null) {
this._listFormatter = new Exhibit.Formatter._ListFormatter(this);
}
this._listFormatter.formatList(iterator, count, valueType, appender);
};
/**
* @param {String} itemID
* @param {Boolean} val
*/
Exhibit.UIContext.prototype.setEditMode = function(itemID, val) {
if (val) {
this._editModeRegistry[itemID] = true;
} else {
this._editModeRegistry[itemID] = false;
}
};
/**
* @param {String} itemID
* @returns {Boolean}
*/
Exhibit.UIContext.prototype.isBeingEdited = function(itemID) {
return !!this._editModeRegistry[itemID];
};
/*----------------------------------------------------------------------
* Internal implementation
*----------------------------------------------------------------------
*/
/**
* @static
* @private
* @param {Exhibit.UIContext} parent
* @returns {Exhibit.UIContext}
*/
Exhibit.UIContext._createWithParent = function(parent) {
var context = new Exhibit.UIContext();
context._parent = parent;
context._exhibit = parent._exhibit;
context._lensRegistry = new Exhibit.LensRegistry(parent.getLensRegistry());
context._editModeRegistry = parent._editModeRegistry;
return context;
};
/**
* @private
* @static
* @param {Exhbit.UIContext} context
* @param {Object} configuration
* @param {Boolean} ignoreLenses
*/
Exhibit.UIContext._configure = function(context, configuration, ignoreLenses) {
Exhibit.UIContext.registerLenses(configuration, context.getLensRegistry());
if (typeof configuration["collectionID"] !== "undefined") {
context._collection = context._exhibit.getCollection(configuration.collectionID);
}
if (typeof configuration["formats"] !== "undefined") {
Exhibit.FormatParser.parseSeveral(context, configuration.formats, 0, {});
}
if (!(ignoreLenses)) {
Exhibit.SettingsUtilities.collectSettings(
configuration, Exhibit.UIContext._settingSpecs, context._settings);
}
};
/*----------------------------------------------------------------------
* Lens utility functions for internal use
*----------------------------------------------------------------------
*/
/**
* @static
* @param {Object} configuration
* @param {Exhibit.LensRegistry} lensRegistry
*/
Exhibit.UIContext.registerLens = function(configuration, lensRegistry) {
var template, i;
template = configuration.templateFile;
if (typeof template !== "undefined" && template !== null) {
if (typeof configuration["itemTypes"] !== "undefined") {
for (i = 0; i < configuration.itemTypes.length; i++) {
lensRegistry.registerLensForType(template, configuration.itemTypes[i]);
}
} else {
lensRegistry.registerDefaultLens(template);
}
}
};
/**
* @param {Element} elmt
* @param {Exhibit.LensRegistry} lensRegistry
*/
Exhibit.UIContext.registerLensFromDOM = function(elmt, lensRegistry) {
var itemTypes, template, url, id, elmt2, i;
$(elmt).hide();
itemTypes = Exhibit.getAttribute(elmt, "itemTypes", ",");
template = null;
url = Exhibit.getAttribute(elmt, "templateFile");
if (typeof url !== "undefined" && url !== null && url.length > 0) {
template = url;
} else {
id = Exhibit.getAttribute(elmt, "template");
elmt2 = id && document.getElementById(id);
if (typeof elmt2 !== "undefined" && elmt2 !== null) {
template = elmt2;
} else {
template = elmt;
}
}
if (typeof template !== "undefined" && template !== null) {
if (typeof itemTypes === "undefined" || itemTypes === null || itemTypes.length === 0 || (itemTypes.length === 1 && itemTypes[0] === "")) {
lensRegistry.registerDefaultLens(template);
} else {
for (i = 0; i < itemTypes.length; i++) {
lensRegistry.registerLensForType(template, itemTypes[i]);
}
}
}
};
/**
* @param {Object} configuration
* @param {Exhibit.LensRegistry} lensRegistry
*/
Exhibit.UIContext.registerLenses = function(configuration, lensRegistry) {
var i, lensSelector;
if (typeof configuration["lenses"] !== "undefined") {
for (i = 0; i < configuration.lenses.length; i++) {
Exhibit.UIContext.registerLens(configuration.lenses[i], lensRegistry);
}
}
if (typeof configuration["lensSelector"] !== "undefined") {
lensSelector = configuration.lensSelector;
if (typeof lensSelector === "function") {
lensRegistry.addLensSelector(lensSelector);
} else {
Exhibit.Debug.log(Exhibit._("%general.error.lensSelectorNotFunction"));
}
}
};
/**
* @param {Element} parentNode
* @param {Exhibit.LensRegistry} lensRegistry
*/
Exhibit.UIContext.registerLensesFromDOM = function(parentNode, lensRegistry) {
var node, role, lensSelectorString, lensSelector;
node = $(parentNode).children().get(0);
while (typeof node !== "undefined" && node !== null) {
if (node.nodeType === 1) {
role = Exhibit.getRoleAttribute(node);
if (role === "lens" || role === "edit-lens") {
Exhibit.UIContext.registerLensFromDOM(node, lensRegistry);
}
}
node = node.nextSibling;
}
lensSelectorString = Exhibit.getAttribute(parentNode, "lensSelector");
if (typeof lensSelectorString !== "undefined" && lensSelectorString !== null && lensSelectorString.length > 0) {
try {
lensSelector = eval(lensSelectorString);
if (typeof lensSelector === "function") {
lensRegistry.addLensSelector(lensSelector);
} else {
Exhibit.Debug.log(Exhibit._("%general.error.lensSelectorExpressionNotFunction", lensSelectorString));
}
} catch (e) {
Exhibit.Debug.exception(e, Exhibit._("%general.error.badLensSelectorExpression", lensSelectorString));
}
}
};
/**
* @param {Object} configuration
* @param {Exhibit.LensRegistry} parentLensRegistry
* @returns {Exhibit.LensRegistry}
*/
Exhibit.UIContext.createLensRegistry = function(configuration, parentLensRegistry) {
var lensRegistry = new Exhibit.LensRegistry(parentLensRegistry);
Exhibit.UIContext.registerLenses(configuration, lensRegistry);
return lensRegistry;
};
/**
* @param {Element} parentNode
* @param {Object} configuration
* @param {Exhibit.LensRegistry} parentLensRegistry
* @returns {Exhibit.LensRegistry}
*/
Exhibit.UIContext.createLensRegistryFromDOM = function(parentNode, configuration, parentLensRegistry) {
var lensRegistry = new Exhibit.LensRegistry(parentLensRegistry);
Exhibit.UIContext.registerLensesFromDOM(parentNode, lensRegistry);
Exhibit.UIContext.registerLenses(configuration, lensRegistry);
return lensRegistry;
};
|
var Crafty = require("../core/core.js");
Crafty.extend({
/**@
* #Crafty.keys
* @category Input
* @kind Property
*
* Object of key names and the corresponding Unicode key code.
*
* ~~~
* BACKSPACE: 8,
* TAB: 9,
* ENTER: 13,
* PAUSE: 19,
* CAPS: 20,
* ESC: 27,
* SPACE: 32,
* PAGE_UP: 33,
* PAGE_DOWN: 34,
* END: 35,
* HOME: 36,
* LEFT_ARROW: 37,
* UP_ARROW: 38,
* RIGHT_ARROW: 39,
* DOWN_ARROW: 40,
* INSERT: 45,
* DELETE: 46,
* 0: 48,
* 1: 49,
* 2: 50,
* 3: 51,
* 4: 52,
* 5: 53,
* 6: 54,
* 7: 55,
* 8: 56,
* 9: 57,
* A: 65,
* B: 66,
* C: 67,
* D: 68,
* E: 69,
* F: 70,
* G: 71,
* H: 72,
* I: 73,
* J: 74,
* K: 75,
* L: 76,
* M: 77,
* N: 78,
* O: 79,
* P: 80,
* Q: 81,
* R: 82,
* S: 83,
* T: 84,
* U: 85,
* V: 86,
* W: 87,
* X: 88,
* Y: 89,
* Z: 90,
* NUMPAD_0: 96,
* NUMPAD_1: 97,
* NUMPAD_2: 98,
* NUMPAD_3: 99,
* NUMPAD_4: 100,
* NUMPAD_5: 101,
* NUMPAD_6: 102,
* NUMPAD_7: 103,
* NUMPAD_8: 104,
* NUMPAD_9: 105,
* MULTIPLY: 106,
* ADD: 107,
* SUBSTRACT: 109,
* DECIMAL: 110,
* DIVIDE: 111,
* F1: 112,
* F2: 113,
* F3: 114,
* F4: 115,
* F5: 116,
* F6: 117,
* F7: 118,
* F8: 119,
* F9: 120,
* F10: 121,
* F11: 122,
* F12: 123,
* SHIFT: 16,
* CTRL: 17,
* ALT: 18,
* PLUS: 187,
* COMMA: 188,
* MINUS: 189,
* PERIOD: 190,
* PULT_UP: 29460,
* PULT_DOWN: 29461,
* PULT_LEFT: 4,
* PULT_RIGHT': 5
* ~~~
*/
keys: {
BACKSPACE: 8,
TAB: 9,
ENTER: 13,
PAUSE: 19,
CAPS: 20,
ESC: 27,
SPACE: 32,
PAGE_UP: 33,
PAGE_DOWN: 34,
END: 35,
HOME: 36,
LEFT_ARROW: 37,
UP_ARROW: 38,
RIGHT_ARROW: 39,
DOWN_ARROW: 40,
INSERT: 45,
DELETE: 46,
"0": 48,
"1": 49,
"2": 50,
"3": 51,
"4": 52,
"5": 53,
"6": 54,
"7": 55,
"8": 56,
"9": 57,
A: 65,
B: 66,
C: 67,
D: 68,
E: 69,
F: 70,
G: 71,
H: 72,
I: 73,
J: 74,
K: 75,
L: 76,
M: 77,
N: 78,
O: 79,
P: 80,
Q: 81,
R: 82,
S: 83,
T: 84,
U: 85,
V: 86,
W: 87,
X: 88,
Y: 89,
Z: 90,
NUMPAD_0: 96,
NUMPAD_1: 97,
NUMPAD_2: 98,
NUMPAD_3: 99,
NUMPAD_4: 100,
NUMPAD_5: 101,
NUMPAD_6: 102,
NUMPAD_7: 103,
NUMPAD_8: 104,
NUMPAD_9: 105,
MULTIPLY: 106,
ADD: 107,
SUBSTRACT: 109,
DECIMAL: 110,
DIVIDE: 111,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PLUS: 187,
COMMA: 188,
MINUS: 189,
PERIOD: 190,
PULT_UP: 29460,
PULT_DOWN: 29461,
PULT_LEFT: 4,
PULT_RIGHT: 5
},
/**@
* #Crafty.mouseButtons
* @category Input
* @kind Property
*
* An object mapping mouseButton names to the corresponding button ID.
* In all mouseEvents, we add the `e.mouseButton` property with a value normalized to match e.button of modern webkit browsers:
*
* ~~~
* LEFT: 0,
* MIDDLE: 1,
* RIGHT: 2
* ~~~
*/
mouseButtons: {
LEFT: 0,
MIDDLE: 1,
RIGHT: 2
}
});
|
var m = [80, 80, 80, 80];
var w = 850 - m[1] - m[3];
var h = 400 - m[0] - m[2];
var data = [];
var data1 = [];
for (var i = 0; i < 12; i++) {
data[i] = Math.floor((Math.random() * 1000) + 1);
data1[i] = Math.floor((Math.random() * 1000) + 1);
console.log(data[i]);
};
function formatCurrency(d) {
return "$" + d;
}
var xLabels = d3.time.scale().domain([new Date(2013, 0, 1), new Date(2013, 11, 31)]).range([0, w]);
var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
var y = d3.scale.linear().domain([0, d3.max(data)]).range([h, 0]);
var line = d3.svg.line()
.x(function(d, i) {
console.log('Plotting X value for data point: ' + d + ' using index: ' + i + ' to be at: ' + x(i) + ' using our xScale.');
return x(i);
})
.y(function(d) {
console.log('Plotting Y value for data point: ' + d + ' to be at: ' + y(d) + " using our yScale.");
return y(d);
})
var graph = d3.select("#monthChart").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + 120 + "," + m[0] + ")");
var xAxis = d3.svg.axis().scale(xLabels).ticks(d3.time.months).tickFormat(d3.time.format("%B")).tickSize(-h).tickSubdivide(true);
graph.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
var yAxisLeft = d3.svg.axis().scale(y).ticks(7).tickFormat(formatCurrency).orient("left");
graph.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(-25,0)")
.call(yAxisLeft);
graph.append("svg:path")
.attr("d", line(data))
.attr('class', 'line');
graph.append("svg:path")
.attr("d", line(data1))
.attr('class', 'line1');
|
version https://git-lfs.github.com/spec/v1
oid sha256:7110445f212f78c6c0ae7bb26a45c29514396818379302eed6b901051008f486
size 3424
|
Package.describe({
summary: '%summary%',
version: '%version%',
name: 'jasonlam604:borderjs',
git: 'https://github.com/jasonlam604/borderjs',
});
Package.onUse(function(api) {
api.versionsFrom('1.0.0');
api.export('Border', 'client');
api.addFiles('border.js', 'client');
});
|
import React, { createRef, useState, useRef, useEffect } from "react";
import * as d3 from "d3";
import * as moment from "moment";
// each charted value has a display name for tooltip
// tooltip may or may not have a charted value
// each line takes a
export default function LineChart(props) {
const chart = createRef();
let innerWidth;
const defaultHeight = 220;
var containerElement;
let YOYdiff;
// const [chartData, setChartData] = useState(props.data);
// const [innerWidth, setInnerWidth] = useState();
let chartData = props.data;
// const [valueArray, setValueArray] = useState(props.valueArray);
let valueArray = props.valueArray;
// function getLineDiffValue(line0, lineTwo) {
// return line0 == null || lineTwo == null ? null : line0 - lineTwo;
// }
let xTicks = props.xTicks || 5;
function getYOYdiffColor(YOY) {
if (YOY < 0) {
return "YOYred";
} else {
return "YOYgreen";
}
}
function prepMaxVal(myData, myArrayOfKeys) {
let tempArr = [];
let tempStartVal = [];
for (let i = 0; i < myData.length; i++) {
// push whatever arr[j] is in the array as a key into
for (let j = 0; j < myArrayOfKeys.length; j++) {
if (myData[i][myArrayOfKeys[j]] !== null) {
tempArr.push(myData[i][myArrayOfKeys[j]["dataKey"]]);
}
}
}
return tempArr;
}
function getMaxVal(myData, myArrayOfKeys) {
// console.log(startVals, startValsRef);
let tempArr = prepMaxVal(myData, myArrayOfKeys);
let tempArrB = prepMaxVal(myData, myArrayOfKeys);
let tempMax = tempArr.reduce((a, b) => Math.max(a, b));
let tempMin = tempArrB.reduce((a, b) => Math.min(a, b));
return { min: tempMin, max: tempMax };
}
function createChart(chartData, myArrayOfKeys, myID, numberFormatFn) {
containerElement = chart.current;
innerWidth = chart.current.clientWidth;
containerElement.innerHTML = "";
let tempMinMax = getMaxVal(chartData, myArrayOfKeys);
let minVal = tempMinMax.min;
let maxVal = tempMinMax.max;
// let currentMonth = getCurrentMonth();
let margin = { top: 20, right: 60, bottom: 0, left: 10 };
//////////////////////// Establish the reused vals and the bound functions ////////////////////////
let width = Number.isNaN(
parseInt(d3.select(containerElement).style("width"))
)
? 0
: parseInt(d3.select(containerElement).style("width")) -
margin.left -
margin.right;
let height = 300 - margin.top;
let justBisect = d3.bisector(d => chartData.indexOf(d)).left;
//////////////////////// Set the scales ////////////////////////
let x = d3.scaleLinear().range([0, width]);
let y = d3.scaleLinear().range([height, 0]);
// //////////////////////// Set the axis ////////////////////////
let xAxis = d3
.axisBottom(x)
.tickFormat(function(d) {
return chartData[d].niceDateAbbrev;
})
.ticks(xTicks)
.tickPadding(6);
let yAxis = d3
.axisRight(y)
.tickFormat(d => {
return numberFormatFn(d);
})
.ticks(6)
.tickPadding(6);
// //////////////////////// Define the lines and/or areas ////////////////////////
// put consts of the lines into the global scope
// defined means it can show gaps, isNan means it can have zero as a value
function createLineConsts() {
let myArr = [];
myArrayOfKeys.map((val, index) => {
myArr.push(
d3
.line()
.defined(d => {
return !Number.isNaN(d[val["dataKey"]]);
})
.x((d, i) => {
return x(i);
})
.y(d => y(d[val["dataKey"]]))
);
});
return myArr;
}
const lineConst = createLineConsts();
// // //////////////////////// Define parent SVG ////////////////////////
const CVsvg = d3
.select(containerElement)
.append("svg")
.attr("class", "line-chart-svg-container")
.attr("id", myID)
.attr("width", "100%")
.attr("height", height + margin.top + margin.bottom + 40)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// // // //////////////////////// Loop through / sort data ////////////////////////
chartData.forEach(d => {
d = +d;
});
// // // //////////////////////// Set the domains ////////////////////////
x.domain([
parseInt(d3.min(chartData, (d, i) => i)),
parseInt(d3.max(chartData, (d, i) => i))
]);
y.domain([minVal, maxVal]);
// y.domain([0, maxVal]);
// // // //////////////////////// Append the lines / areas ////////////////////////
myArrayOfKeys.forEach((item, index) => {
CVsvg.append("path")
.datum(chartData)
.attr("class", "line")
.attr("stroke", item["color"])
.attr("d", lineConst[index])
.transition()
.duration(1000);
});
// // // /////////////////////// Add the X & Y Axis ////////////////////////
CVsvg.append("g")
.attr("class", "yAxis")
.attr("transform", "translate(" + (width + 6) + ",0)")
.call(yAxis);
CVsvg.append("g")
.attr("class", "xAxis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// // // //////////////////////// Add Line Tracing on mouse and markers ////////////////////////
const lineTrace = CVsvg.append("line")
.attr("class", "mouse-line x")
.style("opacity", 0.5)
.attr("y1", 0)
.attr("y2", height);
function createMarkers() {
myArrayOfKeys.forEach((item, index) => {
CVsvg.append("g")
.attr("class", `marker${index}`)
.append("circle")
.attr("class", `line-marker`)
.attr("stroke", item["marker"])
.transition()
.duration(500)
.attr("r", 5);
});
}
createMarkers();
// // // //////////////////////// Tooltip ////////////////////////
const tooltipDiv = d3
.select(containerElement)
.append("div")
.attr("class", "tooltipDiv")
.attr("id", `${myID}Tooltip`);
const dateContainer = tooltipDiv
.append("div")
.attr("class", "text-container");
dateContainer
.append("div")
.attr("class", "label-style mr-1")
.text("Date:");
const dateText = dateContainer.append("div").attr("class", "value-text");
function createLineDivTextConsts() {
let myArr = [];
myArrayOfKeys.map((val, index) => {
myArr.push(tooltipDiv.append("div").attr("class", "text-container"));
});
return myArr;
}
const lineTextContainer = createLineDivTextConsts();
myArrayOfKeys.forEach((item, index) => {
lineTextContainer[index]
.append("div")
.attr("class", "label-style mr-1")
.text(item["tooltipLabel"]);
lineTextContainer[index]
.append("div")
.attr("class", "dash")
.style("background-color", item["marker"]);
});
function createLineTextConsts() {
let myArr = [];
myArrayOfKeys.map((item, index) => {
myArr.push(
lineTextContainer[index]
.append("div")
.attr("class", `value-text`)
.attr("id", `lineTextConst${myID}${index}`)
);
});
return myArr;
}
const lineTextConsts = createLineTextConsts();
// const YOYContainer = tooltipDiv
// .append("div")
// .attr("class", "text-container");
// YOYContainer.append("div")
// .attr("class", "label-style mr-1")
// .text("YOY");
// const YOYText = YOYContainer.append("div");
// // //////////////////////// Add Rect to Capture Mouse Movements ////////////////////////
CVsvg.append("rect")
.on("mouseover", () => {
lineTrace.style("display", null);
d3.select(`#${myID} .mouse-line`).style("opacity", "1");
// d3.selectAll(".mouse-per-line .line-marker").style("opacity", "1");
})
.on("mousemove", () => {
let xy = d3.mouse(d3.event.currentTarget);
let x0 = x.invert(xy[0]);
let mouseIndex = justBisect(chartData, x0, 1);
let d0 = chartData[mouseIndex - 1];
let d1 = chartData[mouseIndex];
let d;
if (d1 !== undefined) {
d = x0 - chartData.indexOf(d0) > chartData.indexOf(d1) - x0 ? d1 : d0;
} else {
d = d0;
}
lineTrace.attr(
"transform",
"translate(" + x(chartData.indexOf(d)) + ",0)"
);
myArrayOfKeys.forEach((item, index) => {
d3.select(`#${myID} .marker${index}`).attr(
"transform",
"translate(" +
x(chartData.indexOf(d)) +
"," +
y(d[item["dataKey"]]) +
")"
);
});
myArrayOfKeys.forEach((item, index) => {
let myText =
d[myArrayOfKeys[index]] !== null
? numberFormatFn(d[item["dataKey"]])
: "";
d3.select(`#${myID}Tooltip #lineTextConst${myID}${index}`).text(
myText
);
});
dateText.text(d.niceDate + ", " + d.niceTime);
d3.select(`#${myID} .mouse-line`).attr("y2", height);
})
.on("mouseleave", () => {
d3.select(`#${myID} .mouse-line`).style("opacity", ".5");
})
.attr("class", "totalRect")
.attr("fill", "none")
.attr("x", 0)
.attr("pointer-events", "all")
.attr("width", width)
.attr("transform", "translate(0,0)")
.attr("height", height)
.transition()
.duration(500);
// ////////////////////////// Set the data on load ////////////////////////
d3.set().add(chartData[chartData.length - 1]);
let d = chartData[chartData.length - 1];
lineTrace.attr("transform", "translate(" + x(chartData.indexOf(d)) + ",0)");
myArrayOfKeys.forEach((item, index) => {
d3.select(`#${myID} .marker${index}`).attr(
"transform",
"translate(" +
x(chartData.indexOf(d)) +
"," +
y(d[item["dataKey"]]) +
")"
);
});
myArrayOfKeys.forEach((item, index) => {
let myText =
d[myArrayOfKeys[index]] !== null
? numberFormatFn(d[item["dataKey"]])
: "";
d3.select(`#${myID}Tooltip #lineTextConst${myID}${index}`).text(myText);
});
dateText.text(d.niceDate + ", " + d.niceTime);
// // YOYText.text(YOYdiff);
// // YOYText.attr("class", YOYdiffColor);
d3.select(`#${myID} .mouse-line`).attr("y2", height);
}
useEffect(() => {
createChart(chartData, valueArray, props.myID, props.numberFormatFn);
}, []);
useEffect(() => {
createChart(chartData, valueArray, props.myID, props.numberFormatFn);
}, [props.resize]);
return <div ref={chart}></div>;
}
|
/* eslint-disable */
import Component from '../../../../../ui-base/component';
import _ from '../../../../../ui-base/_';
import template from './index.html';
import TimePickerPanel from '../../panel/Time/time/index';
import RangeTimePickerPanel from '../../panel/Time/time.range/index';
import KLDrop from '../../../../layout/KLDrop/index';
import KLDropHeader from '../../../../layout/KLDrop/KLDropHeader/index';
import KLDropMenu from '../../../../layout/KLDrop/KLDropMenu/index';
import {
DEFAULT_FORMATS,
RANGE_SEPARATOR,
TYPE_VALUE_RESOLVER_MAP,
getDayCountOfMonth,
} from '../../util';
const findComponentsDownward = (context, componentName) => context.$children.reduce((components, child) => {
if (child.$options.name === componentName) components.push(child);
const foundChilds = findComponentsDownward(child, componentName);
return components.concat(foundChilds);
}, []);
const prefixCls = 'ivu-date-picker';
const pickerPrefixCls = 'ivu-picker';
const isEmptyArray = val => val.reduce((isEmpty, str) => isEmpty && !str || (typeof str === 'string' && str.trim() === ''), true);
const keyValueMapper = {
40: 'up',
39: 'right',
38: 'down',
37: 'left',
};
const mapPossibleValues = (key, horizontal, vertical) => {
if (key === 'left') return horizontal * -1;
if (key === 'right') return horizontal * 1;
if (key === 'up') return vertical * 1;
if (key === 'down') return vertical * -1;
};
const pulseElement = (el) => {
const pulseClass = 'ivu-date-picker-btn-pulse';
el.classList.add(pulseClass);
setTimeout(() => el.classList.remove(pulseClass), 200);
};
const extractTime = (date) => {
if (!date) return [0, 0, 0];
return [
date.getHours(), date.getMinutes(), date.getSeconds(),
];
};
const KLTime = Component.extend({
name: 'kl-time',
template,
config() {
_.extend(this.data, {
disabledHours: [],
disabledMinutes: [],
disabledSeconds: [],
hideDisabledOptions: false,
format: '',
placeholder: '',
elementId: '',
name: '',
readonly: false,
disabled: false,
confirm: false,
Boolean: false,
splitPanels: false,
showWeekNumbers: false,
open: false,
editable: true,
clearable: true,
startDate: new Date(),
size: 'default', // 'small', 'large', 'default'
steps: [],
value: null,
timePickerOptions: {},
options: {},
prefixCls,
showClose: false,
visible: false,
disableClickOutSide: false, // fixed when click a date,trigger clickoutside to close picker
disableCloseUnderTransfer: false, // transfer 模式下,点击Drop也会触发关闭,
forceInputRerender: 1,
isFocused: false,
internalFocus: false,
type: 'time',
});
this.supr();
},
init() {
this.supr();
const isRange = this.data.type.includes('range');
const emptyArray = isRange ? [null, null] : [null];
const initialValue = isEmptyArray((isRange ? this.data.value : [this.data.value]) || []) ? emptyArray : this.data.parseDate(this.data.value);
const focusedTime = initialValue.map(extractTime);
this.data.internalValue = initialValue;
this.data.selectionMode = this.onSelectionModeChange(this.data.type);
this.data.focusedDate = initialValue[0] || this.data.startDate || new Date();
this.data.focusedTime = {
column: 0, // which column inside the picker
picker: 0, // which picker
time: focusedTime, // the values array into [hh, mm, ss],
active: false,
};
// mounted
// const initialValue = this.data.value;
const parsedValue = this.data.publicVModelValue;
if (typeof initialValue !== typeof parsedValue || JSON.stringify(initialValue) !== JSON.stringify(parsedValue)) {
this.$emit('input', this.data.publicVModelValue); // to update v-model
}
if (this.data.open !== null) this.data.visible = this.data.open;
// to handle focus from confirm buttons
this.$on('focus-input', () => this.focus());
// this.$watch('visible', (val) => {
// if (state === false) {
// this.$refs.drop.destroy();
// }
// this.$refs.drop.update();
// this.$emit('open-change', state);
// });
this.$watch('value', (val) => {
this.data.internalValue = this.parseDate(val);
});
this.$watch('open', (val) => {
this.data.visible = val === true;
});
this.$watch('type', (type) => {
this.onSelectionModeChange(type);
});
this.$watch('publicVModelValue', (now, before) => {
const newValue = JSON.stringify(now);
const oldValue = JSON.stringify(before);
const shouldEmitInput = newValue !== oldValue || typeof now !== typeof before;
if (shouldEmitInput) this.$emit('input', now); // to update v-model
});
},
computed: {
wrapperClasses() {
const isFocusedCls = this.data.isFocused ? `${prefixCls}-focused` : '';
return `${prefixCls} ${isFocusedCls}`;
},
// publicVModelValue() {
// const store = this.data;
//
// if (store.multiple) {
// return store.internalValue.slice();
// }
// const isRange = store.type.includes('range');
// let val = store.internalValue.map(date => date instanceof Date ? new Date(date) : (date || ''));
//
// if (store.type.match(/^time/)) val = val.map(store.formatDate);
// return (isRange || store.multiple) ? val : val[0];
// },
publicStringValue() {
const {formatDate, publicVModelValue, type} = this;
if (type.match(/^time/)) return publicVModelValue;
if (this.data.multiple) return formatDate(publicVModelValue);
return Array.isArray(publicVModelValue) ? publicVModelValue.map(formatDate) : formatDate(publicVModelValue);
},
opened() {
return this.data.open === null ? this.data.visible : this.data.open;
},
iconType() {
let icon = 'ios-calendar-outline';
if (this.data.type === 'time' || this.data.type === 'timerange') icon = 'ios-time-outline';
if (this.data.showClose) icon = 'ios-close-circle';
return icon;
},
transition() {
const bottomPlaced = this.data.placement.match(/^bottom/);
return bottomPlaced ? 'slide-up' : 'slide-down';
},
visualValue() {
return this.formatDate(this.data.internalValue);
},
isConfirm() {
return this.data.confirm || this.data.type === 'datetime' || this.data.type === 'datetimerange' || this.data.multiple;
},
},
onSelectionModeChange(type = 'time') {
if (type.match(/^date/)) type = 'date';
this.data.selectionMode = type;
return this.data.selectionMode;
},
// 开启 transfer 时,点击 Drop 即会关闭,这里不让其关闭
handleTransferClick() {
if (this.data.transfer) this.data.disableCloseUnderTransfer = true;
},
handleClose(e) {
if (this.data.disableCloseUnderTransfer) {
this.data.disableCloseUnderTransfer = false;
return false;
}
if (e && e.type === 'mousedown' && this.data.visible) {
e.preventDefault();
e.stopPropagation();
return;
}
if (this.data.visible) {
const pickerPanel = this.$refs.pickerPanel && this.$refs.pickerPanel.$el;
if (e && pickerPanel && pickerPanel.contains(e.target)) return; // its a click inside own component, lets ignore it.
this.data.visible = false;
e && e.preventDefault();
e && e.stopPropagation();
return;
}
this.data.isFocused = false;
this.data.disableClickOutSide = false;
},
handleFocus(e) {
if (this.data.readonly) return;
this.data.isFocused = true;
if (e && e.type === 'focus') return; // just focus, don't open yet
this.data.visible = true;
},
handleBlur(e) {
const store = this.data;
if (store.internalFocus) {
thstores.internalFocus = false;
return;
}
if (store.visible) {
e.preventDefault();
return;
}
store.isFocused = false;
this.onSelectionModeChange(store.type);
store.internalValue = store.internalValue.slice(); // trigger panel watchers to reset views
this.reset();
this.$refs.pickerPanel.onToggleVisibility(false);
},
handleKeydown(e) {
const store = this.data;
const keyCode = e.keyCode;
// handle "tab" key
if (keyCode === 9) {
if (store.visible) {
e.stopPropagation();
e.preventDefault();
if (store.isConfirm) {
const selector = `.${pickerPrefixCls}-confirm > *`;
const tabbable = this.$refs.drop.$el.querySelectorAll(selector);
store.internalFocus = true;
const element = [...tabbable][e.shiftKey ? 'pop' : 'shift']();
element.focus();
} else {
this.handleClose();
}
} else {
store.focused = false;
}
}
// open the panel
const arrows = [37, 38, 39, 40];
if (!store.visible && arrows.includes(keyCode)) {
store.visible = true;
return;
}
// close on "esc" key
if (keyCode === 27) {
if (store.visible) {
e.stopPropagation();
this.handleClose();
}
}
// select date, "Enter" key
if (keyCode === 13) {
const timePickers = findComponentsDownward(this, 'TimeSpinner');
if (timePickers.length > 0) {
const columnsPerPicker = timePickers[0].showSeconds ? 3 : 2;
const pickerIndex = Math.floor(store.focusedTime.column / columnsPerPicker);
const value = store.focusedTime.time[pickerIndex];
timePickers[pickerIndex].chooseValue(value);
return;
}
if (store.type.match(/range/)) {
this.$refs.pickerPanel.handleRangePick(store.focusedDate, 'date');
} else {
const panels = findComponentsDownward(this, 'PanelTable');
const compareDate = (d) => {
const sliceIndex = ['year', 'month', 'date'].indexOf((store.type)) + 1;
return [d.getFullYear(), d.getMonth(), d.getDate()].slice(0, sliceIndex).join('-');
};
const dateIsValid = panels.find(({cells}) => cells.find(({date, disabled}) => compareDate(date) === compareDate(store.focusedDate) && !disabled));
if (dateIsValid) this.onPick(store.focusedDate, false, 'date');
}
}
if (!arrows.includes(keyCode)) return; // ignore rest of keys
// navigate times and dates
if (store.focusedTime.active) e.preventDefault(); // to prevent cursor from moving
this.navigateDatePanel(keyValueMapper[keyCode], e.shiftKey);
},
reset() {
// this.$refs.pickerPanel.reset && this.$refs.pickerPanel.reset();
},
navigateTimePanel(direction) {
const store = this.data;
store.focusedTime.active = true;
const horizontal = direction.match(/left|right/);
const vertical = direction.match(/up|down/);
const timePickers = findComponentsDownward(this, 'TimeSpinner');
const maxNrOfColumns = (timePickers[0].showSeconds ? 3 : 2) * timePickers.length;
const column = ((currentColumn) => {
const incremented = currentColumn + (horizontal ? (direction === 'left' ? -1 : 1) : 0);
return (incremented + maxNrOfColumns) % maxNrOfColumns;
})(store.focusedTime.column);
const columnsPerPicker = maxNrOfColumns / timePickers.length;
const pickerIndex = Math.floor(column / columnsPerPicker);
const col = column % columnsPerPicker;
if (horizontal) {
const time = store.internalValue.map(extractTime);
store.focusedTime = {
...store.focusedTime,
column,
time,
};
timePickers.forEach((instance, i) => {
if (i === pickerIndex) instance.updateFocusedTime(col, time[pickerIndex]);
else instance.updateFocusedTime(-1, instance.focusedTime);
});
}
if (vertical) {
const increment = direction === 'up' ? 1 : -1;
const timeParts = ['hours', 'minutes', 'seconds'];
const pickerPossibleValues = timePickers[pickerIndex][`${timeParts[col]}List`];
const nextIndex = pickerPossibleValues.findIndex(({text}) => store.focusedTime.time[pickerIndex][col] === text) + increment;
const nextValue = pickerPossibleValues[nextIndex % pickerPossibleValues.length].text;
const times = store.focusedTime.time.map((time, i) => {
if (i !== pickerIndex) return time;
time[col] = nextValue;
return time;
});
store.focusedTime = {
...store.focusedTime,
time: times,
};
timePickers.forEach((instance, i) => {
if (i === pickerIndex) instance.updateFocusedTime(col, times[i]);
else instance.updateFocusedTime(-1, instance.focusedTime);
});
}
},
navigateDatePanel(direction, shift) {
const store = this.data;
const timePickers = findComponentsDownward(this, 'TimeSpinner');
if (timePickers.length > 0) {
// we are in TimePicker mode
this.navigateTimePanel(direction, shift, timePickers);
return;
}
if (shift) {
if (store.type === 'year') {
store.focusedDate = new Date(
store.focusedDate.getFullYear() + mapPossibleValues(direction, 0, 10),
store.focusedDate.getMonth(),
store.focusedDate.getDate(),
);
} else {
store.focusedDate = new Date(
store.focusedDate.getFullYear() + mapPossibleValues(direction, 0, 1),
store.focusedDate.getMonth() + mapPossibleValues(direction, 1, 0),
store.focusedDate.getDate(),
);
}
const position = direction.match(/left|down/) ? 'prev' : 'next';
const double = direction.match(/up|down/) ? '-double' : '';
// pulse button
const button = this.$refs.drop.$el.querySelector(`.ivu-date-picker-${position}-btn-arrow${double}`);
if (button) pulseElement(button);
return;
}
const initialDate = store.focusedDate || (store.internalValue && store.internalValue[0]) || new Date();
const focusedDate = new Date(initialDate);
if (store.type.match(/^date/)) {
const lastOfMonth = getDayCountOfMonth(initialDate.getFullYear(), initialDate.getMonth());
const startDay = initialDate.getDate();
const nextDay = focusedDate.getDate() + mapPossibleValues(direction, 1, 7);
if (nextDay < 1) {
if (direction.match(/left|right/)) {
focusedDate.setMonth(focusedDate.getMonth() + 1);
focusedDate.setDate(nextDay);
} else {
focusedDate.setDate(startDay + Math.floor((lastOfMonth - startDay) / 7) * 7);
}
} else if (nextDay > lastOfMonth) {
if (direction.match(/left|right/)) {
focusedDate.setMonth(focusedDate.getMonth() - 1);
focusedDate.setDate(nextDay);
} else {
focusedDate.setDate(startDay % 7);
}
} else {
focusedDate.setDate(nextDay);
}
}
if (store.type.match(/^month/)) {
focusedDate.setMonth(focusedDate.getMonth() + mapPossibleValues(direction, 1, 3));
}
if (store.type.match(/^year/)) {
focusedDate.setFullYear(focusedDate.getFullYear() + mapPossibleValues(direction, 1, 3));
}
store.focusedDate = focusedDate;
},
handleInputChange(event) {
const store = this.data;
const isArrayValue = store.type.includes('range') || store.multiple;
const oldValue = store.visualValue;
const newValue = event.target.value;
const newDate = this.parseDate(newValue);
const disabledDateFn =
store.options &&
typeof store.options.disabledDate === 'function' &&
store.options.disabledDate;
const valueToTest = isArrayValue ? newDate : newDate[0];
const isDisabled = disabledDateFn && disabledDateFn(valueToTest);
const isValidDate = newDate.reduce((valid, date) => valid && date instanceof Date, true);
if (newValue !== oldValue && !isDisabled && isValidDate) {
this.emitChange(store.type);
store.internalValue = newDate;
} else {
store.forceInputRerender++;
}
},
handleInputMouseenter() {
const store = this.data;
if (store.readonly || store.disabled) return;
if (store.visualValue && store.clearable) {
store.showClose = true;
}
},
handleInputMouseleave() {
this.data.showClose = false;
},
handleIconClick() {
const store = this.data;
if (store.showClose) {
this.handleClear();
} else if (!store.disabled) {
this.handleFocus();
}
},
handleClear() {
const store = this.data;
store.visible = false;
store.internalValue = store.internalValue.map(() => null);
this.$emit('clear');
// this.dispatch('FormItem', 'on-form-change', '');
this.emitChange(store.type);
this.reset();
setTimeout(
() => this.onSelectionModeChange(store.type),
500, // delay to improve dropdown close visual effect
);
},
emitChange(type) {
const store = this.data;
setTimeout(
() => {
this.$emit('change', store.publicStringValue, type);
// this.dispatch('FormItem', 'on-form-change', store.publicStringValue);
},
);
},
parseDate(val) {
const store = this.data;
const isRange = store.type.includes('range');
const type = store.type;
const parser = (
TYPE_VALUE_RESOLVER_MAP[type] ||
TYPE_VALUE_RESOLVER_MAP.default
).parser;
const format = store.format || DEFAULT_FORMATS[type];
const multipleParser = TYPE_VALUE_RESOLVER_MAP.multiple.parser;
if (val && type === 'time' && !(val instanceof Date)) {
val = parser(val, format);
} else if (store.multiple && val) {
val = multipleParser(val, format);
} else if (isRange) {
if (!val) {
val = [null, null];
} else if (typeof val === 'string') {
val = parser(val, format);
} else if (type === 'timerange') {
val = parser(val, format).map(v => v || '');
} else {
const [start, end] = val;
if (start instanceof Date && end instanceof Date) {
val = val.map(date => new Date(date));
} else if (typeof start === 'string' && typeof end === 'string') {
val = parser(val.join(RANGE_SEPARATOR), format);
} else if (!start || !end) {
val = [null, null];
}
}
} else if (typeof val === 'string' && type.indexOf('time') !== 0) {
val = parser(val, format) || null;
}
return (isRange || store.multiple) ? (val || []) : [val];
},
formatDate(value) {
const store = this.data;
const format = DEFAULT_FORMATS[store.type];
if (store.multiple) {
const formatter = TYPE_VALUE_RESOLVER_MAP.multiple.formatter;
return formatter(value, store.format || format);
}
const {formatter} = (
TYPE_VALUE_RESOLVER_MAP[store.type] ||
TYPE_VALUE_RESOLVER_MAP.default
);
return formatter(value, store.format || format);
},
onPick(e ) {
const [ dates, visible, type ] = [ e.value, e.visible || false, e.type ];
const store = this.data;
if (store.multiple) {
const pickedTimeStamp = dates.getTime();
const indexOfPickedDate = store.internalValue.findIndex(date => date && date.getTime() === pickedTimeStamp);
const allDates = [...store.internalValue, dates].filter(Boolean);
const timeStamps = allDates.map(date => date.getTime()).filter((ts, i, arr) => arr.indexOf(ts) === i && i !== indexOfPickedDate); // filter away duplicates
store.internalValue = timeStamps.map(ts => new Date(ts));
} else {
store.internalValue = Array.isArray(dates) ? dates : [dates];
}
if (store.internalValue[0]) store.focusedDate = store.internalValue[0];
store.focusedTime = {
...store.focusedTime,
time: store.internalValue.map(extractTime),
};
if (!store.isConfirm) this.onSelectionModeChange(this.type); // reset the selectionMode
if (!store.isConfirm) store.visible = visible;
this.emitChange(type);
},
onPickSuccess() {
this.data.isShow = !this.data.isShow;
this.$emit('ok');
this.focus();
this.reset();
},
focus() {
this.$refs.input && this.$refs.input.focus();
},
});
module.exports = KLTime;
|
import Promise from 'bluebird';
import isUpgradeable from './is_upgradeable';
import _ from 'lodash';
import { format } from 'util';
module.exports = function (server) {
const MAX_INTEGER = Math.pow(2, 53) - 1;
const { callWithInternalUser } = server.plugins.elasticsearch.getCluster('admin');
const config = server.config();
function createNewConfig() {
return callWithInternalUser('create', {
index: config.get('kibana.index'),
type: 'config',
body: { buildNum: config.get('pkg.buildNum') },
id: config.get('pkg.version')
});
}
return function (response) {
const newConfig = {};
// Check to see if there are any doc. If not then we set the build number and id
if (response.hits.hits.length === 0) {
return createNewConfig();
}
// if we already have a the current version in the index then we need to stop
const devConfig = _.find(response.hits.hits, function currentVersion(hit) {
return hit._id !== '@@version' && hit._id === config.get('pkg.version');
});
if (devConfig) {
return Promise.resolve();
}
// Look for upgradeable configs. If none of them are upgradeable
// then create a new one.
const body = _.find(response.hits.hits, isUpgradeable.bind(null, server));
if (!body) {
return createNewConfig();
}
// if the build number is still the template string (which it wil be in development)
// then we need to set it to the max interger. Otherwise we will set it to the build num
body._source.buildNum = config.get('pkg.buildNum');
server.log(['plugin', 'elasticsearch'], {
tmpl: 'Upgrade config from <%= prevVersion %> to <%= newVersion %>',
prevVersion: body._id,
newVersion: config.get('pkg.version')
});
return callWithInternalUser('create', {
index: config.get('kibana.index'),
type: 'config',
body: body._source,
id: config.get('pkg.version')
});
};
};
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var roomSchema = new Schema({
room_id: Schema.Types.String,
members: Schema.Types.Array,
history: Schema.Types.Mixed,
type: Schema.Types.String,
created_at: {type: Schema.Types.Date, default: Date.now},
modified_at: {type: Schema.Types.Date, default: Date.now}
});
module.exports = mongoose.model('Room', roomSchema);
|
Ext.define('doweown.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
requires: [
'Ext.TitleBar',
'Ext.form.Panel',
'Ext.form.FieldSet',
'Ext.field.Select',
'doweown.view.History',
'doweown.store.LibraryStore'
],
config: {
tabBarPosition: 'bottom',
items: [
{
title: 'Scan',
iconCls: 'search',
//styleHtmlContent: false,
scrollable: false,
layout: 'fit',
items: [{
xtype: 'navigationview',
itemId: 'mainscreen',
id: 'mainscreen',
items: [{
title: 'Do We Own This?',
padding: '5 10 10 10',
items: [
{ xtype: 'container', html: '<center><b>Do We Own This?</b></center> is an app that you can use to see if a book is in the Harvard Library. Simply scan a book\'s barcode or enter in its ISBN number to find out!' , padding: '10 5 10 5'},
{ xtype: 'spacer' , padding: 10},
{ xtype: 'container', html: 'Scan a book\'s ISBN barcode:', padding: '0 10 0 10'},
{ xtype: 'spacer' , padding: 10},
{ xtype: 'button', itemId: 'scanBtn', text: 'Press Here to Scan', padding: '0 10 0 10'},
{ xtype: 'spacer', padding: 10},
{ xtype: 'container', html: 'Or enter an ISBN number below:', padding: '0 10 0 10'},
{ xtype: 'spacer', padding: 10 },
{ xtype: 'textfield', itemId: 'isbnField', label: 'ISBN:', maxLength: 13, padding: '0 10 5 10'}
]
}]
}]
},
{
itemId: 'hitlist',
title: 'History',
iconCls: 'bookmarks',
//styleHtmlContent: false,
layout: 'fit',
items: [{
xtype: 'navigationview',
itemId: 'historynav',
id: 'historynav',
title: 'History',
items: [
{ xtype: 'history'}
]
}]
},
{
itemId: 'prefs',
title: 'Prefs',
iconCls: 'settings',
layout: 'fit',
items: [{
xtype: 'formpanel',
itemId: 'prefsform',
items: [
{ xtype: 'titlebar', title: 'Settings', docked: 'top' },
{ xtype: 'fieldset',
title: 'Enter your email settings here.',
items: [
{xtype: 'textfield', name: 'firstname', label: 'First <br>Name'},
{xtype: 'textfield', name: 'lastname', label: 'Last <br>Name'},
{xtype: 'textfield', name: 'email', label: 'E-mail'},
{xtype: 'selectfield', name: 'library', label: 'Library', store: 'LibraryStore', displayField: 'name', valueField: 'libcode'},
{xtype: 'textfield', name: 'school', label: 'School /<br>Unit'},
{xtype: 'selectfield', name: 'affiliation', label: 'Affiliation',
options: [
{text: 'Harvard Faculty', value: 'Harvard Faculty' },
{text: 'Harvard Undergraduate Student', value: 'Harvard Undergraduate Student' },
{text: 'Harvard Graduate Student', value: 'Harvard Graduate Student' },
{text: 'Harvard Staff', value: 'Harvard Staff' },
{text: 'Harvard Alumnus/a', value: 'Harvard Alumnus/a' },
{text: 'Harvard Other', value: 'Harvard Other' },
{text: 'Other Institution Faculty', value: 'Other Institution Faculty' },
{text: 'Other Institution Undergraduate Student', value: 'Other Institution Undergraduate Student' },
{text: 'Other Institution Graduate Student', value: 'Other Institution Graduate Student' },
{text: 'High School Student', value: 'High School Student' },
{text: 'Independent Researcher', value: 'Independent Researcher' },
{text: 'Other', value: 'Other' }
]
}
]
},
{ xtype: 'toolbar',
layout: { pack: 'center' },
ui: 'plain',
items: [
{ xtype: 'spacer'},
{xtype: 'button', text: 'Reset', ui: 'decline', itemId: 'resetBtn' },
{ xtype: 'spacer'},
{xtype: 'button', text: 'Save', ui: 'confirm', itemId: 'saveBtn' },
{ xtype: 'spacer'}
]
}
]
}]
},
{
itemId: 'about',
title: 'About',
iconCls: 'info',
layout: 'fit',
scrollable: true,
items: [
{ xtype: 'titlebar', title: 'About', docked: 'top' },
{ xtype: 'spacer'},
{ xtype: 'panel', styleHtmlContent: true, scrollable: true,
html: '<p><b>Do we own this?</b><br>' +
'A mobile app for library collection development' +
'<p>Version: ' + doweown.config.Config.getVersion() +
'<p><i>Project Team:</i><br>' +
'Thomas Ma, Bibliographic Services Manager, Information and Technical Services<br>' +
'Chip Goines, Digital Library Software Engineer, Library Technology Services<br>' +
'Donna Viscuglia, Senior Cataloger, ITS<br>' +
'Mariko Honshuku, Librarian for Japanese Law, Law Library<p/>' +
'<p>Produced by: The Harvard Library Lab, ' +
'<a href="https://osc.hul.harvard.edu/liblab" onclick="window.open(this.href,\'_system\'); return false;" >https://osc.hul.harvard.edu/liblab</a></p>' +
'Contact us:<br> ' +
'<a href="mailto:doweownthis@hulmail.harvard.edu' +
'?subject=%5Bdoweown%5D%20App%20Feedback" onclick="window.open(this.href,\'_system\'); return false;"><b>General Questions</b></a> | ' +
'<a href="mailto:doweownthis-dev@hulmail.harvard.edu' +
'?subject=%5Bdoweown%5D%20Technical%20Support%20Question" onclick="window.open(this.href,\'_system\'); return false;"><b>Technical Support</b></a> <p> <br>' +
'License: GNU GPL v3.0<p>'
}
]
}
]
}
});
|
/**
* Route provider
* @version v0.1.0 - 2014-04-09
* @link
* @author
* @license MIT License, http://www.opensource.org/licenses/MIT
*/angular.module("ngSymbiosis.routeProvider",[]).constant("stateFactory",function(a,b){function c(a){return a.replace(/(?:^[A-Z]{2,})/g,function(a){return a.toLowerCase()+"-"}).replace(/(?:[A-Z]+)/g,function(a){return"-"+a.toLowerCase()}).replace(/^-/,"")}var d=a+"CtrlInit",e={url:"/"+c(a),templateUrl:"states/"+c(a)+"/index/main-view.html",controller:a+"Ctrl"};try{e.resolve={init:["$injector",function(a){if(a.has(d)){var b=a.get(d);if("function"!=typeof b.prepare)throw d+" has no prepare method.";return b.prepare()}}]}}catch(f){throw"Serious error occurred trying to load controller.: "+f}return angular.extend(e,b)});
|
"use strict";
var OctocatSchema = {
name: {
type: String,
required: true,
validate: function (name, callback) {
//async test
if(name === null) {
callback(false);
return;
}
callback(true);
}
},
age : {
"type" : Number,
"required" : false,
"default" : 5,
"validate" : function(age) {
if(age >= 100) {
return "tooOld-shared";
}
return true;
}
},
birthday: Date,
location : {
type : String,
validate : function(location) {
if(location === "") {
return false;
}
return true;
}
},
shared : String
};
module.exports = OctocatSchema;
|
/**
*
* Form Tambah Product
*
*
**/
Ext.define('App.view.master.product.wizard.formProduct',{
alias : 'widget.frmNewProduct',
extend: 'Ext.panel.Panel',
requires: [
// 'Ext.form.Panel',
'Ext.form.field.Text',
'App.form.combobox.cbCatproduct',
'App.form.combobox.cbSupplier',
'App.form.combobox.cbTypeProduct',
'App.form.combobox.cbSatuan',
'App.form.combobox.cbCurrencies',
'App.form.combobox.cbGradeKain',
'App.form.combobox.cbColor',
'App.form.combobox.cbUnits'
],
layout : { type : 'fit', align: 'stretch' },
initComponent : function() { log('Form Add Product Loaded'); this.callParent(arguments); },
items : [
{
xtype : 'form',
id: 'frmaddproduct',
padding: '5 5 0 5',
border: false,
style: 'background-color: #fff;',
layout : { type : 'vbox', align: 'stretch' },
fieldDefaults: {
anchor: '100%',
labelAlign: 'left',
allowBlank: false,
combineErrors: true,
msgTarget: 'side',
},
items : [
{ xtype: 'container'}
]
}
]
});
|
import React, { Component } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet
} from 'react-native';
import * as colors from '../../common/colors';
import Icon from 'react-native-vector-icons/MaterialIcons';
export default class Checkbox extends Component {
constructor(props) {
super(props);
}
renderIconCheck(checked) {
if (checked) {
return (
<Icon name='check-box' color={colors.getList().app} size={23} />
);
} else {
return (
<Icon name='check-box-outline-blank' color="#FFF" size={23} />
);
}
}
render() {
return (
<TouchableOpacity
style={styles.row}
activeOpacity={1}
onPress={this.props.onChange.bind(this, this.props.checked)}>
<Text style={{color: '#FFF'}}>{this.props.checked ? 'Habilitado' : 'Deshabilitado'}</Text>
{this.renderIconCheck(this.props.checked)}
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}
});
|
import Vue from 'vue'
import TabSet from '../../src/modules/tab/TabSet.vue'
import { createVm,createVue,destroyVm } from '../util.js'
describe('TabSet', function() {
let vm
afterEach(() => {
destroyVm(vm)
})
it('vertical', function (done){
vm = createVm(TabSet,{
vertical: true
})
setTimeout(()=>{
expect(vm.$el.classList.contains('ph-tabs-vertical')).toBe(true)
done()
})
})
})
|
$("#phone").intlTelInput({
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
callback(countryCode);
});
},
utilsScript: "js/utils.js?1535108287294" // just for formatting/placeholders etc
});
/*
* Let us validate the phone number
*/
var telInput = $("#phone"),
errorMsg = $("#error-msg"),
validMsg = $("#valid-msg"); //Shut this on the main page cause I won't need it
var reset = function() {
telInput.removeClass("error");
errorMsg.addClass("hide");
validMsg.addClass("hide");
};
// on blur: validate
telInput.blur(function() {
reset();
if ($.trim(telInput.val())) {
if (telInput.intlTelInput("isValidNumber")) {
validMsg.removeClass("hide");
} else {
telInput.addClass("error");
errorMsg.removeClass("hide");
}
}
});
// on keyup / change flag: reset
telInput.on("keyup change", reset);
|
//to inform user which email they are signed in with
$(document).ready(function (){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
email= user.email;
document.getElementById("signedInAs").innerHTML = email;
}
});
});
|
'use strict';
var Reflux = require('reflux');
var DeskActions = require('../../action/desk/DeskActions.js');
var defaultModel = {
isToolbarLeftShown: true,
isToolbarTopShown: true,
isAvailableComponentsButtonActive: false,
isComponentOptionsButtonActive: false,
isStyleOptionsButtonActive: false,
isComponentsHierarchyButtonActive: false,
isEditMode: true,
isLivePreviewMode: false,
isDocumentMode: false,
LoadUserProfile: false
};
var DeskStore = Reflux.createStore({
model: defaultModel,
listenables: DeskActions,
onStartEditMode: function(){
if(!this.model.isEditMode){
this.model.isEditMode = true;
this.model.isLivePreviewMode = false;
this.model.isDocumentMode = false;
this.trigger(this.model);
}
},
onStartDocumentMode: function(){
if(!this.model.isDocumentMode){
this.model.isEditMode = false;
this.model.isLivePreviewMode = false;
this.model.isDocumentMode = true;
//
this.model.isAvailableComponentsButtonActive = false;
this.model.isComponentOptionsButtonActive = false;
this.model.isStyleOptionsButtonActive = false;
this.model.isComponentsHierarchyButtonActive = false;
//
this.trigger(this.model);
}
},
onStartLivePreviewMode: function(){
if(!this.model.isLivePreviewMode){
this.model.isEditMode = false;
this.model.isLivePreviewMode = true;
this.model.isDocumentMode = false;
//
this.model.isAvailableComponentsButtonActive = false;
this.model.isComponentOptionsButtonActive = false;
this.model.isStyleOptionsButtonActive = false;
this.model.isComponentsHierarchyButtonActive = false;
//
this.trigger(this.model);
}
},
onToggleAvailableComponents: function(){
this.model.isAvailableComponentsButtonActive = !this.model.isAvailableComponentsButtonActive;
this.trigger(this.model);
},
onToggleStyleOptions: function(){
this.model.isStyleOptionsButtonActive = !this.model.isStyleOptionsButtonActive;
this.trigger(this.model);
},
onToggleComponentsHierarchy: function(){
this.model.isComponentsHierarchyButtonActive = !this.model.isComponentsHierarchyButtonActive;
this.trigger(this.model);
}
});
module.exports = DeskStore;
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12.36 6l.4 2H18v6h-3.36l-.4-2H7V6h5.36M14 4H5v17h2v-7h5.6l.4 2h7V6h-5.6L14 4z" />
, 'FlagOutlined');
|
import React from 'react';
import Star from 'wix-ui-icons-common/Star';
import DownloadImportSmall from 'wix-ui-icons-common/DownloadImportSmall';
import DuplicateSmall from 'wix-ui-icons-common/DuplicateSmall';
import PrintSmall from 'wix-ui-icons-common/PrintSmall';
import { classes } from '../TableActionCell.story.st.css';
import { TableActionCell } from 'wix-style-react';
const Example = () => (
<div className={classes.exampleRow}>
<TableActionCell
size="small"
dataHook="story-small-buttons"
alwaysShowSecondaryActions
primaryAction={{
text: 'Edit',
skin: 'inverted',
onClick: () => window.alert('Primary action was triggered!'),
}}
secondaryActions={[
{
text: 'Star',
icon: <Star size="small" />,
onClick: () => window.alert('Star action was triggered.'),
},
{
text: 'Download',
icon: <DownloadImportSmall />,
onClick: () => window.alert('Download action was triggered.'),
},
{
text: 'Duplicate',
icon: <DuplicateSmall />,
onClick: () => window.alert('Duplicate action was triggered.'),
},
{
text: 'Print',
icon: <PrintSmall />,
onClick: () => window.alert('Print action was triggered.'),
},
]}
numOfVisibleSecondaryActions={2}
/>
</div>
);
export default Example;
|
/*
* grunt-mustache-generator
* https://github.com/MattWilliamsDev/grunt-mustache-generator
*
* Copyright (c) 2014 Matt Williams
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('mustache_generator', 'Create (touch) mustache template files', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
|
var photoCollectionHolder, addPhotoLink, $newPhotoLinkLi;
function addTagForm() {
var prototype = photoCollectionHolder.attr('data-prototype');
var newForm = prototype.replace(/\$\$name\$\$/g, photoCollectionHolder.children().length);
var $newFormLi = $('<li></li>').append(newForm);
$newPhotoLinkLi.before($newFormLi);
addTagFormDeleteLink($newFormLi);
}
function addTagFormDeleteLink($tagFormLi) {
var $removeFormA = $('<br /><a href="#" class="plain button medium red">Usuń</a>');
$tagFormLi.append($removeFormA);
$removeFormA.bind('click', function(e) {
e.preventDefault();
$tagFormLi.remove();
});
}
jQuery(document).ready(function() {
photoCollectionHolder = $('#photos');
addPhotoLink = $('<br class="clear" /><a href="#" class="plain button medium green">Dodaj zdjęcie</a>');
$newPhotoLinkLi = $('<li></li>').append(addPhotoLink);
photoCollectionHolder.find('li').each(function() {
addTagFormDeleteLink($(this));
});
photoCollectionHolder.append($newPhotoLinkLi);
addPhotoLink.bind('click', function(e) {
e.preventDefault();
addTagForm();
});
});
|
import Hook from 'util/hook'
import schemaGen from './gensrc/schema'
import resolverGen from './gensrc/resolver'
import schema from './schema'
import resolver from './resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import {ObjectId} from "mongodb";
import {CAPABILITY_SEND_NEWSLETTER} from './constants'
// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
deepMergeToFirst(resolvers, resolver(db), resolverGen(db))
})
// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
schemas.push(schemaGen)
schemas.push(schema)
})
// Hook to add or modify user roles
Hook.on('createUserRoles', ({userRoles}) => {
userRoles.forEach(userRole => {
if (['administrator', 'editor', 'author'].indexOf(userRole.name) >= 0) {
console.log(`Add capabilities "${CAPABILITY_SEND_NEWSLETTER}" for user role "${userRole.name}"`)
userRole.capabilities.push(CAPABILITY_SEND_NEWSLETTER)
}
})
})
// Hook to add mongodb schema
Hook.on('NewUserCreated', async ({meta, email, insertResult, db, language}) => {
if (insertResult.insertedId) {
if (meta && meta.newsletter) {
const user = (await db.collection('User').findOne({email}))
// insert or update
const data = {
email, list: (meta.newsletterList ? meta.newsletterList.reduce((o, id) => {
o.push(ObjectId(id));
return o
}, []) : []), confirmed: false, state: 'optin'
}
if (meta.newsletterLocation) {
data.location = meta.newsletterLocation
}
if (user && user._id) {
data.account = user._id
}
if( language ){
data.language = language
}
const insertResult = await db.collection('NewsletterSubscriber').insertOne(data)
}
}
})
Hook.on('UserConfirmed', async ({context,db, user}) => {
if (user && user.meta && user.meta.newsletter) {
// also confirm newsletter
resolver(db).Query.confirmNewsletter({email: user.email, location: user.meta.newsletterLocation}, {context})
}
})
|
'use strict';
var ANCESTRY_FILE = require('./ancestry.js');
var ancestry = JSON.parse(ANCESTRY_FILE);
var theSet = ['Carel Haverbeke', 'Maria van Brussel',
'Donald Duck'];
function isInSet(set, person) {
return set.indexOf(person.name) > -1;
}
console.log(ancestry.filter(function(person) {
return isInSet(theSet, person);
}));
console.log(ancestry.filter(isInSet.bind(null, theSet)));
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
build: {
src: 'presence.js',
dest: 'presence.min.js'
}
},
jshint: {
src: ['presence.js']
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['jshint']);
grunt.registerTask('build', ['uglify', 'jshint']);
};
|
(function() {
'use strict';
/* Services */
angular.module('myApp.services', [])
// put your services here!
// .service('serviceName', ['dependency', function(dependency) {}]);
.factory('messageList', ['fbutil', function(fbutil) {
return fbutil.syncArray('messages', {limit: 10, endAt: null});
}])
.factory('activeUser', ['$rootScope','fbutil', 'simpleLogin', function($rootScope, fbutil, simpleLogin){
simpleLogin.getUser().then(function(user, error) {
if (user) {
$rootScope.$emit("login", user);
}
else if (error) {
$rootScope.$emit("loginError", error);
}
else {
$rootScope.$emit("logout");
console.log("NÃO FEZ PORRA NENHUMA");
}
});
}]);
})();
|
var searchData=
[
['select',['select',['../class_database.html#a1efc6b974510d4c668660f1abe184182',1,'Database\select()'],['../interface_database_interface.html#a1efc6b974510d4c668660f1abe184182',1,'DatabaseInterface\select()'],['../class_my_s_q_l_database.html#a1efc6b974510d4c668660f1abe184182',1,'MySQLDatabase\select()'],['../class_postgre_s_q_l_database.html#a1efc6b974510d4c668660f1abe184182',1,'PostgreSQLDatabase\select()'],['../class_s_q_lite_database.html#a1efc6b974510d4c668660f1abe184182',1,'SQLiteDatabase\select()']]],
['sort_5fasc',['SORT_ASC',['../class_database.html#a9517f2622dfc5fbb0cc64feef247eb06',1,'Database\SORT_ASC()'],['../class_my_s_q_l_database.html#a9517f2622dfc5fbb0cc64feef247eb06',1,'MySQLDatabase\SORT_ASC()'],['../class_postgre_s_q_l_database.html#a9517f2622dfc5fbb0cc64feef247eb06',1,'PostgreSQLDatabase\SORT_ASC()'],['../class_s_q_lite_database.html#a9517f2622dfc5fbb0cc64feef247eb06',1,'SQLiteDatabase\SORT_ASC()']]],
['sort_5fdesc',['SORT_DESC',['../class_database.html#a0e633ab431ae1e5cc483a37cfe73bb09',1,'Database\SORT_DESC()'],['../class_my_s_q_l_database.html#a0e633ab431ae1e5cc483a37cfe73bb09',1,'MySQLDatabase\SORT_DESC()'],['../class_postgre_s_q_l_database.html#a0e633ab431ae1e5cc483a37cfe73bb09',1,'PostgreSQLDatabase\SORT_DESC()'],['../class_s_q_lite_database.html#a0e633ab431ae1e5cc483a37cfe73bb09',1,'SQLiteDatabase\SORT_DESC()']]],
['sort_5fnone',['SORT_NONE',['../class_database.html#af3826c676cb54905f393f9d1f7ad48ea',1,'Database\SORT_NONE()'],['../class_my_s_q_l_database.html#af3826c676cb54905f393f9d1f7ad48ea',1,'MySQLDatabase\SORT_NONE()'],['../class_postgre_s_q_l_database.html#af3826c676cb54905f393f9d1f7ad48ea',1,'PostgreSQLDatabase\SORT_NONE()'],['../class_s_q_lite_database.html#af3826c676cb54905f393f9d1f7ad48ea',1,'SQLiteDatabase\SORT_NONE()']]],
['sqlitecondition',['SQLiteCondition',['../class_s_q_lite_condition.html',1,'']]],
['sqlitecondition_2ephp',['SQLiteCondition.php',['../_s_q_lite_condition_8php.html',1,'']]],
['sqlitedatabase',['SQLiteDatabase',['../class_s_q_lite_database.html',1,'']]],
['sqlitedatabase_2ephp',['SQLiteDatabase.php',['../_s_q_lite_database_8php.html',1,'']]],
['sqliteexception',['SQLiteException',['../class_s_q_lite_exception.html',1,'']]],
['sqliteexception_2ephp',['SQLiteException.php',['../_s_q_lite_exception_8php.html',1,'']]]
];
|
import r from 'restructure';
import fs from 'fs';
var fontkit = {};
export default fontkit;
fontkit.logErrors = false;
let formats = [];
fontkit.registerFormat = function(format) {
formats.push(format);
};
fontkit.openSync = function(filename, postscriptName) {
if (BROWSER) {
throw new Error('fontkit.openSync unavailable for browser build');
}
let buffer = fs.readFileSync(filename);
return fontkit.create(buffer, postscriptName);
};
fontkit.open = function(filename, postscriptName, callback) {
if (BROWSER) {
throw new Error('fontkit.open unavailable for browser build');
}
if (typeof postscriptName === 'function') {
callback = postscriptName;
postscriptName = null;
}
fs.readFile(filename, function(err, buffer) {
if (err) { return callback(err); }
try {
var font = fontkit.create(buffer, postscriptName);
} catch (e) {
return callback(e);
}
return callback(null, font);
});
return;
};
fontkit.create = function(buffer, postscriptName) {
for (let i = 0; i < formats.length; i++) {
let format = formats[i];
if (format.probe(buffer)) {
let font = new format(new r.DecodeStream(buffer));
if (postscriptName) {
return font.getFont(postscriptName);
}
return font;
}
}
throw new Error('Unknown font format');
};
fontkit.defaultLanguage = 'en';
fontkit.setDefaultLanguage = function(lang = 'en') {
fontkit.defaultLanguage = lang;
};
|
exports.port = 8080;
exports.host = '192.168.216.2';
|
const hexToBuf = hex => {
for (var bytes = [], c = 0; c < hex.length; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return new Uint8Array(bytes);
};
const bufToHex = buf => {
let byteArray = new Uint8Array(buf),
hexString = '',
nextHexByte;
for (let i=0; i<byteArray.byteLength; i++) {
nextHexByte = byteArray[i].toString(16);
if (nextHexByte.length < 2) {
nextHexByte = '0' + nextHexByte;
}
hexString += nextHexByte;
}
return hexString;
};
const strToBuf = str => (new TextEncoder().encode(str));
const bufToStr = str => (new TextDecoder().decode(str));
const strToB64 = str => btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => String.fromCharCode('0x' + p1)));
const b64ToStr = str => decodeURIComponent(Array.prototype.map.call(atob(str), c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
const bufToB64 = buf => btoa(Array.prototype.map.call(buf, ch => String.fromCharCode(ch)).join(''));
const b64ToBuf = b64 => {
const binstr = atob(b64),
buf = new Uint8Array(binstr.length);
Array.prototype.forEach.call(binstr, (ch, i) => {
buf[i] = ch.charCodeAt(0);
});
return buf;
}
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, '\\$&');
let regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
SESSION_LOADED: 'SESSION_LOADED',
DATA_UPDATE: 'DATA_UPDATE',
SOCKET_CONNECTED: 'SOCKET_CONNECTED',
SOCKET_DISCONNECTED: 'SOCKET_DISCONNECTED'
};
|
define(['css!index1.css', 'css!index2.css'], function() {
return {};
});
|
class Stringer {
constructor(initialString, length) {
this.initialString = initialString;
this.length = Number(length);
}
get innerString() {
return this.initialString;
}
get innerLength() {
return this.length;
}
set innerLength(value) {
this.length = Math.max(0, value);
}
increase(length) {
this.innerLength = this.innerLength + length;
}
decrease(length) {
this.innerLength = this.innerLength - length;
}
toString() {
if (this.innerString.length > this.innerLength) {
return this.innerString.substr(0, this.innerLength) + '...';
}
return this.innerString;
}
}
|
"use strict";
module.exports = () => {
const get = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
return {
get
};
};
|
export var ACTION_MOUSE = 'mouse';
export var ACTION_KEYBOARD = 'keyboard';
export var ACTION_GAMEPAD = 'gamepad';
export var AXIS_MOUSE_X = 'mousex';
export var AXIS_MOUSE_Y = 'mousey';
export var AXIS_PAD_L_X = 'padlx';
export var AXIS_PAD_L_Y = 'padly';
export var AXIS_PAD_R_X = 'padrx';
export var AXIS_PAD_R_Y = 'padry';
export var AXIS_KEY = 'key';
/**
* @constant
* @type {string}
* @name pc.EVENT_KEYDOWN
* @description Name of event fired when a key is pressed.
*/
export var EVENT_KEYDOWN = 'keydown';
/**
* @constant
* @type {string}
* @name pc.EVENT_KEYUP
* @description Name of event fired when a key is released.
*/
export var EVENT_KEYUP = 'keyup';
/**
* @constant
* @type {string}
* @name pc.EVENT_MOUSEDOWN
* @description Name of event fired when a mouse button is pressed.
*/
export var EVENT_MOUSEDOWN = "mousedown";
/**
* @constant
* @type {string}
* @name pc.EVENT_MOUSEMOVE
* @description Name of event fired when the mouse is moved.
*/
export var EVENT_MOUSEMOVE = "mousemove";
/**
* @constant
* @type {string}
* @name pc.EVENT_MOUSEUP
* @description Name of event fired when a mouse button is released.
*/
export var EVENT_MOUSEUP = "mouseup";
/**
* @constant
* @type {string}
* @name pc.EVENT_MOUSEWHEEL
* @description Name of event fired when the mouse wheel is rotated.
*/
export var EVENT_MOUSEWHEEL = "mousewheel";
/**
* @constant
* @type {string}
* @name pc.EVENT_TOUCHSTART
* @description Name of event fired when a new touch occurs. For example, a finger is placed on the device.
*/
export var EVENT_TOUCHSTART = 'touchstart';
/**
* @constant
* @type {string}
* @name pc.EVENT_TOUCHEND
* @description Name of event fired when touch ends. For example, a finger is lifted off the device.
*/
export var EVENT_TOUCHEND = 'touchend';
/**
* @constant
* @type {string}
* @name pc.EVENT_TOUCHMOVE
* @description Name of event fired when a touch moves.
*/
export var EVENT_TOUCHMOVE = 'touchmove';
/**
* @constant
* @type {string}
* @name pc.EVENT_TOUCHCANCEL
* @description Name of event fired when a touch point is interrupted in some way.
* The exact reasons for cancelling a touch can vary from device to device.
* For example, a modal alert pops up during the interaction; the touch point leaves the document area,
* or there are more touch points than the device supports, in which case the earliest touch point is canceled.
*/
export var EVENT_TOUCHCANCEL = 'touchcancel';
/**
* @constant
* @type {string}
* @name pc.EVENT_SELECT
* @description Name of event fired when a new xr select occurs. For example, primary trigger was pressed.
*/
export var EVENT_SELECT = 'select';
/**
* @constant
* @type {string}
* @name pc.EVENT_SELECTSTART
* @description Name of event fired when a new xr select starts. For example, primary trigger is now pressed.
*/
export var EVENT_SELECTSTART = 'selectstart';
/**
* @constant
* @type {string}
* @name pc.EVENT_SELECTEND
* @description Name of event fired when xr select ends. For example, a primary trigger is now released.
*/
export var EVENT_SELECTEND = 'selectend';
/**
* @constant
* @type {number}
* @name pc.KEY_BACKSPACE
*/
export var KEY_BACKSPACE = 8;
/**
* @constant
* @type {number}
* @name pc.KEY_TAB
*/
export var KEY_TAB = 9;
/**
* @constant
* @type {number}
* @name pc.KEY_RETURN
*/
export var KEY_RETURN = 13;
/**
* @constant
* @type {number}
* @name pc.KEY_ENTER
*/
export var KEY_ENTER = 13;
/**
* @constant
* @type {number}
* @name pc.KEY_SHIFT
*/
export var KEY_SHIFT = 16;
/**
* @constant
* @type {number}
* @name pc.KEY_CONTROL
*/
export var KEY_CONTROL = 17;
/**
* @constant
* @type {number}
* @name pc.KEY_ALT
*/
export var KEY_ALT = 18;
/**
* @constant
* @type {number}
* @name pc.KEY_PAUSE
*/
export var KEY_PAUSE = 19;
/**
* @constant
* @type {number}
* @name pc.KEY_CAPS_LOCK
*/
export var KEY_CAPS_LOCK = 20;
/**
* @constant
* @type {number}
* @name pc.KEY_ESCAPE
*/
export var KEY_ESCAPE = 27;
/**
* @constant
* @type {number}
* @name pc.KEY_SPACE
*/
export var KEY_SPACE = 32;
/**
* @constant
* @type {number}
* @name pc.KEY_PAGE_UP
*/
export var KEY_PAGE_UP = 33;
/**
* @constant
* @type {number}
* @name pc.KEY_PAGE_DOWN
*/
export var KEY_PAGE_DOWN = 34;
/**
* @constant
* @type {number}
* @name pc.KEY_END
*/
export var KEY_END = 35;
/**
* @constant
* @type {number}
* @name pc.KEY_HOME
*/
export var KEY_HOME = 36;
/**
* @constant
* @type {number}
* @name pc.KEY_LEFT
*/
export var KEY_LEFT = 37;
/**
* @constant
* @type {number}
* @name pc.KEY_UP
*/
export var KEY_UP = 38;
/**
* @constant
* @type {number}
* @name pc.KEY_RIGHT
*/
export var KEY_RIGHT = 39;
/**
* @constant
* @type {number}
* @name pc.KEY_DOWN
*/
export var KEY_DOWN = 40;
/**
* @constant
* @type {number}
* @name pc.KEY_PRINT_SCREEN
*/
export var KEY_PRINT_SCREEN = 44;
/**
* @constant
* @type {number}
* @name pc.KEY_INSERT
*/
export var KEY_INSERT = 45;
/**
* @constant
* @type {number}
* @name pc.KEY_DELETE
*/
export var KEY_DELETE = 46;
/**
* @constant
* @type {number}
* @name pc.KEY_0
*/
export var KEY_0 = 48;
/**
* @constant
* @type {number}
* @name pc.KEY_1
*/
export var KEY_1 = 49;
/**
* @constant
* @type {number}
* @name pc.KEY_2
*/
export var KEY_2 = 50;
/**
* @constant
* @type {number}
* @name pc.KEY_3
*/
export var KEY_3 = 51;
/**
* @constant
* @type {number}
* @name pc.KEY_4
*/
export var KEY_4 = 52;
/**
* @constant
* @type {number}
* @name pc.KEY_5
*/
export var KEY_5 = 53;
/**
* @constant
* @type {number}
* @name pc.KEY_6
*/
export var KEY_6 = 54;
/**
* @constant
* @type {number}
* @name pc.KEY_7
*/
export var KEY_7 = 55;
/**
* @constant
* @type {number}
* @name pc.KEY_8
*/
export var KEY_8 = 56;
/**
* @constant
* @type {number}
* @name pc.KEY_9
*/
export var KEY_9 = 57;
/**
* @constant
* @type {number}
* @name pc.KEY_SEMICOLON
*/
export var KEY_SEMICOLON = 59;
/**
* @constant
* @type {number}
* @name pc.KEY_EQUAL
*/
export var KEY_EQUAL = 61;
/**
* @constant
* @type {number}
* @name pc.KEY_A
*/
export var KEY_A = 65;
/**
* @constant
* @type {number}
* @name pc.KEY_B
*/
export var KEY_B = 66;
/**
* @constant
* @type {number}
* @name pc.KEY_C
*/
export var KEY_C = 67;
/**
* @constant
* @type {number}
* @name pc.KEY_D
*/
export var KEY_D = 68;
/**
* @constant
* @type {number}
* @name pc.KEY_E
*/
export var KEY_E = 69;
/**
* @constant
* @type {number}
* @name pc.KEY_F
*/
export var KEY_F = 70;
/**
* @constant
* @type {number}
* @name pc.KEY_G
*/
export var KEY_G = 71;
/**
* @constant
* @type {number}
* @name pc.KEY_H
*/
export var KEY_H = 72;
/**
* @constant
* @type {number}
* @name pc.KEY_I
*/
export var KEY_I = 73;
/**
* @constant
* @type {number}
* @name pc.KEY_J
*/
export var KEY_J = 74;
/**
* @constant
* @type {number}
* @name pc.KEY_K
*/
export var KEY_K = 75;
/**
* @constant
* @type {number}
* @name pc.KEY_L
*/
export var KEY_L = 76;
/**
* @constant
* @type {number}
* @name pc.KEY_M
*/
export var KEY_M = 77;
/**
* @constant
* @type {number}
* @name pc.KEY_N
*/
export var KEY_N = 78;
/**
* @constant
* @type {number}
* @name pc.KEY_O
*/
export var KEY_O = 79;
/**
* @constant
* @type {number}
* @name pc.KEY_P
*/
export var KEY_P = 80;
/**
* @constant
* @type {number}
* @name pc.KEY_Q
*/
export var KEY_Q = 81;
/**
* @constant
* @type {number}
* @name pc.KEY_R
*/
export var KEY_R = 82;
/**
* @constant
* @type {number}
* @name pc.KEY_S
*/
export var KEY_S = 83;
/**
* @constant
* @type {number}
* @name pc.KEY_T
*/
export var KEY_T = 84;
/**
* @constant
* @type {number}
* @name pc.KEY_U
*/
export var KEY_U = 85;
/**
* @constant
* @type {number}
* @name pc.KEY_V
*/
export var KEY_V = 86;
/**
* @constant
* @type {number}
* @name pc.KEY_W
*/
export var KEY_W = 87;
/**
* @constant
* @type {number}
* @name pc.KEY_X
*/
export var KEY_X = 88;
/**
* @constant
* @type {number}
* @name pc.KEY_Y
*/
export var KEY_Y = 89;
/**
* @constant
* @type {number}
* @name pc.KEY_Z
*/
export var KEY_Z = 90;
/**
* @constant
* @type {number}
* @name pc.KEY_WINDOWS
*/
export var KEY_WINDOWS = 91;
/**
* @constant
* @type {number}
* @name pc.KEY_CONTEXT_MENU
*/
export var KEY_CONTEXT_MENU = 93;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_0
*/
export var KEY_NUMPAD_0 = 96;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_1
*/
export var KEY_NUMPAD_1 = 97;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_2
*/
export var KEY_NUMPAD_2 = 98;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_3
*/
export var KEY_NUMPAD_3 = 99;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_4
*/
export var KEY_NUMPAD_4 = 100;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_5
*/
export var KEY_NUMPAD_5 = 101;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_6
*/
export var KEY_NUMPAD_6 = 102;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_7
*/
export var KEY_NUMPAD_7 = 103;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_8
*/
export var KEY_NUMPAD_8 = 104;
/**
* @constant
* @type {number}
* @name pc.KEY_NUMPAD_9
*/
export var KEY_NUMPAD_9 = 105;
/**
* @constant
* @type {number}
* @name pc.KEY_MULTIPLY
*/
export var KEY_MULTIPLY = 106;
/**
* @constant
* @type {number}
* @name pc.KEY_ADD
*/
export var KEY_ADD = 107;
/**
* @constant
* @type {number}
* @name pc.KEY_SEPARATOR
*/
export var KEY_SEPARATOR = 108;
/**
* @constant
* @type {number}
* @name pc.KEY_SUBTRACT
*/
export var KEY_SUBTRACT = 109;
/**
* @constant
* @type {number}
* @name pc.KEY_DECIMAL
*/
export var KEY_DECIMAL = 110;
/**
* @constant
* @type {number}
* @name pc.KEY_DIVIDE
*/
export var KEY_DIVIDE = 111;
/**
* @constant
* @type {number}
* @name pc.KEY_F1
*/
export var KEY_F1 = 112;
/**
* @constant
* @type {number}
* @name pc.KEY_F2
*/
export var KEY_F2 = 113;
/**
* @constant
* @type {number}
* @name pc.KEY_F3
*/
export var KEY_F3 = 114;
/**
* @constant
* @type {number}
* @name pc.KEY_F4
*/
export var KEY_F4 = 115;
/**
* @constant
* @type {number}
* @name pc.KEY_F5
*/
export var KEY_F5 = 116;
/**
* @constant
* @type {number}
* @name pc.KEY_F6
*/
export var KEY_F6 = 117;
/**
* @constant
* @type {number}
* @name pc.KEY_F7
*/
export var KEY_F7 = 118;
/**
* @constant
* @type {number}
* @name pc.KEY_F8
*/
export var KEY_F8 = 119;
/**
* @constant
* @type {number}
* @name pc.KEY_F9
*/
export var KEY_F9 = 120;
/**
* @constant
* @type {number}
* @name pc.KEY_F10
*/
export var KEY_F10 = 121;
/**
* @constant
* @type {number}
* @name pc.KEY_F11
*/
export var KEY_F11 = 122;
/**
* @constant
* @type {number}
* @name pc.KEY_F12
*/
export var KEY_F12 = 123;
/**
* @constant
* @type {number}
* @name pc.KEY_COMMA
*/
export var KEY_COMMA = 188;
/**
* @constant
* @type {number}
* @name pc.KEY_PERIOD
*/
export var KEY_PERIOD = 190;
/**
* @constant
* @type {number}
* @name pc.KEY_SLASH
*/
export var KEY_SLASH = 191;
/**
* @constant
* @type {number}
* @name pc.KEY_OPEN_BRACKET
*/
export var KEY_OPEN_BRACKET = 219;
/**
* @constant
* @type {number}
* @name pc.KEY_BACK_SLASH
*/
export var KEY_BACK_SLASH = 220;
/**
* @constant
* @type {number}
* @name pc.KEY_CLOSE_BRACKET
*/
export var KEY_CLOSE_BRACKET = 221;
/**
* @constant
* @type {number}
* @name pc.KEY_META
*/
export var KEY_META = 224;
/**
* @constant
* @type {number}
* @name pc.MOUSEBUTTON_NONE
* @description No mouse buttons pressed.
*/
export var MOUSEBUTTON_NONE = -1;
/**
* @constant
* @type {number}
* @name pc.MOUSEBUTTON_LEFT
* @description The left mouse button.
*/
export var MOUSEBUTTON_LEFT = 0;
/**
* @constant
* @type {number}
* @name pc.MOUSEBUTTON_MIDDLE
* @description The middle mouse button.
*/
export var MOUSEBUTTON_MIDDLE = 1;
/**
* @constant
* @type {number}
* @name pc.MOUSEBUTTON_RIGHT
* @description The right mouse button.
*/
export var MOUSEBUTTON_RIGHT = 2;
/**
* @constant
* @type {number}
* @name pc.PAD_1
* @description Index for pad 1.
*/
export var PAD_1 = 0;
/**
* @constant
* @type {number}
* @name pc.PAD_2
* @description Index for pad 2.
*/
export var PAD_2 = 1;
/**
* @constant
* @type {number}
* @name pc.PAD_3
* @description Index for pad 3.
*/
export var PAD_3 = 2;
/**
* @constant
* @type {number}
* @name pc.PAD_4
* @description Index for pad 4.
*/
export var PAD_4 = 3;
/**
* @constant
* @type {number}
* @name pc.PAD_FACE_1
* @description The first face button, from bottom going clockwise.
*/
export var PAD_FACE_1 = 0;
/**
* @constant
* @type {number}
* @name pc.PAD_FACE_2
* @description The second face button, from bottom going clockwise.
*/
export var PAD_FACE_2 = 1;
/**
* @constant
* @type {number}
* @name pc.PAD_FACE_3
* @description The third face button, from bottom going clockwise.
*/
export var PAD_FACE_3 = 2;
/**
* @constant
* @type {number}
* @name pc.PAD_FACE_4
* @description The fourth face button, from bottom going clockwise.
*/
export var PAD_FACE_4 = 3;
/**
* @constant
* @type {number}
* @name pc.PAD_L_SHOULDER_1
* @description The first shoulder button on the left.
*/
export var PAD_L_SHOULDER_1 = 4;
/**
* @constant
* @type {number}
* @name pc.PAD_R_SHOULDER_1
* @description The first shoulder button on the right.
*/
export var PAD_R_SHOULDER_1 = 5;
/**
* @constant
* @type {number}
* @name pc.PAD_L_SHOULDER_2
* @description The second shoulder button on the left.
*/
export var PAD_L_SHOULDER_2 = 6;
/**
* @constant
* @type {number}
* @name pc.PAD_R_SHOULDER_2
* @description The second shoulder button on the right.
*/
export var PAD_R_SHOULDER_2 = 7;
/**
* @constant
* @type {number}
* @name pc.PAD_SELECT
* @description The select button.
*/
export var PAD_SELECT = 8;
/**
* @constant
* @type {number}
* @name pc.PAD_START
* @description The start button.
*/
export var PAD_START = 9;
/**
* @constant
* @type {number}
* @name pc.PAD_L_STICK_BUTTON
* @description The button when depressing the left analogue stick.
*/
export var PAD_L_STICK_BUTTON = 10;
/**
* @constant
* @type {number}
* @name pc.PAD_R_STICK_BUTTON
* @description The button when depressing the right analogue stick.
*/
export var PAD_R_STICK_BUTTON = 11;
/**
* @constant
* @type {number}
* @name pc.PAD_UP
* @description Direction pad up.
*/
export var PAD_UP = 12;
/**
* @constant
* @type {number}
* @name pc.PAD_DOWN
* @description Direction pad down.
*/
export var PAD_DOWN = 13;
/**
* @constant
* @type {number}
* @name pc.PAD_LEFT
* @description Direction pad left.
*/
export var PAD_LEFT = 14;
/**
* @constant
* @type {number}
* @name pc.PAD_RIGHT
* @description Direction pad right.
*/
export var PAD_RIGHT = 15;
/**
* @constant
* @type {number}
* @name pc.PAD_VENDOR
* @description Vendor specific button.
*/
export var PAD_VENDOR = 16;
/**
* @constant
* @type {number}
* @name pc.PAD_L_STICK_X
* @description Horizontal axis on the left analogue stick.
*/
export var PAD_L_STICK_X = 0;
/**
* @constant
* @type {number}
* @name pc.PAD_L_STICK_Y
* @description Vertical axis on the left analogue stick.
*/
export var PAD_L_STICK_Y = 1;
/**
* @constant
* @type {number}
* @name pc.PAD_R_STICK_X
* @description Horizontal axis on the right analogue stick.
*/
export var PAD_R_STICK_X = 2;
/**
* @constant
* @type {number}
* @name pc.PAD_R_STICK_Y
* @description Vertical axis on the right analogue stick.
*/
export var PAD_R_STICK_Y = 3;
|
'use strict';
let path = require('path');
let webpack = require('webpack');
let baseConfig = require('./base');
let defaultSettings = require('./defaults');
// Add needed plugins here
let BowerWebpackPlugin = require('bower-webpack-plugin');
let config = Object.assign({}, baseConfig, {
entry: [
'webpack-dev-server/client?http://127.0.0.1:' + defaultSettings.port,
'webpack/hot/only-dev-server',
'./src/index'
],
cache: true,
devtool: 'eval-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new BowerWebpackPlugin({
searchResolveModulesDirectories: false
})
],
module: defaultSettings.getDefaultModules()
});
// Add needed loaders to the defaults here
config.module.loaders.push({
test: /\.(js|jsx)$/,
loader: 'react-hot!babel-loader',
include: [].concat(
config.additionalPaths,
[ path.join(__dirname, '/../src') ]
)
},{
test: /\.css$/,
loader: 'autoprefixer-loader'
}, {
test: /\.sass/,
loader: 'autoprefixer-loader'
},
{
test: /\.(png|jpg|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=8192'
});
module.exports = config;
|
'use strict';
let expect = require('chai').expect,
Q = require('q'),
makeServer = require('./makeServer'),
client = require('./client'),
routes = require('../index')
describe('route configurations', () => {
let server = null
let customRoutes = routes.configure({
errorHandler: (res, error) => res.json({code: error.code})
})
before((done) => {
server = makeServer((app) => {
app.get('/error', customRoutes.json(() => Q.fcall(() => { throw {code: 401} })))
}, done)
})
after((done) => {
server.close(done)
})
it('support default value overriding', (done) => {
client.get('/error')
.get('body')
.then(JSON.parse)
.then(body => expect(body.code).to.equal(401))
.then(bare(done))
.done()
})
})
function bare(fn) {
return function() { fn() }
}
|
import React from "react";
const education = {
year: "2007-2012",
title: `Victoria University of Wellington`,
university: `Bachelor of Engineering, Software Engineering, First Class Honours`,
};
export default function Education() {
return (
<div className="educationContent">
<div className="root">
<h1>Education</h1>
<div className="educationContainer">
<h2 className="content">{education.university}</h2>
<h3 className="content">{education.title}</h3>
<em className="content">{education.year}</em>
</div>
</div>
</div>
);
}
|
'use strict'
const config = require('./config')
const db = require('./db')
const app = require('../http/app')
console.log('#'.repeat(40))
console.log((new Date()).toUTCString())
db.init(config.dbUrl, 'shortlinks').then(() => {
app.listen(config.port, () => {
console.log('Server listening on port ' + config.port + '…')
})
}).catch((error) => {
console.log('>>> Error during database initialization:\n')
console.log(error)
process.exit(1)
})
|
Meteor.publish('directory', function() {
return Lists.find({});
});
Meteor.publish('items', function(listId) {
check(listId, String);
return Items.find({listId: listId});
});
Meteor.publish('comments', function(listId) {
check(listId, String);
var list = Lists.findOne({_id: listId});
// no comments for your own list
if (this.userId == list.userId) {
this.ready();
return null;
} else {
return Comments.find({listId: listId});
}
});
Meteor.publish('users', function() {
return Meteor.users.find({});
});
|
var searchApp = angular.module('searchApp');
searchApp.filter('showAllResults', function(){
return function(input, first, last, hideToggle){
if (!input || !input.length) return;
if (hideToggle)
return input.slice(first, last);
else
return input;
}
})
|
angular.module('Documentation', [])
.controller('MainController', function ($scope) {
});
|
import { __awaiter, __generator } from "tslib";
import { bufferToImage } from './bufferToImage';
import { fetchOrThrow } from './fetchOrThrow';
export function fetchImage(uri) {
return __awaiter(this, void 0, void 0, function () {
var res, blob;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetchOrThrow(uri)];
case 1:
res = _a.sent();
return [4 /*yield*/, (res).blob()];
case 2:
blob = _a.sent();
if (!blob.type.startsWith('image/')) {
throw new Error("fetchImage - expected blob type to be of type image/*, instead have: " + blob.type + ", for url: " + res.url);
}
return [2 /*return*/, bufferToImage(blob)];
}
});
});
}
//# sourceMappingURL=fetchImage.js.map
|
var Transport = require('./redis-queue-transport')
var Seneca = require('seneca')
Seneca({
default_plugins: {
transport: true
}
})
.use(Transport)
.client({ host: 'server', port: 8000 })
.act('color:red', console.log)
|
import React from "react";
import { connect } from "react-redux";
import {
selectCurrentPage,
selectHeaderLinks,
} from "redux/selectors/navigation";
import { doNavigate } from "redux/actions/navigation";
import SubHeader from "./view";
const select = (state, props) => ({
currentPage: selectCurrentPage(state),
subLinks: selectHeaderLinks(state),
});
const perform = dispatch => ({
navigate: path => dispatch(doNavigate(path)),
});
export default connect(select, perform)(SubHeader);
|
var express = require('express');
var app = module.exports = express();
var fs = require('fs');
var mongoose = require('mongoose');
var configFile = './../config.json';
var config = require(configFile);
app.get('/settings/', function(req, res){
var requestApi = req.query.api;
if(requestApi != config.config.private_key){
res.send(403);
}
res.send({cron: config.cron});
});
app.post('/settings/', function(req,res){
var cronName = req.query.cronName;
var cronDesc = req.query.cronDesc;
var cronRule = req.query.cronRule;
var cronScript=req.query.cronScript;
var cronType = req.query.cronType;
var requestApi = req.query.api;
if(requestApi != config.config.private_key){
res.send(403);
}
configContent = fs.readFileSync('config.json');
configContent = JSON.parse(configContent);
configContent.cron[cronName] = { name: cronName, script: cronScript, rule: cronRule, description: cronDesc, type: cronType};
fs.writeFileSync('config.json', JSON.stringify(configContent));
config = configContent;
res.send({error: "Success"});
});
app.put('/settings/', function(req,res){
var cronName = req.query.cronName;
var cronDesc = req.query.cronDesc;
var cronRule = req.query.cronRule;
var cronScript=req.query.cronScript;
var cronType = req.query.cronType;
var requestApi = req.query.api;
if(requestApi != config.config.private_key){
res.send(403);
}
configContent = fs.readFileSync('config.json');
configContent = JSON.parse(configContent);
configContent.cron[cronName].name = cronName;
configContent.cron[cronName].rule = cronRule;
configContent.cron[cronName].description = cronDesc;
configContent.cron[cronName].script = cronScript;
configContent.cron[cronName].type = cronType;
console.log("CronType: "+cronType);
fs.writeFileSync('config.json', JSON.stringify(configContent));
config = configContent;
res.send({error: "Success"});
});
app.delete('/settings/', function(req,res){
var cronName = req.query.cronName;
var requestApi = req.query.api;
if(requestApi != config.config.private_key){
res.send(403);
}
configContent = fs.readFileSync('config.json');
configContent = JSON.parse(configContent);
configContent.cron[cronName] = null;
delete configContent.cron[cronName];
fs.writeFileSync('config.json', JSON.stringify(configContent));
config = configContent;
res.send({error: "Success"});
});
app.delete('/settings/', function(req,res){
var cronName = req.query.cronName;
var requestApi = req.query.api;
if(requestApi != config.config.private_key){
res.send(403);
}
});
|
var class_pathfinder_1_1_event_1_1_network_map_load_content_event =
[
[ "NetworkMapLoadContentEvent", "class_pathfinder_1_1_event_1_1_network_map_load_content_event.html#a086329ed48d7b2f6705ad7770b3ff90d", null ],
[ "NetMap", "class_pathfinder_1_1_event_1_1_network_map_load_content_event.html#af2ff4aea9af5d492762baf0ce7a82c26", null ]
];
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var auth = require('./routes/auth');
var app = express();
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/api/users', auth, users);
/* mysql connection */
var mysql = require('mysql');
var connection = mysql.createConnection({
host :'localhost',
port : 3306,
user : 'calmemo',
password : '00000123',
database:'calmemo'
});
connection.connect(function(err) {
if (err) {
console.error('mysql connection error');
console.error(err);
throw err;
}
});
// application -------------------------------------------------------------
app.get('*', function (req, res) {
// load the single view file
// (angular will handle the page changes on the front-end)
res.sendfile('./public/index.html');
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
});
module.exports = app;
|
'use strict'
module.exports = function (sequelize, DataTypes) {
var taxonomy = sequelize.define(
'taxonomy',
{
name: {
type: DataTypes.STRING,
comment: 'Scientific name of the recorded taxon',
allowNull: false,
unique: 'uq_name',
},
ncbi: {
type: DataTypes.INTEGER,
comment:
'Unique Identifier from the National Center for Biotechnology Information',
},
tsn: {
type: DataTypes.INTEGER,
comment:
'Unique identifier from the Integrated Taxonomic Information System',
},
eol: {
type: DataTypes.INTEGER,
comment: 'Unique identifier from the Encyclopedia of Life',
},
bold: {
type: DataTypes.INTEGER,
comment: 'Unique identifier from the Barcode of Life Database',
},
/* gbif: {
type: DataTypes.INTEGER,
comment: "Unique identifier from the GBIF infrastructure",
},
col: {
type: DataTypes.STRING,
comment: 'Unique identifier from the Catalog of Life infrastructure',
},
rank: {
type: DataTypes.ENUM,
comment: 'Taxonomic rank',
values: [
'kingdom',
'subkingdom',
'infrakingdom',
'superdivision',
'division',
'subdivision',
'phylum',
'subclass',
'class',
'superorder',
'order',
'superfamily',
'family',
'genus',
'subgenus',
'species',
'infraspecies',
],
},*/
},
{
underscored: true,
freezeTableName: true,
classMethods: {},
},
)
taxonomy.associate = function (models) {
taxonomy.hasMany(models.node, {
foreignKey: 'taxonomy_id',
})
taxonomy.hasMany(models.trait, {
onDelete: 'cascade',
foreignKey: 'taxonomy_id',
})
}
return taxonomy
}
|
/**
* jQuery extensions for:
* (a) Tracking properties of a given element
* (b) Tracking position of a given element
*/
define([ 'jquery'],
function($)
{
$(function()
{
$.fn.extend(
{
/**
* Allow the specified controls to track the CSS of a given control
* @param {JQuery Object} control
* @param {Object} options
* @returns {Array}
*/
ruTrack: function(control, options)
{
return this.each(function()
{
let _this = this;
var width = 9999999;
var set = function(target, $control, _options)
{
let $target = $(target);
var css = {};
$.each(_options, function(i, option)
{
var value = $control.css(option);
// Fix up for Safari width bug
if(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0 && option === 'width')
{
if($('html').width() < width)
{
value = parseInt(value) - (parseInt($control.css('padding-left')) + parseInt($control.css('padding-right')));
}
width = $('html').width();
}
css[option] = value;
});
$target.css(css);
};
set(_this, $(control), options);
$(window).bind('resize', function() {set(_this, $(control), options)});
});
},
/**
* Allow the specified controls to follow a given control
* @param {JQuery Object} control
* @param {Object} options
* @returns {Array}
*/
ruFollow: function(control, options) {
options.top = options.top || 0;
options.bottom = options.bottom || 0;
options.left = options.left || 0;
options.right = options.right || 0;
return this.each(function()
{
var set = function()
{
// Not required yet - so unimplemented
throw "Not implemented";
};
set();
$(window).bind('resize', set);
});
}
});
});
}
);
|
$(function () {
var $b = $('#builder');
QUnit.module('plugins.not-group', {
afterEach: function () {
$b.queryBuilder('destroy');
}
});
QUnit.test('Not checkbox', function (assert) {
$b.queryBuilder({
filters: basic_filters,
rules: basic_rules,
plugins: ['not-group']
});
assert.ok(
$b.find('[data-not=group]').length > 0,
'Should add "not" buttons"'
);
$('#builder_group_0>.rules-group-header [data-not=group]').trigger('click');
assert.ok(
$b.queryBuilder('getModel').not,
'The root group should have "not" flag set to true'
);
assert.ok(
$b.queryBuilder('getRules').not,
'The root json should have "not" flag set to true'
);
$b.queryBuilder('destroy');
$b.queryBuilder({
plugins: {
'not-group': {disable_template: true}
},
filters: basic_filters,
rules: basic_rules
});
assert.ok(
$b.find('[data-not="group"]').length === 0,
'Should not have added the button with disable_template=true'
);
});
QUnit.test('SQL export', function (assert) {
$b.queryBuilder({
filters: basic_filters,
rules: rules,
plugins: ['not-group']
});
assert.equal(
$b.queryBuilder('getSQL').sql,
sql,
'Should export SQL with NOT function'
);
});
QUnit.test('SQL import', function (assert) {
$b.queryBuilder({
filters: basic_filters,
plugins: ['not-group']
});
$b.queryBuilder('setRulesFromSQL', sql);
assert.rulesMatch(
$b.queryBuilder('getRules'),
rules,
'Should parse NOT SQL function'
);
$b.queryBuilder('setRulesFromSQL', sql2);
assert.rulesMatch(
$b.queryBuilder('getRules'),
rules2,
'Should parse NOT SQL function with only one rule'
);
$b.queryBuilder('setRulesFromSQL', sql3);
assert.rulesMatch(
$b.queryBuilder('getRules'),
rules3,
'Should parse NOT SQL function with same operation'
);
$b.queryBuilder('setRulesFromSQL', sql4);
assert.rulesMatch(
$b.queryBuilder('getRules'),
rules4,
'Should parse NOT SQL function with negated root group'
);
$b.queryBuilder('setRulesFromSQL', sql5);
assert.rulesMatch(
$b.queryBuilder('getRules'),
rules5,
'Should parse NOT SQL function with double negated root group'
);
});
QUnit.test('Mongo export', function (assert) {
$b.queryBuilder({
filters: basic_filters,
rules: rules,
plugins: ['not-group']
});
assert.deepEqual(
$b.queryBuilder('getMongo'),
mongo,
'Should export MongoDB with $nor function'
);
$b.queryBuilder('reset');
$b.queryBuilder('setRulesFromMongo', mongo);
assert.rulesMatch(
$b.queryBuilder('getRules'),
rules,
'Should parse $nor MongoDB function'
);
});
var rules = {
condition: 'OR',
not: false,
rules: [{
id: 'name',
operator: 'equal',
value: 'Mistic'
}, {
condition: 'AND',
not: true,
rules: [{
id: 'price',
operator: 'less',
value: 10.25
}, {
id: 'category',
field: 'category',
operator: 'in',
value: ['mo', 'mu']
}]
}]
};
var sql = 'name = \'Mistic\' OR ( NOT ( price < 10.25 AND category IN(\'mo\', \'mu\') ) ) ';
var rules2 = {
condition: 'OR',
not: false,
rules: [{
id: 'name',
operator: 'equal',
value: 'Mistic'
}, {
condition: 'AND',
not: true,
rules: [{
id: 'price',
operator: 'less',
value: 10.25
}]
}]
};
var sql2 = 'name = \'Mistic\' OR ( NOT ( price < 10.25 ) ) ';
var rules3 = {
condition: 'OR',
not: false,
rules: [{
id: 'name',
operator: 'equal',
value: 'Mistic'
}, {
condition: 'OR',
not: true,
rules: [{
id: 'price',
operator: 'less',
value: 10.25
}, {
id: 'category',
field: 'category',
operator: 'in',
value: ['mo', 'mu']
}]
}]
};
var sql3 = 'name = \'Mistic\' OR ( NOT ( price < 10.25 OR category IN(\'mo\', \'mu\') ) ) ';
var rules4 = {
condition: 'AND',
not: true,
rules: [{
id: 'price',
operator: 'less',
value: 10.25
}]
};
var sql4 = 'NOT ( price < 10.25 )';
var rules5 = {
condition: 'AND',
not: false,
rules: [{
condition: 'AND',
not: true,
rules: [{
id: 'price',
operator: 'less',
value: 10.25
}]
}, {
condition: 'AND',
not: true,
rules: [{
id: 'price',
operator: 'greater',
value: 20.5
}]
}]
};
var sql5 = 'NOT ( price < 10.25 ) AND NOT ( price > 20.5 )';
var mongo = {
"$or": [{
"name": "Mistic"
},
{
"$nor": [{
"$and": [{
"price": {"$lt": 10.25}
}, {
"category": {"$in": ["mo", "mu"]}
}]
}]
}]
};
});
|
describe("pgApexApp.page.CreatePageController", function() {
beforeEach(module("pgApexApp.page"));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
it("should populate $scope.routeParams with $routeParams", function() {
var injections = {
"$scope": {},
"$routeParams": {"applicationId": 123}
};
$controller("pgApexApp.page.PagesController", injections);
expect(injections.$scope.routeParams.applicationId).toEqual(123);
});
});
|
'use strict';
const {validDirectory, validFiles} = require('../data');
const {GIVEN, WHEN, THEN} = require('../steps');
/**
* @memberof tests.directory
* @function
* @name case5
* @description
* GIVEN the destination folder is removed<br>
* WHEH I want to render 1 directory<br>
* AND indicate the content file with --input<br>
* AND indicate the template directory with -t<br>
* AND indicate the destination directory with -o<br>
* THEN the command should not return any output<br>
* AND the command should not return any error<br>
* AND the rendered file should be the only in the destination directory<br>
* AND the rendered file should have expected name<br>
* AND the rendered file should have expected content<br>
*/
module.exports = () => {
it('case5', (done) => {
GIVEN.removeOutput().then(() => {
return WHEN.render('--input', validDirectory, '-t', '-o', false, '', '');
}).then(() => {
return THEN.readOutput(validFiles);
}).catch((err) => {
fail(err);
}).finally(done);
});
};
|
this will whrow error
|
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { BadRequest, BadSymbol, ExchangeError, ArgumentsRequired, AuthenticationError, InsufficientFunds, NotSupported, OrderNotFound, ExchangeNotAvailable, RateLimitExceeded, PermissionDenied, InvalidOrder, InvalidAddress, OnMaintenance, RequestTimeout, AccountSuspended, NetworkError, DDoSProtection, DuplicateOrderId, BadResponse } = require ('./base/errors');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class zb extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'zb',
'name': 'ZB',
'countries': [ 'CN' ],
'rateLimit': 100,
'version': 'v1',
'certified': true,
'pro': true,
'has': {
'CORS': undefined,
'spot': true,
'margin': undefined, // has but unimplemented
'swap': true,
'future': undefined,
'option': undefined,
'addMargin': true,
'cancelAllOrders': true,
'cancelOrder': true,
'createMarketOrder': undefined,
'createOrder': true,
'createReduceOnlyOrder': false,
'fetchBalance': true,
'fetchBorrowRate': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDepositAddresses': true,
'fetchDeposits': true,
'fetchFundingHistory': false,
'fetchFundingRate': true,
'fetchFundingRateHistory': true,
'fetchFundingRates': true,
'fetchLedger': true,
'fetchLeverage': false,
'fetchLeverageTiers': false,
'fetchMarketLeverageTiers': false,
'fetchMarkets': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchPosition': true,
'fetchPositions': true,
'fetchPositionsRisk': false,
'fetchPremiumIndexOHLCV': false,
'fetchTicker': true,
'fetchTickers': true,
'fetchTrades': true,
'fetchWithdrawals': true,
'reduceMargin': true,
'setLeverage': true,
'setMarginMode': false,
'setPositionMode': false,
'transfer': true,
'withdraw': true,
},
'timeframes': {
'1m': '1m',
'3m': '3m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'4h': '4h',
'6h': '6h',
'12h': '12h',
'1d': '1d',
'3d': '3d',
'5d': '5d',
'1w': '1w',
},
'exceptions': {
'ws': {
// '1000': ExchangeError, // The call is successful.
'1001': ExchangeError, // General error prompt
'1002': ExchangeError, // Internal Error
'1003': AuthenticationError, // Fail to verify
'1004': AuthenticationError, // The transaction password is locked
'1005': AuthenticationError, // Wrong transaction password, please check it and re-enter。
'1006': PermissionDenied, // Real-name authentication is pending approval or unapproved
'1007': ExchangeError, // Channel does not exist
'1009': OnMaintenance, // This interface is under maintenance
'1010': ExchangeNotAvailable, // Not available now
'1012': PermissionDenied, // Insufficient permissions
'1013': ExchangeError, // Cannot trade, please contact email: support@zb.cn for support.
'1014': ExchangeError, // Cannot sell during the pre-sale period
'2001': InsufficientFunds, // Insufficient CNY account balance
'2002': InsufficientFunds, // Insufficient BTC account balance
'2003': InsufficientFunds, // Insufficient LTC account balance
'2005': InsufficientFunds, // Insufficient ETH account balance
'2006': InsufficientFunds, // ETCInsufficient account balance
'2007': InsufficientFunds, // BTSInsufficient account balance
'2008': InsufficientFunds, // EOSInsufficient account balance
'2009': InsufficientFunds, // BCCInsufficient account balance
'3001': OrderNotFound, // Order not found or is completed
'3002': InvalidOrder, // Invalid amount
'3003': InvalidOrder, // Invalid quantity
'3004': AuthenticationError, // User does not exist
'3005': BadRequest, // Invalid parameter
'3006': PermissionDenied, // Invalid IP or not consistent with the bound IP
'3007': RequestTimeout, // The request time has expired
'3008': ExchangeError, // Transaction not found
'3009': InvalidOrder, // The price exceeds the limit
'3010': PermissionDenied, // It fails to place an order, due to you have set up to prohibit trading of this market.
'3011': InvalidOrder, // The entrusted price is abnormal, please modify it and place order again
'3012': InvalidOrder, // Duplicate custom customerOrderId
'4001': AccountSuspended, // APIThe interface is locked for one hour
'4002': RateLimitExceeded, // Request too frequently
},
'exact': {
// '1000': 'Successful operation',
'10001': ExchangeError, // Operation failed
'10002': PermissionDenied, // Operation is forbidden
'10003': BadResponse, // Data existed
'10004': BadResponse, // Date not exist
'10005': PermissionDenied, // Forbidden to access the interface
'10006': BadRequest, // Currency invalid or expired
'10007': ExchangeError, // {0}
'10008': ExchangeError, // Operation failed: {0}
'10009': ExchangeError, // URL error
'1001': ExchangeError, // 'General error message',
'10010': AuthenticationError, // API KEY not exist
'10011': AuthenticationError, // API KEY CLOSED
'10012': AccountSuspended, // User API has been frozen, please contact customer service for processing
'10013': AuthenticationError, // API verification failed
'10014': AuthenticationError, // Invalid signature(1001)
'10015': AuthenticationError, // Invalid signature(1002)
'10016': AuthenticationError, // Invalid ip
'10017': PermissionDenied, // Permission denied
'10018': AccountSuspended, // User has been frozen, please contact customer service
'10019': RequestTimeout, // Request time has expired
'1002': ExchangeError, // 'Internal error',
'10020': BadRequest, // {0}Parameter cannot be empty
'10021': BadRequest, // {0}Invalid parameter
'10022': BadRequest, // Request method error
'10023': RateLimitExceeded, // Request frequency is too fast, exceeding the limit allowed by the interface
'10024': AuthenticationError, // Login failed
'10025': ExchangeError, // Non-personal operation
'10026': NetworkError, // Failed to request interface, please try again
'10027': RequestTimeout, // Timed out, please try again later
'10028': ExchangeNotAvailable, // System busy, please try again later
'10029': DDoSProtection, // Frequent operation, please try again later
'1003': AuthenticationError, // 'Verification does not pass',
'10030': BadRequest, // Currency already exist
'10031': BadRequest, // Currency does not exist
'10032': BadRequest, // Market existed
'10033': BadRequest, // Market not exist
'10034': BadRequest, // Currency error
'10035': BadRequest, // Market not open
'10036': BadRequest, // Ineffective market type
'10037': ArgumentsRequired, // User id cannot be empty
'10038': BadRequest, // Market id cannot be empty
'10039': BadResponse, // Failed to get mark price
'1004': AuthenticationError, // 'Funding security password lock',
'10040': BadResponse, // Failed to obtain the opening margin configuration
'10041': BadResponse, // Failed to obtain maintenance margin allocation
'10042': ExchangeError, // Avg. price error
'10043': ExchangeError, // Abnormal acquisition of liquidation price
'10044': ExchangeError, // Unrealized profit and loss acquisition exception
'10045': ExchangeError, // jdbcData source acquisition failed
'10046': ExchangeError, // Invalid position opening direction
'10047': ExchangeError, // The maximum position allowed by the current leverage multiple has been exceeded
'10048': ExchangeError, // The maximum allowable order quantity has been exceeded
'10049': NetworkError, // Failed to get the latest price
'1005': AuthenticationError, // 'Funds security password is incorrect, please confirm and re-enter.',
'1006': AuthenticationError, // 'Real-name certification pending approval or audit does not pass',
'1009': ExchangeNotAvailable, // 'This interface is under maintenance',
'1010': ExchangeNotAvailable, // Not available now
'10100': OnMaintenance, // Sorry! System maintenance, stop operation
'1012': PermissionDenied, // Insufficient permissions
'1013': ExchangeError, // Cannot trade, please contact email: support@zb.cn for support.
'1014': ExchangeError, // Cannot sell during the pre-sale period
'11000': ExchangeError, // Funding change failed
'11001': ExchangeError, // Position change failed
'110011': ExchangeError, // Exceeds the maximum leverage allowed by the position
'11002': ExchangeError, // Funding not exist
'11003': ExchangeError, // Freeze records not exist
'11004': InsufficientFunds, // Insufficient frozen funds
'11005': InvalidOrder, // Insufficient positions
'11006': InsufficientFunds, // Insufficient frozen positions
'11007': OrderNotFound, // Position not exist
'11008': ExchangeError, // The contract have positions, cannot be modified
'11009': ExchangeError, // Failed to query data
'110110': ExchangeError, // Exceed the market's maximum leverage
'11012': InsufficientFunds, // Insufficient margin
'11013': ExchangeError, // Exceeding accuracy limit
'11014': ExchangeError, // Invalid bill type
'11015': AuthenticationError, // Failed to add default account
'11016': AuthenticationError, // Account not exist
'11017': ExchangeError, // Funds are not frozen or unfrozen
'11018': InsufficientFunds, // Insufficient funds
'11019': ExchangeError, // Bill does not exist
'11021': InsufficientFunds, // Inconsistent currency for funds transfer
'11023': ExchangeError, // Same transaction currency
'11030': PermissionDenied, // Position is locked, the operation is prohibited
'11031': ExchangeError, // The number of bill changes is zero
'11032': ExchangeError, // The same request is being processed, please do not submit it repeatedly
'11033': ArgumentsRequired, // Position configuration data is empty
'11034': ExchangeError, // Funding fee is being settled, please do not operate
'12000': InvalidOrder, // Invalid order price
'12001': InvalidOrder, // Invalid order amount
'12002': InvalidOrder, // Invalid order type
'12003': InvalidOrder, // Invalid price accuracy
'12004': InvalidOrder, // Invalid quantity precision
'12005': InvalidOrder, // order value less than the minimum or greater than the maximum
'12006': InvalidOrder, // Customize's order number format is wrong
'12007': InvalidOrder, // Direction error
'12008': InvalidOrder, // Order type error
'12009': InvalidOrder, // Commission type error
'12010': InvalidOrder, // Failed to place the order, the loss of the order placed at this price will exceed margin
'12011': InvalidOrder, // it's not a buz order
'12012': OrderNotFound, // order not exist
'12013': InvalidOrder, // Order user does not match
'12014': InvalidOrder, // Order is still in transaction
'12015': InvalidOrder, // Order preprocessing failed
'12016': InvalidOrder, // Order cannot be canceled
'12017': InvalidOrder, // Transaction Record not exist
'12018': InvalidOrder, // Order failed
'12019': ArgumentsRequired, // extend parameter cannot be empty
'12020': ExchangeError, // extend Parameter error
'12021': InvalidOrder, // The order price is not within the price limit rules!
'12022': InvalidOrder, // Stop placing an order while the system is calculating the fund fee
'12023': OrderNotFound, // There are no positions to close
'12024': InvalidOrder, // Orders are prohibited, stay tuned!
'12025': InvalidOrder, // Order cancellation is prohibited, so stay tuned!
'12026': DuplicateOrderId, // Order failed, customize order number exists
'12027': ExchangeNotAvailable, // System busy, please try again later
'12028': InvalidOrder, // The market has banned trading
'12029': InvalidOrder, // Forbidden place order, stay tuned
'12201': InvalidOrder, // Delegation strategy does not exist or the status has changed
'12202': InvalidOrder, // Delegation strategy has been changed, cannot be canceled
'12203': InvalidOrder, // Wrong order type
'12204': InvalidOrder, // Invalid trigger price
'12205': InvalidOrder, // The trigger price must be greater than the market’s selling price or lower than the buying price.
'12206': InvalidOrder, // Direction and order type do not match
'12207': RateLimitExceeded, // Submission failed, exceeding the allowed limit
'13001': AuthenticationError, // User not exist
'13002': PermissionDenied, // User did not activate futures
// '13003': AuthenticationError, // User is locked
'13003': InvalidOrder, // Margin gear is not continuous
'13004': InvalidOrder, // The margin quick calculation amount is less than 0
'13005': RateLimitExceeded, // You have exceeded the number of exports that day
'13006': ExchangeError, // No markets are bookmarked
'13007': ExchangeError, // Market not favorited
'13008': ExchangeError, // Not in any market user whitelist
'13009': ExchangeError, // Not in the whitelist of users in this market
'14000': ExchangeError, // {0}not support
'14001': AuthenticationError, // Already logged in, no need to log in multiple times
'14002': AuthenticationError, // Not logged in yet, please log in before subscribing
'14003': ExchangeError, // This is a channel for one-time queries, no need to unsubscribe
'14100': ExchangeError, // Accuracy does not support
'14101': RateLimitExceeded, // Request exceeded frequency limit
'14200': ArgumentsRequired, // id empty
'14300': ExchangeError, // activity not exist
'14301': ExchangeError, // The event has been opened and cannot be admitted
'14302': ExchangeError, // The purchase time has passed and cannot be admitted
'14303': ExchangeError, // Not yet open for the purchase
'14305': ExchangeError, // Cannot enter, the maximum number of returns has been exceeded
'14306': ExchangeError, // Cannot repeat admission
'14307': InvalidOrder, // Unable to cancel, status has been changed
'14308': InvalidOrder, // Unable to cancel, the amount does not match
'14309': ExchangeError, // Activity has not started
'14310': NotSupported, // Activity is over
'14311': NotSupported, // The activity does not support orders placed in this market
'14312': ExchangeError, // You have not participated in this activity
'14313': PermissionDenied, // Sorry! The purchase failed, the maximum number of participants has been reached
'14314': ExchangeError, // Active period id error
'2001': InsufficientFunds, // 'Insufficient CNY Balance',
'2002': InsufficientFunds, // 'Insufficient BTC Balance',
'2003': InsufficientFunds, // 'Insufficient LTC Balance',
'2005': InsufficientFunds, // 'Insufficient ETH Balance',
'2006': InsufficientFunds, // 'Insufficient ETC Balance',
'2007': InsufficientFunds, // 'Insufficient BTS Balance',
'2008': InsufficientFunds, // EOSInsufficient account balance
'2009': InsufficientFunds, // 'Account balance is not enough',
'3001': OrderNotFound, // 'Pending orders not found',
'3002': InvalidOrder, // 'Invalid price',
'3003': InvalidOrder, // 'Invalid amount',
'3004': AuthenticationError, // 'User does not exist',
'3005': BadRequest, // 'Invalid parameter',
'3006': AuthenticationError, // 'Invalid IP or inconsistent with the bound IP',
'3007': AuthenticationError, // 'The request time has expired',
'3008': OrderNotFound, // 'Transaction records not found',
'3009': InvalidOrder, // 'The price exceeds the limit',
'3010': PermissionDenied, // It fails to place an order, due to you have set up to prohibit trading of this market.
'3011': InvalidOrder, // 'The entrusted price is abnormal, please modify it and place order again',
'3012': InvalidOrder, // Duplicate custom customerOrderId
'4001': ExchangeNotAvailable, // 'API interface is locked or not enabled',
'4002': RateLimitExceeded, // 'Request too often',
'9999': ExchangeError, // Unknown error
},
'broad': {
'提币地址有误, 请先添加提币地址。': InvalidAddress, // {"code":1001,"message":"提币地址有误,请先添加提币地址。"}
'资金不足,无法划账': InsufficientFunds, // {"code":1001,"message":"资金不足,无法划账"}
'响应超时': RequestTimeout, // {"code":1001,"message":"响应超时"}
},
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/32859187-cd5214f0-ca5e-11e7-967d-96568e2e2bd1.jpg',
'api': {
'spot': {
'v1': {
'public': 'https://api.zb.work/data',
'private': 'https://trade.zb.work/api',
},
},
'contract': {
'v1': {
'public': 'https://fapi.zb.com/api/public',
},
'v2': {
'public': 'https://fapi.zb.com/Server/api',
'private': 'https://fapi.zb.com/Server/api',
},
},
},
'www': 'https://www.zb.com',
'doc': 'https://www.zb.com/i/developer',
'fees': 'https://www.zb.com/i/rate',
'referral': {
'url': 'https://www.zbex.club/en/register?ref=4301lera',
'discount': 0.16,
},
},
'api': {
'spot': {
'v1': {
'public': {
'get': [
'markets',
'ticker',
'allTicker',
'depth',
'trades',
'kline',
'getGroupMarkets',
'getFeeInfo',
],
},
'private': {
'get': [
// spot API
'order',
'orderMoreV2',
'cancelOrder',
'getOrder',
'getOrders',
'getOrdersNew',
'getOrdersIgnoreTradeType',
'getUnfinishedOrdersIgnoreTradeType',
'getFinishedAndPartialOrders',
'getAccountInfo',
'getUserAddress',
'getPayinAddress',
'getWithdrawAddress',
'getWithdrawRecord',
'getChargeRecord',
'getCnyWithdrawRecord',
'getCnyChargeRecord',
'withdraw',
// sub accounts
'addSubUser',
'getSubUserList',
'doTransferFunds',
'createSubUserKey', // removed on 2021-03-16 according to the update log in the API doc
// leverage API
'getLeverAssetsInfo',
'getLeverBills',
'transferInLever',
'transferOutLever',
'loan',
'cancelLoan',
'getLoans',
'getLoanRecords',
'borrow',
'autoBorrow',
'repay',
'doAllRepay',
'getRepayments',
'getFinanceRecords',
'changeInvestMark',
'changeLoop',
// cross API
'getCrossAssets',
'getCrossBills',
'transferInCross',
'transferOutCross',
'doCrossLoan',
'doCrossRepay',
'getCrossRepayRecords',
],
},
},
},
'contract': {
'v1': {
'public': {
'get': [
'depth',
'fundingRate',
'indexKline',
'indexPrice',
'kline',
'markKline',
'markPrice',
'ticker',
'trade',
],
},
},
'v2': {
'public': {
'get': [
'allForceOrders',
'config/marketList',
'topLongShortAccountRatio',
'topLongShortPositionRatio',
'fundingRate',
'premiumIndex',
],
},
'private': {
'get': [
'Fund/balance',
'Fund/getAccount',
'Fund/getBill',
'Fund/getBillTypeList',
'Fund/marginHistory',
'Positions/getPositions',
'Positions/getNominalValue',
'Positions/marginInfo',
'setting/get',
'trade/getAllOrders',
'trade/getOrder',
'trade/getOrderAlgos',
'trade/getTradeList',
'trade/getUndoneOrders',
'trade/tradeHistory',
],
'post': [
'activity/buyTicket',
'Fund/transferFund',
'Positions/setMarginCoins',
'Positions/updateAppendUSDValue',
'Positions/updateMargin',
'setting/setLeverage',
'trade/batchOrder',
'trade/batchCancelOrder',
'trade/cancelAlgos',
'trade/cancelAllOrders',
'trade/cancelOrder',
'trade/order',
'trade/orderAlgo',
'trade/updateOrderAlgo',
],
},
},
},
},
'fees': {
'funding': {
'withdraw': {},
},
'trading': {
'maker': 0.2 / 100,
'taker': 0.2 / 100,
},
},
'commonCurrencies': {
'ANG': 'Anagram',
'ENT': 'ENTCash',
'BCHABC': 'BCHABC', // conflict with BCH / BCHA
'BCHSV': 'BCHSV', // conflict with BCH / BSV
},
'options': {
'timeframes': {
'spot': {
'1m': '1min',
'3m': '3min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '1hour',
'2h': '2hour',
'4h': '4hour',
'6h': '6hour',
'12h': '12hour',
'1d': '1day',
'3d': '3day',
'1w': '1week',
},
'swap': {
'1m': '1M',
'5m': '5M',
'15m': '15M',
'30m': '30M',
'1h': '1H',
'6h': '6H',
'1d': '1D',
'5d': '5D',
},
},
},
});
}
async fetchMarkets (params = {}) {
const markets = await this.spotV1PublicGetMarkets (params);
//
// {
// "zb_qc":{
// "amountScale":2,
// "minAmount":0.01,
// "minSize":5,
// "priceScale":4,
// },
// }
//
const contracts = await this.contractV2PublicGetConfigMarketList (params);
//
// {
// BTC_USDT: {
// symbol: 'BTC_USDT',
// buyerCurrencyId: '6',
// contractType: '1',
// defaultMarginMode: '1',
// marketType: '2',
// historyDBName: 'trade_history_readonly.dbc',
// defaultLeverage: '20',
// id: '100',
// canCancelOrder: true,
// area: '1',
// mixMarginCoinName: 'usdt',
// fundingRateRatio: '0.25',
// marginCurrencyName: 'usdt',
// minTradeMoney: '0.0001',
// enableTime: '1638954000000',
// maxTradeMoney: '10000000',
// canTrade: true,
// maxLeverage: '125',
// defaultPositionsMode: '2',
// onlyWhitelistVisible: false,
// riskWarnRatio: '0.8',
// marginDecimal: '8',
// spot: false,
// status: '1',
// amountDecimal: '3',
// leverage: false,
// minAmount: '0.001',
// canOrder: true,
// duration: '1',
// feeDecimal: '8',
// sellerCurrencyId: '1',
// maxAmount: '1000',
// canOpenPosition: true,
// isSupportMixMargin: false,
// markPriceLimitRate: '0.05',
// marginCurrencyId: '6',
// stopFundingFee: false,
// priceDecimal: '2',
// lightenUpFeeRate: '0',
// futures: true,
// sellerCurrencyName: 'btc',
// marketPriceLimitRate: '0.05',
// canRebate: true,
// marketName: 'BTC_USDT',
// depth: [ 0.01, 0.1, 1 ],
// createTime: '1607590430094',
// mixMarginCoinIds: [ 6 ],
// buyerCurrencyName: 'usdt',
// stopService: false
// },
// }
//
const contractsData = this.safeValue (contracts, 'data', []);
const contractsById = this.indexBy (contractsData, 'marketName');
const dataById = this.deepExtend (contractsById, markets);
const keys = Object.keys (dataById);
const result = [];
for (let i = 0; i < keys.length; i++) {
const id = keys[i];
const market = dataById[id];
const [ baseId, quoteId ] = id.split ('_');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const settleId = this.safeValue (market, 'marginCurrencyName');
const settle = this.safeCurrencyCode (settleId);
const spot = settle === undefined;
const swap = this.safeValue (market, 'futures', false);
const linear = swap ? true : undefined;
let active = true;
let symbol = base + '/' + quote;
const amountPrecisionString = this.safeString2 (market, 'amountScale', 'amountDecimal');
const pricePrecisionString = this.safeString2 (market, 'priceScale', 'priceDecimal');
if (swap) {
const status = this.safeString (market, 'status');
active = (status === '1');
symbol = base + '/' + quote + ':' + settle;
}
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': swap ? 'swap' : 'spot',
'spot': spot,
'margin': false,
'swap': swap,
'future': false,
'option': false,
'active': active,
'contract': swap,
'linear': linear,
'inverse': swap ? !linear : undefined,
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': parseInt (amountPrecisionString),
'price': parseInt (pricePrecisionString),
},
'limits': {
'leverage': {
'min': undefined,
'max': this.safeNumber (market, 'maxLeverage'),
},
'amount': {
'min': this.safeNumber (market, 'minAmount'),
'max': this.safeNumber (market, 'maxAmount'),
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber2 (market, 'minSize', 'minTradeMoney'),
'max': this.safeNumber (market, 'maxTradeMoney'),
},
},
'info': market,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.spotV1PublicGetGetFeeInfo (params);
//
// {
// "code":1000,
// "message":"success",
// "result":{
// "USDT":[
// {
// "chainName":"TRC20",
// "canWithdraw":true,
// "fee":1.0,
// "mainChainName":"TRX",
// "canDeposit":true
// },
// {
// "chainName":"OMNI",
// "canWithdraw":true,
// "fee":5.0,
// "mainChainName":"BTC",
// "canDeposit":true
// },
// {
// "chainName":"ERC20",
// "canWithdraw":true,
// "fee":15.0,
// "mainChainName":"ETH",
// "canDeposit":true
// }
// ],
// }
// }
//
const currencies = this.safeValue (response, 'result', {});
const ids = Object.keys (currencies);
const result = {};
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const currency = currencies[id];
const code = this.safeCurrencyCode (id);
const precision = undefined;
let isWithdrawEnabled = true;
let isDepositEnabled = true;
const fees = {};
for (let j = 0; j < currency.length; j++) {
const networkItem = currency[j];
const network = this.safeString (networkItem, 'chainName');
// const name = this.safeString (networkItem, 'name');
const withdrawFee = this.safeNumber (networkItem, 'fee');
const depositEnable = this.safeValue (networkItem, 'canDeposit');
const withdrawEnable = this.safeValue (networkItem, 'canWithdraw');
isDepositEnabled = isDepositEnabled || depositEnable;
isWithdrawEnabled = isWithdrawEnabled || withdrawEnable;
fees[network] = withdrawFee;
}
const active = (isWithdrawEnabled && isDepositEnabled);
result[code] = {
'id': id,
'name': undefined,
'code': code,
'precision': precision,
'info': currency,
'active': active,
'deposit': isDepositEnabled,
'withdraw': isWithdrawEnabled,
'fee': undefined,
'fees': fees,
'limits': this.limits,
};
}
return result;
}
parseBalance (response) {
const balances = this.safeValue (response['result'], 'coins');
const result = {
'info': response,
};
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
// { enName: "BTC",
// freez: "0.00000000",
// unitDecimal: 8, // always 8
// cnName: "BTC",
// isCanRecharge: true, // TODO: should use this
// unitTag: "฿",
// isCanWithdraw: true, // TODO: should use this
// available: "0.00000000",
// key: "btc" }
const account = this.account ();
const currencyId = this.safeString (balance, 'key');
const code = this.safeCurrencyCode (currencyId);
account['free'] = this.safeString (balance, 'available');
account['used'] = this.safeString (balance, 'freez');
result[code] = account;
}
return this.safeBalance (result);
}
parseSwapBalance (response) {
const result = {
'info': response,
};
const data = this.safeValue (response, 'data', {});
for (let i = 0; i < data.length; i++) {
const balance = data[i];
//
// {
// "userId": "6896693805014120448",
// "currencyId": "6",
// "currencyName": "usdt",
// "amount": "30.56585118",
// "freezeAmount": "0",
// "contractType": 1,
// "id": "6899113714763638819",
// "createTime": "1644876888934",
// "modifyTime": "1645787446037",
// "accountBalance": "30.56585118",
// "allMargin": "0",
// "allowTransferOutAmount": "30.56585118"
// },
//
const code = this.safeCurrencyCode (this.safeString (balance, 'currencyName'));
const account = this.account ();
account['total'] = this.safeString (balance, 'accountBalance');
account['free'] = this.safeString (balance, 'allowTransferOutAmount');
account['used'] = this.safeString (balance, 'freezeAmount');
result[code] = account;
}
return this.safeBalance (result);
}
parseMarginBalance (response, marginType) {
const result = {
'info': response,
};
let levers = undefined;
if (marginType === 'isolated') {
const message = this.safeValue (response, 'message', {});
const data = this.safeValue (message, 'datas', {});
levers = this.safeValue (data, 'levers', []);
} else {
const crossResponse = this.safeValue (response, 'result', {});
levers = this.safeValue (crossResponse, 'list', []);
}
for (let i = 0; i < levers.length; i++) {
const balance = levers[i];
//
// Isolated Margin
//
// {
// "cNetUSD": "0.00",
// "repayLeverShow": "-",
// "cCanLoanIn": "0.002115400000000",
// "fNetCNY": "147.76081161",
// "fLoanIn": "0.00",
// "repayLevel": 0,
// "level": 1,
// "netConvertCNY": "147.760811613032",
// "cFreeze": "0.00",
// "cUnitTag": "BTC",
// "version": 1646783178609,
// "cAvailableUSD": "0.00",
// "cNetCNY": "0.00",
// "riskRate": "-",
// "fAvailableUSD": "20.49273433",
// "fNetUSD": "20.49273432",
// "cShowName": "BTC",
// "leverMultiple": "5.00",
// "couldTransferOutFiat": "20.49273433",
// "noticeLine": "1.13",
// "fFreeze": "0.00",
// "cUnitDecimal": 8,
// "fCanLoanIn": "81.970937320000000",
// "cAvailable": "0.00",
// "repayLock": false,
// "status": 1,
// "forbidType": 0,
// "totalConvertCNY": "147.760811613032",
// "cAvailableCNY": "0.00",
// "unwindPrice": "0.00",
// "fOverdraft": "0.00",
// "fShowName": "USDT",
// "statusShow": "%E6%AD%A3%E5%B8%B8",
// "cOverdraft": "0.00",
// "netConvertUSD": "20.49273433",
// "cNetBtc": "0.00",
// "loanInConvertCNY": "0.00",
// "fAvailableCNY": "147.760811613032",
// "key": "btcusdt",
// "fNetBtc": "0.0005291",
// "fUnitDecimal": 8,
// "loanInConvertUSD": "0.00",
// "showName": "BTC/USDT",
// "startLine": "1.25",
// "totalConvertUSD": "20.49273433",
// "couldTransferOutCoin": "0.00",
// "cEnName": "BTC",
// "leverMultipleInterest": "3.00",
// "fAvailable": "20.49273433",
// "fEnName": "USDT",
// "forceRepayLine": "1.08",
// "cLoanIn": "0.00"
// }
//
// Cross Margin
//
// [
// {
// "fundType": 2,
// "loanIn": 0,
// "amount": 0,
// "freeze": 0,
// "overdraft": 0,
// "key": "BTC",
// "canTransferOut": 0
// },
// ],
//
const account = this.account ();
if (marginType === 'isolated') {
const code = this.safeCurrencyCode (this.safeString (balance, 'fShowName'));
account['total'] = this.safeString (balance, 'fAvailableUSD'); // total amount in USD
account['free'] = this.safeString (balance, 'couldTransferOutFiat');
account['used'] = this.safeString (balance, 'fFreeze');
result[code] = account;
} else {
const code = this.safeCurrencyCode (this.safeString (balance, 'key'));
account['total'] = this.safeString (balance, 'amount');
account['free'] = this.safeString (balance, 'canTransferOut');
account['used'] = this.safeString (balance, 'freeze');
result[code] = account;
}
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const [ marketType, query ] = this.handleMarketTypeAndParams ('fetchBalance', undefined, params);
const margin = (marketType === 'margin');
const swap = (marketType === 'swap');
let marginMethod = undefined;
const defaultMargin = margin ? 'isolated' : 'cross';
const marginType = this.safeString2 (this.options, 'defaultMarginType', 'marginType', defaultMargin);
if (marginType === 'isolated') {
marginMethod = 'spotV1PrivateGetGetLeverAssetsInfo';
} else if (marginType === 'cross') {
marginMethod = 'spotV1PrivateGetGetCrossAssets';
}
const method = this.getSupportedMapping (marketType, {
'spot': 'spotV1PrivateGetGetAccountInfo',
'swap': 'contractV2PrivateGetFundBalance',
'margin': marginMethod,
});
const request = {
// 'futuresAccountType': 1, // SWAP
// 'currencyId': currency['id'], // SWAP
// 'currencyName': 'usdt', // SWAP
};
if (swap) {
request['futuresAccountType'] = 1;
}
const response = await this[method] (this.extend (request, query));
//
// Spot
//
// {
// "result": {
// "coins": [
// {
// "isCanWithdraw": "true",
// "canLoan": false,
// "fundstype": 51,
// "showName": "ZB",
// "isCanRecharge": "true",
// "cnName": "ZB",
// "enName": "ZB",
// "available": "0",
// "freez": "0",
// "unitTag": "ZB",
// "key": "zb",
// "unitDecimal": 8
// },
// ],
// "version": 1645856691340,
// "base": {
// "auth_google_enabled": true,
// "auth_mobile_enabled": false,
// "trade_password_enabled": true,
// "username": "blank@gmail.com"
// }
// },
// "leverPerm": true,
// "otcPerm": false,
// "assetPerm": true,
// "moneyPerm": true,
// "subUserPerm": true,
// "entrustPerm": true
// }
//
// Swap
//
// {
// "code": 10000,
// "data": [
// {
// "userId": "6896693805014120448",
// "currencyId": "6",
// "currencyName": "usdt",
// "amount": "30.56585118",
// "freezeAmount": "0",
// "contractType": 1,
// "id": "6899113714763638819",
// "createTime": "1644876888934",
// "modifyTime": "1645787446037",
// "accountBalance": "30.56585118",
// "allMargin": "0",
// "allowTransferOutAmount": "30.56585118"
// },
// ],
// "desc": "操作成功"
// }
//
// Isolated Margin
//
// {
// "code": 1000,
// "message": {
// "des": "success",
// "isSuc": true,
// "datas": {
// "leverPerm": true,
// "levers": [
// {
// "cNetUSD": "0.00",
// "repayLeverShow": "-",
// "cCanLoanIn": "0.002115400000000",
// "fNetCNY": "147.76081161",
// "fLoanIn": "0.00",
// "repayLevel": 0,
// "level": 1,
// "netConvertCNY": "147.760811613032",
// "cFreeze": "0.00",
// "cUnitTag": "BTC",
// "version": 1646783178609,
// "cAvailableUSD": "0.00",
// "cNetCNY": "0.00",
// "riskRate": "-",
// "fAvailableUSD": "20.49273433",
// "fNetUSD": "20.49273432",
// "cShowName": "BTC",
// "leverMultiple": "5.00",
// "couldTransferOutFiat": "20.49273433",
// "noticeLine": "1.13",
// "fFreeze": "0.00",
// "cUnitDecimal": 8,
// "fCanLoanIn": "81.970937320000000",
// "cAvailable": "0.00",
// "repayLock": false,
// "status": 1,
// "forbidType": 0,
// "totalConvertCNY": "147.760811613032",
// "cAvailableCNY": "0.00",
// "unwindPrice": "0.00",
// "fOverdraft": "0.00",
// "fShowName": "USDT",
// "statusShow": "%E6%AD%A3%E5%B8%B8",
// "cOverdraft": "0.00",
// "netConvertUSD": "20.49273433",
// "cNetBtc": "0.00",
// "loanInConvertCNY": "0.00",
// "fAvailableCNY": "147.760811613032",
// "key": "btcusdt",
// "fNetBtc": "0.0005291",
// "fUnitDecimal": 8,
// "loanInConvertUSD": "0.00",
// "showName": "BTC/USDT",
// "startLine": "1.25",
// "totalConvertUSD": "20.49273433",
// "couldTransferOutCoin": "0.00",
// "cEnName": "BTC",
// "leverMultipleInterest": "3.00",
// "fAvailable": "20.49273433",
// "fEnName": "USDT",
// "forceRepayLine": "1.08",
// "cLoanIn": "0.00"
// }
// ]
// }
// }
// }
//
// Cross Margin
//
// {
// "code": 1000,
// "message": "操作成功",
// "result": {
// "loanIn": 0,
// "total": 71.167,
// "riskRate": "-",
// "list" :[
// {
// "fundType": 2,
// "loanIn": 0,
// "amount": 0,
// "freeze": 0,
// "overdraft": 0,
// "key": "BTC",
// "canTransferOut": 0
// },
// ],
// "net": 71.167
// }
// }
//
// todo: use this somehow
// let permissions = response['result']['base'];
if (swap) {
return this.parseSwapBalance (response);
} else if (margin) {
return this.parseMarginBalance (response, marginType);
} else {
return this.parseBalance (response);
}
}
parseDepositAddress (depositAddress, currency = undefined) {
//
// fetchDepositAddress
//
// {
// "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
// }
//
// fetchDepositAddresses
//
// {
// "blockChain": "btc",
// "isUseMemo": false,
// "address": "1LL5ati6pXHZnTGzHSA3rWdqi4mGGXudwM",
// "canWithdraw": true,
// "canDeposit": true
// }
// {
// "blockChain": "bts",
// "isUseMemo": true,
// "account": "btstest",
// "memo": "123",
// "canWithdraw": true,
// "canDeposit": true
// }
//
let address = this.safeString2 (depositAddress, 'key', 'address');
let tag = undefined;
const memo = this.safeString (depositAddress, 'memo');
if (memo !== undefined) {
tag = memo;
} else if (address.indexOf ('_') >= 0) {
const parts = address.split ('_');
address = parts[0]; // WARNING: MAY BE tag_address INSTEAD OF address_tag FOR SOME CURRENCIES!!
tag = parts[1];
}
const currencyId = this.safeString (depositAddress, 'blockChain');
const code = this.safeCurrencyCode (currencyId, currency);
return {
'currency': code,
'address': address,
'tag': tag,
'network': undefined,
'info': depositAddress,
};
}
async fetchDepositAddresses (codes = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.spotV1PrivateGetGetPayinAddress (params);
//
// {
// "code": 1000,
// "message": {
// "des": "success",
// "isSuc": true,
// "datas": [
// {
// "blockChain": "btc",
// "isUseMemo": false,
// "address": "1LL5ati6pXHZnTGzHSA3rWdqi4mGGXudwM",
// "canWithdraw": true,
// "canDeposit": true
// },
// {
// "blockChain": "bts",
// "isUseMemo": true,
// "account": "btstest",
// "memo": "123",
// "canWithdraw": true,
// "canDeposit": true
// },
// ]
// }
// }
//
const message = this.safeValue (response, 'message', {});
const datas = this.safeValue (message, 'datas', []);
return this.parseDepositAddresses (datas, codes);
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const response = await this.spotV1PrivateGetGetUserAddress (this.extend (request, params));
//
// {
// "code": 1000,
// "message": {
// "des": "success",
// "isSuc": true,
// "datas": {
// "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
// }
// }
// }
//
const message = this.safeValue (response, 'message', {});
const datas = this.safeValue (message, 'datas', {});
return this.parseDepositAddress (datas, currency);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
// 'market': market['id'], // only applicable to SPOT
// 'symbol': market['id'], // only applicable to SWAP
// 'size': limit, // 1-50 applicable to SPOT and SWAP
// 'merge': 5.0, // float default depth only applicable to SPOT
// 'scale': 5, // int accuracy, only applicable to SWAP
};
const marketIdField = market['swap'] ? 'symbol' : 'market';
request[marketIdField] = market['id'];
const method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PublicGetDepth',
'swap': 'contractV1PublicGetDepth',
});
if (limit !== undefined) {
request['size'] = limit;
}
const response = await this[method] (this.extend (request, params));
//
// Spot
//
// {
// "asks":[
// [35000.0,0.2741],
// [34949.0,0.0173],
// [34900.0,0.5004],
// ],
// "bids":[
// [34119.32,0.0030],
// [34107.83,0.1500],
// [34104.42,0.1500],
// ],
// "timestamp":1624536510
// }
//
// Swap
//
// {
// "code": 10000,
// "desc": "操作成功",
// "data": {
// "asks": [
// [43416.6,0.02],
// [43418.25,0.04],
// [43425.82,0.02]
// ],
// "bids": [
// [43414.61,0.1],
// [43414.18,0.04],
// [43413.03,0.05]
// ],
// "time": 1645087743071
// }
// }
//
let result = undefined;
let timestamp = undefined;
if (market['type'] === 'swap') {
result = this.safeValue (response, 'data');
timestamp = this.safeInteger (result, 'time');
} else {
result = response;
timestamp = this.safeTimestamp (response, 'timestamp');
}
return this.parseOrderBook (result, symbol, timestamp);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.spotV1PublicGetAllTicker (params);
const result = {};
const marketsByIdWithoutUnderscore = {};
const marketIds = Object.keys (this.markets_by_id);
for (let i = 0; i < marketIds.length; i++) {
const tickerId = marketIds[i].replace ('_', '');
marketsByIdWithoutUnderscore[tickerId] = this.markets_by_id[marketIds[i]];
}
const ids = Object.keys (response);
for (let i = 0; i < ids.length; i++) {
const market = marketsByIdWithoutUnderscore[ids[i]];
result[market['symbol']] = this.parseTicker (response[ids[i]], market);
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
// 'market': market['id'], // only applicable to SPOT
// 'symbol': market['id'], // only applicable to SWAP
};
const marketIdField = market['swap'] ? 'symbol' : 'market';
request[marketIdField] = market['id'];
const method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PublicGetTicker',
'swap': 'contractV1PublicGetTicker',
});
const response = await this[method] (this.extend (request, params));
//
// Spot
//
// {
// "date":"1624399623587",
// "ticker":{
// "high":"33298.38",
// "vol":"56152.9012",
// "last":"32578.55",
// "low":"28808.19",
// "buy":"32572.68",
// "sell":"32615.37",
// "turnover":"1764201303.6100",
// "open":"31664.85",
// "riseRate":"2.89"
// }
// }
//
// Swap
//
// {
// "code": 10000,
// "desc": "操作成功",
// "data": {
// "BTC_USDT": [44053.47,44357.77,42911.54,43297.79,53471.264,-1.72,1645093002,302201.255084]
// }
// }
//
let ticker = undefined;
if (market['type'] === 'swap') {
ticker = {};
const data = this.safeValue (response, 'data');
const values = this.safeValue (data, market['id']);
for (let i = 0; i < values.length; i++) {
ticker['open'] = this.safeValue (values, 0);
ticker['high'] = this.safeValue (values, 1);
ticker['low'] = this.safeValue (values, 2);
ticker['last'] = this.safeValue (values, 3);
ticker['vol'] = this.safeValue (values, 4);
ticker['riseRate'] = this.safeValue (values, 5);
}
} else {
ticker = this.safeValue (response, 'ticker', {});
ticker['date'] = this.safeValue (response, 'date');
}
return this.parseTicker (ticker, market);
}
parseTicker (ticker, market = undefined) {
//
// Spot
//
// {
// "date":"1624399623587", // injected from outside
// "high":"33298.38",
// "vol":"56152.9012",
// "last":"32578.55",
// "low":"28808.19",
// "buy":"32572.68",
// "sell":"32615.37",
// "turnover":"1764201303.6100",
// "open":"31664.85",
// "riseRate":"2.89"
// }
//
// Swap
//
// {
// open: 44083.82,
// high: 44357.77,
// low: 42911.54,
// last: 43097.87,
// vol: 53451.641,
// riseRate: -2.24
// }
//
const timestamp = this.safeInteger (ticker, 'date', this.milliseconds ());
const last = this.safeString (ticker, 'last');
return this.safeTicker ({
'symbol': this.safeSymbol (undefined, market),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeString (ticker, 'high'),
'low': this.safeString (ticker, 'low'),
'bid': this.safeString (ticker, 'buy'),
'bidVolume': undefined,
'ask': this.safeString (ticker, 'sell'),
'askVolume': undefined,
'vwap': undefined,
'open': this.safeString (ticker, 'open'),
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeString (ticker, 'vol'),
'quoteVolume': undefined,
'info': ticker,
}, market, false);
}
parseOHLCV (ohlcv, market = undefined) {
if (market['swap']) {
const ohlcvLength = ohlcv.length;
if (ohlcvLength > 5) {
return [
this.safeInteger (ohlcv, 5),
this.safeNumber (ohlcv, 0),
this.safeNumber (ohlcv, 1),
this.safeNumber (ohlcv, 2),
this.safeNumber (ohlcv, 3),
this.safeNumber (ohlcv, 4),
];
} else {
return [
this.safeInteger (ohlcv, 4),
this.safeNumber (ohlcv, 0),
this.safeNumber (ohlcv, 1),
this.safeNumber (ohlcv, 2),
this.safeNumber (ohlcv, 3),
undefined,
];
}
} else {
return [
this.safeInteger (ohlcv, 0),
this.safeNumber (ohlcv, 1),
this.safeNumber (ohlcv, 2),
this.safeNumber (ohlcv, 3),
this.safeNumber (ohlcv, 4),
this.safeNumber (ohlcv, 5),
];
}
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const swap = market['swap'];
const options = this.safeValue (this.options, 'timeframes', {});
const timeframes = this.safeValue (options, market['type'], {});
const timeframeValue = this.safeString (timeframes, timeframe);
if (timeframeValue === undefined) {
throw new NotSupported (this.id + ' fetchOHLCV() does not support ' + timeframe + ' timeframe for ' + market['type'] + ' markets');
}
if (limit === undefined) {
limit = 1000;
}
const request = {
// 'market': market['id'], // spot only
// 'symbol': market['id'], // swap only
// 'type': timeframeValue, // spot only
// 'period': timeframeValue, // swap only
// 'since': since, // spot only
// 'limit': limit, // spot only
// 'size': limit, // swap only
};
const marketIdField = swap ? 'symbol' : 'market';
request[marketIdField] = market['id'];
const periodField = swap ? 'period' : 'type';
request[periodField] = timeframeValue;
const sizeField = swap ? 'size' : 'limit';
request[sizeField] = limit;
const method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PublicGetKline',
'swap': 'contractV1PublicGetKline',
});
if (since !== undefined) {
request['since'] = since;
}
if (limit !== undefined) {
request['size'] = limit;
}
const response = await this[method] (this.extend (request, params));
//
// Spot
//
// {
// "symbol": "BTC",
// "data": [
// [1645091400000,43183.24,43187.49,43145.92,43182.28,0.9110],
// [1645091460000,43182.18,43183.15,43182.06,43183.15,1.4393],
// [1645091520000,43182.11,43240.1,43182.11,43240.1,0.3802]
// ],
// "moneyType": "USDT"
// }
//
// Swap
//
// {
// "code": 10000,
// "desc": "操作成功",
// "data": [
// [41433.44,41433.44,41405.88,41408.75,21.368,1646366460],
// [41409.25,41423.74,41408.8,41423.42,9.828,1646366520],
// [41423.96,41429.39,41369.98,41370.31,123.104,1646366580]
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
async fetchMarkOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const options = this.safeValue (this.options, 'timeframes', {});
const timeframes = this.safeValue (options, market['type'], {});
const timeframeValue = this.safeString (timeframes, timeframe);
if (timeframeValue === undefined) {
throw new NotSupported (this.id + ' fetchMarkOHLCV() does not support ' + timeframe + ' timeframe for ' + market['type'] + ' markets');
}
if (limit === undefined) {
limit = 1000;
}
const request = {
'symbol': market['id'],
'period': timeframeValue,
'size': limit,
};
if (since !== undefined) {
request['since'] = since;
}
if (limit !== undefined) {
request['size'] = limit;
}
const response = await this.contractV1PublicGetMarkKline (this.extend (request, params));
//
// {
// "code": 10000,
// "desc": "操作成功",
// "data": [
// [41603.39,41603.39,41591.59,41600.81,1646381760],
// [41600.36,41605.75,41587.69,41601.97,1646381820],
// [41601.97,41601.97,41562.62,41593.96,1646381880]
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
async fetchIndexOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const options = this.safeValue (this.options, 'timeframes', {});
const timeframes = this.safeValue (options, market['type'], {});
const timeframeValue = this.safeString (timeframes, timeframe);
if (timeframeValue === undefined) {
throw new NotSupported (this.id + ' fetchIndexOHLCV() does not support ' + timeframe + ' timeframe for ' + market['type'] + ' markets');
}
if (limit === undefined) {
limit = 1000;
}
const request = {
'symbol': market['id'],
'period': timeframeValue,
'size': limit,
};
if (since !== undefined) {
request['since'] = since;
}
if (limit !== undefined) {
request['size'] = limit;
}
const response = await this.contractV1PublicGetIndexKline (this.extend (request, params));
//
// {
// "code": 10000,
// "desc": "操作成功",
// "data": [
// [41697.53,41722.29,41689.16,41689.16,1646381640],
// [41690.1,41691.73,41611.61,41611.61,1646381700],
// [41611.61,41619.49,41594.87,41594.87,1646381760]
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
parseTrade (trade, market = undefined) {
//
// Spot
//
// {
// "date":1624537391,
// "amount":"0.0142",
// "price":"33936.42",
// "trade_type":"ask",
// "type":"sell",
// "tid":1718869018
// }
//
// Swap
//
// {
// "amount": "0.002",
// "createTime": "1645787446034",
// "feeAmount": "-0.05762699",
// "feeCurrency": "USDT",
// "id": "6902932868050395136",
// "maker": false,
// "orderId": "6902932868042006528",
// "price": "38417.99",
// "relizedPnl": "0.30402",
// "side": 4,
// "userId": "6896693805014120448"
// },
//
const sideField = market['swap'] ? 'side' : 'trade_type';
let side = this.safeString (trade, sideField);
let takerOrMaker = undefined;
const maker = this.safeValue (trade, 'maker');
if (maker !== undefined) {
takerOrMaker = maker ? 'maker' : 'taker';
}
if (market['spot']) {
side = (side === 'bid') ? 'buy' : 'sell';
} else {
if (side === '3') {
side = 'sell'; // close long
} else if (side === '4') {
side = 'buy'; // close short
} else if (side === '1') {
side = 'buy'; // open long
} else if (side === '2') {
side = 'sell'; // open short
}
}
let timestamp = undefined;
if (market['swap']) {
timestamp = this.safeInteger (trade, 'createTime');
} else {
timestamp = this.safeTimestamp (trade, 'date');
}
const price = this.safeString (trade, 'price');
const amount = this.safeString (trade, 'amount');
let fee = undefined;
const feeCostString = this.safeString (trade, 'feeAmount');
if (feeCostString !== undefined) {
const feeCurrencyId = this.safeString (trade, 'feeCurrency');
fee = {
'cost': feeCostString,
'currency': this.safeCurrencyCode (feeCurrencyId),
};
}
market = this.safeMarket (undefined, market);
return this.safeTrade ({
'info': trade,
'id': this.safeString (trade, 'tid'),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'type': undefined,
'side': side,
'order': this.safeString (trade, 'orderId'),
'takerOrMaker': takerOrMaker,
'price': price,
'amount': amount,
'cost': undefined,
'fee': fee,
}, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchTrades() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const swap = market['swap'];
const request = {
// 'market': market['id'], // SPOT
// 'symbol': market['id'], // SWAP
// 'side': 1, // SWAP
// 'dateRange': 0, // SWAP
// 'startTime': since, // SWAP
// 'endtime': this.milliseconds (), // SWAP
// 'pageNum': 1, // SWAP
// 'pageSize': limit, // SWAP default is 10
};
if (limit !== undefined) {
request['pageSize'] = limit;
}
if (since !== undefined) {
request['startTime'] = since;
}
const marketIdField = swap ? 'symbol' : 'market';
request[marketIdField] = market['id'];
if (swap && params['pageNum'] === undefined) {
request['pageNum'] = 1;
}
const method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PublicGetTrades',
'swap': 'contractV2PrivateGetTradeTradeHistory',
});
let response = await this[method] (this.extend (request, params));
//
// Spot
//
// [
// {"date":1624537391,"amount":"0.0142","price":"33936.42","trade_type":"ask","type":"sell","tid":1718869018},
// {"date":1624537391,"amount":"0.0010","price":"33936.42","trade_type":"ask","type":"sell","tid":1718869020},
// {"date":1624537391,"amount":"0.0133","price":"33936.42","trade_type":"ask","type":"sell","tid":1718869021},
// ]
//
// Swap
//
// {
// "code": 10000,
// "data": {
// "list": [
// {
// "amount": "0.002",
// "createTime": "1645787446034",
// "feeAmount": "-0.05762699",
// "feeCurrency": "USDT",
// "id": "6902932868050395136",
// "maker": false,
// "orderId": "6902932868042006528",
// "price": "38417.99",
// "relizedPnl": "0.30402",
// "side": 4,
// "userId": "6896693805014120448"
// },
// ],
// "pageNum": 1,
// "pageSize": 10
// },
// "desc": "操作成功"
// }
//
if (swap) {
const data = this.safeValue (response, 'data');
response = this.safeValue (data, 'list');
}
return this.parseTrades (response, market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const swap = market['swap'];
const spot = market['spot'];
const timeInForce = this.safeString (params, 'timeInForce');
if (type === 'market') {
throw new InvalidOrder (this.id + ' createOrder() on ' + market['type'] + ' markets does not allow market orders');
}
const method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PrivateGetOrder',
'swap': 'contractV2PrivatePostTradeOrder',
});
const request = {
'amount': this.amountToPrecision (symbol, amount),
};
if (price) {
request['price'] = this.priceToPrecision (symbol, price);
}
if (spot) {
request['tradeType'] = (side === 'buy') ? '1' : '0';
request['currency'] = market['id'];
} else if (swap) {
const reduceOnly = this.safeValue (params, 'reduceOnly');
params = this.omit (params, 'reduceOnly');
if (side === 'sell' && reduceOnly) {
request['side'] = 3; // close long
} else if (side === 'buy' && reduceOnly) {
request['side'] = 4; // close short
} else if (side === 'buy') {
request['side'] = 1; // open long
} else if (side === 'sell') {
request['side'] = 2; // open short
}
if (type === 'limit') {
request['action'] = 1;
} else if (timeInForce === 'IOC') {
request['action'] = 3;
} else if (timeInForce === 'PO') {
request['action'] = 4;
} else if (timeInForce === 'FOK') {
request['action'] = 5;
} else {
request['action'] = type;
}
request['symbol'] = market['id'];
request['clientOrderId'] = params['clientOrderId']; // OPTIONAL '^[a-zA-Z0-9-_]{1,36}$', // The user-defined order number
request['extend'] = params['extend']; // OPTIONAL {"orderAlgos":[{"bizType":1,"priceType":1,"triggerPrice":"70000"},{"bizType":2,"priceType":1,"triggerPrice":"40000"}]}
}
let response = await this[method] (this.extend (request, params));
//
// Spot
//
// {
// "code": 1000,
// "message": "操作成功",
// "id": "202202224851151555"
// }
//
// Swap
//
// {
// "code": 10000,
// "desc": "操作成功",
// "data": {
// "orderId": "6901786759944937472",
// "orderCode": null
// }
// }
//
if (swap) {
response = this.safeValue (response, 'data');
}
response['timeInForce'] = timeInForce;
response['type'] = request['tradeType'];
response['total_amount'] = amount;
response['price'] = price;
return this.parseOrder (response, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const swap = market['swap'];
const request = {
// 'currency': this.marketId (symbol), // only applicable to SPOT
// 'id': id.toString (), // only applicable to SPOT
// 'symbol': this.marketId (symbol), // only applicable to SWAP
// 'orderId': id.toString (), // only applicable to SWAP
// 'clientOrderId': params['clientOrderId'], // only applicable to SWAP
};
const marketIdField = swap ? 'symbol' : 'currency';
request[marketIdField] = this.marketId (symbol);
const orderIdField = swap ? 'orderId' : 'id';
request[orderIdField] = id.toString ();
const method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PrivateGetCancelOrder',
'swap': 'contractV2PrivatePostTradeCancelOrder',
});
const response = await this[method] (this.extend (request, params));
//
// Spot
//
// {
// "code": 1000,
// "message": "Success。"
// }
//
// Swap
//
// {
// "code": 10007,
// "desc": "orderId与clientOrderId选填1个"
// }
//
return this.parseOrder (response, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelAllOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
if (market['spot']) {
throw new NotSupported (this.id + ' cancelAllOrders() is not supported on ' + market['type'] + ' markets');
}
const request = {
'symbol': market['id'],
};
return await this.contractV2PrivatePostTradeCancelAllOrders (this.extend (request, params));
}
async fetchOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrder() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const swap = market['swap'];
const request = {
// 'currency': this.marketId (symbol), // only applicable to SPOT
// 'id': id.toString (), // only applicable to SPOT
// 'symbol': this.marketId (symbol), // only applicable to SWAP
// 'orderId': id.toString (), // only applicable to SWAP
// 'clientOrderId': params['clientOrderId'], // only applicable to SWAP
};
const marketIdField = swap ? 'symbol' : 'currency';
request[marketIdField] = this.marketId (symbol);
const orderIdField = swap ? 'orderId' : 'id';
request[orderIdField] = id.toString ();
const method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PrivateGetGetOrder',
'swap': 'contractV2PrivateGetTradeGetOrder',
});
let response = await this[method] (this.extend (request, params));
//
// Spot
//
// {
// 'total_amount': 0.01,
// 'id': '20180910244276459',
// 'price': 180.0,
// 'trade_date': 1536576744960,
// 'status': 2,
// 'trade_money': '1.96742',
// 'trade_amount': 0.01,
// 'type': 0,
// 'currency': 'eth_usdt'
// }
//
// Swap
//
// {
// "code": 10000,
// "data": {
// "action": 1,
// "amount": "0.002",
// "availableAmount": "0.002",
// "availableValue": "60",
// "avgPrice": "0",
// "canCancel": true,
// "cancelStatus": 20,
// "createTime": "1646185684379",
// "entrustType": 1,
// "id": "6904603200733782016",
// "leverage": 2,
// "margin": "30",
// "marketId": "100",
// "modifyTime": "1646185684416",
// "price": "30000",
// "priority": 0,
// "showStatus": 1,
// "side": 1,
// "sourceType": 4,
// "status": 12,
// "tradeAmount": "0",
// "tradeValue": "0",
// "type": 1,
// "userId": "6896693805014120448",
// "value": "60"
// },
// "desc":"操作成功"
// }
//
if (swap) {
response = this.safeValue (response, 'data', {});
}
return this.parseOrder (response, market);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + 'fetchOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const swap = market['swap'];
const request = {
'pageSize': limit, // default pageSize is 50 for spot, 30 for swap
// 'currency': market['id'], // only applicable to SPOT
// 'pageIndex': 1, // only applicable to SPOT
// 'symbol': market['id'], // only applicable to SWAP
// 'pageNum': 1, // only applicable to SWAP
// 'type': params['type'], // only applicable to SWAP
// 'side': params['side'], // only applicable to SWAP
// 'dateRange': params['dateRange'], // only applicable to SWAP
// 'action': params['action'], // only applicable to SWAP
// 'endTime': params['endTime'], // only applicable to SWAP
// 'startTime': since, // only applicable to SWAP
};
const marketIdField = market['swap'] ? 'symbol' : 'currency';
request[marketIdField] = market['id'];
const pageNumField = market['swap'] ? 'pageNum' : 'pageIndex';
request[pageNumField] = 1;
if (swap) {
request['startTime'] = since;
}
let method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PrivateGetGetOrdersIgnoreTradeType',
'swap': 'contractV2PrivateGetTradeGetAllOrders',
});
// tradeType 交易类型1/0[buy/sell]
if ('tradeType' in params) {
method = 'spotV1PrivateGetGetOrdersNew';
}
let response = undefined;
try {
response = await this[method] (this.extend (request, params));
} catch (e) {
if (e instanceof OrderNotFound) {
return [];
}
throw e;
}
// Spot
//
// [
// {
// "acctType": 0,
// "currency": "btc_usdt",
// "fees": 0,
// "id": "202202234857482656",
// "price": 30000.0,
// "status": 3,
// "total_amount": 0.0006,
// "trade_amount": 0.0000,
// "trade_date": 1645610254524,
// "trade_money": 0.000000,
// "type": 1,
// "useZbFee": false,
// "webId": 0
// }
// ]
//
// Swap
//
// {
// "code": 10000,
// "data": {
// "list": [
// {
// "action": 1,
// "amount": "0.004",
// "availableAmount": "0.004",
// "availableValue": "120",
// "avgPrice": "0",
// "canCancel": true,
// "cancelStatus": 20,
// "createTime": "1645609643885",
// "entrustType": 1,
// "id": "6902187111785635850",
// "leverage": 5,
// "margin": "24",
// "marketId": "100",
// "marketName": "BTC_USDT",
// "modifyTime": "1645609643889",
// "price": "30000",
// "showStatus": 1,
// "side": 1,
// "sourceType": 1,
// "status": 12,
// "tradeAmount": "0",
// "tradeValue": "0",
// "type": 1,
// "userId": "6896693805014120448",
// "value": "120"
// },
// ],
// "pageNum": 1,
// "pageSize": 10
// },
// "desc": "操作成功"
// }
//
if (swap) {
const data = this.safeValue (response, 'data', {});
response = this.safeValue (data, 'list', []);
}
return this.parseOrders (response, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = 10, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + 'fetchClosedOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'currency': market['id'],
'pageIndex': 1, // default pageIndex is 1
'pageSize': limit, // default pageSize is 10, doesn't work with other values now
};
const response = await this.spotV1PrivateGetGetFinishedAndPartialOrders (this.extend (request, params));
return this.parseOrders (response, market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + 'fetchOpenOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const swap = market['swap'];
const request = {
// 'pageSize': limit, // default pageSize is 10 for spot, 30 for swap
// 'currency': market['id'], // spot only
// 'pageIndex': 1, // spot only
// 'symbol': market['id'], // swap only
// 'pageNum': 1, // swap only
// 'type': params['type'], // swap only
// 'side': params['side'], // swap only
// 'action': params['action'], // swap only
};
if (limit !== undefined) {
request['pageSize'] = limit; // default pageSize is 10 for spot, 30 for swap
}
const marketIdField = market['swap'] ? 'symbol' : 'currency';
request[marketIdField] = market['id'];
const pageNumField = market['swap'] ? 'pageNum' : 'pageIndex';
request[pageNumField] = 1;
if (swap && (since !== undefined)) {
request['startTime'] = since;
}
let method = this.getSupportedMapping (market['type'], {
'spot': 'spotV1PrivateGetGetUnfinishedOrdersIgnoreTradeType',
'swap': 'contractV2PrivateGetTradeGetUndoneOrders',
});
// tradeType 交易类型1/0[buy/sell]
if ('tradeType' in params) {
method = 'spotV1PrivateGetGetOrdersNew';
}
let response = undefined;
try {
response = await this[method] (this.extend (request, params));
} catch (e) {
if (e instanceof OrderNotFound) {
return [];
}
throw e;
}
//
// Spot
//
// [
// {
// "currency": "btc_usdt",
// "id": "20150928158614292",
// "price": 1560,
// "status": 3,
// "total_amount": 0.1,
// "trade_amount": 0,
// "trade_date": 1443410396717,
// "trade_money": 0,
// "type": 0,
// "fees": "0.03",
// "useZbFee": true
// },
// ]
//
// Swap
//
// {
// "code": 10000,
// "data": {
// "list": [
// {
// "action": 1,
// "amount": "0.003",
// "availableAmount": "0.003",
// "availableValue": "90",
// "avgPrice": "0",
// "canCancel": true,
// "cancelStatus": 20,
// "createTime": "1645694610880",
// "entrustType": 1,
// "id": "6902543489192632320",
// "leverage": 5,
// "margin": "18",
// "marketId": "100",
// "modifyTime": "1645694610883",
// "price": "30000",
// "priority": 0,
// "showStatus": 1,
// "side": 1,
// "sourceType": 1,
// "status": 12,
// "tradeAmount": "0",
// "tradeValue": "0",
// "type": 1,
// "userId": "6896693805014120448",
// "value": "90"
// }
// ],
// "pageNum": 1,
// "pageSize": 30
// },
// "desc": "操作成功"
// }
//
if (swap) {
const data = this.safeValue (response, 'data', {});
response = this.safeValue (data, 'list', []);
}
return this.parseOrders (response, market, since, limit);
}
parseOrder (order, market = undefined) {
//
// fetchOrder Spot
//
// {
// acctType: 0,
// currency: 'btc_usdt',
// fees: 3.6e-7,
// id: '202102282829772463',
// price: 45177.5,
// status: 2,
// total_amount: 0.0002,
// trade_amount: 0.0002,
// trade_date: 1614515104998,
// trade_money: 8.983712,
// type: 1,
// useZbFee: false
// },
//
// fetchOrder Swap
//
// {
// "action": 1,
// "amount": "0.002",
// "availableAmount": "0.002",
// "availableValue": "60",
// "avgPrice": "0",
// "canCancel": true,
// "cancelStatus": 20,
// "createTime": "1646185684379",
// "entrustType": 1,
// "id": "6904603200733782016",
// "leverage": 2,
// "margin": "30",
// "marketId": "100",
// "modifyTime": "1646185684416",
// "price": "30000",
// "priority": 0,
// "showStatus": 1,
// "side": 1,
// "sourceType": 4,
// "status": 12,
// "tradeAmount": "0",
// "tradeValue": "0",
// "type": 1,
// "userId": "6896693805014120448",
// "value": "60"
// },
//
// Spot
//
// {
// code: '1000',
// message: '操作成功',
// id: '202202224851151555',
// type: '1',
// total_amount: 0.0002,
// price: 30000
// }
//
// Swap
//
// {
// orderId: '6901786759944937472',
// orderCode: null,
// timeInForce: 'IOC',
// total_amount: 0.0002,
// price: 30000
// }
//
let orderId = market['swap'] ? this.safeValue (order, 'orderId') : this.safeValue (order, 'id');
if (orderId === undefined) {
orderId = this.safeValue (order, 'id');
}
let side = this.safeInteger (order, 'type');
if (side === undefined) {
side = undefined;
} else {
side = (side === 1) ? 'buy' : 'sell';
}
let timestamp = this.safeInteger (order, 'trade_date');
if (timestamp === undefined) {
timestamp = this.safeInteger (order, 'createTime');
}
const marketId = this.safeString (order, 'currency');
market = this.safeMarket (marketId, market, '_');
const price = this.safeString (order, 'price');
const filled = market['swap'] ? this.safeString (order, 'tradeAmount') : this.safeString (order, 'trade_amount');
let amount = this.safeString (order, 'total_amount');
if (amount === undefined) {
amount = this.safeString (order, 'amount');
}
const cost = this.safeString (order, 'trade_money');
const status = this.parseOrderStatus (this.safeString (order, 'status'));
const timeInForce = this.safeString (order, 'timeInForce');
const postOnly = (timeInForce === 'PO');
const feeCost = this.safeNumber (order, 'fees');
let fee = undefined;
if (feeCost !== undefined) {
let feeCurrency = undefined;
const zbFees = this.safeValue (order, 'useZbFee');
if (zbFees === true) {
feeCurrency = 'ZB';
} else {
feeCurrency = (side === 'sell') ? market['quote'] : market['base'];
}
fee = {
'cost': feeCost,
'currency': feeCurrency,
};
}
return this.safeOrder ({
'info': order,
'id': orderId,
'clientOrderId': this.safeString (order, 'userId'),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': market['symbol'],
'type': 'limit', // market order is not available on ZB
'timeInForce': timeInForce,
'postOnly': postOnly,
'side': side,
'price': price,
'stopPrice': undefined,
'average': this.safeString (order, 'avgPrice'),
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': undefined,
'status': status,
'fee': fee,
'trades': undefined,
}, market);
}
parseOrderStatus (status) {
const statuses = {
'0': 'open',
'1': 'canceled',
'2': 'closed',
'3': 'open', // partial
};
return this.safeString (statuses, status, status);
}
parseTransactionStatus (status) {
const statuses = {
'0': 'pending', // submitted, pending confirmation
'1': 'failed',
'2': 'ok',
'3': 'canceled',
'5': 'ok', // confirmed
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// withdraw
//
// {
// "code": 1000,
// "message": "success",
// "id": "withdrawalId"
// }
//
// fetchWithdrawals
//
// {
// "amount": 0.01,
// "fees": 0.001,
// "id": 2016042556231,
// "manageTime": 1461579340000,
// "status": 3,
// "submitTime": 1461579288000,
// "toAddress": "14fxEPirL9fyfw1i9EF439Pq6gQ5xijUmp",
// }
//
// fetchDeposits
//
// {
// "address": "1FKN1DZqCm8HaTujDioRL2Aezdh7Qj7xxx",
// "amount": "1.00000000",
// "confirmTimes": 1,
// "currency": "BTC",
// "description": "Successfully Confirm",
// "hash": "7ce842de187c379abafadd64a5fe66c5c61c8a21fb04edff9532234a1dae6xxx",
// "id": 558,
// "itransfer": 1,
// "status": 2,
// "submit_time": "2016-12-07 18:51:57",
// }
//
const id = this.safeString (transaction, 'id');
const txid = this.safeString (transaction, 'hash');
const amount = this.safeNumber (transaction, 'amount');
let timestamp = this.parse8601 (this.safeString (transaction, 'submit_time'));
timestamp = this.safeInteger (transaction, 'submitTime', timestamp);
let address = this.safeString2 (transaction, 'toAddress', 'address');
let tag = undefined;
if (address !== undefined) {
const parts = address.split ('_');
address = this.safeString (parts, 0);
tag = this.safeString (parts, 1);
}
const confirmTimes = this.safeInteger (transaction, 'confirmTimes');
const updated = this.safeInteger (transaction, 'manageTime');
let type = undefined;
const currencyId = this.safeString (transaction, 'currency');
const code = this.safeCurrencyCode (currencyId, currency);
if (address !== undefined) {
type = (confirmTimes === undefined) ? 'withdrawal' : 'deposit';
}
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
let fee = undefined;
const feeCost = this.safeNumber (transaction, 'fees');
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': code,
};
}
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'network': undefined,
'addressFrom': undefined,
'address': address,
'addressTo': address,
'tagFrom': undefined,
'tag': tag,
'tagTo': tag,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': fee,
};
}
async setLeverage (leverage, symbol = undefined, params = {}) {
await this.loadMarkets ();
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' setLeverage() requires a symbol argument');
}
if ((leverage < 1) || (leverage > 125)) {
throw new BadRequest (this.id + ' leverage should be between 1 and 125');
}
const market = this.market (symbol);
let accountType = undefined;
if (!market['swap']) {
throw new BadSymbol (this.id + ' setLeverage() supports swap contracts only');
} else {
accountType = 1;
}
const request = {
'symbol': market['id'],
'leverage': leverage,
'futuresAccountType': accountType, // 1: USDT perpetual swaps
};
return await this.contractV2PrivatePostSettingSetLeverage (this.extend (request, params));
}
async fetchFundingRateHistory (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'symbol': market['id'],
// 'startTime': since,
// 'endTime': endTime, // current time by default
// 'limit': limit, // default 100, max 1000
};
if (symbol !== undefined) {
const market = this.market (symbol);
symbol = market['symbol'];
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['startTime'] = since;
}
const till = this.safeInteger (params, 'till');
const endTime = this.safeString (params, 'endTime');
params = this.omit (params, [ 'endTime', 'till' ]);
if (till !== undefined) {
request['endTime'] = till;
} else if (endTime !== undefined) {
request['endTime'] = endTime;
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.contractV2PublicGetFundingRate (this.extend (request, params));
//
// {
// "code": 10000,
// "data": [
// {
// "symbol": "BTC_USDT",
// "fundingRate": "0.0001",
// "fundingTime": "1645171200000"
// },
// ],
// "desc": "操作成功"
// }
//
const data = this.safeValue (response, 'data');
const rates = [];
for (let i = 0; i < data.length; i++) {
const entry = data[i];
const marketId = this.safeString (entry, 'symbol');
const symbol = this.safeSymbol (marketId);
const timestamp = this.safeString (entry, 'fundingTime');
rates.push ({
'info': entry,
'symbol': symbol,
'fundingRate': this.safeNumber (entry, 'fundingRate'),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
});
}
const sorted = this.sortBy (rates, 'timestamp');
return this.filterBySymbolSinceLimit (sorted, symbol, since, limit);
}
async fetchFundingRate (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (!market['swap']) {
throw new BadSymbol (this.id + ' fetchFundingRate() does not supports contracts only');
}
const request = {
'symbol': market['id'],
};
const response = await this.contractV1PublicGetFundingRate (this.extend (request, params));
//
// {
// "code": 10000,
// "desc": "操作成功",
// "data": {
// "fundingRate": "0.0001",
// "nextCalculateTime": "2022-02-19 00:00:00"
// }
// }
//
const data = this.safeValue (response, 'data');
return this.parseFundingRate (data, market);
}
parseFundingRate (contract, market = undefined) {
//
// fetchFundingRate
//
// {
// "fundingRate": "0.0001",
// "nextCalculateTime": "2022-02-19 00:00:00"
// }
//
// fetchFundingRates
//
// {
// "symbol": "BTC_USDT",
// "markPrice": "43254.42",
// "indexPrice": "43278.61",
// "lastFundingRate": "0.0001",
// "nextFundingTime": "1646121600000"
// }
//
const marketId = this.safeString (contract, 'symbol');
const symbol = this.safeSymbol (marketId, market);
const fundingRate = this.safeNumber (contract, 'fundingRate');
const nextFundingDatetime = this.safeString (contract, 'nextCalculateTime');
return {
'info': contract,
'symbol': symbol,
'markPrice': this.safeString (contract, 'markPrice'),
'indexPrice': this.safeString (contract, 'indexPrice'),
'interestRate': undefined,
'estimatedSettlePrice': undefined,
'timestamp': undefined,
'datetime': undefined,
'fundingRate': fundingRate,
'fundingTimestamp': undefined,
'fundingDatetime': undefined,
'nextFundingRate': undefined,
'nextFundingTimestamp': this.parse8601 (nextFundingDatetime),
'nextFundingDatetime': nextFundingDatetime,
'previousFundingRate': this.safeString (contract, 'lastFundingRate'),
'previousFundingTimestamp': undefined,
'previousFundingDatetime': undefined,
};
}
async fetchFundingRates (symbols, params = {}) {
await this.loadMarkets ();
const response = await this.contractV2PublicGetPremiumIndex (params);
//
// {
// "code": 10000,
// "data": [
// {
// "symbol": "BTC_USDT",
// "markPrice": "43254.42",
// "indexPrice": "43278.61",
// "lastFundingRate": "0.0001",
// "nextFundingTime": "1646121600000"
// },
// ],
// "desc":"操作成功"
// }
//
const data = this.safeValue (response, 'data', []);
const result = this.parseFundingRates (data);
return this.filterByArray (result, 'symbol', symbols);
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
const password = this.safeString (params, 'safePwd', this.password);
if (password === undefined) {
throw new ArgumentsRequired (this.id + ' withdraw() requires exchange.password or a safePwd parameter');
}
const fees = this.safeNumber (params, 'fees');
if (fees === undefined) {
throw new ArgumentsRequired (this.id + ' withdraw() requires a fees parameter');
}
this.checkAddress (address);
await this.loadMarkets ();
const currency = this.currency (code);
if (tag !== undefined) {
address += '_' + tag;
}
const request = {
'amount': this.currencyToPrecision (code, amount),
'currency': currency['id'],
'fees': this.currencyToPrecision (code, fees),
// 'itransfer': 0, // agree for an internal transfer, 0 disagree, 1 agree, the default is to disagree
'method': 'withdraw',
'receiveAddr': address,
'safePwd': password,
};
const response = await this.spotV1PrivateGetWithdraw (this.extend (request, params));
//
// {
// "code": 1000,
// "message": "success",
// "id": "withdrawalId"
// }
//
const transaction = this.parseTransaction (response, currency);
return this.extend (transaction, {
'type': 'withdrawal',
'address': address,
'addressTo': address,
'amount': amount,
});
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'currency': currency['id'],
// 'pageIndex': 1,
// 'pageSize': limit,
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['id'];
}
if (limit !== undefined) {
request['pageSize'] = limit;
}
const response = await this.spotV1PrivateGetGetWithdrawRecord (this.extend (request, params));
//
// {
// "code": 1000,
// "message": {
// "des": "success",
// "isSuc": true,
// "datas": {
// "list": [
// {
// "amount": 0.01,
// "fees": 0.001,
// "id": 2016042556231,
// "manageTime": 1461579340000,
// "status": 3,
// "submitTime": 1461579288000,
// "toAddress": "14fxEPirL9fyfw1i9EF439Pq6gQ5xijUmp",
// },
// ],
// "pageIndex": 1,
// "pageSize": 10,
// "totalCount": 4,
// "totalPage": 1
// }
// }
// }
//
const message = this.safeValue (response, 'message', {});
const datas = this.safeValue (message, 'datas', {});
const withdrawals = this.safeValue (datas, 'list', []);
return this.parseTransactions (withdrawals, currency, since, limit);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'currency': currency['id'],
// 'pageIndex': 1,
// 'pageSize': limit,
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['id'];
}
if (limit !== undefined) {
request['pageSize'] = limit;
}
const response = await this.spotV1PrivateGetGetChargeRecord (this.extend (request, params));
//
// {
// "code": 1000,
// "message": {
// "des": "success",
// "isSuc": true,
// "datas": {
// "list": [
// {
// "address": "1FKN1DZqCm8HaTujDioRL2Aezdh7Qj7xxx",
// "amount": "1.00000000",
// "confirmTimes": 1,
// "currency": "BTC",
// "description": "Successfully Confirm",
// "hash": "7ce842de187c379abafadd64a5fe66c5c61c8a21fb04edff9532234a1dae6xxx",
// "id": 558,
// "itransfer": 1,
// "status": 2,
// "submit_time": "2016-12-07 18:51:57",
// },
// ],
// "pageIndex": 1,
// "pageSize": 10,
// "total": 8
// }
// }
// }
//
const message = this.safeValue (response, 'message', {});
const datas = this.safeValue (message, 'datas', {});
const deposits = this.safeValue (datas, 'list', []);
return this.parseTransactions (deposits, currency, since, limit);
}
async fetchPosition (symbol, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const request = {
'futuresAccountType': 1, // 1: USDT-M Perpetual Futures
// 'symbol': market['id'],
// 'marketId': market['id'],
// 'side': params['side'],
};
const response = await this.contractV2PrivateGetPositionsGetPositions (this.extend (request, params));
//
// {
// "code": 10000,
// "data": [
// {
// "amount": "0.002",
// "appendAmount": "0",
// "autoLightenRatio": "0",
// "avgPrice": "38570",
// "bankruptcyPrice": "46288.41",
// "contractType": 1,
// "createTime": "1645784751867",
// "freezeAmount": "0",
// "freezeList": [
// {
// "amount": "15.436832",
// "currencyId": "6",
// "currencyName": "usdt",
// "modifyTime": "1645784751867"
// }
// ],
// "id": "6902921567894972486",
// "lastAppendAmount": "0",
// "leverage": 5,
// "liquidateLevel": 1,
// "liquidatePrice": "46104",
// "maintainMargin": "0.30912384",
// "margin": "15.436832",
// "marginAppendCount": 0,
// "marginBalance": "15.295872",
// "marginMode": 1,
// "marginRate": "0.020209",
// "marketId": "100",
// "marketName": "BTC_USDT",
// "modifyTime": "1645784751867",
// "nominalValue": "77.14736",
// "originAppendAmount": "0",
// "originId": "6902921567894972591",
// "refreshType": "Timer",
// "returnRate": "-0.0091",
// "side": 0,
// "status": 1,
// "unrealizedPnl": "-0.14096",
// "userId": "6896693805014120448"
// }
// ],
// "desc": "操作成功"
// }
//
const data = this.safeValue (response, 'data', []);
const firstPosition = this.safeValue (data, 0);
return this.parsePosition (firstPosition, market);
}
async fetchPositions (symbols = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbols !== undefined) {
market = this.market (symbols);
}
const request = {
'futuresAccountType': 1, // 1: USDT-M Perpetual Futures
// 'symbol': market['id'],
// 'marketId': market['id'],
// 'side': params['side'],
};
const response = await this.contractV2PrivateGetPositionsGetPositions (this.extend (request, params));
//
// {
// "code": 10000,
// "data": [
// {
// "amount": "0.002",
// "appendAmount": "0",
// "autoLightenRatio": "0",
// "avgPrice": "38570",
// "bankruptcyPrice": "46288.41",
// "contractType": 1,
// "createTime": "1645784751867",
// "freezeAmount": "0",
// "freezeList": [
// {
// "amount": "15.436832",
// "currencyId": "6",
// "currencyName": "usdt",
// "modifyTime": "1645784751867"
// }
// ],
// "id": "6902921567894972486",
// "lastAppendAmount": "0",
// "leverage": 5,
// "liquidateLevel": 1,
// "liquidatePrice": "46104",
// "maintainMargin": "0.30912384",
// "margin": "15.436832",
// "marginAppendCount": 0,
// "marginBalance": "15.295872",
// "marginMode": 1,
// "marginRate": "0.020209",
// "marketId": "100",
// "marketName": "BTC_USDT",
// "modifyTime": "1645784751867",
// "nominalValue": "77.14736",
// "originAppendAmount": "0",
// "originId": "6902921567894972591",
// "refreshType": "Timer",
// "returnRate": "-0.0091",
// "side": 0,
// "status": 1,
// "unrealizedPnl": "-0.14096",
// "userId": "6896693805014120448"
// },
// ],
// "desc": "操作成功"
// }
//
const data = this.safeValue (response, 'data', []);
return this.parsePositions (data, market);
}
parsePosition (position, market = undefined) {
//
// {
// "amount": "0.002",
// "appendAmount": "0",
// "autoLightenRatio": "0",
// "avgPrice": "38570",
// "bankruptcyPrice": "46288.41",
// "contractType": 1,
// "createTime": "1645784751867",
// "freezeAmount": "0",
// "freezeList": [
// {
// "amount": "15.436832",
// "currencyId": "6",
// "currencyName": "usdt",
// "modifyTime": "1645784751867"
// }
// ],
// "id": "6902921567894972486",
// "lastAppendAmount": "0",
// "leverage": 5,
// "liquidateLevel": 1,
// "liquidatePrice": "46104",
// "maintainMargin": "0.30912384",
// "margin": "15.436832",
// "marginAppendCount": 0,
// "marginBalance": "15.295872",
// "marginMode": 1,
// "marginRate": "0.020209",
// "marketId": "100",
// "marketName": "BTC_USDT",
// "modifyTime": "1645784751867",
// "nominalValue": "77.14736",
// "originAppendAmount": "0",
// "originId": "6902921567894972591",
// "refreshType": "Timer",
// "returnRate": "-0.0091",
// "side": 0,
// "status": 1,
// "unrealizedPnl": "-0.14096",
// "userId": "6896693805014120448"
// }
//
market = this.safeMarket (this.safeString (position, 'marketName'), market);
const symbol = market['symbol'];
const contracts = this.safeString (position, 'amount');
const entryPrice = this.safeNumber (position, 'avgPrice');
const initialMargin = this.safeString (position, 'margin');
const rawSide = this.safeString (position, 'side');
const side = (rawSide === '1') ? 'long' : 'short';
const openType = this.safeString (position, 'marginMode');
const marginType = (openType === '1') ? 'isolated' : 'cross';
const leverage = this.safeString (position, 'leverage');
const liquidationPrice = this.safeNumber (position, 'liquidatePrice');
const unrealizedProfit = this.safeNumber (position, 'unrealizedPnl');
const maintenanceMargin = this.safeNumber (position, 'maintainMargin');
const marginRatio = this.safeNumber (position, 'marginRate');
const notional = this.safeNumber (position, 'nominalValue');
const percentage = Precise.stringMul (this.safeString (position, 'returnRate'), '100');
const timestamp = this.safeNumber (position, 'createTime');
return {
'info': position,
'symbol': symbol,
'contracts': this.parseNumber (contracts),
'contractSize': undefined,
'entryPrice': entryPrice,
'collateral': undefined,
'side': side,
'unrealizedProfit': unrealizedProfit,
'leverage': this.parseNumber (leverage),
'percentage': percentage,
'marginType': marginType,
'notional': notional,
'markPrice': undefined,
'liquidationPrice': liquidationPrice,
'initialMargin': this.parseNumber (initialMargin),
'initialMarginPercentage': undefined,
'maintenanceMargin': maintenanceMargin,
'maintenanceMarginPercentage': undefined,
'marginRatio': marginRatio,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
};
}
parsePositions (positions) {
const result = [];
for (let i = 0; i < positions.length; i++) {
result.push (this.parsePosition (positions[i]));
}
return result;
}
parseLedgerEntryType (type) {
const types = {
'1': 'realized pnl',
'2': 'commission',
'3': 'funding fee subtract',
'4': 'funding fee addition',
'5': 'insurance clear',
'6': 'transfer in',
'7': 'transfer out',
'8': 'margin addition',
'9': 'margin subtraction',
'10': 'commission addition',
'11': 'bill type freeze',
'12': 'bill type unfreeze',
'13': 'system take over margin',
'14': 'transfer',
'15': 'realized pnl collection',
'16': 'funding fee collection',
'17': 'recommender return commission',
'18': 'by level subtract positions',
'19': 'system add',
'20': 'system subtract',
'23': 'trading competition take over fund',
'24': 'trading contest tickets',
'25': 'return of trading contest tickets',
'26': 'experience expired recall',
'50': 'test register gift',
'51': 'register gift',
'52': 'deposit gift',
'53': 'trading volume gift',
'54': 'awards gift',
'55': 'trading volume gift',
'56': 'awards gift expire',
'201': 'open positions',
'202': 'close positions',
'203': 'take over positions',
'204': 'trading competition take over positions',
'205': 'one way open long',
'206': 'one way open short',
'207': 'one way close long',
'208': 'one way close short',
'301': 'coupon deduction service charge',
'302': 'experience deduction',
'303': 'experience expired',
};
return this.safeString (types, type, type);
}
parseLedgerEntry (item, currency = undefined) {
//
// [
// {
// "type": 3,
// "changeAmount": "0.00434664",
// "isIn": 0,
// "beforeAmount": "30.53353135",
// "beforeFreezeAmount": "21.547",
// "createTime": "1646121604997",
// "available": "30.52918471",
// "unit": "usdt",
// "symbol": "BTC_USDT"
// },
// ],
//
const timestamp = this.safeString (item, 'createTime');
let direction = undefined;
const changeDirection = this.safeNumber (item, 'isIn');
if (changeDirection === 1) {
direction = 'increase';
} else {
direction = 'reduce';
}
let fee = undefined;
const feeCost = this.safeNumber (item, 'fee');
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': this.safeCurrencyCode (this.safeString (item, 'unit')),
};
}
return {
'id': this.safeString (item, 'id'),
'info': item,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'direction': direction,
'account': this.safeString (item, 'userId'),
'referenceId': undefined,
'referenceAccount': undefined,
'type': this.parseLedgerEntryType (this.safeInteger (item, 'type')),
'currency': this.safeCurrencyCode (this.safeString (item, 'unit')),
'amount': this.safeNumber (item, 'changeAmount'),
'before': this.safeNumber (item, 'beforeAmount'),
'after': this.safeNumber (item, 'available'),
'status': undefined,
'fee': fee,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
if (code === undefined) {
throw new ArgumentsRequired (this.id + ' fetchLedger() requires a code argument');
}
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'futuresAccountType': 1,
// 'currencyId': '11',
// 'type': 1,
// 'endTime': this.milliseconds (),
// 'pageNum': 1,
};
if (code !== undefined) {
request['currencyName'] = currency['id'];
}
if (since !== undefined) {
request['startTime'] = since;
}
if (limit !== undefined) {
request['pageSize'] = limit;
}
const response = await this.contractV2PrivateGetFundGetBill (this.extend (request, params));
//
// {
// "code": 10000,
// "data": {
// "list": [
// {
// "type": 3,
// "changeAmount": "0.00434664",
// "isIn": 0,
// "beforeAmount": "30.53353135",
// "beforeFreezeAmount": "21.547",
// "createTime": "1646121604997",
// "available": "30.52918471",
// "unit": "usdt",
// "symbol": "BTC_USDT"
// },
// ],
// "pageNum": 1,
// "pageSize": 10
// },
// "desc": "操作成功"
// }
//
const data = this.safeValue (response, 'data', {});
const list = this.safeValue (data, 'list', []);
return this.parseLedger (list, currency, since, limit);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
await this.loadMarkets ();
const [ marketType, query ] = this.handleMarketTypeAndParams ('transfer', undefined, params);
const currency = this.currency (code);
const margin = (marketType === 'margin');
const swap = (marketType === 'swap');
let side = undefined;
let marginMethod = undefined;
const request = {
'amount': amount, // Swap, Cross Margin, Isolated Margin
// 'coin': currency['id'], // Margin
// 'currencyName': currency['id'], // Swap
// 'clientId': this.safeString (params, 'clientId'), // Swap "2sdfsdfsdf232342"
// 'side': side, // Swap, 1:Deposit (zb account -> futures account),0:Withdrawal (futures account -> zb account)
// 'marketName': this.safeString (params, 'marketName'), // Isolated Margin
};
if (swap) {
if (fromAccount === 'spot' || toAccount === 'future') {
side = 1;
} else {
side = 0;
}
request['currencyName'] = currency['id'];
request['clientId'] = this.safeString (params, 'clientId');
request['side'] = side;
} else {
const defaultMargin = margin ? 'isolated' : 'cross';
const marginType = this.safeString2 (this.options, 'defaultMarginType', 'marginType', defaultMargin);
if (marginType === 'isolated') {
if (fromAccount === 'spot' || toAccount === 'isolated') {
marginMethod = 'spotV1PrivateGetTransferInLever';
} else {
marginMethod = 'spotV1PrivateGetTransferOutLever';
}
request['marketName'] = this.safeString (params, 'marketName');
} else if (marginType === 'cross') {
if (fromAccount === 'spot' || toAccount === 'cross') {
marginMethod = 'spotV1PrivateGetTransferInCross';
} else {
marginMethod = 'spotV1PrivateGetTransferOutCross';
}
}
request['coin'] = currency['id'];
}
const method = this.getSupportedMapping (marketType, {
'swap': 'contractV2PrivatePostFundTransferFund',
'margin': marginMethod,
});
const response = await this[method] (this.extend (request, query));
//
// Swap
//
// {
// "code": 10000,
// "data": "2sdfsdfsdf232342",
// "desc": "Success"
// }
//
// Margin
//
// {
// "code": 1000,
// "message": "Success"
// }
//
const timestamp = this.milliseconds ();
const transfer = {
'id': this.safeString (response, 'data'),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'currency': code,
'amount': amount,
'fromAccount': fromAccount,
'toAccount': toAccount,
'status': this.safeInteger (response, 'code'),
};
return this.parseTransfer (transfer, code);
}
parseTransfer (transfer, currency = undefined) {
//
// {
// "id": "2sdfsdfsdf232342",
// "timestamp": "",
// "datetime": "",
// "currency": "USDT",
// "amount": "10",
// "fromAccount": "futures account",
// "toAccount": "zb account",
// "status": 10000,
// }
//
const currencyId = this.safeString (transfer, 'currency');
return {
'info': transfer,
'id': this.safeString (transfer, 'id'),
'timestamp': this.safeInteger (transfer, 'timestamp'),
'datetime': this.safeString (transfer, 'datetime'),
'currency': this.safeCurrencyCode (currencyId, currency),
'amount': this.safeNumber (transfer, 'amount'),
'fromAccount': this.safeString (transfer, 'fromAccount'),
'toAccount': this.safeString (transfer, 'toAccount'),
'status': this.safeInteger (transfer, 'status'),
};
}
async modifyMarginHelper (symbol, amount, type, params = {}) {
if (params['positionsId'] === undefined) {
throw new ArgumentsRequired (this.id + ' modifyMarginHelper() requires a positionsId argument in the params');
}
await this.loadMarkets ();
const market = this.market (symbol);
amount = this.amountToPrecision (symbol, amount);
const position = this.safeString (params, 'positionsId');
const request = {
'positionsId': position,
'amount': amount,
'type': type, // 1 increase, 0 reduce
'futuresAccountType': 1, // 1: USDT Perpetual Futures
};
const response = await this.contractV2PrivatePostPositionsUpdateMargin (this.extend (request, params));
//
// {
// "code": 10000,
// "data": {
// "amount": "0.002",
// "appendAmount": "0",
// "avgPrice": "43927.23",
// "bankruptcyPrice": "41730.86",
// "createTime": "1646208695609",
// "freezeAmount": "0",
// "id": "6900781818669377576",
// "keyMark": "6896693805014120448-100-1-",
// "lastAppendAmount": "0",
// "lastTime": "1646209235505",
// "leverage": 20,
// "liquidateLevel": 1,
// "liquidatePrice": "41898.46",
// "maintainMargin": "0",
// "margin": "4.392723",
// "marginAppendCount": 0,
// "marginBalance": "0",
// "marginMode": 1,
// "marginRate": "0",
// "marketId": "100",
// "marketName": "BTC_USDT",
// "modifyTime": "1646209235505",
// "nominalValue": "87.88828",
// "originAppendAmount": "0",
// "originId": "6904699716827818029",
// "positionsMode": 2,
// "sellerCurrencyId": "1",
// "side": 1,
// "status": 1,
// "unrealizedPnl": "0.03382",
// "usable": true,
// "userId": "6896693805014120448"
// },
// "desc":"操作成功"
// }
//
const data = this.safeValue (response, 'data', {});
const side = (type === 1) ? 'add' : 'reduce';
const errorCode = this.safeInteger (data, 'status');
const status = (errorCode === 1) ? 'ok' : 'failed';
return {
'info': response,
'type': side,
'amount': amount,
'code': market['quote'],
'symbol': market['symbol'],
'status': status,
};
}
async reduceMargin (symbol, amount, params = {}) {
if (params['positionsId'] === undefined) {
throw new ArgumentsRequired (this.id + ' reduceMargin() requires a positionsId argument in the params');
}
return await this.modifyMarginHelper (symbol, amount, 0, params);
}
async addMargin (symbol, amount, params = {}) {
if (params['positionsId'] === undefined) {
throw new ArgumentsRequired (this.id + ' addMargin() requires a positionsId argument in the params');
}
return await this.modifyMarginHelper (symbol, amount, 1, params);
}
async fetchBorrowRate (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'coin': currency['id'],
};
const response = await this.spotV1PrivateGetGetLoans (this.extend (request, params));
//
// {
// code: '1000',
// message: '操作成功',
// result: [
// {
// interestRateOfDay: '0.0005',
// repaymentDay: '30',
// amount: '148804.4841',
// balance: '148804.4841',
// rateOfDayShow: '0.05 %',
// coinName: 'USDT',
// lowestAmount: '0.01'
// },
// ]
// }
//
const timestamp = this.milliseconds ();
const data = this.safeValue (response, 'result');
const rates = [];
for (let i = 0; i < data.length; i++) {
const entry = data[i];
rates.push ({
'currency': this.safeCurrencyCode (this.safeString (entry, 'coinName')),
'rate': this.safeNumber (entry, 'interestRateOfDay'),
'period': this.safeNumber (entry, 'repaymentDay'),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'info': entry,
});
}
return rates;
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const [ section, version, access ] = api;
let url = this.urls['api'][section][version][access];
if (access === 'public') {
if (path === 'getFeeInfo') {
url = this.urls['api'][section][version]['private'] + '/' + path;
} else {
url += '/' + version + '/' + path;
}
if (Object.keys (params).length) {
url += '?' + this.urlencode (params);
}
} else if (section === 'contract') {
const timestamp = this.milliseconds ();
const iso8601 = this.iso8601 (timestamp);
let signedString = iso8601 + method + '/Server/api/' + version + '/' + path;
params = this.keysort (params);
headers = {
'ZB-APIKEY': this.apiKey,
'ZB-TIMESTAMP': iso8601,
// 'ZB-LAN': 'cn', // cn, en, kr
};
url += '/' + version + '/' + path;
if (method === 'POST') {
headers['Content-Type'] = 'application/json';
body = this.json (params);
signedString += this.urlencode (params);
} else {
if (Object.keys (params).length) {
const query = this.urlencode (params);
url += '?' + query;
signedString += query;
}
}
const secret = this.hash (this.encode (this.secret), 'sha1');
const signature = this.hmac (this.encode (signedString), this.encode (secret), 'sha256', 'base64');
headers['ZB-SIGN'] = signature;
} else {
let query = this.keysort (this.extend ({
'method': path,
'accesskey': this.apiKey,
}, params));
const nonce = this.nonce ();
query = this.keysort (query);
const auth = this.rawencode (query);
const secret = this.hash (this.encode (this.secret), 'sha1');
const signature = this.hmac (this.encode (auth), this.encode (secret), 'md5');
const suffix = 'sign=' + signature + '&reqTime=' + nonce.toString ();
url += '/' + path + '?' + auth + '&' + suffix;
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (response === undefined) {
return; // fallback to default error handler
}
if (body[0] === '{') {
const feedback = this.id + ' ' + body;
this.throwBroadlyMatchedException (this.exceptions['broad'], body, feedback);
if ('code' in response) {
const code = this.safeString (response, 'code');
this.throwExactlyMatchedException (this.exceptions['exact'], code, feedback);
if ((code !== '1000') && (code !== '10000')) {
throw new ExchangeError (feedback);
}
}
// special case for {"result":false,"message":"服务端忙碌"} (a "Busy Server" reply)
const result = this.safeValue (response, 'result');
if (result !== undefined) {
if (!result) {
const message = this.safeString (response, 'message');
if (message === '服务端忙碌') {
throw new ExchangeNotAvailable (feedback);
} else {
throw new ExchangeError (feedback);
}
}
}
}
}
};
|
var domHelpers = require('../helpers-dom.js');
var mathHelpers = require('../helpers-math.js');
var Pair = require('./pair.js');
var Hardcode = require('./hardcode.js');
var Subtree = require('./subtree.js');
var CommonalityElement = require('./commonality-element.js');
var CommonalityAncestor = require('./commonality-ancestor.js');
var SOME_ALPHABETIC = /[A-Z]/i;
function Fase2Algortime(main) {
this._main = main;
this._titles = [];
this._texts = [];
this._images = [];
this._pairs = [];
this._reducedTitleObject = null;
this._reducedTextObject = null;
this._reducedImageObject = null;
this._calculatedTitle = null;
this._adjustDistance = new mathHelpers.RangeObject();
}
module.exports = Fase2Algortime;
function adjustLikelihood(list) {
var range = new mathHelpers.RangeObject();
if (list.length !== 0) {
range.update(list[0].likelihood);
range.update(list[list.length - 1].likelihood);
}
for (var c = 0, r = list.length; c < r; c++) {
list[c].likelihood = range.adjust(list[c].likelihood);
}
return list;
}
// Update the internal titles, texts and images collections,
// by getting the some of the best sugestions and then calculate a
// new adjusted the likelihood properties ranging from 1 to 0
Fase2Algortime.prototype.update = function () {
// Usually titles are perfect or wrong, so use only the very best sugestions
this._titles = adjustLikelihood( this._main._fase1title.result() ).slice(0, 3);
// Multiply text containers can contain the same correct text with some added
// noice, but can also be a completly diffrent container. The amount of
// good sugestions should allow multiply good containers, but make it difficult
// to get a wrong container there matches the title.
this._texts = adjustLikelihood( this._main._fase1text.result() );
// All images can be used, they will later be reduced and adjused from the
// (title, text) combination
this._images = adjustLikelihood( this._main._fase1image.result() );
};
// Figure what the best combination of title and text is. Its important to
// understand that this involves looking at both title and text since there
// are features such as closeness there can only be incorporated by creating
// (title, text) pairs.
Fase2Algortime.prototype.combine = function () {
for (var i = 0, l = this._titles.length; i < l; i++) {
for (var n = 0, r = this._texts.length; n < r; n++) {
if (this._texts[n].node === this._titles[i].node) continue;
var textend = domHelpers.positionRange(this._texts[n].node)[1];
if (this._titles[i].node.identifyer > textend) continue;
this._pairs.push(new Pair(this, this._titles[i], this._texts[n]));
}
}
// Calculate likelihood
for (var j = 0, t = this._pairs.length; j < t; j++) {
this._pairs[j].calculateLikelihood();
}
// Sort pairs
this._pairs = this._pairs.sort(function (a, b) {
return b.likelihood - a.likelihood;
});
};
//
// Naive approach to remove some very wrong images
//
Fase2Algortime.prototype._reduceImage = function () {
var bestpair = this._pairs[0];
var parent = domHelpers.commonParent(bestpair.title.node, bestpair.text.node);
var images = this._images.filter(function (item) {
for (var i = 0, l = item.from.length; i < l; i++) {
if (item.from[i].type === 'meta:og') {
return true;
}
else if (item.from[i].type === 'img' || item.from[i].type === 'media') {
if (domHelpers.containerOf(parent, item.from[i].node)) {
return true;
}
}
}
return false;
});
this._reducedImageObject = images[0];
};
//
// The title can't really be reduced
//
Fase2Algortime.prototype._reduceTitle = function () {
this._reducedTitleObject = this._pairs[0].title.node;
};
Fase2Algortime.prototype._reduceText = function () {
this._reducedTextObject = this._pairs[0].text.node;
var elementAnalyser = new CommonalityElement(this._reducedTextObject);
var ancestorAnalyser = new CommonalityAncestor(this._reducedTextObject);
var tree = new Subtree(this._reducedTextObject);
var hardcode = new Hardcode(this._reducedTextObject);
// Remove all not even sugested images
var legalImages = {};
this._images.forEach(function (node) {
legalImages[node.href] = true;
});
tree.findImages().forEach(function (node) {
if (node.tagname === 'img' && legalImages.hasOwnProperty(node.attr.src) === false) {
node.remove();
}
});
// Now cleanup the subtree
// This will also inline some text nodes with other text nodes
tree.reduceTree();
// Remove all textnodes there contains only none alphabetic charecters
tree.findTextNodes().forEach(function (node) {
if (SOME_ALPHABETIC.test(node.getText()) === false) {
node.remove();
}
});
// Reduce the tree using hardcoded features
hardcode.reduce();
// Reduce the subtree again
tree.reduceTree();
// Reduce subtree by analysing the commonality
// between (tagname, classnames) and the container density
var ratio = [0.20, 0.35, 0.60];
for (var i = 0, l = ratio.length; i < l; i++) {
elementAnalyser.collect(tree.containerNodes());
elementAnalyser.reduce(ratio[i]);
tree.reduceTree();
}
// Reduce subtree by analysing the commonality between
// (parent-pattern, children-pattern) and the container density
// Compared to the element-analyser this algortime is designed to remove
// small containers, therefor it has a lower ratio
var ratio = [0.20, 0.35];
for (var i = 0, l = ratio.length; i < l; i++) {
ancestorAnalyser.collect(tree.containerNodes());
ancestorAnalyser.reduce(ratio[i]);
tree.reduceTree();
}
// Try to remove some small containers using the element-analyser
elementAnalyser.collect(tree.containerNodes());
elementAnalyser.reduce(0.20);
tree.reduceTree();
};
Fase2Algortime.prototype.reduce = function () {
this._reduceImage();
this._reduceTitle();
// The reduce text mutates the DOM in such a way that the title text might
// be removed. Save it now so we don't have to care about it.
this._calculatedTitle = this._reducedTitleObject.getText().trim();
this._reduceText();
};
// Return the final result
Fase2Algortime.prototype.result = function () {
return {
title: this._calculatedTitle,
text: this._reducedTextObject.getText().trim(),
image: this._reducedImageObject ? this._reducedImageObject.href : null
};
};
|
'use strict'
const debug = require('debug')('skiff.states.candidate')
const Base = require('./base')
class Candidate extends Base {
start () {
debug('%s is candidate', this.id)
this.name = 'candidate'
super.start()
this._stopped = false
this._node.state.incrementTerm()
// vote for self
this._node.state.setVotedFor(this.id)
process.nextTick(this._gatherVotes.bind(this))
}
stop () {
super.stop()
this._stopped = true
}
_gatherVotes () {
debug('gathering votes...')
const self = this
let majorityReached = false
let votedForMe = 1
let voteCount = 1
maybeDone()
this._node.network.peers().forEach(peer => {
debug('candidate requesting vote from %s', peer)
const requestVoteArgs = {
term: this._node.state.term(),
candidateId: this.id,
lastLogIndex: this._node.log._lastLogIndex,
lastLogTerm: this._node.log._lastLogTerm
}
this._node.network.rpc(
{
to: peer,
action: 'RequestVote',
params: requestVoteArgs
},
// eslint-disable-next-line handle-callback-err
(err, reply) => { // callback
voteCount++
if ((!this._stopped) && reply && reply.params.voteGranted) {
votedForMe++
maybeDone()
}
}
)
})
function maybeDone () {
debug('maybeDone()')
if (!majorityReached) {
if (self._node.network.isMajority(votedForMe)) {
// won
majorityReached = true
debug('%s: election won', self.id)
self._node.state.transition('leader')
} else {
debug('still don\'t have majority')
}
if (self._node.network.isMajority(voteCount - votedForMe)) {
// lost
debug('%s: election lost', self.id)
majorityReached = true
self._resetElectionTimeout()
}
}
}
}
}
module.exports = Candidate
|
/*!
* random-word-generator -- v0.9.0 -- 2013
* http://github.com/thriqon/random-word-generator
*
* Copyright (C) 2013 "thriqon" Jonas Weber
* Licensed under MIT
* see file `LICENSE` for details
*/
"use strict";
// source data
var english_consonants =
['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];
var english_vowels =
['a', 'e', 'i', 'o', 'u'];
var default_pattern = 'Cvcvcvcvcv';
// helpers
var switch_if_given = function (value, getterF, setterF) {
var oldVal = getterF();
if (typeof value !== 'undefined' && value !== null) {
setterF(value);
}
return oldVal;
};
var setter = function (obj, prop) {
return function (value) {
obj[prop] = value;
};
};
var getter = function (obj, prop) {
return function () {
return obj[prop];
};
};
var generate_exec = function (pattern, groups, cb) {
var random_array_element = function (arr) {
return arr[Math.floor(Math.random() * arr.length)];
};
var result = pattern.split('').map(function (p) {
if (p === p.toUpperCase()) {
return (random_array_element(groups[p.toLowerCase()]) || ' ').toUpperCase();
} else {
return random_array_element(groups[p]) || ' ';
}
}).join('');
if (typeof cb !== 'undefined' && cb !== null) {
cb(null, result);
}
return result;
};
/**
A word generator utility
Patterns
--------
A pattern describes how to generate words. It consists of
a series of characters, each referencing a group. If
the letter is uppercase, the result will also be in uppercase.
Example:
var generator = new Generator();
generator.pattern('Cvcvcv');
generator.generate(); // returns something like 'Tafenu'
Groups
------
Groups are simple arrays with characters.
@class Generator
@constructor
*/
module.exports = function () {
var self = this,
mgroups = {
'c' : english_consonants.slice(0),
'v' : english_vowels.slice(0)
},
mpattern = default_pattern;
return {
/**
* Generates a word using this instances pattern and groups.
*
* @method generate
* @param {Callback (error, result) } [callback] node-style callback with the word as second parameter
* @return {String} the word
*/
generate: function (cb) {
return generate_exec(mpattern, mgroups, cb);
},
/**
* Gives the group for the key, or sets this group
*
* @method group
* @param {Character} key the name of this group (one character, lowercase)
* @param {Array Character} [value] the new array of characters for this group
* @return {Array Character} the current group (in case of setting, the old group)
*/
group: function (c, val) { return switch_if_given(val, getter(mgroups, c), setter(mgroups, c)); },
/**
* Gives the pattern, or sets it
*
* @method pattern
* @param {String} [pattern] the pattern, see chapter in documentation for details
* @return {String} the current pattern (the old, if set)
*/
pattern: function (p) { return switch_if_given(p, function() { return mpattern; }, function (x) { mpattern = x; });}
};
};
/**
generates a default-configured word, with optional callback
@method generate
@for Generator
@static
@param {Callback (error, result)} [callback] node-style callback with word as second parameter
@return {String} the word
*/
module.exports.generate = function (cb) {
return generate_exec(default_pattern, { 'c' : english_consonants, 'v': english_vowels }, cb);
};
// documentation follows
/**
The module providing the generator
@module Generator
*/
|
// flow-typed signature: 0ba99159e7480a4a5b97e94b5af3fa94
// flow-typed version: <<STUB>>/@emdaer/plugin-code-block_v^1.0.0-alpha.7/flow_v0.45.0
/**
* This is an autogenerated libdef stub for:
*
* '@emdaer/plugin-code-block'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module '@emdaer/plugin-code-block' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module '@emdaer/plugin-code-block/__tests__/index' {
declare module.exports: any;
}
declare module '@emdaer/plugin-code-block/lib/index' {
declare module.exports: any;
}
declare module '@emdaer/plugin-code-block/src/index' {
declare module.exports: any;
}
// Filename aliases
declare module '@emdaer/plugin-code-block/__tests__/index.js' {
declare module.exports: $Exports<'@emdaer/plugin-code-block/__tests__/index'>;
}
declare module '@emdaer/plugin-code-block/lib/index.js' {
declare module.exports: $Exports<'@emdaer/plugin-code-block/lib/index'>;
}
declare module '@emdaer/plugin-code-block/src/index.js' {
declare module.exports: $Exports<'@emdaer/plugin-code-block/src/index'>;
}
|
import React, { Component } from 'react';
import ButtonAppBar from './component/ButtonAppBar';
export class SideNav extends Component {
render() {
return <div />;
}
}
|
import * as task from '../lib/consts/pen';
/** Public api for pens */
class PenApi {
/**
* The pen listing api stuff
* @param connection To the connection to stream content through.
*/
constructor(connection) {
this.connection = connection;
}
/** Add a new pen */
create() {
this.connection.socket.send(JSON.stringify({
path: 'pen',
request: task.NEW
}));
}
/** Select a new pen */
select(id) {
this.connection.socket.send(JSON.stringify({
path: 'pen',
request: task.SELECT,
target: id
}));
}
/**
* Delete a pen
* @param id The id of the pen to delete
*/
delete(id) {
this.connection.socket.send(JSON.stringify({
path: 'pen',
request: task.DELETE,
id: id
}));
}
/** Update the list of know pens */
list() {
this.connection.socket.send(JSON.stringify({
path: 'pen',
request: task.QUERY
}));
}
}
// Publish
export default function factory(connection) {
if (!window.periscope) { window.periscope = {}; }
window.periscope.pen = new PenApi(connection);
return { name: 'Pen' };
}
|
b=navigator.appName,
addScroll=false;
if ((navigator.userAgent.indexOf('MSIE 5')>0) || (navigator.userAgent.indexOf('MSIE 6'))>0) {
addScroll = true;
}
var off = 0;
var txt = "";
var pX = 0;
var pY = 0;
document.onmousemove = mouseMove;
if (b == "Netscape") {
document.captureEvents(Event.MOUSEMOVE)
};
function mouseMove(evn){
if (b == "Netscape"){
pX=evn.pageX-5;
pY=evn.pageY;
}else{
pX=event.x-5;
pY=event.y;
}
if (b == "Netscape"){
if (document.layers['ToolTip'].visibility=='show') {
PopTip();
}
}else{
if (document.all['ToolTip'].style.visibility=='visible') {
PopTip();
}
}
}
function PopTip(){
if (b == "Netscape"){
theLayer = eval('document.layers[\'ToolTip\']');
if ((pX+120)>window.innerWidth) {
pX=window.innerWidth-150;
}
theLayer.left=pX+10;
theLayer.top=pY+15;
theLayer.visibility='show';
} else {
theLayer = eval('document.all[\'ToolTip\']');
if (theLayer){
pX=event.x-5;
pY=event.y;
if (addScroll) {
pX=pX+document.body.scrollLeft;
pY=pY+document.body.scrollTop;
}
if ((pX+120)>document.body.clientWidth) {
pX=pX-150;
}
theLayer.style.pixelLeft=pX+10;
theLayer.style.pixelTop=pY+15;
theLayer.style.visibility='visible';
}
}
}
function HideTip() {
args=HideTip.arguments;
if (b == "Netscape") {
document.layers['ToolTip'].visibility='hide';
}else {
document.all['ToolTip'].style.visibility='hidden';
}
}
function HideMenu1() {
if (b == "Netscape"){
document.layers['menu1'].visibility='hide';
} else{
document.all['menu1'].style.visibility='hidden';
}
}
function ShowMenu1(){
if (b == "Netscape"){
theLayer = eval('document.layers[\'menu1\']');
theLayer.visibility='show';
} else {
theLayer = eval('document.all[\'menu1\']');
theLayer.style.visibility='visible';
}
}//
function HideMenu2(){
if (b == "Netscape"){
document.layers['menu2'].visibility='hide';
}else{
document.all['menu2'].style.visibility='hidden';
}
} function ShowMenu2(){
if (b == "Netscape"){
theLayer = eval('document.layers[\'menu2\']');
theLayer.visibility='show';
} else {
theLayer = eval('document.all[\'menu2\']');
theLayer.style.visibility='visible';
}
} // fostata
|
/**
* @fileoverview Provide the Boulder (aka Zora) class.
* @author scott@scottlininger.com (Scott Lininger)
*/
/**
* Constructor for the Boulder class, baddie who walks around and hurls rocks.
* @constructor
* @extends {ace.BaseClass}
*/
ace.Boulder = function(game, room) {
ace.base(this, game, room);
this.name = 'Boulder';
this.rotX = -.5
this.hitWidth = 8;
this.hitHeight = 8;
this.zOffset = 8;
this.rotZ - 0;
this.rotX2 = 0;
};
ace.inherits(ace.Boulder, ace.Enemy);
/**
* What to do every frame.
* @param {ace.Game} The game.
*/
ace.Boulder.prototype.onTick = function(game) {
if (this.standardDeathCheck(game)) return;
this.y += this.dY;
this.x += this.dX;
if (this.y < this.baseY - 200) {
this.y = this.baseY + ace.randomInt(32);
this.x = this.baseX - 16 + ace.randomInt(32);
}
var bounceZ = Math.abs(Math.cos(this.y / 32)) * 8;
if (bounceZ < .5) {
if (Math.random() < .3) {
this.dX *= -1;
}
}
this.targetRotZ = this.dX / 8;
this.rotZ = (this.rotZ * 3 + this.targetRotZ) / 4;
var targetZ = game.getWorldZ(this.x, this.y) + bounceZ;
this.z = (this.z * 3 + targetZ) / 4;
this.draw('boulder');
this.rotX2 += .6;
};
/**
* Applies damage to my this.hitPoints value.
* @param {number} damge The damage to apply.
*/
ace.Boulder.prototype.takeDamage = function(damage) {
return false;
};
/**
* What happens when we spawn.
* @param {ace.Runner} The game Runner.
*/
ace.Boulder.prototype.onSpawn = function() {
this.dX = 2;
this.dY = -2;
this.baseY = this.y + 64;
this.baseX = this.x - 120;
this.y = this.baseY + ace.randomInt(32);
};
/**
* What happens when the avatar touches us.
* @param {ace.Game} The game Runner.
*/
ace.Boulder.prototype.onTouchAvatar = function(game) {
// Do the "usual" thing, in case we're a coin or something.
if (this.standardOnTouchAvatar(game)) return;
// Otherwise, dose out some damage...
game.avatar.takeDamage(.5);
};
|
define(function(require) {
'use strict';
const BaseView = require('oroui/js/app/views/base/view');
const __ = require('orotranslation/js/translator');
const _ = require('underscore');
const UserResetPasswordView = BaseView.extend({
autoRender: true,
optionNames: BaseView.prototype.optionNames.concat(['passwordInputSelector']),
events: {
'click [data-role="generate-pass"]': 'onGeneratePassButtonClick',
'click [data-role="show-hide-pass"]': 'onShowHideButtonClick'
},
defaults: {
passwordMinLength: 1
},
passwordShowHideTemplate: require('tpl-loader!orouser/templates/user-reset-password-show-hide.html'),
passwordSuggestionTemplate: require('tpl-loader!orouser/templates/user-reset-password-suggestion.html'),
charsets: {
lower_case: 'abcdefghijklmnopqrstuvwxyz',
upper_case: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
numbers: '0123456789',
special_chars: ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
},
/**
* @inheritDoc
*/
constructor: function UserResetPasswordView(options) {
UserResetPasswordView.__super__.constructor.call(this, options);
},
render: function() {
const $passwordInput = this._getPasswordInput();
$passwordInput.after(this.passwordShowHideTemplate({
title: __('oro.user.show_hide_password.label')
}));
$passwordInput.after(this.passwordSuggestionTemplate({
label: __('oro.user.suggest_password.label')
}));
return UserResetPasswordView.__super__.render.call(this);
},
onShowHideButtonClick: function(e) {
const $passwordInput = this._getPasswordInput();
const $target = this.$(e.target);
if ($target.hasClass('fa-eye')) {
$passwordInput.attr('type', 'password');
$target.removeClass('fa-eye');
$target.addClass('fa-eye-slash');
} else {
$passwordInput.attr('type', 'text');
$target.removeClass('fa-eye-slash');
$target.addClass('fa-eye');
}
},
onGeneratePassButtonClick: function(e) {
e.preventDefault();
this._getPasswordInput().val(this._generatePassword());
},
_generatePassword: function() {
const length = this._getRequiredPasswordLength();
const rules = this._getPasswordRequirements();
let pass = '';
// make sure we have at least one symbol for each rule, shuffle them later
rules.forEach(function(rule) {
if (this.charsets.hasOwnProperty(rule)) {
pass += this.charsets[rule].charAt(_.random(this.charsets[rule].length - 1));
}
}.bind(this));
// create a pool for picking random chars that is reasonably strong
const charset = this.charsets.lower_case + this.charsets.upper_case + this.charsets.numbers;
// fill up to the minLength with random symbols
for (let i = pass.length; i < length; ++i) {
pass = pass + charset.charAt(_.random(charset.length - 1));
}
// shuffle the password
pass = pass.split('').sort(function() {
return 0.5 - Math.random();
}).join('');
return pass;
},
_getPasswordInput: function() {
return this.$(this.passwordInputSelector);
},
_getRequiredPasswordLength: function() {
return this._getPasswordInput().data('suggest-length') || this.defaults.passwordMinLength;
},
_getPasswordRequirements: function() {
const rules = this._getPasswordInput().data('suggest-rules');
return rules ? rules.split(',') : [];
}
});
return UserResetPasswordView;
});
|
// THIS IS A GENERATED FILE! DO NOT EDIT, INSTEAD EDIT THE FILE IN bitjs/build/io.
var bitjs = bitjs || {};
bitjs.io = bitjs.io || {};
bitjs.io.BitStream =
/*
* bitstream-def.js
*
* Provides readers for bitstreams.
*
* Licensed under the MIT License
*
* Copyright(c) 2011 Google Inc.
* Copyright(c) 2011 antimatter15
*/
(function () {
// mask for getting N number of bits (0-8)
const BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
/**
* This object allows you to peek and consume bits and bytes out of a stream.
* Note that this stream is optimized, and thus, will *NOT* throw an error if
* the end of the stream is reached. Only use this in scenarios where you
* already have all the bits you need.
*/
class BitStream {
/**
* @param {ArrayBuffer} ab An ArrayBuffer object or a Uint8Array.
* @param {boolean} mtl Whether the stream reads bits from the byte starting with the
* most-significant-bit (bit 7) to least-significant (bit 0). False means the direciton is
* from least-significant-bit (bit 0) to most-significant (bit 7).
* @param {Number} opt_offset The offset into the ArrayBuffer
* @param {Number} opt_length The length of this BitStream
*/
constructor(ab, mtl, opt_offset, opt_length) {
if (!(ab instanceof ArrayBuffer)) {
throw 'Error! BitArray constructed with an invalid ArrayBuffer object';
}
const offset = opt_offset || 0;
const length = opt_length || ab.byteLength;
/**
* The bytes in the stream.
* @type {Uint8Array}
* @private
*/
this.bytes = new Uint8Array(ab, offset, length);
/**
* The byte in the stream that we are currently on.
* @type {Number}
* @private
*/
this.bytePtr = 0;
/**
* The bit in the current byte that we will read next (can have values 0 through 7).
* @type {Number}
* @private
*/
this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7)
/**
* An ever-increasing number.
* @type {Number}
* @private
*/
this.bitsRead_ = 0;
this.peekBits = mtl ? this.peekBits_mtl : this.peekBits_ltm;
}
/**
* Returns how many bites have been read in the stream since the beginning of time.
*/
getNumBitsRead() {
return this.bitsRead_;
}
/**
* Returns how many bits are currently in the stream left to be read.
*/
getNumBitsLeft() {
const bitsLeftInByte = 8 - this.bitPtr;
return (this.bytes.byteLength - this.bytePtr - 1) * 8 + bitsLeftInByte;
}
/**
* byte0 byte1 byte2 byte3
* 7......0 | 7......0 | 7......0 | 7......0
*
* The bit pointer starts at least-significant bit (0) of byte0 and moves left until it reaches
* bit7 of byte0, then jumps to bit0 of byte1, etc.
* @param {number} n The number of bits to peek, must be a positive integer.
* @param {boolean=} movePointers Whether to move the pointer, defaults false.
* @return {number} The peeked bits, as an unsigned number.
*/
peekBits_ltm(n, opt_movePointers) {
const NUM = parseInt(n, 10);
let num = NUM;
if (n !== num || num <= 0) {
return 0;
}
const movePointers = opt_movePointers || false;
let bytes = this.bytes;
let bytePtr = this.bytePtr;
let bitPtr = this.bitPtr;
let result = 0;
let bitsIn = 0;
// keep going until we have no more bits left to peek at
while (num > 0) {
// We overflowed the stream, so just return what we got.
if (bytePtr >= bytes.length) {
break;
}
const numBitsLeftInThisByte = (8 - bitPtr);
if (num >= numBitsLeftInThisByte) {
const mask = (BITMASK[numBitsLeftInThisByte] << bitPtr);
result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn);
bytePtr++;
bitPtr = 0;
bitsIn += numBitsLeftInThisByte;
num -= numBitsLeftInThisByte;
} else {
const mask = (BITMASK[num] << bitPtr);
result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn);
bitPtr += num;
break;
}
}
if (movePointers) {
this.bitPtr = bitPtr;
this.bytePtr = bytePtr;
this.bitsRead_ += NUM;
}
return result;
}
/**
* byte0 byte1 byte2 byte3
* 7......0 | 7......0 | 7......0 | 7......0
*
* The bit pointer starts at bit7 of byte0 and moves right until it reaches
* bit0 of byte0, then goes to bit7 of byte1, etc.
* @param {number} n The number of bits to peek. Must be a positive integer.
* @param {boolean=} movePointers Whether to move the pointer, defaults false.
* @return {number} The peeked bits, as an unsigned number.
*/
peekBits_mtl(n, opt_movePointers) {
const NUM = parseInt(n, 10);
let num = NUM;
if (n !== num || num <= 0) {
return 0;
}
const movePointers = opt_movePointers || false;
let bytes = this.bytes;
let bytePtr = this.bytePtr;
let bitPtr = this.bitPtr;
let result = 0;
// keep going until we have no more bits left to peek at
while (num > 0) {
// We overflowed the stream, so just return the bits we got.
if (bytePtr >= bytes.length) {
break;
}
const numBitsLeftInThisByte = (8 - bitPtr);
if (num >= numBitsLeftInThisByte) {
result <<= numBitsLeftInThisByte;
result |= (BITMASK[numBitsLeftInThisByte] & bytes[bytePtr]);
bytePtr++;
bitPtr = 0;
num -= numBitsLeftInThisByte;
} else {
result <<= num;
const numBits = 8 - num - bitPtr;
result |= ((bytes[bytePtr] & (BITMASK[num] << numBits)) >> numBits);
bitPtr += num;
break;
}
}
if (movePointers) {
this.bitPtr = bitPtr;
this.bytePtr = bytePtr;
this.bitsRead_ += NUM;
}
return result;
}
/**
* Peek at 16 bits from current position in the buffer.
* Bit at (bytePtr,bitPtr) has the highest position in returning data.
* Taken from getbits.hpp in unrar.
* TODO: Move this out of BitStream and into unrar.
*/
getBits() {
return (((((this.bytes[this.bytePtr] & 0xff) << 16) +
((this.bytes[this.bytePtr + 1] & 0xff) << 8) +
((this.bytes[this.bytePtr + 2] & 0xff))) >>> (8 - this.bitPtr)) & 0xffff);
}
/**
* Reads n bits out of the stream, consuming them (moving the bit pointer).
* @param {number} n The number of bits to read. Must be a positive integer.
* @return {number} The read bits, as an unsigned number.
*/
readBits(n) {
return this.peekBits(n, true);
}
/**
* This returns n bytes as a sub-array, advancing the pointer if movePointers
* is true. Only use this for uncompressed blocks as this throws away remaining
* bits in the current byte.
* @param {number} n The number of bytes to peek. Must be a positive integer.
* @param {boolean=} movePointers Whether to move the pointer, defaults false.
* @return {Uint8Array} The subarray.
*/
peekBytes(n, opt_movePointers) {
const num = parseInt(n, 10);
if (n !== num || num < 0) {
throw 'Error! Called peekBytes() with a non-positive integer: ' + n;
} else if (num === 0) {
return new Uint8Array();
}
// Flush bits until we are byte-aligned.
// from http://tools.ietf.org/html/rfc1951#page-11
// "Any bits of input up to the next byte boundary are ignored."
while (this.bitPtr != 0) {
this.readBits(1);
}
const numBytesLeft = this.getNumBitsLeft() / 8;
if (num > numBytesLeft) {
throw 'Error! Overflowed the bit stream! n=' + num + ', bytePtr=' + this.bytePtr +
', bytes.length=' + this.bytes.length + ', bitPtr=' + this.bitPtr;
}
const movePointers = opt_movePointers || false;
const result = new Uint8Array(num);
let bytes = this.bytes;
let ptr = this.bytePtr;
let bytesLeftToCopy = num;
while (bytesLeftToCopy > 0) {
const bytesLeftInStream = bytes.length - ptr;
const sourceLength = Math.min(bytesLeftToCopy, bytesLeftInStream);
result.set(bytes.subarray(ptr, ptr + sourceLength), num - bytesLeftToCopy);
ptr += sourceLength;
// Overflowed the stream, just return what we got.
if (ptr >= bytes.length) {
break;
}
bytesLeftToCopy -= sourceLength;
}
if (movePointers) {
this.bytePtr += num;
this.bitsRead_ += (num * 8);
}
return result;
}
/**
* @param {number} n The number of bytes to read.
* @return {Uint8Array} The subarray.
*/
readBytes(n) {
return this.peekBytes(n, true);
}
}
return BitStream;
})();
|
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
github: {
id: String,
displayName: String,
username: String,
publicRepos: Number
},
nbrClicks: {
clicks: Number
},
surveys: Array
});
module.exports = mongoose.model('User', User);
|
(function(root, undefined) {
"use strict";
/* ObjLoader main */
// Base object.
// var ObjLoader = function() {
// if (!(this instanceof ObjLoader)) {
// return new ObjLoader();
// }
// };
var ObjLoader = (function() {
var loader = {
supported_model_formats: {
'obj': true,
'fbx': false,
'dae': false
},
getExtension: function(file) {
var i = file.lastIndexOf('.');
if(i < 0)
return '';
return file.substring(i+1);
}
};
/**
* Class for models
*
* @param {String} url Url to model
* @param {String} name Identifier for model
*/
loader.Model = function Model(url, name){
if(!(this instanceof Model)) {
return new Model(url, name);
}
this.url = url;
this.name = name;
this.loaded = false;
this.vertices = null;
this.texcoords = null;
this.normals = null;
this.indices = null;
this.tangents = null;
this.bitangents = null;
this.vertexBuffer = null;
this.texcoordBuffer = null;
this.normalBuffer = null;
this.indexBuffer = null;
this.tangentBuffer = null;
this.bitangentBuffer = null;
};
/**
* { LOAD MODEL }
* Load a model if it's not already loaded
*
* @param {String} url url to model
* @param {Function} done callback for done
* @param {Function} error callback for error
* @param {Function} progress callback for progress update
*/
loader.loadModel = function(url, done, error, progress){
var model;
var ext = loader.getExtension(url);
if(!loader.supported_model_formats[ext]){
// File format is not supported
if(error)
error('File format not supported');
return;
}
model = new loader.Model(url);
var xhr = new XMLHttpRequest();
xhr.onprogress = function(ev){
if(progress)
progress(ev);
};
xhr.onerror = function(ev){
if(error)
error("Couldn't fetch model {status="+xhr.status+"}", ev);
};
xhr.onload = function(ev){
if(xhr.readyState != 4 || xhr.status != 200){
if(error)
error("Couldn't fetch model {status="+xhr.status+"}", ev);
return;
}
var file_data = xhr.responseText;
// Depending on file format handle the data different
switch(ext){
case 'obj': loader.handleObj(file_data, model); break;
}
// When the model is loaded and setup
// model itself will call the done callback on all who is bound
if(done)
done(model);
};
xhr.open(
'GET',
url
);
xhr.send();
return model;
};
/**
* { HANDLE OBJ }
* Reads .obj data from string and stores in model
* @param {String} data data in .obj format
* @param {Model} model model which will be used to store data
* @return {Model} returns the loaded model
*/
loader.handleObj = function(data, model){
var i, j, vertexIndex, texIndex, normalIndex;
var obj = {};
obj.vertices = [];
obj.normaldata = [];
obj.normals = [];
obj.texdata = [];
obj.texcoords = [];
obj.indices = [];
obj.faces = [];
obj.vertexBuffer = null;
obj.texcoordBuffer = null;
obj.normalBuffer = null;
obj.indexBuffer = null;
obj.smooth = null;
/* Loop through all data */
for(i = 0; i < data.length; ++i){
if(data[i] == '#') {
while(data[++i] != '\n')
;
continue;
}
// var c = data[i];
var d = '';
switch(data[i]){
/* VERTEX */
case 'v':
i++;
/* TEXTURE */
if(data[i] == 't') {
while(++i < data.length){
if(data[i] == ' ' || data[i] == '\n'){
if(d.length > 0)
obj.texdata.push(parseFloat(d));
d = '';
if(data[i] == '\n')
break;
}
else {
d += data[i];
}
}
}
/* NORMAL */
else if(data[i] == 'n'){
while(data[++i] != '\n' && i < data.length){
if(data[i] == ' '){
if(d.length > 0)
obj.normaldata.push(parseFloat(d));
d = '';
}
else
d += data[i];
}
if(d.length > 0)
obj.normaldata.push(parseFloat(d));
}
/* POSITION */
else {
while(data[++i] != '\n' && i < data.length){
if(data[i] == ' '){
if(d.length > 0)
obj.vertices.push(parseFloat(d));
d = '';
}
else
d += data[i];
}
if(d.length > 0)
obj.vertices.push(parseFloat(d));
}
break;
/* SMOOTH */
case 's':
i++;
while(data[i] == ' ')
++i;
if(data[i] == '0' || (data[i] == 'o' && data[i+1] == 'f' && data[i+2] == 'f')){
obj.smooth = false;
i += 3;
}
else if(data[i] == '1'){
obj.smooth = true;
}
break;
/* FACE */
case 'f':
// var f = [];
var face = {
vertices: [],
texcoords: [],
normals: []
};
var v = [], vi=0;
while(++i < data.length){
/* Space character, add information */
if(data[i] == ' ' || data[i] == '\n'){
if(v[0]){
face.vertices.push(parseInt(v[0], 10)-1);
}
if(v[1]){
face.texcoords.push(parseInt(v[1], 10)-1);
}
if(v[2]){
face.normals.push(parseInt(v[2], 10)-1);
}
if(data[i] == '\n')
break;
v = [];
vi=0;
}
/* New type */
else if(data[i] == '/')
++vi;
/* Value */
else {
if(!v[vi])v[vi] = '';
v[vi] += data[i];
}
}
// ADD THE FACE
if(face.vertices.length > 0)
obj.faces.push(face);
break;
/* UNIMPLEMENTED */
default:
while(data[i] != '\n' && i < data.length)
++i;
break;
}
}
/* SMOOTH */
if( obj.smooth ){
var temp = {};
temp.vertices = [];
temp.texcoords = [];
temp.normals = [];
temp.indices = [];
var indexI = 0;
for(i = 0; i < obj.faces.length; ++i){
for(j = 0; j < obj.faces[ i ].vertices.length; ++j ) {
vertexIndex = obj.faces[ i ].vertices[ j ];
temp.vertices.push(obj.vertices[vertexIndex * 3]);
temp.vertices.push(obj.vertices[vertexIndex * 3 + 1]);
temp.vertices.push(obj.vertices[vertexIndex * 3 + 2]);
}
for(j = 0; j < obj.faces[ i ].texcoords.length; ++j) {
texIndex = obj.faces[ i ].texcoords[ j ];
temp.texcoords.push(obj.texdata[texIndex * 2]);
temp.texcoords.push(obj.texdata[texIndex * 2 + 1]);
}
for(j = 0; j < obj.faces[ i ].normals.length; ++j ) {
normalIndex = obj.faces[ i ].normals[ j ];
temp.normals.push(obj.normaldata[normalIndex * 3]);
temp.normals.push(obj.normaldata[normalIndex * 3 + 1]);
temp.normals.push(obj.normaldata[normalIndex * 3 + 2]);
}
for(j = 0; j < obj.faces[i].vertices.length-2; ++j) {
temp.indices.push(indexI);
temp.indices.push(indexI + j + 1);
temp.indices.push(indexI + j + 2);
}
indexI += obj.faces[i].vertices.length;
}
obj.vertices = temp.vertices;
obj.texcoords = temp.texcoords;
obj.normals = temp.normals;
obj.indices = temp.indices;
}
/* NONE-SMOOTH OBJECT ( FLAT ) */
else {
var holder = {
vertices: [],
normals: [],
indices: [],
texcoords: []
};
var index=0;
for(i = 0; i < obj.faces.length; ++i){
/* ASSERTION */
if(obj.faces[i].vertices.length < 3){
console.log('Assertion failed: \nLess than 3 vertices in face.');
// alert('Assertion failed: \nLess than 3 vertices in face.');
continue;
}
// CREATE THE NEW VERTICES
for(j = 0; j < obj.faces[i].vertices.length; ++j){
// ADD A NEW VERTEX POSITION
vertexIndex = obj.faces[ i ].vertices[ j ];
holder.vertices[ index * 3 ] = obj.vertices[ vertexIndex * 3 ];
holder.vertices[ index * 3 + 1 ] = obj.vertices[ vertexIndex * 3 + 1 ];
holder.vertices[ index * 3 + 2 ] = obj.vertices[ vertexIndex * 3 + 2 ];
// ADD A NEW VERTEX TEXCOORD
texIndex = obj.faces[ i ].texcoords[ j ];
if( texIndex !== undefined ) {
holder.texcoords[ index * 2 ] = obj.texdata[ texIndex * 2 ];
holder.texcoords[ index * 2 + 1 ] = obj.texdata[ texIndex * 2 + 1];
}
// ADD A NEW VERTEX NORMAL
normalIndex = obj.faces[ i ].normals[ j ];
if( normalIndex !== undefined ) {
holder.normals[ index * 3 ] = obj.normaldata[ normalIndex * 3 ];
holder.normals[ index * 3 + 1 ] = obj.normaldata[ normalIndex * 3 + 1 ];
holder.normals[ index * 3 + 2 ] = obj.normaldata[ normalIndex * 3 + 2 ];
}
++index;
}
// CREATE THE TRIANGLE INDICES
var startIndex = index - obj.faces[i].vertices.length;
for(j = 0; j < obj.faces[i].vertices.length - 2; ++j){
holder.indices.push( startIndex );
holder.indices.push( startIndex + j + 1 );
holder.indices.push( startIndex + j + 2 );
}
}
obj.vertices = holder.vertices;
obj.texcoords = holder.texcoords;
obj.normals = holder.normals;
obj.indices = holder.indices;
}
// Setup model from data in temp holder obj
model.vertices = obj.vertices;
model.texcoords = obj.texcoords;
model.normals = obj.normals;
model.indices = obj.indices;
// #Dependency
// Some library which defines vec3 and neede functions
if(typeof vec3 !== 'undefined' && vec3.cross) {
loader.calculateBitangents(model);
if(vec3.create && vec3.scale && vec3.normalize && vec3.subtract) {
loader.calculateTangent(model);
}
}
/* CREATE BUFFERS */
/* VERTEX */
// model.vertexBuffer = gl.createBuffer();
// gl.bindBuffer(gl.ARRAY_BUFFER, model.vertexBuffer);
// gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(model.vertices), gl.STATIC_DRAW);
// model.vertexBuffer.itemSize = 3;
// model.vertexBuffer.numItems = model.vertices.length / model.vertexBuffer.itemSize;
/* TEXTURE */
// if( model.texcoords.length > 0 ) {
// model.texcoordBuffer = gl.createBuffer();
// gl.bindBuffer(gl.ARRAY_BUFFER, model.texcoordBuffer);
// gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(model.texcoords), gl.STATIC_DRAW);
// model.texcoordBuffer.itemSize = 2;
// model.texcoordBuffer.numItems = model.texcoords.length / model.texcoordBuffer.itemSize;
// }
/* NORMAL */
// if( model.normals.length > 0 ) {
// model.normalBuffer = gl.createBuffer();
// gl.bindBuffer(gl.ARRAY_BUFFER, model.normalBuffer);
// gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(model.normals), gl.STATIC_DRAW);
// model.normalBuffer.itemSize = 3;
// model.normalBuffer.numItems = model.normals.length / model.normalBuffer.itemSize;
// }
/* TANGENT */
// if( model.tangents.length > 0 ) {
// model.tangentBuffer = gl.createBuffer();
// gl.bindBuffer(gl.ARRAY_BUFFER, model.tangentBuffer);
// gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(model.tangents), gl.STATIC_DRAW);
// model.tangentBuffer.itemSize = 3;
// model.tangentBuffer.numItems = model.tangents.length / model.tangentBuffer.itemSize;
// }
/* BITANGENT */
// if( model.bitangents.length > 0 ) {
// model.bitangentBuffer = gl.createBuffer();
// gl.bindBuffer(gl.ARRAY_BUFFER, model.bitangentBuffer);
// gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(model.bitangents), gl.STATIC_DRAW);
// model.bitangentBuffer.itemSize = 3;
// model.bitangentBuffer.numItems = model.bitangents.length / model.bitangentBuffer.itemSize;
// }
/* INDEX */
// model.indexBuffer = gl.createBuffer();
// gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.indexBuffer);
// gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(model.indices), gl.STATIC_DRAW);
// model.indexBuffer.itemSize = 1;
// model.indexBuffer.numItems = model.indices.length / model.indexBuffer.itemSize;
model.loaded = true;
// Return model when done
return model;
};
/**
* Calculate bitangents for a mesh
* @param {[type]} model [description]
* @return {[type]} [description]
*/
loader.calculateBitangents = function(model){
if(!model.bitangents)
model.bitangents = new Array(model.tangents.length);
for(var a = 0; a < model.indices.length / 3; a++){
var i1 = model.indices[a*3];
var i2 = model.indices[a*3+1];
var i3 = model.indices[a*3+2];
var t1 = [ model.tangents[i1*3], model.tangents[i1*3+1], model.tangents[i1*3+2] ];
var t2 = [ model.tangents[i2*3], model.tangents[i2*3+1], model.tangents[i2*3+2] ];
var t3 = [ model.tangents[i3*3], model.tangents[i3*3+1], model.tangents[i3*3+2] ];
var n1 = [ model.normals[i1*3], model.normals[i1*3+1], model.normals[i1*3+2] ];
var n2 = [ model.normals[i2*3], model.normals[i2*3+1], model.normals[i2*3+2] ];
var n3 = [ model.normals[i3*3], model.normals[i3*3+1], model.normals[i3*3+2] ];
var b = [0, 0, 0];
vec3.cross(b, [t1, t2, t3], [n1, n2, n3]);
// model.bitangents[i1*3]
}
};
/**
* Calculate tangents for a mesh
* @param {[type]} model [description]
* @return {[type]} [description]
*/
loader.calculateTangent = function(model){
// Vector3D *tan1 = new Vector3D[vertexCount * 2];
// Vector3D *tan2 = tan1 + vertexCount;
var tan1 = new Array(model.vertices.length);
// var tan2 = new Array(model.vertices.length);
for(var a = 0; a < model.vertices.length; a++){
tan1[a] = 0;
}
if(!model.tangents)
model.tangents = new Array(model.vertices.length);
/**
* Loop through all triangles
*/
for (a = 0; a < model.indices.length; a+=3)
{
var i1 = model.indices[a];
var i2 = model.indices[a+1];
var i3 = model.indices[a+2];
var v1 = [ model.vertices[i1*3], model.vertices[i1*3+1], model.vertices[i1*3+2] ];
var v2 = [ model.vertices[i2*3], model.vertices[i2*3+1], model.vertices[i2*3+2] ];
var v3 = [ model.vertices[i3*3], model.vertices[i3*3+1], model.vertices[i3*3+2] ];
var w1 = [ model.texcoords[i1*2], model.texcoords[i1*2+1] ];
var w2 = [ model.texcoords[i2*2], model.texcoords[i2*2+1] ];
var w3 = [ model.texcoords[i3*2], model.texcoords[i3*2+1] ];
////////////
// FLOATS //
////////////
var x1 = v2[0] - v1[0];
var x2 = v3[0] - v1[0];
var y1 = v2[1] - v1[1];
var y2 = v3[1] - v1[1];
var z1 = v2[2] - v1[2];
var z2 = v3[2] - v1[2];
var s1 = w2[0] - w1[0];
var s2 = w3[0] - w1[0];
var t1 = w2[1] - w1[1];
var t2 = w3[1] - w1[1];
// FLOAT
var div = (s1 * t2 - s2 * t1);
var r = 1.0 / (div === 0)? 1 : div;
var sdir = [(t2 * x1 - t1 * x2) * r,
(t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r];
// var tdir = [(s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
// (s1 * z2 - s2 * z1) * r];
tan1[i1*3+0] += sdir[0];
tan1[i1*3+1] += sdir[1];
tan1[i1*3+2] += sdir[2];
tan1[i2*3+0] += sdir[0];
tan1[i2*3+1] += sdir[1];
tan1[i2*3+2] += sdir[2];
tan1[i3*3+0] += sdir[0];
tan1[i3*3+1] += sdir[1];
tan1[i3*3+2] += sdir[2];
// tan2[i1] += tdir;
// tan2[i2] += tdir;
// tan2[i3] += tdir;
// triangle++;
}
for(a = 0; a < model.vertices.length; a+=3){
var n = [ model.normals[a], model.normals[a+1], model.normals[a+2] ];
var t = [ tan1[a], tan1[a+1], tan1[a+2] ];
var d = vec3.dot(n, t);
vec3.scale(n, n, d);
var mt = vec3.create();
vec3.subtract(mt, t, n);
vec3.normalize(mt, mt);
model.tangents[a] = mt[0];
model.tangents[a+1] = mt[1];
model.tangents[a+2] = mt[2];
}
// for (long a = 0; a < vertexCount; a++)
// {
// const Vector3D& n = normal[a];
// const Vector3D& t = tan1[a];
// // Gram-Schmidt orthogonalize
// tangent[a] = (t - n * Dot(n, t)).Normalize();
// // Calculate handedness
// tangent[a].w = (Dot(Cross(n, t), tan2[a]) < 0.0F) ? -1.0F : 1.0F;
// }
};
return loader;
}());
// Version.
ObjLoader.VERSION = '0.0.0';
// Export to the root, which is probably `window`.
root.ObjLoader = ObjLoader;
}(this));
|
var seneca = require('seneca')();
seneca.use('../suncalculator');
// Uses today's date for the calcuation
seneca.act({role: 'suncalculator', cmd: 'calc', lat: 35.227085, long: -80.843124}, console.log);
// Uses a passed in date for the calcuation
seneca.act({role: 'suncalculator', cmd: 'calc', lat: 35.227085, long: -80.843124, date: new Date('Wed Mar 23 2017 22:40:23 GMT-0400 (Eastern Daylight Time)')}, console.log)
|
/**
* Created by dwendling on 3/16/17.
*/
var studentDataModule = {
init: function(settings){
studentDataModule.config = {
table: '.studentTableBody',
students: {
NACSStudents_589: "",
NPStudents_594: "",
RPStudents_500: "",
RHSStudents_599: "",
SPStudents_501: "",
LCAStudents_517: ""
}
};
$.extend(studentDataModule.config, settings);
studentDataModule.setup();
},
setup: function(){
},
//TODO: Cache the data so that another ajax call doesn't have to happen if the user clicks on the same tab again
getStudentInfo: function(schoolId)
{
var returnData = studentDataModule.checkCachedData(schoolId);
console.log(returnData);
if (!returnData){
studentDataModule.getData(schoolId);
} else {
$('.studentTableBody').html("");
studentDataModule.displayCachedStudentInfo(returnData, schoolId);
}
},
checkCachedData: function(schoolId){
for (var student in studentDataModule.config.students){
var school_id = student.split("_")[1];
if (school_id == schoolId.toString()) {
var studentString = studentDataModule.config.students[student];
if (studentString.length > 0) {
return studentString;
} else {
return false;
}
}
}
return false;
},
getData: function(schoolId){
var studentData = "";
commonModule.post(
{'schoolId' : schoolId },
{
success: function (response) {
$('.studentTableBody').html("");
var studentArr = JSON.parse(response);
studentArr.forEach(function(student){
emailClass = studentDataModule.getEmailClass(student);
newStudent = studentDataModule.createStudentInfoRow(student, emailClass);
studentData += newStudent;
});
studentDataModule.displayCachedStudentInfo(studentData, schoolId);
studentDataModule.cacheData(studentData);
}
}, '/updateStudentInfo');
},
cacheData: function (studentData){
for (var student in studentDataModule.config.students){
var school_id = student.split("_")[1];
if (school_id == schoolId.toString()) {
studentDataModule.config.students[student] = studentData;
return studentDataModule.config.students
}
}
},
displayCachedStudentInfo: function(studentData, schoolId){
$(studentDataModule.config.table).html(studentData);
$('.school-tab').removeClass('active');
$('li[data-school-id ="'+ schoolId + '"').addClass('active');
schoolsModule.filterEmails();
schoolsModule.clearSearch();
},
getEmailClass: function(student){
//Apply algorithm to determine if the email follows the formula
var emailBeginning = student.email.split("@")[0];
var lastName = emailBeginning.substring(1, emailBeginning.length);
return student.lastName.toLowerCase() === lastName.toLowerCase() ? 'follows' : 'does-not-follow';
},
createStudentInfoRow: function(student, emailClass){
return "<tr><td>" + student.firstName + "</td><td> " + student.lastName + "</td><td class="+emailClass+">" + student.email + "</td><td>" + student.password +"</td><td>" + student.id + "</td><td>" + student.homeroomId.name + "</td><td>" + student.grade + "</td></tr>";
}
}
$(document).ready(function(){
studentDataModule.init();
});
|
import React from 'react';
const Title = props => (
<h1>{props.title}</h1>
);
Title.propTypes = {
title: React.PropTypes.string,
};
export default Title;
|
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/test'
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('contact');
});
router.post('/insert/submit',function(req,res,next) {
// var id = req.body.;
});
module.exports = router;
|
(function () {
'use strict';
VideoPlayer.Player = wig.View.extend({
className: 'Player',
template: [
'<section class="video"></section>',
'<section class="progress"></section>',
'<section class="controls"></section>'
],
renderMap: {
'video': '.video',
'*': '.controls'
},
render: function () {
var source = 'http://www.kaltura.com/p/243342/sp/24334200/playManifest/entryId/0_c0r624gh/flavorId/0_w48dtkyq/format/url/protocol/http/a.mp4';
VideoPlayer.Video
.add({
id: 'video',
source: source,
type: 'video/mp4',
onProgress: this.updateProgress.bind(this)
}, this);
VideoPlayer.base.Paragraph
.add({
id: 'progress',
text: ''
}, this);
this.addControlButton('fa fa-play', this.playVideo);
this.addControlButton('fa fa-pause', this.pauseVideo);
},
addControlButton: function (cssClass, callback) {
VideoPlayer.base.Button
.add({
css: cssClass,
onClick: callback.bind(this)
}, this);
},
updateProgress: function (currentTime) {
this.getView('progress')
.update({
text: parseInt(currentTime || 0)
});
},
playVideo: function () {
this.getView('video')
.play();
},
pauseVideo: function () {
this.getView('video')
.pause();
}
});
}());
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.