hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
104694f27ed78f6dca5f22caf1e31c703624863f | 10,425 | js | JavaScript | public/js/pagetransitions.js | haooon/DA | 5ce16a28fb8008e507162e4c40c9dc013378dcdc | [
"MIT"
] | null | null | null | public/js/pagetransitions.js | haooon/DA | 5ce16a28fb8008e507162e4c40c9dc013378dcdc | [
"MIT"
] | null | null | null | public/js/pagetransitions.js | haooon/DA | 5ce16a28fb8008e507162e4c40c9dc013378dcdc | [
"MIT"
] | null | null | null | var PageTransitions = (function() {
var $main = $( '#pt-main' ),
$pages = $main.children( 'div.pt-page' ),
$iterate = $( '#iterateEffects' ),
animcursor = 36,
pagesCount = $pages.length,
current = 0,
isAnimating = false,
endCurrPage = false,
endNextPage = false,
animEndEventNames = {
'WebkitAnimation' : 'webkitAnimationEnd',
'OAnimation' : 'oAnimationEnd',
'msAnimation' : 'MSAnimationEnd',
'animation' : 'animationend'
},
// animation end event name
animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ],
// support css animations
support = Modernizr.cssanimations;
function init() {
$pages.each( function() {
var $page = $( this );
$page.data( 'originalClassList', $page.attr( 'class' ) );
} );
$pages.eq( current ).addClass( 'pt-page-current' );
$( '#dl-menu' ).dlmenu( {
animationClasses : { in : 'dl-animate-in-2', out : 'dl-animate-out-2' },
onLinkClick : function( el, ev ) {
ev.preventDefault();
nextPage( el.data( 'animation' ) );
}
} );
$iterate.on( 'click', function() {
if( isAnimating ) {
return false;
}
if( animcursor > 67 ) {
animcursor = 1;
}
nextPage( animcursor );
++animcursor;
} );
}
function nextPage(options ) {
var animation = (options.animation) ? options.animation : options;
if( isAnimating ) {
return false;
}
isAnimating = true;
var $currPage = $pages.eq( current );
if(options.showPage){
if( options.showPage < pagesCount - 1 ) {
current = options.showPage;
}
else {
current = 0;
}
}
else{
if( current < pagesCount - 1 ) {
++current;
}
else {
current = 0;
}
}
var $nextPage = $pages.eq( current ).addClass( 'pt-page-current' ),
outClass = '', inClass = '';
switch( animation ) {
case 1:
outClass = 'pt-page-moveToLeft';
inClass = 'pt-page-moveFromRight';
break;
case 2:
outClass = 'pt-page-moveToRight';
inClass = 'pt-page-moveFromLeft';
break;
case 3:
outClass = 'pt-page-moveToTop';
inClass = 'pt-page-moveFromBottom';
break;
case 4:
outClass = 'pt-page-moveToBottom';
inClass = 'pt-page-moveFromTop';
break;
case 5:
outClass = 'pt-page-fade';
inClass = 'pt-page-moveFromRight pt-page-ontop';
break;
case 6:
outClass = 'pt-page-fade';
inClass = 'pt-page-moveFromLeft pt-page-ontop';
break;
case 7:
outClass = 'pt-page-fade';
inClass = 'pt-page-moveFromBottom pt-page-ontop';
break;
case 8:
outClass = 'pt-page-fade';
inClass = 'pt-page-moveFromTop pt-page-ontop';
break;
case 9:
outClass = 'pt-page-moveToLeftFade';
inClass = 'pt-page-moveFromRightFade';
break;
case 10:
outClass = 'pt-page-moveToRightFade';
inClass = 'pt-page-moveFromLeftFade';
break;
case 11:
outClass = 'pt-page-moveToTopFade';
inClass = 'pt-page-moveFromBottomFade';
break;
case 12:
outClass = 'pt-page-moveToBottomFade';
inClass = 'pt-page-moveFromTopFade';
break;
case 13:
outClass = 'pt-page-moveToLeftEasing pt-page-ontop';
inClass = 'pt-page-moveFromRight';
break;
case 14:
outClass = 'pt-page-moveToRightEasing pt-page-ontop';
inClass = 'pt-page-moveFromLeft';
break;
case 15:
outClass = 'pt-page-moveToTopEasing pt-page-ontop';
inClass = 'pt-page-moveFromBottom';
break;
case 16:
outClass = 'pt-page-moveToBottomEasing pt-page-ontop';
inClass = 'pt-page-moveFromTop';
break;
case 17:
outClass = 'pt-page-scaleDown';
inClass = 'pt-page-moveFromRight pt-page-ontop';
break;
case 18:
outClass = 'pt-page-scaleDown';
inClass = 'pt-page-moveFromLeft pt-page-ontop';
break;
case 19:
outClass = 'pt-page-scaleDown';
inClass = 'pt-page-moveFromBottom pt-page-ontop';
break;
case 20:
outClass = 'pt-page-scaleDown';
inClass = 'pt-page-moveFromTop pt-page-ontop';
break;
case 21:
outClass = 'pt-page-scaleDown';
inClass = 'pt-page-scaleUpDown pt-page-delay300';
break;
case 22:
outClass = 'pt-page-scaleDownUp';
inClass = 'pt-page-scaleUp pt-page-delay300';
break;
case 23:
outClass = 'pt-page-moveToLeft pt-page-ontop';
inClass = 'pt-page-scaleUp';
break;
case 24:
outClass = 'pt-page-moveToRight pt-page-ontop';
inClass = 'pt-page-scaleUp';
break;
case 25:
outClass = 'pt-page-moveToTop pt-page-ontop';
inClass = 'pt-page-scaleUp';
break;
case 26:
outClass = 'pt-page-moveToBottom pt-page-ontop';
inClass = 'pt-page-scaleUp';
break;
case 27:
outClass = 'pt-page-scaleDownCenter';
inClass = 'pt-page-scaleUpCenter pt-page-delay400';
break;
case 28:
outClass = 'pt-page-rotateRightSideFirst';
inClass = 'pt-page-moveFromRight pt-page-delay200 pt-page-ontop';
break;
case 29:
outClass = 'pt-page-rotateLeftSideFirst';
inClass = 'pt-page-moveFromLeft pt-page-delay200 pt-page-ontop';
break;
case 30:
outClass = 'pt-page-rotateTopSideFirst';
inClass = 'pt-page-moveFromTop pt-page-delay200 pt-page-ontop';
break;
case 31:
outClass = 'pt-page-rotateBottomSideFirst';
inClass = 'pt-page-moveFromBottom pt-page-delay200 pt-page-ontop';
break;
case 32:
outClass = 'pt-page-flipOutRight';
inClass = 'pt-page-flipInLeft pt-page-delay500';
break;
case 33:
outClass = 'pt-page-flipOutLeft';
inClass = 'pt-page-flipInRight pt-page-delay500';
break;
case 34:
outClass = 'pt-page-flipOutTop';
inClass = 'pt-page-flipInBottom pt-page-delay500';
break;
case 35:
outClass = 'pt-page-flipOutBottom';
inClass = 'pt-page-flipInTop pt-page-delay500';
break;
case 36:
outClass = 'pt-page-rotateFall pt-page-ontop';
inClass = 'pt-page-scaleUp';
break;
case 37:
outClass = 'pt-page-rotateOutNewspaper';
inClass = 'pt-page-rotateInNewspaper pt-page-delay500';
break;
case 38:
outClass = 'pt-page-rotatePushLeft';
inClass = 'pt-page-moveFromRight';
break;
case 39:
outClass = 'pt-page-rotatePushRight';
inClass = 'pt-page-moveFromLeft';
break;
case 40:
outClass = 'pt-page-rotatePushTop';
inClass = 'pt-page-moveFromBottom';
break;
case 41:
outClass = 'pt-page-rotatePushBottom';
inClass = 'pt-page-moveFromTop';
break;
case 42:
outClass = 'pt-page-rotatePushLeft';
inClass = 'pt-page-rotatePullRight pt-page-delay180';
break;
case 43:
outClass = 'pt-page-rotatePushRight';
inClass = 'pt-page-rotatePullLeft pt-page-delay180';
break;
case 44:
outClass = 'pt-page-rotatePushTop';
inClass = 'pt-page-rotatePullBottom pt-page-delay180';
break;
case 45:
outClass = 'pt-page-rotatePushBottom';
inClass = 'pt-page-rotatePullTop pt-page-delay180';
break;
case 46:
outClass = 'pt-page-rotateFoldLeft';
inClass = 'pt-page-moveFromRightFade';
break;
case 47:
outClass = 'pt-page-rotateFoldRight';
inClass = 'pt-page-moveFromLeftFade';
break;
case 48:
outClass = 'pt-page-rotateFoldTop';
inClass = 'pt-page-moveFromBottomFade';
break;
case 49:
outClass = 'pt-page-rotateFoldBottom';
inClass = 'pt-page-moveFromTopFade';
break;
case 50:
outClass = 'pt-page-moveToRightFade';
inClass = 'pt-page-rotateUnfoldLeft';
break;
case 51:
outClass = 'pt-page-moveToLeftFade';
inClass = 'pt-page-rotateUnfoldRight';
break;
case 52:
outClass = 'pt-page-moveToBottomFade';
inClass = 'pt-page-rotateUnfoldTop';
break;
case 53:
outClass = 'pt-page-moveToTopFade';
inClass = 'pt-page-rotateUnfoldBottom';
break;
case 54:
outClass = 'pt-page-rotateRoomLeftOut pt-page-ontop';
inClass = 'pt-page-rotateRoomLeftIn';
break;
case 55:
outClass = 'pt-page-rotateRoomRightOut pt-page-ontop';
inClass = 'pt-page-rotateRoomRightIn';
break;
case 56:
outClass = 'pt-page-rotateRoomTopOut pt-page-ontop';
inClass = 'pt-page-rotateRoomTopIn';
break;
case 57:
outClass = 'pt-page-rotateRoomBottomOut pt-page-ontop';
inClass = 'pt-page-rotateRoomBottomIn';
break;
case 58:
outClass = 'pt-page-rotateCubeLeftOut pt-page-ontop';
inClass = 'pt-page-rotateCubeLeftIn';
break;
case 59:
outClass = 'pt-page-rotateCubeRightOut pt-page-ontop';
inClass = 'pt-page-rotateCubeRightIn';
break;
case 60:
outClass = 'pt-page-rotateCubeTopOut pt-page-ontop';
inClass = 'pt-page-rotateCubeTopIn';
break;
case 61:
outClass = 'pt-page-rotateCubeBottomOut pt-page-ontop';
inClass = 'pt-page-rotateCubeBottomIn';
break;
case 62:
outClass = 'pt-page-rotateCarouselLeftOut pt-page-ontop';
inClass = 'pt-page-rotateCarouselLeftIn';
break;
case 63:
outClass = 'pt-page-rotateCarouselRightOut pt-page-ontop';
inClass = 'pt-page-rotateCarouselRightIn';
break;
case 64:
outClass = 'pt-page-rotateCarouselTopOut pt-page-ontop';
inClass = 'pt-page-rotateCarouselTopIn';
break;
case 65:
outClass = 'pt-page-rotateCarouselBottomOut pt-page-ontop';
inClass = 'pt-page-rotateCarouselBottomIn';
break;
case 66:
outClass = 'pt-page-rotateSidesOut';
inClass = 'pt-page-rotateSidesIn pt-page-delay200';
break;
case 67:
outClass = 'pt-page-rotateSlideOut';
inClass = 'pt-page-rotateSlideIn';
break;
}
$currPage.addClass( outClass ).on( animEndEventName, function() {
$currPage.off( animEndEventName );
endCurrPage = true;
if( endNextPage ) {
onEndAnimation( $currPage, $nextPage );
}
} );
$nextPage.addClass( inClass ).on( animEndEventName, function() {
$nextPage.off( animEndEventName );
endNextPage = true;
if( endCurrPage ) {
onEndAnimation( $currPage, $nextPage );
}
} );
if( !support ) {
onEndAnimation( $currPage, $nextPage );
}
}
function onEndAnimation( $outpage, $inpage ) {
endCurrPage = false;
endNextPage = false;
resetPage( $outpage, $inpage );
isAnimating = false;
}
function resetPage( $outpage, $inpage ) {
$outpage.attr( 'class', $outpage.data( 'originalClassList' ) );
$inpage.attr( 'class', $inpage.data( 'originalClassList' ) + ' pt-page-current' );
}
init();
return {
init : init,
nextPage : nextPage,
};
})();
| 26.12782 | 84 | 0.638753 |
1046efa0b87562163d9e5ce82a8ae6d533dbb623 | 1,126 | js | JavaScript | multiples_promesas.js | MauVal96/JavaScript | 33f2d3c0a5b45ca484370c20fed1e4b455d2115c | [
"MIT"
] | null | null | null | multiples_promesas.js | MauVal96/JavaScript | 33f2d3c0a5b45ca484370c20fed1e4b455d2115c | [
"MIT"
] | null | null | null | multiples_promesas.js | MauVal96/JavaScript | 33f2d3c0a5b45ca484370c20fed1e4b455d2115c | [
"MIT"
] | null | null | null | // Fundamentos de JavaScript -- Promesas Multiples
// Datos de la API
const API_URL = 'https://swapi.dev/api/';
const PEOPLE_URL = 'people/:id';
const opts = { crossDomain: true };
// Funcion para la peticion al API utilizando promesas
function obtenerPersonaje(id) {
return new Promise( (resolve,reject) => {
const url = `${API_URL}${PEOPLE_URL.replace(':id',id)}`;
$.get(url, opts, function (data) {
resolve(data);
}).fail( () => {
reject(id);
});
});
}
// Funcion para el caso de error
function onError(id) {
console.log(`Sucedio un error al obtener el personaje ${id}`);
}
// Arreglo de ids a consultar
var ids = [1, 2, 3, 4, 5, 6, 7];
// Funcion para crear el arreglo de promesas usando Array.map()
var promesas = ids.map(function (id) {
return obtenerPersonaje(id);
})
// Version alternativa usando arrow functions
var promesasArrow = ids.map( (id) => obtenerPersonaje(id));
// Llamado al arreglo de promesas usando el metodo Promise.all()
Promise.all(promesas).then( (personajes) => {
console.log(personajes);
}).catch(onError);
| 25.590909 | 66 | 0.642096 |
104720f0dfb9515befead0e144bff9dd52a17032 | 826 | js | JavaScript | issues/issues-router.js | Co-make-bw/back-end | fe2732e6494d7eeab957a91474b118f6da3a6024 | [
"MIT"
] | null | null | null | issues/issues-router.js | Co-make-bw/back-end | fe2732e6494d7eeab957a91474b118f6da3a6024 | [
"MIT"
] | 1 | 2020-04-01T15:20:02.000Z | 2020-04-01T15:20:02.000Z | issues/issues-router.js | Co-make-bw/back-end | fe2732e6494d7eeab957a91474b118f6da3a6024 | [
"MIT"
] | null | null | null | const router = require('express').Router();
const Issues = require('./issues-model');
router.get('/', (req, res) => {
Issues.get()
.then(issues => {
res.status(200).json(issues)
})
.catch(err => {
console.log(err)
res.status(500).json({message: 'Failed to get issues' })
})
})
router.get('/:id', (req, res) => {
const {id} = req.params;
Issues.getById(id)
.then(issue => {
if(issue) {
res.status(200).json(issue)
} else {
res.status(404).json({ message: 'Failed to find issue with given ID' })
}
})
.catch(err => {
console.log(err)
res.status(500).json({message: 'Failed to get issue' })
})
})
module.exports = router; | 25.8125 | 87 | 0.479419 |
f6c472db217fab4461b6aa093ab85682681226da | 285 | js | JavaScript | src/components/Depoimento/styled.js | matheushmacedo/site-gatsby | e34b2d28d2105c754f4ba153002135d51506d939 | [
"RSA-MD"
] | null | null | null | src/components/Depoimento/styled.js | matheushmacedo/site-gatsby | e34b2d28d2105c754f4ba153002135d51506d939 | [
"RSA-MD"
] | null | null | null | src/components/Depoimento/styled.js | matheushmacedo/site-gatsby | e34b2d28d2105c754f4ba153002135d51506d939 | [
"RSA-MD"
] | null | null | null | import styled from 'styled-components'
import Icons from '../Icons'
export const UserIcon = styled(Icons.User)`
color: grey;
margin-right: 10px;
height: 100px;
`
export const StarIcon = styled(Icons.StarFill)`
color: #FFC107;
margin-right: 10px;
width: 25px;
` | 21.923077 | 47 | 0.680702 |
f6c47c18a64d89971f7c6fad3d8f5deeb9cd2bdd | 2,862 | js | JavaScript | src/ui/uibase.js | qulongjun/JTable | 8999464e6e23012ad722be727f1f6e7134916bc5 | [
"MIT"
] | 2 | 2016-05-17T10:22:39.000Z | 2016-07-27T12:16:33.000Z | src/ui/uibase.js | qulongjun/JTable | 8999464e6e23012ad722be727f1f6e7134916bc5 | [
"MIT"
] | null | null | null | src/ui/uibase.js | qulongjun/JTable | 8999464e6e23012ad722be727f1f6e7134916bc5 | [
"MIT"
] | null | null | null | (function () {
var utils = JT.utils,
uiUtils = JT.ui.uiUtils,
//EventBase = JT.EventBase,
UIBase = JT.ui.UIBase = function () {
};
UIBase.prototype = {
className:'',
uiName:'',
initOptions:function (options) {
var me = this;
for (var k in options) {
me[k] = options[k];
}
this.id = this.id || 'edui' + uiUtils.uid();
},
initUIBase:function () {
this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
},
render:function (holder) {
var html = this.renderHtml();
var el = uiUtils.createElementByHtml(html);
//by xuheng 给每个node添加class
var list = domUtils.getElementsByTagName(el, "*");
var theme = "edui-" + (this.theme || this.editor.options.theme);
var layer = document.getElementById('edui_fixedlayer');
for (var i = 0, node; node = list[i++];) {
domUtils.addClass(node, theme);
}
domUtils.addClass(el, theme);
if(layer){
layer.className="";
domUtils.addClass(layer,theme);
}
var seatEl = this.getDom();
if (seatEl != null) {
seatEl.parentNode.replaceChild(el, seatEl);
uiUtils.copyAttributes(el, seatEl);
} else {
if (typeof holder == 'string') {
holder = document.getElementById(holder);
}
holder = holder || uiUtils.getFixedLayer();
domUtils.addClass(holder, theme);
holder.appendChild(el);
}
this.postRender();
},
getDom:function (name) {
if (!name) {
return document.getElementById(this.id);
} else {
return document.getElementById(this.id + '_' + name);
}
},
postRender:function () {
this.fireEvent('postrender');
},
getHtmlTpl:function () {
return '';
},
formatHtml:function (tpl) {
var prefix = 'edui-' + this.uiName;
return (tpl
.replace(/##/g, this.id)
.replace(/%%-/g, this.uiName ? prefix + '-' : '')
.replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
.replace(/\$\$/g, this._globalKey));
},
renderHtml:function () {
return this.formatHtml(this.getHtmlTpl());
},
dispose:function () {
var box = this.getDom();
if (box) baidu.editor.dom.domUtils.remove(box);
uiUtils.unsetGlobal(this.id);
}
};
//utils.inherits(UIBase, EventBase);
})();
| 34.071429 | 83 | 0.469602 |
f6c4c46bbcb24922bc5a7b185716dd02263475a8 | 1,049 | js | JavaScript | middleware/sync_by_install.js | LoicMahieu/cnpmjs.org | e6667cceb855406f2d975240fa2a0fab142ba8e3 | [
"MIT"
] | null | null | null | middleware/sync_by_install.js | LoicMahieu/cnpmjs.org | e6667cceb855406f2d975240fa2a0fab142ba8e3 | [
"MIT"
] | null | null | null | middleware/sync_by_install.js | LoicMahieu/cnpmjs.org | e6667cceb855406f2d975240fa2a0fab142ba8e3 | [
"MIT"
] | null | null | null | /**!
* cnpmjs.org - middleware/sync_by_install.js
*
* Copyright(c) cnpmjs.org and other contributors.
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
*/
'use strict';
/**
* Module dependencies.
*/
var config = require('../config');
/**
* this.allowSync - allow sync triggle by cnpm install
*/
module.exports = function* syncByInstall(next) {
this.allowSync = false;
if (!config.syncByInstall || !config.enablePrivate) {
// only config.enablePrivate should enable sync on install
return yield* next;
}
// request not by node, consider it request from web
var ua = this.get('user-agent');
if (!ua || ua.indexOf('node') < 0) {
return yield* next;
}
// if request with `/xxx?write=true`, meaning the read request using for write
if (this.query.write) {
return yield* next;
}
var name = this.params.name || this.params[0];
// scoped package dont sync
if (name && name[0] === '@') {
return yield* next;
}
this.allowSync = true;
yield* next;
};
| 20.98 | 80 | 0.64061 |
f6c512863ef312b20d76d6b0f8f1a32482e635ee | 296 | js | JavaScript | frontend/components/not_found.js | IceWreck/dashboard | 4a5a51b551574ce4b993e580470f8f2c3fa2bea0 | [
"MIT"
] | 7 | 2020-02-20T20:38:50.000Z | 2020-06-01T09:28:50.000Z | frontend/components/not_found.js | IceWreck/dashboard | 4a5a51b551574ce4b993e580470f8f2c3fa2bea0 | [
"MIT"
] | 44 | 2020-01-04T17:55:31.000Z | 2020-07-31T08:42:40.000Z | frontend/components/not_found.js | IceWreck/dashboard | 4a5a51b551574ce4b993e580470f8f2c3fa2bea0 | [
"MIT"
] | 34 | 2019-11-21T12:09:36.000Z | 2020-04-09T09:32:20.000Z | import * as React from "react";
import { Alert, PageSection } from "@patternfly/react-core";
const NotFound = () => (
<PageSection>
<Alert
variant="danger"
title="404! This view hasn't been created yet."
/>
</PageSection>
);
export { NotFound };
| 21.142857 | 60 | 0.570946 |
f6c5bed53d5a0f94dffb6bbf8d5f8ad0813a9ecf | 1,594 | js | JavaScript | src/modules/ui/directives/assetStatus/AssetStatus.js | xucito/TurtleNetworkGUI | 4a27b37600c247454c64ba82214f2398c16c6aa7 | [
"MIT"
] | 5 | 2020-03-19T16:44:13.000Z | 2021-03-29T22:27:13.000Z | src/modules/ui/directives/assetStatus/AssetStatus.js | xucito/TurtleNetworkGUI | 4a27b37600c247454c64ba82214f2398c16c6aa7 | [
"MIT"
] | 139 | 2020-02-24T18:38:11.000Z | 2021-11-26T09:02:08.000Z | src/modules/ui/directives/assetStatus/AssetStatus.js | xucito/TurtleNetworkGUI | 4a27b37600c247454c64ba82214f2398c16c6aa7 | [
"MIT"
] | 17 | 2020-02-17T20:48:32.000Z | 2021-07-03T12:22:03.000Z | (function () {
'use strict';
/**
* @param Base
* @param $scope
* @param user
* @param waves
* @param utils
* @return {AssetInfoHead}
*/
const controller = function (Base, $scope, user, waves, utils) {
class AssetInfoHead extends Base {
$postLink() {
this._getAssetInfo();
this.observe('assetId', this._getAssetInfo);
}
/**
* @private
*/
_getAssetInfo() {
const {
isVerified,
isGateway,
isSuspicious,
isGatewaySoon,
isThirdPartyGateway,
hasLabel
} = utils.getDataFromOracles(this.assetId);
this.isThirdPartyGateway = isThirdPartyGateway;
this.isGateway = isThirdPartyGateway === false ? isGateway : false;
this.isVerified = isVerified;
this.isSuspicious = isVerified ? false : isSuspicious;
this.isGatewaySoon = isGateway ? false : isGatewaySoon;
this.hasLabel = hasLabel;
}
}
return new AssetInfoHead();
};
controller.$inject = ['Base', '$scope', 'user', 'waves', 'utils'];
angular.module('app.ui')
.component('wAssetStatus', {
controller: controller,
templateUrl: 'modules/ui/directives/assetStatus/asset-status.html',
bindings: {
assetId: '<'
}
});
})();
| 27.964912 | 83 | 0.479297 |
f6c5e54510bc34dd68b0b0227480993475eb0506 | 628 | js | JavaScript | test/Basics/StringCharCodeAt.js | P1umer/ChakraCore | 6b471d9b9096ded789a924bc7f0518bbb000c320 | [
"MIT"
] | 8,664 | 2016-01-13T17:33:19.000Z | 2019-05-06T19:55:36.000Z | test/Basics/StringCharCodeAt.js | P1umer/ChakraCore | 6b471d9b9096ded789a924bc7f0518bbb000c320 | [
"MIT"
] | 5,058 | 2016-01-13T17:57:02.000Z | 2019-05-04T15:41:54.000Z | test/Basics/StringCharCodeAt.js | P1umer/ChakraCore | 6b471d9b9096ded789a924bc7f0518bbb000c320 | [
"MIT"
] | 1,367 | 2016-01-13T17:54:57.000Z | 2019-04-29T18:16:27.000Z | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function test(s, i)
{
var ch = s.charCodeAt(i);
WScript.Echo(ch);
}
var s = "Hello";
// Valid range
test(s, 0);
test(s, 1);
// Invalid range
test(s, -1);
test(s, 10);
// position.ToInteger()
test(s, 2.32);
test(s, Math.PI);
| 25.12 | 106 | 0.407643 |
f6c64e667c60375c1bf5474fa94f27260a2904d8 | 2,692 | js | JavaScript | server/game/components/logger/index.js | MrEliasen/path-to-power-server | 5ed4d04a17a0d663fe66e1f40840144ff69660a2 | [
"CC-BY-3.0"
] | 16 | 2018-02-11T14:29:58.000Z | 2021-07-29T01:25:55.000Z | server/game/components/logger/index.js | MrEliasen/road-to-legend-server | 5ed4d04a17a0d663fe66e1f40840144ff69660a2 | [
"CC-BY-3.0"
] | 119 | 2018-02-11T17:09:14.000Z | 2018-06-07T21:33:10.000Z | server/game/components/logger/index.js | MrEliasen/road-to-legend-server | 5ed4d04a17a0d663fe66e1f40840144ff69660a2 | [
"CC-BY-3.0"
] | 6 | 2018-02-12T15:05:18.000Z | 2020-12-28T10:54:33.000Z | import chalk from 'chalk';
import ConsoleLogger from './console';
import FileLogger from './file';
/**
* https://gist.github.com/etalisoft/81280a2a1a312ca6aab91daa909ccba0
*/
class Logger {
/**
* class constructor
*/
constructor(config) {
const levels = [
'debug',
'info',
'warn',
'error',
];
const level = levels.indexOf(config.level);
const consoleDebug = new ConsoleLogger({groupName: 'DEBUG:', method: 'debug', color: chalk.blue}, levels.indexOf('debug'), level);
const consoleInfo = new ConsoleLogger({groupName: 'LOG:', method: 'info', color: chalk.reset}, levels.indexOf('info'), level);
const consoleWarn = new ConsoleLogger({groupName: 'WARN:', method: 'warn', color: chalk.yellow}, levels.indexOf('warn'), level);
const consoleError = new ConsoleLogger({groupName: 'ERROR:', method: 'error', color: chalk.red}, levels.indexOf('error'), level);
const fileDebug = new FileLogger({groupName: 'DEBUG:', file: config.debugFile}, levels.indexOf('debug'), level);
const fileInfo = new FileLogger({groupName: 'INFO:', file: config.infoFile}, levels.indexOf('info'), level);
const fileWarn = new FileLogger({groupName: 'WARN:', file: config.warnFile}, levels.indexOf('warn'), level);
const fileError = new FileLogger({groupName: 'ERROR:', file: config.errorFile}, levels.indexOf('error'), level);
this.actions = {consoleInfo, consoleDebug, consoleWarn, consoleError, fileInfo, fileDebug, fileWarn, fileError};
this.debug = run(consoleDebug);
this.info = run(consoleInfo);
this.warn = run(consoleWarn, fileWarn);
this.error = run(consoleError, fileError);
this.custom = run;
/**
* parse the args
* @param {Args Array} args
* @return {Object}
*/
function parse(...args) {
// NOTE: Node doesn't supply Error.fileName and Error.lineNumber
// So we have to try to dig it out of the current stacktrace
const stackFrame = new Error().stack.split('\n')[3] || '';
const regFile = /\((.+):(\d+):(\d+)\)/;
const [, fileName, line, column] = stackFrame.match(regFile) || [];
return {args, fileName, line, column};
}
/**
* Do the actual logging
* @param {Array} actions
*/
function run(...actions) {
return (...args) => {
const data = parse(...args);
return Promise.all(actions.map((action) => action.log(data)));
};
}
}
}
export default Logger;
| 39.588235 | 138 | 0.583952 |
f6c68bba4fbce86c991db0a1f17daa4263c31560 | 17,660 | js | JavaScript | lib/engine.js | think-in-universe/aurora.js | fcaf78bcaf68ef3aee641e23ecfd53ebf8edc28d | [
"CC0-1.0"
] | null | null | null | lib/engine.js | think-in-universe/aurora.js | fcaf78bcaf68ef3aee641e23ecfd53ebf8edc28d | [
"CC0-1.0"
] | null | null | null | lib/engine.js | think-in-universe/aurora.js | fcaf78bcaf68ef3aee641e23ecfd53ebf8edc28d | [
"CC0-1.0"
] | null | null | null | /* This is free and unencumbered software released into the public domain. */
import { AccountID, Address } from './account.js';
import { BlockProxy, parseBlockID, } from './block.js';
import { NETWORKS } from './config.js';
import { KeyStore } from './key_store.js';
import { Err, Ok } from './prelude.js';
import { SubmitResult, FunctionCallArgs, GetStorageAtArgs, InitCallArgs, NewCallArgs, ViewCallArgs, FungibleTokenMetadata, TransactionStatus, WrappedSubmitResult, } from './schema.js';
import { TransactionID } from './transaction.js';
import { base58ToBytes } from './utils.js';
import { defaultAbiCoder } from '@ethersproject/abi';
import { arrayify as parseHexString } from '@ethersproject/bytes';
import { parse as parseRawTransaction } from '@ethersproject/transactions';
import { toBigIntBE, toBufferBE } from 'bigint-buffer';
import { Buffer } from 'buffer';
import BN from 'bn.js';
import * as NEAR from 'near-api-js';
export { getAddress as parseAddress } from '@ethersproject/address';
export { arrayify as parseHexString } from '@ethersproject/bytes';
export class AddressState {
constructor(address, nonce = BigInt(0), balance = BigInt(0), code, storage = new Map()) {
this.address = address;
this.nonce = nonce;
this.balance = balance;
this.code = code;
this.storage = storage;
}
}
export var EngineStorageKeyPrefix;
(function (EngineStorageKeyPrefix) {
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Config"] = 0] = "Config";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Nonce"] = 1] = "Nonce";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Balance"] = 2] = "Balance";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Code"] = 3] = "Code";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Storage"] = 4] = "Storage";
})(EngineStorageKeyPrefix || (EngineStorageKeyPrefix = {}));
export class EngineState {
constructor(storage = new Map()) {
this.storage = storage;
}
}
const DEFAULT_NETWORK_ID = 'local';
export class Engine {
constructor(near, keyStore, signer, networkID, contractID) {
this.near = near;
this.keyStore = keyStore;
this.signer = signer;
this.networkID = networkID;
this.contractID = contractID;
}
static async connect(options, env) {
const networkID = options.network || (env && env.NEAR_ENV) || DEFAULT_NETWORK_ID;
const network = NETWORKS.get(networkID); // TODO: error handling
const contractID = AccountID.parse(options.contract || (env && env.AURORA_ENGINE) || network.contractID).unwrap();
const signerID = AccountID.parse(options.signer || (env && env.NEAR_MASTER_ACCOUNT)).unwrap(); // TODO: error handling
const keyStore = KeyStore.load(networkID, env);
const near = new NEAR.Near({
deps: { keyStore },
networkId: networkID,
nodeUrl: options.endpoint || (env && env.NEAR_URL) || network.nearEndpoint,
});
const signer = await near.account(signerID.toString());
return new Engine(near, keyStore, signer, networkID, contractID);
}
async install(contractCode) {
const contractAccount = (await this.getAccount()).unwrap();
const result = await contractAccount.deployContract(contractCode);
return Ok(TransactionID.fromHex(result.transaction.hash));
}
async upgrade(contractCode) {
return await this.install(contractCode);
}
async initialize(options) {
const newArgs = new NewCallArgs(parseHexString(defaultAbiCoder.encode(['uint256'], [options.chain || 0])), options.owner || '', options.bridgeProver || '', new BN(options.upgradeDelay || 0));
const default_ft_metadata = FungibleTokenMetadata.default();
const given_ft_metadata = options.metadata || default_ft_metadata;
const ft_metadata = new FungibleTokenMetadata(given_ft_metadata.spec || default_ft_metadata.spec, given_ft_metadata.name || default_ft_metadata.name, given_ft_metadata.symbol || default_ft_metadata.symbol, given_ft_metadata.icon || default_ft_metadata.icon, given_ft_metadata.reference || default_ft_metadata.reference, given_ft_metadata.reference_hash || default_ft_metadata.reference_hash, given_ft_metadata.decimals || default_ft_metadata.decimals);
// default values are the testnet values
const connectorArgs = new InitCallArgs(options.prover || 'prover.ropsten.testnet', options.ethCustodian || '9006a6D7d08A388Eeea0112cc1b6b6B15a4289AF', ft_metadata);
// TODO: this should be able to be a single transaction with multiple actions,
// but there doesn't seem to be a good way to do that in `near-api-js` presently.
const tx = await this.promiseAndThen(this.callMutativeFunction('new', newArgs.encode()), (_) => this.callMutativeFunction('new_eth_connector', connectorArgs.encode()));
return tx.map(({ id }) => id);
}
// Like Result.andThen, but wrapped up in Promises
async promiseAndThen(p, f) {
const r = await p;
if (r.isOk()) {
const t = r.unwrap();
return await f(t);
}
else {
return Err(r.unwrapErr());
}
}
async getAccount() {
return Ok(await this.near.account(this.contractID.toString()));
}
async getBlockHash() {
const contractAccount = (await this.getAccount()).unwrap();
const state = (await contractAccount.state());
return Ok(state.block_hash);
}
async getBlockHeight() {
const contractAccount = (await this.getAccount()).unwrap();
const state = (await contractAccount.state());
return Ok(state.block_height);
}
async getBlockInfo() {
return Ok({
hash: '',
coinbase: Address.zero(),
timestamp: 0,
number: 0,
difficulty: 0,
gasLimit: 0,
});
}
async getBlockTransactionCount(blockID) {
try {
const provider = this.near.connection.provider;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const block = (await provider.block(parseBlockID(blockID)));
const chunk_mask = block.header.chunk_mask;
const requests = block.chunks
.filter((_, index) => chunk_mask[index])
.map(async (chunkHeader) => {
if (chunkHeader.tx_root == '11111111111111111111111111111111') {
return 0; // no transactions in this chunk
}
else {
const chunk = await provider.chunk(chunkHeader.chunk_hash);
return chunk.transactions.length;
}
});
const counts = (await Promise.all(requests));
return Ok(counts.reduce((a, b) => a + b, 0));
}
catch (error) {
//console.error('Engine#getBlockTransactionCount', error);
return Err(error.message);
}
}
async getBlock(blockID, options) {
const provider = this.near.connection.provider;
return await BlockProxy.fetch(provider, blockID, options);
}
async hasBlock(blockID) {
const provider = this.near.connection.provider;
return await BlockProxy.lookup(provider, blockID);
}
async getCoinbase() {
return Ok(Address.zero()); // TODO
}
async getVersion(options) {
return (await this.callFunction('get_version', undefined, options)).map((output) => output.toString());
}
async getOwner(options) {
return (await this.callFunction('get_owner', undefined, options)).andThen((output) => AccountID.parse(output.toString()));
}
async getBridgeProvider(options) {
return (await this.callFunction('get_bridge_provider', undefined, options)).andThen((output) => AccountID.parse(output.toString()));
}
async getChainID(options) {
const result = await this.callFunction('get_chain_id', undefined, options);
return result.map(toBigIntBE);
}
// TODO: getUpgradeIndex()
// TODO: stageUpgrade()
// TODO: deployUpgrade()
async deployCode(bytecode) {
const args = parseHexString(bytecode);
const outcome = await this.callMutativeFunction('deploy_code', args);
return outcome.map(({ output }) => {
const result = SubmitResult.decode(Buffer.from(output));
return Address.parse(Buffer.from(result.output().unwrap()).toString('hex')).unwrap();
});
}
async call(contract, input) {
const args = new FunctionCallArgs(contract.toBytes(), this.prepareInput(input));
return (await this.callMutativeFunction('call', args.encode())).map(({ output }) => output);
}
async submit(input) {
try {
const inputBytes = this.prepareInput(input);
try {
const rawTransaction = parseRawTransaction(inputBytes); // throws Error
if (rawTransaction.gasLimit.toBigInt() < 21000n) {
// See: https://github.com/aurora-is-near/aurora-relayer/issues/17
return Err('ERR_INTRINSIC_GAS');
}
}
catch (error) {
//console.error(error); // DEBUG
return Err('ERR_INVALID_TX');
}
return (await this.callMutativeFunction('submit', inputBytes)).map(({ output, gasBurned, tx }) => {
return new WrappedSubmitResult(SubmitResult.decode(Buffer.from(output)), gasBurned, tx);
});
}
catch (error) {
//console.error(error); // DEBUG
return Err(error.message);
}
}
// TODO: metaCall()
async view(sender, address, amount, input, options) {
const args = new ViewCallArgs(sender.toBytes(), address.toBytes(), toBufferBE(BigInt(amount), 32), this.prepareInput(input));
const result = await this.callFunction('view', args.encode(), options);
return result.map((output) => {
const status = TransactionStatus.decode(output);
if (status.success !== undefined)
return status.success.output;
else if (status.revert !== undefined)
return status.revert.output;
else if (status.outOfGas !== undefined)
return Err(status.outOfGas);
else if (status.outOfFund !== undefined)
return Err(status.outOfFund);
else if (status.outOfOffset !== undefined)
return Err(status.outOfOffset);
else if (status.callTooDeep !== undefined)
return Err(status.callTooDeep);
else
return Err('Failed to retrieve data from the contract');
});
}
async getCode(address, options) {
const args = address.toBytes();
if (typeof options === 'object' && options.block) {
options.block = (options.block + 1);
}
return await this.callFunction('get_code', args, options);
}
async getBalance(address, options) {
const args = address.toBytes();
const result = await this.callFunction('get_balance', args, options);
return result.map(toBigIntBE);
}
async getNonce(address, options) {
const args = address.toBytes();
const result = await this.callFunction('get_nonce', args, options);
return result.map(toBigIntBE);
}
async getStorageAt(address, key, options) {
const args = new GetStorageAtArgs(address.toBytes(), parseHexString(defaultAbiCoder.encode(['uint256'], [key])));
const result = await this.callFunction('get_storage_at', args.encode(), options);
return result.map(toBigIntBE);
}
async getAuroraErc20Address(nep141, options) {
const args = Buffer.from(nep141.id, 'utf-8');
const result = await this.callFunction('get_erc20_from_nep141', args, options);
return result.map((output) => {
return Address.parse(output.toString('hex')).unwrap();
});
}
async getNEP141Account(erc20, options) {
const args = erc20.toBytes();
const result = await this.callFunction('get_nep141_from_erc20', args, options);
return result.map((output) => {
return AccountID.parse(output.toString('utf-8')).unwrap();
});
}
// TODO: beginChain()
// TODO: beginBlock()
async getStorage() {
const result = new Map();
const contractAccount = (await this.getAccount()).unwrap();
const records = await contractAccount.viewState('', { finality: 'final' });
for (const record of records) {
const record_type = record.key[0];
if (record_type == EngineStorageKeyPrefix.Config)
continue; // skip EVM metadata
const key = record_type == EngineStorageKeyPrefix.Storage
? record.key.subarray(1, 21)
: record.key.subarray(1);
const address = Buffer.from(key).toString('hex');
if (!result.has(address)) {
result.set(address, new AddressState(Address.parse(address).unwrap()));
}
const state = result.get(address);
switch (record_type) {
case EngineStorageKeyPrefix.Config:
break; // unreachable
case EngineStorageKeyPrefix.Nonce:
state.nonce = toBigIntBE(record.value);
break;
case EngineStorageKeyPrefix.Balance:
state.balance = toBigIntBE(record.value);
break;
case EngineStorageKeyPrefix.Code:
state.code = record.value;
break;
case EngineStorageKeyPrefix.Storage: {
state.storage.set(toBigIntBE(record.key.subarray(21)), toBigIntBE(record.value));
break;
}
}
}
return Ok(result);
}
async callFunction(methodName, args, options) {
const result = await this.signer.connection.provider.query({
request_type: 'call_function',
account_id: this.contractID.toString(),
method_name: methodName,
args_base64: this.prepareInput(args).toString('base64'),
finality: options?.block === undefined || options?.block === null
? 'final'
: undefined,
block_id: options?.block !== undefined && options?.block !== null
? options.block
: undefined,
});
if (result.logs && result.logs.length > 0)
console.debug(result.logs); // TODO
return Ok(Buffer.from(result.result));
}
async callMutativeFunction(methodName, args) {
this.keyStore.reKey();
const gas = new BN('300000000000000'); // TODO?
try {
const result = await this.signer.functionCall(this.contractID.toString(), methodName, this.prepareInput(args), gas);
if (typeof result.status === 'object' &&
typeof result.status.SuccessValue === 'string') {
const transactionId = result?.transaction_outcome?.id;
return Ok({
id: TransactionID.fromHex(result.transaction.hash),
output: Buffer.from(result.status.SuccessValue, 'base64'),
tx: transactionId,
gasBurned: await this.transactionGasBurned(transactionId),
});
}
return Err(result.toString()); // FIXME: unreachable?
}
catch (error) {
//assert(error instanceof ServerTransactionError);
switch (error?.type) {
case 'FunctionCallError': {
const transactionId = error?.transaction_outcome?.id;
const details = {
tx: transactionId,
gasBurned: await this.transactionGasBurned(transactionId),
};
const errorKind = error?.kind?.ExecutionError;
if (errorKind) {
const errorCode = errorKind.replace('Smart contract panicked: ', '');
return Err(this.errorWithDetails(errorCode, details));
}
return Err(this.errorWithDetails(error.message, details));
}
case 'MethodNotFound':
return Err(error.message);
default:
console.debug(error);
return Err(error.toString());
}
}
}
prepareInput(args) {
if (typeof args === 'undefined')
return Buffer.alloc(0);
if (typeof args === 'string')
return Buffer.from(parseHexString(args));
return Buffer.from(args);
}
errorWithDetails(message, details) {
return `${message}|${JSON.stringify(details)}`;
}
async transactionGasBurned(id) {
try {
const transactionStatus = await this.near.connection.provider.txStatus(base58ToBytes(id), this.contractID.toString());
const receiptsGasBurned = transactionStatus.receipts_outcome.reduce((sum, value) => sum + value.outcome.gas_burnt, 0);
const transactionGasBurned = transactionStatus.transaction_outcome.outcome.gas_burnt || 0;
return receiptsGasBurned + transactionGasBurned;
}
catch (error) {
return 0;
}
}
}
| 46.351706 | 460 | 0.603567 |
f6c6a71d7d1363b853b484abd0bb75c13c64aeb7 | 880 | js | JavaScript | js/connection.js | emmadarbois/xanplay-cai | 3d5a4439de2fdd7d71a582596cf8371dc89871e7 | [
"MIT"
] | null | null | null | js/connection.js | emmadarbois/xanplay-cai | 3d5a4439de2fdd7d71a582596cf8371dc89871e7 | [
"MIT"
] | 1 | 2020-12-15T15:08:10.000Z | 2020-12-15T15:47:04.000Z | js/connection.js | emmadarbois/xanplay-cai | 3d5a4439de2fdd7d71a582596cf8371dc89871e7 | [
"MIT"
] | null | null | null | document.addEventListener("pageViewRendered", () => {
console.log(1)
var user = document.getElementsByName("user")[0];
var mdp = document.getElementsByName("mdp")[0];
var btn_connect = document.getElementById("btn_connect");
var btn_no_account = document.getElementById("create_account");
console.log(user.value)
console.log(mdp.value)
console.log(btn_connect)
console.log(btn_no_account)
console.log(2)
btn_connect.onclick = () => {
console.log('in')
if ((user.value === "admin") && (mdp.value === "admin")) {
window.location.href="?account";
}
else {
window.alert("Aucun compte ne correspond à cette adresse !");
}
}
console.log(3)
btn_no_account.onclick = () => {
window.alert("Nous ne pouvons créer de nouveau compte pour le moment.")
}
}); | 30.344828 | 79 | 0.6125 |
f6c6f517af5ad2805980f59b94036132fb76cc71 | 59 | js | JavaScript | src/utils/config.js | xDreamers/wangzhe_back | 552ec503cd0034919e90d74f79a838bc4711c5fb | [
"Apache-2.0"
] | null | null | null | src/utils/config.js | xDreamers/wangzhe_back | 552ec503cd0034919e90d74f79a838bc4711c5fb | [
"Apache-2.0"
] | null | null | null | src/utils/config.js | xDreamers/wangzhe_back | 552ec503cd0034919e90d74f79a838bc4711c5fb | [
"Apache-2.0"
] | null | null | null | export const host = 'https://www.xkjtencent.cn:3002/api/';
| 29.5 | 58 | 0.711864 |
f6c6fefaeab0b54fd7568df97f1c84dced67013a | 6,445 | js | JavaScript | src/streamserver/plugins/form-auth.js | michaelBenin/js-sdk | 83a1e1a407cc94c9f7ffed7f9cbdb5ac3e8c66e0 | [
"Apache-2.0"
] | 1 | 2015-11-07T12:36:53.000Z | 2015-11-07T12:36:53.000Z | src/streamserver/plugins/form-auth.js | michaelBenin/js-sdk | 83a1e1a407cc94c9f7ffed7f9cbdb5ac3e8c66e0 | [
"Apache-2.0"
] | null | null | null | src/streamserver/plugins/form-auth.js | michaelBenin/js-sdk | 83a1e1a407cc94c9f7ffed7f9cbdb5ac3e8c66e0 | [
"Apache-2.0"
] | null | null | null | (function(jQuery) {
"use strict";
var $ = jQuery;
/**
* @class Echo.StreamServer.Controls.Submit.Plugins.FormAuth
* Adds the authentication section to the Echo Submit control
*
* var identityManager = {
* "width": 400,
* "height": 240,
* "url": "http://example.com/auth"
* };
*
* new Echo.StreamServer.Controls.Submit({
* "target": document.getElementById("submit"),
* "appkey": "echo.jssdk.demo.aboutecho.com",
* "plugins": [{
* "name": "FormAuth",
* "submitPermissions": "forceLogin",
* "identityManager": {
* "login": identityManager,
* "signup": identityManager
* }
* }]
* });
*
* Note: it is strongly recommended to use
* {@link Echo.StreamServer.Controls.Submit.Plugins.JanrainAuth JanrainAuth} plugin
* in case of integration with Janrain authentication provider because it is
* based on the most current <a href="http://janrain.com/products/engage/social-login/" target="_blank">Janrain Social Login Widget</a>
* implementation.
*
* More information regarding the plugins installation can be found
* in the [“How to initialize Echo components”](#!/guide/how_to_initialize_components-section-2) guide.
*
* @extends Echo.Plugin
*
* @package streamserver/plugins.pack.js
* @package streamserver.pack.js
*/
var plugin = Echo.Plugin.manifest("FormAuth", "Echo.StreamServer.Controls.Submit");
if (Echo.Plugin.isDefined(plugin)) return;
plugin.init = function() {
if (this._userStatus() === "forcedLogin") {
this.extendTemplate("replace", "header", plugin.templates.forcedLogin);
}
this.extendTemplate("insertBefore", "header", plugin.templates.auth);
this.component.addPostValidator(this._validator());
};
plugin.config = {
/**
* @cfg {Object} identityManager The list of handlers for login, edit
* and signup actions. If some action is omitted then it will not be
* available for users in the Auth control. Each handler accepts sessionID
* as GET parameter. This parameter is necessary for communication with
* the Backplane server. When the handler finishes working it constructs the
* corresponding Backplane message (for login, signup or user data update)
* and sends this message to the Backplane server.
*
* @cfg {Object} [identityManager.login]
* Encapsulates data for login workflow
*
* @cfg {Number} [identityManager.login.width]
* Specifies the width of the visible auth area
*
* @cfg {Number} [identityManager.login.height]
* Specifies the height of the visible auth area
*
* @cfg {String} [identityManager.login.url]
* Specifies the URL to be opened as an auth handler
*
* @cfg {String} [identityManager.login.title]
* Specifies the Title of the auth modal dialog
*
* @cfg {Object} [identityManager.signup]
* Encapsulates data for signup workflow
*
* @cfg {Number} [identityManager.signup.width]
* Specifies the width of the visible auth area
*
* @cfg {Number} [identityManager.signup.height]
* Specifies the height of the visible auth area
*
* @cfg {String} [identityManager.signup.url]
* Specifies the URL to be opened as an auth handler
*
* @cfg {String} [identityManager.signup.title]
* Specifies the Title of the auth modal dialog
*
* @cfg {Object} [identityManager.edit]
* Encapsulates data for edit workflow
*
* @cfg {Number} [identityManager.edit.width]
* Specifies the width of the visible auth area
*
* @cfg {Number} [identityManager.edit.height]
* Specifies the height of the visible auth area
*
* @cfg {String} [identityManager.edit.url]
* Specifies the URL to be opened as an auth handler
*
* @cfg {String} [identityManager.edit.title]
* Specifies the Title of the auth modal dialog
*/
"identityManager": {},
/**
* @cfg {String} submitPermissions
* Specifies the permitted commenting modes.
* The two options are:
*
* + "allowGuest" - allows to guest users submit an activity item (comment etc)
* + "forceLogin" - submit permissions allowed only for logged in users
*/
"submitPermissions": "allowGuest"
};
plugin.enabled = function() {
return (this.component.user && this.component.user.get("sessionID") &&
this.config.get("identityManager.login") &&
this.config.get("identityManager.signup"));
};
plugin.labels = {
/**
* @echo_label
*/
"youMustBeLoggedIn": "You must be logged in to comment"
};
plugin.dependencies = [{
"control": "Echo.IdentityServer.Controls.Auth",
"url": "{config:cdnBaseURL.sdk}/identityserver.pack.js"
}];
/**
* @echo_template
*/
plugin.templates.auth = '<div class="{plugin.class:auth}"></div>';
/**
* @echo_template
*/
plugin.templates.forcedLogin =
'<div class="{class:header} echo-primaryFont">' +
'<span class="{plugin.class:forcedLoginMessage} echo-secondaryColor">' +
'{plugin.label:youMustBeLoggedIn}' +
'</span>' +
'</div>';
/**
* @echo_renderer
*/
plugin.component.renderers.header = function(element) {
var plugin = this;
if (plugin._userStatus() === "logged") {
return element.empty();
}
return plugin.parentRenderer("header", arguments);
};
/**
* @echo_renderer
*/
plugin.component.renderers.container = function(element) {
var plugin = this;
plugin.parentRenderer("container", arguments);
var _class = function(postfix) {
return plugin.cssPrefix + postfix;
};
return element
.removeClass($.map(["logged", "anonymous", "forcedLogin"], _class).join(" "))
.addClass(_class(plugin._userStatus()));
};
/**
* @echo_renderer
*/
plugin.renderers.auth = function(element) {
var plugin = this;
new Echo.IdentityServer.Controls.Auth(plugin.config.assemble({
"target": element,
"identityManager": plugin.config.get("identityManager")
}));
return element;
};
plugin.methods._validator = function() {
var plugin = this, submit = this.component;
return function() {
if (!submit.user.is("logged") && plugin._permissions() === "forceLogin") {
plugin.view.get("forcedLoginMessage").addClass(plugin.cssPrefix + "error");
return false;
}
return true;
}
};
plugin.methods._permissions = function() {
return this.config.get("submitPermissions");
};
plugin.methods._userStatus = function() {
return this.component.user.is("logged")
? "logged"
: this._permissions() === "forceLogin"
? "forcedLogin"
: "anonymous";
};
plugin.css =
'.{plugin.class:forcedLoginMessage} { font-size: 14px; font-weight: bold; }' +
'.{plugin.class:error} { color: red; }';
Echo.Plugin.create(plugin);
})(Echo.jQuery);
| 28.901345 | 135 | 0.694802 |
f6c7d9b370f73a50bcab10723194e2c92379b250 | 3,153 | js | JavaScript | extensions/amp-base-carousel/1.0/arrow.js | anubhavAdpushup/amphtml | b5dea36e0b8bd012585d50839766a084f99a3685 | [
"Apache-2.0"
] | 1 | 2020-12-15T22:01:53.000Z | 2020-12-15T22:01:53.000Z | extensions/amp-base-carousel/1.0/arrow.js | anubhavAdpushup/amphtml | b5dea36e0b8bd012585d50839766a084f99a3685 | [
"Apache-2.0"
] | 4 | 2021-06-17T17:22:48.000Z | 2022-03-02T11:26:00.000Z | extensions/amp-base-carousel/1.0/arrow.js | anubhavAdpushup/amphtml | b5dea36e0b8bd012585d50839766a084f99a3685 | [
"Apache-2.0"
] | 1 | 2020-02-03T10:58:37.000Z | 2020-02-03T10:58:37.000Z | /**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Preact from '../../../src/preact';
import {useStyles} from './base-carousel.jss';
/**
* @param {!BaseCarouselDef.ArrowProps} props
* @return {PreactDef.Renderable}
*/
export function Arrow({customArrow, by, advance, disabled}) {
const {
'disabled': customDisabled,
'onClick': onCustomClick,
} = customArrow.props;
const isDisabled = disabled || customDisabled;
const onClick = (e) => {
if (onCustomClick) {
onCustomClick(e);
}
advance(by);
};
const classes = useStyles();
const classNames = `${classes.arrowPlacement} ${
by < 0 ? classes.arrowPrev : classes.arrowNext
} ${isDisabled ? classes.arrowDisabled : ''}`;
return (
<div class={classNames}>
{Preact.cloneElement(customArrow, {
'onClick': onClick,
'disabled': isDisabled,
'aria-disabled': isDisabled,
})}
</div>
);
}
/**
* @param {!BaseCarouselDef.ArrowProps} props
* @return {PreactDef.VNode}
*/
export function ArrowPrev({customArrow, ...rest}) {
return (
<Arrow
by={-1}
customArrow={customArrow || <DefaultArrow by={-1} />}
{...rest}
/>
);
}
/**
* @param {!BaseCarouselDef.ArrowProps} props
* @return {PreactDef.Renderable}
*/
export function ArrowNext({customArrow, ...rest}) {
return (
<Arrow
by={1}
customArrow={customArrow || <DefaultArrow by={1} />}
{...rest}
/>
);
}
/**
* @param {!BaseCarouselDef.ArrowProps} props
* @return {PreactDef.Renderable}
*/
function DefaultArrow({by, ...rest}) {
const classes = useStyles();
return (
<button
class={classes.defaultArrowButton}
aria-label={
by < 0 ? 'Previous item in carousel' : 'Next item in carousel'
}
{...rest}
>
<div class={`${classes.arrowBaseStyle} ${classes.arrowFrosting}`}></div>
<div class={`${classes.arrowBaseStyle} ${classes.arrowBackdrop}`}></div>
<div class={`${classes.arrowBaseStyle} ${classes.arrowBackground}`}></div>
<svg class={classes.arrowIcon} viewBox="0 0 24 24">
{by < 0 ? (
<path
d="M14,7.4 L9.4,12 L14,16.6"
fill="none"
stroke-width="2px"
stroke-linejoin="round"
stroke-linecap="round"
/>
) : (
<path
d="M10,7.4 L14.6,12 L10,16.6"
fill="none"
stroke-width="2px"
stroke-linejoin="round"
stroke-linecap="round"
/>
)}
</svg>
</button>
);
}
| 26.495798 | 80 | 0.598795 |
f6c7f0fc0a1089cc68290f5fd1e2da25f3bf8283 | 2,093 | js | JavaScript | src/App.js | pepeneif/spl-token-wallet | fbe3ce9a63e1cb4701f841a7fc7036d7d3b0a0a7 | [
"Apache-2.0"
] | null | null | null | src/App.js | pepeneif/spl-token-wallet | fbe3ce9a63e1cb4701f841a7fc7036d7d3b0a0a7 | [
"Apache-2.0"
] | null | null | null | src/App.js | pepeneif/spl-token-wallet | fbe3ce9a63e1cb4701f841a7fc7036d7d3b0a0a7 | [
"Apache-2.0"
] | null | null | null | import React, { Suspense } from 'react';
import CssBaseline from '@material-ui/core/CssBaseline';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import {
ThemeProvider,
unstable_createMuiStrictModeTheme as createMuiTheme,
} from '@material-ui/core/styles';
import blue from '@material-ui/core/colors/blue';
import NavigationFrame from './components/NavigationFrame';
import { ConnectionProvider } from './utils/connection';
import WalletPage from './pages/WalletPage';
import { useWallet, WalletProvider } from './utils/wallet';
import LoadingIndicator from './components/LoadingIndicator';
import { SnackbarProvider } from 'notistack';
import PopupPage from './pages/PopupPage';
import LoginPage from './pages/LoginPage';
export default function App() {
// TODO: add toggle for dark mode
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: prefersDarkMode ? 'dark' : 'light',
primary: {
main: '#015ff4',
},
secondary: {
main: '#000d22',
},
},
}),
[prefersDarkMode],
);
// Disallow rendering inside an iframe to prevent clickjacking.
if (window.self !== window.top) {
return null;
}
return (
<Suspense fallback={<LoadingIndicator />}>
<ThemeProvider theme={theme}>
<CssBaseline />
<ConnectionProvider>
<SnackbarProvider maxSnack={5} autoHideDuration={8000}>
<WalletProvider>
<NavigationFrame>
<Suspense fallback={<LoadingIndicator />}>
<PageContents />
</Suspense>
</NavigationFrame>
</WalletProvider>
</SnackbarProvider>
</ConnectionProvider>
</ThemeProvider>
</Suspense>
);
}
function PageContents() {
const wallet = useWallet();
if (!wallet) {
return <LoginPage />;
}
if (window.opener) {
return <PopupPage opener={window.opener} />;
}
return <WalletPage />;
}
| 28.671233 | 72 | 0.627329 |
f6c8149758ba01101f533fdde393e5096cdd16ca | 8,073 | js | JavaScript | addon/components/bs-modal-simple.js | Cloud-Tomatoes/ember-bootstrap | ffb35e819d858bc24a6b78934248d360648115ff | [
"MIT"
] | null | null | null | addon/components/bs-modal-simple.js | Cloud-Tomatoes/ember-bootstrap | ffb35e819d858bc24a6b78934248d360648115ff | [
"MIT"
] | null | null | null | addon/components/bs-modal-simple.js | Cloud-Tomatoes/ember-bootstrap | ffb35e819d858bc24a6b78934248d360648115ff | [
"MIT"
] | null | null | null | /**
Component for creating [Bootstrap modals](http://getbootstrap.com/javascript/#modals) with a some common default markup
including a header, footer and body. Creating a simple modal is easy:
```hbs
<BsModalSimple @title="Simple Dialog">
Hello world!
</BsModalSimple>
```
This will automatically create the appropriate markup, with a modal header containing the title, and a footer containing
a default "Ok" button, that will close the modal automatically (unless you return `false` from `onHide`).
A modal created this way will be visible at once. You can use the `{{#if ...}}` helper to hide all modal elements from
the DOM until needed. Or you can bind the `open` argument to trigger showing and hiding the modal:
```hbs
<BsModalSimple @open={{this.openModal}} @title="Simple Dialog">
Hello world!
</BsModalSimple>
```
### Custom Markup
To customize the markup within the modal you can use the [<BsModal>](Components.Modal.html) component.
### Modals with forms
There is a special case when you have a form inside your modals body: you probably do not want to have a submit button
within your form but instead in your modal footer. Hover pressing the submit button outside of your form would not
trigger the form data to be submitted. In the example below this would not trigger the submit action of the form, an
thus bypass the form validation feature of the form component.
```hbs
<BsModalSimple @title="Form Example" @closeTitle="Cancel" @submitTitle="Ok">
<BsForm @model={{this}} @onSubmit={{this.submit}} @submitOnEnter={{true}} as |Form|>
<Form.element @label="first name" @property="firstname" />
<Form.element @label="last name" @property="lastname" />
</BsForm>
</BsModalSimple>
```
The modal component supports this common case by triggering the submit event programmatically on the body's form if
present whenever the footer's submit button is pressed. To allow the form to be submitted by pressing the enter key
also, you must either set `@submitOnEnter={{true}}` on the `<BsForm>` or include an invisible submit button in the
form (`<button type="submit" class="d-hidden">Submit</button>`).
### Auto-focus
In order to allow key handling to function, the modal's root element is given focus once the modal is shown. If your
modal contains an element such as a text input and you would like it to be given focus rather than the modal element,
then give it the HTML5 autofocus attribute:
```hbs
<BsModalSimple @title="Form Example" @closeTitle="Cancel" @submitTitle="Ok">
<BsForm @model={{this}} @onSubmit={{this.submit}} @submitOnEnter={{true}} as |Form|>
<Form.element @label="first name" @property="firstname" @autofocus={{true}} />
<Form.element @label="last name" @property="lastname" />
</BsForm>
</BsModalSimple>
```
### Modals inside wormhole
Modals make use of the [ember-wormhole](https://github.com/yapplabs/ember-wormhole) addon, which will be installed
automatically alongside ember-bootstrap. This is used to allow the modal to be placed in deeply nested
components/templates where it belongs to logically, but to have the actual DOM elements within a special container
element, which is a child of ember's root element. This will make sure that modals always overlay the whole app, and
are not effected by parent elements with `overflow: hidden` for example.
If you want the modal to render in place, rather than being wormholed, you can set `@renderInPlace={{true}}`.
@class ModalSimple
@namespace Components
@public
*/
/**
* The title of the modal, visible in the modal header. Is ignored if `header` is false.
*
* @property title
* @type string
* @public
*/
/**
* Visibility of the modal. Toggle to show/hide with CSS transitions.
*
* When the modal is closed by user interaction this property will not update by using two-way bindings in order
* to follow DDAU best practices. If you want to react to such changes, subscribe to the `onHide` action
*
* @property open
* @type boolean
* @default true
* @public
*/
/**
* Set to false to disable fade animations.
*
* @property fade
* @type boolean
* @default true
* @public
*/
/**
* Use a semi-transparent modal background to hide the rest of the page.
*
* @property backdrop
* @type boolean
* @default true
* @public
*/
/**
* Closes the modal when escape key is pressed.
*
* @property keyboard
* @type boolean
* @default true
* @public
*/
/**
* [BS4 only!] Vertical position, either 'top' (default) or 'center'
* 'center' will apply the `modal-dialog-centered` class
*
* @property position
* @type {string}
* @default 'top'
* @public
*/
/**
* [BS4 only!] Allows scrolling within the modal body
* 'true' will apply the `modal-dialog-scrollable` class
*
* @property scrollable
* @type boolean
* @default false
* @public
*/
/**
* Property for size styling, set to null (default), 'lg' or 'sm'
*
* Also see the [Bootstrap docs](http://getbootstrap.com/javascript/#modals-sizes)
*
* @property size
* @type String
* @public
*/
/**
* If true clicking on the backdrop will close the modal.
*
* @property backdropClose
* @type boolean
* @default true
* @public
*/
/**
* If true component will render in place, rather than be wormholed.
*
* @property renderInPlace
* @type boolean
* @default false
* @public
*/
/**
* The duration of the fade transition
*
* @property transitionDuration
* @type number
* @default 300
* @public
*/
/**
* The duration of the backdrop fade transition
*
* @property backdropTransitionDuration
* @type number
* @default 150
* @public
*/
/**
* The action to be sent when the modal footer's submit button (if present) is pressed.
* Note that if your modal body contains a form (e.g. [Components.Form](Components.Form.html)) this action will
* not be triggered. Instead a submit event will be triggered on the form itself. See the class description for an
* example.
*
* @property onSubmit
* @type function
* @public
*/
/**
* The action to be sent when the modal is closing.
* This will be triggered by pressing the modal header's close button (x button) or the modal footer's close button.
* Note that this will happen before the modal is hidden from the DOM, as the fade transitions will still need some
* time to finish. Use the `onHidden` if you need the modal to be hidden when the action triggers.
*
* You can return `false` to prevent closing the modal automatically, and do that in your action by
* setting `@open` to `false`.
*
* @property onHide
* @type function
* @public
*/
/**
* The action to be sent after the modal has been completely hidden (including the CSS transition).
*
* @property onHidden
* @type function
* @default null
* @public
*/
/**
* The action to be sent when the modal is opening.
* This will be triggered immediately after the modal is shown (so it's safe to access the DOM for
* size calculations and the like). This means that if `@fade={{true}}`, it will be shown in between the
* backdrop animation and the fade animation.
*
* @property onShow
* @type function
* @default null
* @public
*/
/**
* The action to be sent after the modal has been completely shown (including the CSS transition).
*
* @property onShown
* @type function
* @public
*/
/**
* Display a close button (x icon) in the corner of the modal header.
*
* @property closeButton
* @type boolean
* @default true
* @public
*/
/**
* The title of the default close button.
*
* @property closeTitle
* @type string
* @default 'Ok'
* @public
*/
/**
* The type of the submit button (primary button).
*
* @property submitButtonType
* @type string
* @default 'primary'
* @public
*/
/**
* The title of the submit button (primary button). Will be ignored (i.e. no button) if set to null.
*
* @property submitTitle
* @type string
* @default null
* @public
*/
import templateOnly from '@ember/component/template-only';
export default templateOnly();
| 28.62766 | 122 | 0.702093 |
f6c898478adffd6bbd62a35c7ce7753a2b04379c | 331 | js | JavaScript | src/index.js | cu-project-2021/boil-water | b6aae67f3d8869996eb620e793a8aef82a66dd4b | [
"Apache-2.0"
] | null | null | null | src/index.js | cu-project-2021/boil-water | b6aae67f3d8869996eb620e793a8aef82a66dd4b | [
"Apache-2.0"
] | null | null | null | src/index.js | cu-project-2021/boil-water | b6aae67f3d8869996eb620e793a8aef82a66dd4b | [
"Apache-2.0"
] | null | null | null | const { Client } = require('discord.js');
class DiscordBot extends Client {
constructor() {
super();
}
async init() {
await this.login()
.then(() => console.log("LOGGED IN"))
.catch((error) => console.log(error))
}
login(token = process.env.TOKEN) {
return super.login(token);
}
}
module.exports = DiscordBot | 16.55 | 41 | 0.634441 |
f6c98a327bec28affd4c0acafbcfd18dec5d7640 | 5,332 | js | JavaScript | src/account/login.js | ytt123/gitchat_dianshan | ccb130d761d9df37267c3e479ac07020a495c722 | [
"MIT"
] | null | null | null | src/account/login.js | ytt123/gitchat_dianshan | ccb130d761d9df37267c3e479ac07020a495c722 | [
"MIT"
] | null | null | null | src/account/login.js | ytt123/gitchat_dianshan | ccb130d761d9df37267c3e479ac07020a495c722 | [
"MIT"
] | null | null | null | 'use strict';
import React from 'react';
import {
StyleSheet,
View,
Text,
TouchableOpacity,
TouchableWithoutFeedback,
Image,
TextInput
} from 'react-native';
import px from '../utils/px'
import TopHeader from '../component/header'
import toast from '../utils/toast'
import { NavigationActions } from 'react-navigation';
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
valid: false,
isRegShow: 0,
tel: '',
sent: false
};
this.isPass = true;
}
render() {
return <View style={styles.container}>
{/*顶部组件*/}
<TopHeader title='登录' navigation={this.props.navigation} />
{/*Logo*/}
<Image
source={{ uri: require('../images/logo_new') }}
style={{ width: px(220), height: px(130), marginTop: px(170), marginLeft: px(50), marginBottom: px(80) }} />
{/*手机号输入框*/}
<View style={[styles.input, { marginBottom: px(12) }]}>
<TextInput style={styles.inputTxt}
placeholder='请输入手机号' placeholderTextColor="#b2b3b5"
maxlength={11} keyboardType="numeric"
clearButtonMode='while-editing'
onChangeText={(v) => this.setState({ tel: v })}
underlineColorAndroid="transparent" />
</View>
{/*短信验证码*/}
<View style={[styles.input, { marginBottom: px(62) }]}>
<TextInput style={styles.inputTxt}
placeholder='请输入验证码' placeholderTextColor="#b2b3b5"
maxLength={10} keyboardType="numeric"
onChangeText={(v) => this.setState({ code: v })}
underlineColorAndroid="transparent" />
<Text allowFontScaling={false} style={this.state.sent ? styles.sent : styles.send}
onPress={() => this.sendCode()}>
{this.state.sent ?
`重新获取${this.state.timeout}S` :
`获取验证码`
}
</Text>
</View>
{/*登录按钮*/}
<TouchableOpacity activeOpacity={0.8} onPress={() => this.submit()}>
<View style={[styles.btn, { backgroundColor: '#d0648f' }]}>
<Text allowFontScaling={false} style={{ fontSize: px(30), color: '#fff' }}>
登录</Text>
</View>
</TouchableOpacity>
{/*微信登录*/}
<View style={{ position: 'absolute', bottom: px(80) }}>
<TouchableOpacity style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}
activeOpacity={0.8}
onPress={() => this.loginWeChat()}>
<Image source={{ uri: require('../images/icon-wechat') }} style={{ width: px(38), height: px(38), marginRight: px(13) }} />
<Text allowFontScaling={false} style={{ color: '#679d5e', fontSize: px(28) }}>微信登录</Text>
</TouchableOpacity>
</View>
</View>
}
//发送验证码
sendCode() {
if (this.state.sent) {
return;
}
if (!this.state.tel || this.state.tel.length != 11) {
toast('请输入正确的手机号');
return;
}
this.startTimer();
}
//倒计时
startTimer() {
this.setState({
'sent': Date.now(),
'timeout': 60
});
this.timer = setInterval(() => {
let elapsed = Math.ceil((Date.now() - this.state.sent) / 1000);
if (elapsed > 60) {
this.setState({
'sent': null,
'timeout': null
});
clearInterval(this.timer);
delete this.timer;
} else {
this.setState({
'timeout': 60 - elapsed
});
}
}, 100);
}
//调起微信登录
loginWeChat() {
}
//短信登录
submit() {
toast('登录成功');
this.goTabPage();
}
goTabPage() {
this.props.navigation.dispatch(NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Tabs' })
]
}))
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center'
},
'input': {
width: px(580),
height: px(80),
borderBottomWidth: px(1),
borderBottomColor: '#e5e5e5',
paddingLeft: px(12),
paddingRight: px(12),
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center'
},
'inputTxt': {
fontSize: px(26),
color: '#252426',
flex: 1
},
'send': {
color: '#d0648f',
fontSize: px(26),
marginLeft: px(30)
},
'sent': {
color: '#b2b5b5',
fontSize: px(26),
marginLeft: px(30)
},
'btn': {
width: px(580),
height: px(80),
alignItems: 'center',
justifyContent: 'center',
borderRadius: px(40)
},
}) | 31.550296 | 143 | 0.47018 |
f6ca0c4d991f1f82bbaaf329e9b13c6c0af6870c | 561 | js | JavaScript | frontend/src/router/main.js | nazarov-mi/transsignal | 131208688de6944128d8f51c685cf7978c7924e2 | [
"Apache-2.0"
] | null | null | null | frontend/src/router/main.js | nazarov-mi/transsignal | 131208688de6944128d8f51c685cf7978c7924e2 | [
"Apache-2.0"
] | null | null | null | frontend/src/router/main.js | nazarov-mi/transsignal | 131208688de6944128d8f51c685cf7978c7924e2 | [
"Apache-2.0"
] | null | null | null |
import Main from '@/components/main/Main'
import Products from '@/components/main/Products'
import Categories from '@/components/main/Categories'
export default {
path: '/',
component: Main,
children: [
{
path: '',
name: 'home',
redirect: {
name: 'categories'
}
},
{
path: 'categories',
name: 'categories',
component: Categories
},
{
path: 'products',
name: 'products',
component: Products
},
/*{
path: 'login',
name: 'login',
component: Login,
meta: {
requiresAuth: false
}
}*/
]
}
| 14.025 | 53 | 0.586453 |
f6cacc4365e607e6369c261f2353f44d80ab6e2c | 2,756 | js | JavaScript | static/scripts/packed/mvc/upload/upload-ftp.js | hidelab/galaxy-central-hpc | 75539db90abe90377db95718f83cafa7cfa43301 | [
"CC-BY-3.0"
] | null | null | null | static/scripts/packed/mvc/upload/upload-ftp.js | hidelab/galaxy-central-hpc | 75539db90abe90377db95718f83cafa7cfa43301 | [
"CC-BY-3.0"
] | null | null | null | static/scripts/packed/mvc/upload/upload-ftp.js | hidelab/galaxy-central-hpc | 75539db90abe90377db95718f83cafa7cfa43301 | [
"CC-BY-3.0"
] | null | null | null | define(["utils/utils"],function(a){return Backbone.View.extend({options:{class_add:"upload-icon-button fa fa-square-o",class_remove:"upload-icon-button fa fa-check-square-o"},initialize:function(c){this.app=c;var b=this;this.setElement(this._template());a.get(galaxy_config.root+"api/ftp_files",function(d){b._fill(d)})},events:{mousedown:function(b){b.preventDefault()}},_fill:function(c){if(c.length>0){this.$el.find("#upload-ftp-content").html($(this._template_table()));var b=0;for(key in c){this.add(c[key]);b+=c[key].size}this.$el.find("#upload-ftp-number").html(c.length+" files");this.$el.find("#upload-ftp-disk").html(a.bytesToString(b,true))}else{this.$el.find("#upload-ftp-content").html($(this._template_info()))}this.$el.find("#upload-ftp-wait").hide()},add:function(e){var d=$(this._template_row(e));$(this.el).find("tbody").append(d);var c="";if(this._find(e)){c=this.options.class_remove}else{c=this.options.class_add}d.find("#upload-ftp-add").addClass(c);var b=this;d.find("#upload-ftp-add").on("click",function(){var f=b._find(e);$(this).removeClass();if(!f){b.app.uploadbox.add([{mode:"ftp",name:e.path,size:e.size,path:e.path}]);$(this).addClass(b.options.class_remove)}else{b.app.collection.remove(f);$(this).addClass(b.options.class_add)}})},_find:function(f){var c=this.app.collection.where({file_path:f.path});var b=null;for(var d in c){var e=c[d];if(e.get("status")=="init"&&e.get("file_mode")=="ftp"){b=e.get("id")}}return b},_template_row:function(b){return'<tr><td><div id="upload-ftp-add"/></td><td style="width: 200px"><p style="width: inherit; word-wrap: break-word;">'+b.path+'</p></td><td style="white-space: nowrap;">'+a.bytesToString(b.size)+'</td><td style="white-space: nowrap;">'+b.ctime+"</td></tr>"},_template_table:function(){return'<span style="whitespace: nowrap; float: left;">Available files: </span><span style="whitespace: nowrap; float: right;"><span class="upload-icon fa fa-file-text-o"/><span id="upload-ftp-number"/> <span class="upload-icon fa fa-hdd-o"/><span id="upload-ftp-disk"/></span><table class="grid" style="float: left;"><thead><tr><th></th><th>Name</th><th>Size</th><th>Created</th></tr></thead><tbody></tbody></table>'},_template_info:function(){return'<div class="upload-ftp-warning warningmessage">Your FTP directory does not contain any files.</div>'},_template:function(){return'<div class="upload-ftp"><div id="upload-ftp-wait" class="upload-ftp-wait fa fa-spinner fa-spin"/><div class="upload-ftp-help">This Galaxy server allows you to upload files via FTP. To upload some files, log in to the FTP server at <strong>'+this.app.options.ftp_upload_site+'</strong> using your Galaxy credentials (email address and password).</div><div id="upload-ftp-content"></div><div>'}})}); | 2,756 | 2,756 | 0.711538 |
f6caee45d6e3001b7a257fc2f2fead139988d73c | 8,583 | js | JavaScript | lib/fieldTypes/cloudinaryimage.js | killerbobjr/keystone | 4bd2cc5afa22c1c6beb9441e6891c71b555fe6d3 | [
"MIT"
] | null | null | null | lib/fieldTypes/cloudinaryimage.js | killerbobjr/keystone | 4bd2cc5afa22c1c6beb9441e6891c71b555fe6d3 | [
"MIT"
] | null | null | null | lib/fieldTypes/cloudinaryimage.js | killerbobjr/keystone | 4bd2cc5afa22c1c6beb9441e6891c71b555fe6d3 | [
"MIT"
] | null | null | null | /*!
* Module dependencies.
*/
var _ = require('underscore'),
keystone = require('../../'),
util = require('util'),
cloudinary = require('cloudinary'),
utils = require('keystone-utils'),
super_ = require('../field');
/**
* CloudinaryImage FieldType Constructor
* @extends Field
* @api public
*/
function cloudinaryimage(list, path, options) {
this._underscoreMethods = ['format'];
// TODO: implement filtering, usage disabled for now
options.nofilter = true;
// TODO: implement initial form, usage disabled for now
if (options.initial) {
throw new Error('Invalid Configuration\n\n' +
'CloudinaryImage fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
}
cloudinaryimage.super_.call(this, list, path, options);
// validate cloudinary config
if (!keystone.get('cloudinary config')) {
throw new Error('Invalid Configuration\n\n' +
'CloudinaryImage fields (' + list.key + '.' + this.path + ') require the "cloudinary config" option to be set.\n\n' +
'See http://keystonejs.com/docs/configuration/#cloudinary for more information.\n');
}
}
/*!
* Inherit from Field
*/
util.inherits(cloudinaryimage, super_);
/**
* Registers the field on the List's Mongoose Schema.
*
* @api public
*/
cloudinaryimage.prototype.addToSchema = function() {
var field = this,
schema = this.list.schema;
var paths = this.paths = {
// cloudinary fields
public_id: this._path.append('.public_id'),
version: this._path.append('.version'),
signature: this._path.append('.signature'),
format: this._path.append('.format'),
resource_type: this._path.append('.resource_type'),
url: this._path.append('.url'),
width: this._path.append('.width'),
height: this._path.append('.height'),
secure_url: this._path.append('.secure_url'),
// virtuals
exists: this._path.append('.exists'),
upload: this._path.append('_upload'),
action: this._path.append('_action')
};
var schemaPaths = this._path.addTo({}, {
public_id: String,
version: Number,
signature: String,
format: String,
resource_type: String,
url: String,
width: Number,
height: Number,
secure_url: String
});
schema.add(schemaPaths);
var exists = function(item) {
return (item.get(paths.public_id) ? true : false);
};
// The .exists virtual indicates whether an image is stored
schema.virtual(paths.exists).get(function() {
return schemaMethods.exists.apply(this);
});
var src = function(item, options) {
if (!exists(item)) {
return '';
}
options = ('object' == typeof options) ? options : {};
if (!('fetch_format' in options) && keystone.get('cloudinary webp') !== false) {
options.fetch_format = "auto";
}
if (!('progressive' in options) && keystone.get('cloudinary progressive') !== false) {
options.progressive = true;
}
if (!('secure' in options) && keystone.get('cloudinary secure')) {
options.secure = true;
}
return cloudinary.url(item.get(paths.public_id) + '.' + item.get(paths.format), options);
};
var reset = function(item) {
item.set(field.path, {
public_id: '',
version: 0,
signature: '',
format: '',
resource_type: '',
url: '',
width: 0,
height: 0,
secure_url: ''
});
};
var addSize = function(options, width, height, other) {
if (width) options.width = width;
if (height) options.height = height;
if ('object' == typeof other) {
_.extend(options, other);
}
return options;
};
var schemaMethods = {
exists: function() {
return exists(this);
},
src: function(options) {
return src(this, options);
},
tag: function(options) {
return exists(this) ? cloudinary.image(this.get(field.path), options) : '';
},
scale: function(width, height, options) {
return src(this, addSize({ crop: 'scale' }, width, height, options));
},
fill: function(width, height, options) {
return src(this, addSize({ crop: 'fill', gravity: 'faces' }, width, height, options));
},
lfill: function(width, height, options) {
return src(this, addSize({ crop: 'lfill', gravity: 'faces' }, width, height, options));
},
fit: function(width, height, options) {
return src(this, addSize({ crop: 'fit' }, width, height, options));
},
limit: function(width, height, options) {
return src(this, addSize({ crop: 'limit' }, width, height, options));
},
pad: function(width, height, options) {
return src(this, addSize({ crop: 'pad' }, width, height, options));
},
lpad: function(width, height, options) {
return src(this, addSize({ crop: 'lpad' }, width, height, options));
},
crop: function(width, height, options) {
return src(this, addSize({ crop: 'crop', gravity: 'faces' }, width, height, options));
},
thumbnail: function(width, height, options) {
return src(this, addSize({ crop: 'thumb', gravity: 'faces' }, width, height, options));
},
/**
* Resets the value of the field
*
* @api public
*/
reset: function() {
reset(this);
},
/**
* Deletes the image from Cloudinary and resets the field
*
* @api public
*/
delete: function() {
cloudinary.uploader.destroy(this.get(paths.public_id), function() {});
reset(this);
}
};
_.each(schemaMethods, function(fn, key) {
field.underscoreMethod(key, fn);
});
// expose a method on the field to call schema methods
this.apply = function(item, method) {
return schemaMethods[method].apply(item, Array.prototype.slice.call(arguments, 2));
};
this.bindUnderscoreMethods();
};
/**
* Formats the field value
*
* @api public
*/
cloudinaryimage.prototype.format = function(item) {
return item.get(this.paths.url);
};
/**
* Detects whether the field has been modified
*
* @api public
*/
cloudinaryimage.prototype.isModified = function(item) {
return item.isModified(this.paths.url);
};
/**
* Validates that a value for this field has been provided in a data object
*
* @api public
*/
cloudinaryimage.prototype.validateInput = function(data) {
// TODO - how should image field input be validated?
return true;
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
cloudinaryimage.prototype.updateItem = function(item, data) {
var paths = this.paths;
var setValue = function(key) {
if ( paths[key] ) {
var index = paths[key].indexOf(".");
var field = paths[key].substr(0, index);
if ( data[field] && data[field][key] )
if ( data[field][key] != item.get(paths[key]))
item.set(paths[key], data[field][key] || null);
}
};
_.each(['public_id', 'version', 'signature', 'format', 'resource_type', 'url', 'width', 'height', 'secure_url'], setValue);
};
/**
* Returns a callback that handles a standard form submission for the field
*
* Expected form parts are
* - `field.paths.action` in `req.body` (`clear` or `delete`)
* - `field.paths.upload` in `req.files` (uploads the image to cloudinary)
*
* @api public
*/
cloudinaryimage.prototype.getRequestHandler = function(item, req, paths, callback) {
var field = this;
if (utils.isFunction(paths)) {
callback = paths;
paths = field.paths;
} else if (!paths) {
paths = field.paths;
}
callback = callback || function() {};
return function() {
if (req.body) {
var action = req.body[paths.action];
if (/^(delete|reset)$/.test(action))
field.apply(item, action);
}
if (req.files && req.files[paths.upload] && req.files[paths.upload].size) {
var tp = keystone.get('cloudinary prefix') || '';
if (tp.length)
tp += '_';
var uploadOptions = {
tags: [tp + field.list.path + '_' + field.path, tp + field.list.path + '_' + field.path + '_' + item.id]
};
if (keystone.get('cloudinary prefix'))
uploadOptions.tags.push(keystone.get('cloudinary prefix'));
if (keystone.get('env') != 'production')
uploadOptions.tags.push(tp + 'dev');
cloudinary.uploader.upload(req.files[paths.upload].path, function(result) {
if (result.error) {
callback(result.error);
} else {
item.set(field.path, result);
callback();
}
}, uploadOptions);
} else {
callback();
}
};
};
/**
* Immediately handles a standard form submission for the field (see `getRequestHandler()`)
*
* @api public
*/
cloudinaryimage.prototype.handleRequest = function(item, req, paths, callback) {
this.getRequestHandler(item, req, paths, callback)();
};
/*!
* Export class
*/
exports = module.exports = cloudinaryimage;
| 24.109551 | 127 | 0.639986 |
f6caf852c97a82866db353dac3a22e90708814b6 | 2,138 | js | JavaScript | app/controllers/online_report_config.server.controller.js | hardylake8020/youka-server | ac535bbc3ee1a153c575dbc9013e6aabda1710fa | [
"MIT"
] | null | null | null | app/controllers/online_report_config.server.controller.js | hardylake8020/youka-server | ac535bbc3ee1a153c575dbc9013e6aabda1710fa | [
"MIT"
] | null | null | null | app/controllers/online_report_config.server.controller.js | hardylake8020/youka-server | ac535bbc3ee1a153c575dbc9013e6aabda1710fa | [
"MIT"
] | null | null | null | /**
* Created by wd on 16/05/24.
*/
'use strict';
var path = require('path'),
async = require('async'),
_ = require('lodash'),
fs = require('fs'),
ejs = require('ejs'),
config = require('../../config/config'),
onlineReportConfigError = require('../errors/online_report_config'),
reportConfigService = require('../services/online_report_config');
exports.getReportConfig = function (req, res, next) {
var companyId = req.user ? req.user.company ? req.user.company._id : '' : '';
if(!companyId) {
return res.send({err: onlineReportConfigError.params_null});
}
reportConfigService.getReportConfig(companyId, function(err, config) {
if (err) {
return res.send(err);
}
return res.send(config);
});
};
exports.getOrderExportReportConfig = function (req, res, next) {
var companyId = req.user ? req.user.company ? req.user.company._id : '' : '';
if(!companyId) {
return res.send({err: onlineReportConfigError.params_null});
}
reportConfigService.getOrderExportReportConfig(companyId, function(err, config) {
if (err) {
return res.send(err);
}
return res.send(config);
});
};
exports.saveOrUpdate = function (req, res, next) {
var config = req.body.config;
if (!config) {
return res.send({err: onlineReportConfigError.params_null});
}
config.company_id = req.user ? req.user.company ? req.user.company._id : '' : '';
config.company_name = req.user ? req.user.company ? req.user.company.name : '' : '';
reportConfigService.saveOrUpdate(config, function (err, config) {
if (err) {
return res.send(err);
}
return res.send(config);
});
};
exports.updateExportFields = function (req, res, next) {
var config = req.body.config;
if (!config) {
return res.send({err: onlineReportConfigError.params_null});
}
config.company_id = req.user ? req.user.company ? req.user.company._id : '' : '';
reportConfigService.updateExportFields(config, function (err, config) {
if (err) {
return res.send(err);
}
return res.send(config);
});
}; | 29.287671 | 86 | 0.635641 |
f6cb132e46912d0f88053c36f819dfe6da5b22ec | 561 | js | JavaScript | test/js/flexDirection.js | wangguojingasd/flex | 5d9aff0e1b47cdf3306ea187d15fa52919f7d6db | [
"MIT"
] | null | null | null | test/js/flexDirection.js | wangguojingasd/flex | 5d9aff0e1b47cdf3306ea187d15fa52919f7d6db | [
"MIT"
] | null | null | null | test/js/flexDirection.js | wangguojingasd/flex | 5d9aff0e1b47cdf3306ea187d15fa52919f7d6db | [
"MIT"
] | null | null | null | $(function(){
// div背景色
var item = $(".flex-item");
for(var i = 0;i < item.length;i++){
var color = item[i].getAttribute("data-color");
item[i].style.background = "#" + color;
}
// 单选框单击事件
$(":radio").click(function(){
var value = $(this).val();
if(!($(this).attr("checked"))){
$(":radio").removeAttr("checked");
$(this).attr("checked","checked");
}
$(".flexCon").attr("data-direction",value);
$(".flexCon")[0].style.flexDirection = value;
})
}) | 25.5 | 55 | 0.479501 |
f6cc085afadd68583b1136d33e7e5d8b67be5aea | 49,135 | js | JavaScript | bower_components/tablesorter/docs/js/sugar.min.js | headrun/TLG | 21f939b6a0dd28c073ae0f01f754324f077629f1 | [
"MIT"
] | 735 | 2015-01-13T07:12:15.000Z | 2022-03-25T01:04:45.000Z | bower_components/tablesorter/docs/js/sugar.min.js | headrun/TLG | 21f939b6a0dd28c073ae0f01f754324f077629f1 | [
"MIT"
] | 97 | 2015-01-08T01:58:55.000Z | 2021-07-09T17:26:52.000Z | bower_components/tablesorter/docs/js/sugar.min.js | headrun/TLG | 21f939b6a0dd28c073ae0f01f754324f077629f1 | [
"MIT"
] | 412 | 2015-01-01T01:39:11.000Z | 2021-11-08T21:34:26.000Z | /*
* Sugar Library v1.4.1
*
* Freely distributable and licensed under the MIT-style license.
* Copyright (c) 2013 Andrew Plummer
* http://sugarjs.com/
*
* ---------------------------- */
(function(){function aa(a){return function(){return a}}
var m=Object,p=Array,q=RegExp,r=Date,s=String,t=Number,u=Math,ba="undefined"!==typeof global?global:this,v=m.prototype.toString,da=m.prototype.hasOwnProperty,ea=m.defineProperty&&m.defineProperties,fa="function"===typeof q(),ga=!("0"in new s("a")),ia={},ja=/^\[object Date|Array|String|Number|RegExp|Boolean|Arguments\]$/,w="Boolean Number String Array Date RegExp Function".split(" "),la=ka("boolean",w[0]),y=ka("number",w[1]),z=ka("string",w[2]),A=ma(w[3]),C=ma(w[4]),D=ma(w[5]),F=ma(w[6]);
function ma(a){var b="Array"===a&&p.isArray||function(b,d){return(d||v.call(b))==="[object "+a+"]"};return ia[a]=b}function ka(a,b){function c(c){return G(c)?v.call(c)==="[object "+b+"]":typeof c===a}return ia[b]=c}
function na(a){a.SugarMethods||(oa(a,"SugarMethods",{}),H(a,!1,!0,{extend:function(b,c,d){H(a,!1!==d,c,b)},sugarRestore:function(){return pa(this,a,arguments,function(a,c,d){oa(a,c,d.method)})},sugarRevert:function(){return pa(this,a,arguments,function(a,c,d){d.existed?oa(a,c,d.original):delete a[c]})}}))}function H(a,b,c,d){var e=b?a.prototype:a;na(a);I(d,function(d,f){var h=e[d],l=J(e,d);F(c)&&h&&(f=qa(h,f,c));!1===c&&h||oa(e,d,f);a.SugarMethods[d]={method:f,existed:l,original:h,instance:b}})}
function K(a,b,c,d,e){var g={};d=z(d)?d.split(","):d;d.forEach(function(a,b){e(g,a,b)});H(a,b,c,g)}function pa(a,b,c,d){var e=0===c.length,g=L(c),f=!1;I(b.SugarMethods,function(b,c){if(e||-1!==g.indexOf(b))f=!0,d(c.instance?a.prototype:a,b,c)});return f}function qa(a,b,c){return function(d){return c.apply(this,arguments)?b.apply(this,arguments):a.apply(this,arguments)}}function oa(a,b,c){ea?m.defineProperty(a,b,{value:c,configurable:!0,enumerable:!1,writable:!0}):a[b]=c}
function L(a,b,c){var d=[];c=c||0;var e;for(e=a.length;c<e;c++)d.push(a[c]),b&&b.call(a,a[c],c);return d}function sa(a,b,c){var d=a[c||0];A(d)&&(a=d,c=0);L(a,b,c)}function ta(a){if(!a||!a.call)throw new TypeError("Callback is not callable");}function M(a){return void 0!==a}function N(a){return void 0===a}function J(a,b){return!!a&&da.call(a,b)}function G(a){return!!a&&("object"===typeof a||fa&&D(a))}function ua(a){var b=typeof a;return null==a||"string"===b||"number"===b||"boolean"===b}
function va(a,b){b=b||v.call(a);try{if(a&&a.constructor&&!J(a,"constructor")&&!J(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}return!!a&&"[object Object]"===b&&"hasOwnProperty"in a}function I(a,b){for(var c in a)if(J(a,c)&&!1===b.call(a,c,a[c],a))break}function wa(a,b){for(var c=0;c<a;c++)b(c)}function xa(a,b){I(b,function(c){a[c]=b[c]});return a}function ya(a){ua(a)&&(a=m(a));if(ga&&z(a))for(var b=a,c=0,d;d=b.charAt(c);)b[c++]=d;return a}function O(a){xa(this,ya(a))}
O.prototype.constructor=m;var P=u.abs,za=u.pow,Aa=u.ceil,Q=u.floor,R=u.round,Ca=u.min,S=u.max;function Da(a,b,c){var d=za(10,P(b||0));c=c||R;0>b&&(d=1/d);return c(a*d)/d}var Ea=48,Fa=57,Ga=65296,Ha=65305,Ia=".",Ja="",Ka={},La;function Ma(){return"\t\n\x0B\f\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u2028\u2029\u3000\ufeff"}function Na(a,b){var c="";for(a=a.toString();0<b;)if(b&1&&(c+=a),b>>=1)a+=a;return c}
function Oa(a,b){var c,d;c=a.replace(La,function(a){a=Ka[a];a===Ia&&(d=!0);return a});return d?parseFloat(c):parseInt(c,b||10)}function T(a,b,c,d){d=P(a).toString(d||10);d=Na("0",b-d.replace(/\.\d+/,"").length)+d;if(c||0>a)d=(0>a?"-":"+")+d;return d}function Pa(a){if(11<=a&&13>=a)return"th";switch(a%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}}
function Qa(a,b){function c(a,c){if(a||-1<b.indexOf(c))d+=c}var d="";b=b||"";c(a.multiline,"m");c(a.ignoreCase,"i");c(a.global,"g");c(a.u,"y");return d}function Ra(a){z(a)||(a=s(a));return a.replace(/([\\/\'*+?|()\[\]{}.^$])/g,"\\$1")}function U(a,b){return a["get"+(a._utc?"UTC":"")+b]()}function Sa(a,b,c){return a["set"+(a._utc&&"ISOWeek"!=b?"UTC":"")+b](c)}
function Ta(a,b){var c=typeof a,d,e,g,f,h,l,n;if("string"===c)return a;g=v.call(a);d=va(a,g);e=A(a,g);if(null!=a&&d||e){b||(b=[]);if(1<b.length)for(l=b.length;l--;)if(b[l]===a)return"CYC";b.push(a);d=a.valueOf()+s(a.constructor);f=e?a:m.keys(a).sort();l=0;for(n=f.length;l<n;l++)h=e?l:f[l],d+=h+Ta(a[h],b);b.pop()}else d=-Infinity===1/a?"-0":s(a&&a.valueOf?a.valueOf():a);return c+g+d}function Ua(a,b){return a===b?0!==a||1/a===1/b:Va(a)&&Va(b)?Ta(a)===Ta(b):!1}
function Va(a){var b=v.call(a);return ja.test(b)||va(a,b)}function Wa(a,b,c){var d,e=a.length,g=b.length,f=!1!==b[g-1];if(!(g>(f?1:2)))return Xa(a,e,b[0],f,c);d=[];L(b,function(b){if(la(b))return!1;d.push(Xa(a,e,b,f,c))});return d}function Xa(a,b,c,d,e){d&&(c%=b,0>c&&(c=b+c));return e?a.charAt(c):a[c]}function Ya(a,b){K(b,!0,!1,a,function(a,b){a[b+("equal"===b?"s":"")]=function(){return m[b].apply(null,[this].concat(L(arguments)))}})}na(m);I(w,function(a,b){na(ba[b])});var Za,$a;
for($a=0;9>=$a;$a++)Za=s.fromCharCode($a+Ga),Ja+=Za,Ka[Za]=s.fromCharCode($a+Ea);Ka[","]="";Ka["\uff0e"]=Ia;Ka[Ia]=Ia;La=q("["+Ja+"\uff0e,"+Ia+"]","g");
"use strict";H(m,!1,!1,{keys:function(a){var b=[];if(!G(a)&&!D(a)&&!F(a))throw new TypeError("Object required");I(a,function(a){b.push(a)});return b}});
function ab(a,b,c,d){var e=a.length,g=-1==d,f=g?e-1:0;c=isNaN(c)?f:parseInt(c>>0);0>c&&(c=e+c);if(!g&&0>c||g&&c>=e)c=f;for(;g&&0<=c||!g&&c<e;){if(a[c]===b)return c;c+=d}return-1}function bb(a,b,c,d){var e=a.length,g=0,f=M(c);ta(b);if(0!=e||f)f||(c=a[d?e-1:g],g++);else throw new TypeError("Reduce called on empty array with no initial value");for(;g<e;)f=d?e-g-1:g,f in a&&(c=b(c,a[f],f,a)),g++;return c}function cb(a){if(0===a.length)throw new TypeError("First argument must be defined");}H(p,!1,!1,{isArray:function(a){return A(a)}});
H(p,!0,!1,{every:function(a,b){var c=this.length,d=0;for(cb(arguments);d<c;){if(d in this&&!a.call(b,this[d],d,this))return!1;d++}return!0},some:function(a,b){var c=this.length,d=0;for(cb(arguments);d<c;){if(d in this&&a.call(b,this[d],d,this))return!0;d++}return!1},map:function(a,b){b=arguments[1];var c=this.length,d=0,e=Array(c);for(cb(arguments);d<c;)d in this&&(e[d]=a.call(b,this[d],d,this)),d++;return e},filter:function(a){var b=arguments[1],c=this.length,d=0,e=[];for(cb(arguments);d<c;)d in
this&&a.call(b,this[d],d,this)&&e.push(this[d]),d++;return e},indexOf:function(a,b){return z(this)?this.indexOf(a,b):ab(this,a,b,1)},lastIndexOf:function(a,b){return z(this)?this.lastIndexOf(a,b):ab(this,a,b,-1)},forEach:function(a,b){var c=this.length,d=0;for(ta(a);d<c;)d in this&&a.call(b,this[d],d,this),d++},reduce:function(a,b){return bb(this,a,b)},reduceRight:function(a,b){return bb(this,a,b,!0)}});
H(Function,!0,!1,{bind:function(a){var b=this,c=L(arguments,null,1),d;if(!F(this))throw new TypeError("Function.prototype.bind called on a non-function");d=function(){return b.apply(b.prototype&&this instanceof b?this:a,c.concat(L(arguments)))};d.prototype=this.prototype;return d}});H(r,!1,!1,{now:function(){return(new r).getTime()}});
(function(){var a=Ma().match(/^\s+$/);try{s.prototype.trim.call([1])}catch(b){a=!1}H(s,!0,!a,{trim:function(){return this.toString().trimLeft().trimRight()},trimLeft:function(){return this.replace(q("^["+Ma()+"]+"),"")},trimRight:function(){return this.replace(q("["+Ma()+"]+$"),"")}})})();
(function(){var a=new r(r.UTC(1999,11,31)),a=a.toISOString&&"1999-12-31T00:00:00.000Z"===a.toISOString();K(r,!0,!a,"toISOString,toJSON",function(a,c){a[c]=function(){return T(this.getUTCFullYear(),4)+"-"+T(this.getUTCMonth()+1,2)+"-"+T(this.getUTCDate(),2)+"T"+T(this.getUTCHours(),2)+":"+T(this.getUTCMinutes(),2)+":"+T(this.getUTCSeconds(),2)+"."+T(this.getUTCMilliseconds(),3)+"Z"}})})();
"use strict";function db(a){a=q(a);return function(b){return a.test(b)}}
function eb(a){var b=a.getTime();return function(a){return!(!a||!a.getTime)&&a.getTime()===b}}function fb(a){return function(b,c,d){return b===a||a.call(this,b,c,d)}}function gb(a){return function(b,c,d){return b===a||a.call(d,c,b,d)}}function hb(a,b){var c={};return function(d,e,g){var f;if(!G(d))return!1;for(f in a)if(c[f]=c[f]||ib(a[f],b),!1===c[f].call(g,d[f],e,g))return!1;return!0}}function jb(a){return function(b){return b===a||Ua(b,a)}}
function ib(a,b){if(!ua(a)){if(D(a))return db(a);if(C(a))return eb(a);if(F(a))return b?gb(a):fb(a);if(va(a))return hb(a,b)}return jb(a)}function kb(a,b,c,d){return b?b.apply?b.apply(c,d||[]):F(a[b])?a[b].call(a):a[b]:a}function V(a,b,c,d){var e=+a.length;0>c&&(c=a.length+c);c=isNaN(c)?0:c;for(!0===d&&(e+=c);c<e;){d=c%a.length;if(!(d in a)){lb(a,b,c);break}if(!1===b.call(a,a[d],d,a))break;c++}}
function lb(a,b,c){var d=[],e;for(e in a)e in a&&(e>>>0==e&&4294967295!=e)&&e>=c&&d.push(parseInt(e));d.sort().each(function(c){return b.call(a,a[c],c,a)})}function mb(a,b,c,d,e,g){var f,h,l;0<a.length&&(l=ib(b),V(a,function(b,c){if(l.call(g,b,c,a))return f=b,h=c,!1},c,d));return e?h:f}function nb(a,b){var c=[],d={},e;V(a,function(g,f){e=b?kb(g,b,a,[g,f,a]):g;ob(d,e)||c.push(g)});return c}
function pb(a,b,c){var d=[],e={};b.each(function(a){ob(e,a)});a.each(function(a){var b=Ta(a),h=!Va(a);if(qb(e,b,a,h)!==c){var l=0;if(h)for(b=e[b];l<b.length;)b[l]===a?b.splice(l,1):l+=1;else delete e[b];d.push(a)}});return d}function rb(a,b,c){b=b||Infinity;c=c||0;var d=[];V(a,function(a){A(a)&&c<b?d=d.concat(rb(a,b,c+1)):d.push(a)});return d}function sb(a){var b=[];L(a,function(a){b=b.concat(a)});return b}function qb(a,b,c,d){var e=b in a;d&&(a[b]||(a[b]=[]),e=-1!==a[b].indexOf(c));return e}
function ob(a,b){var c=Ta(b),d=!Va(b),e=qb(a,c,b,d);d?a[c].push(b):a[c]=b;return e}function tb(a,b,c,d){var e,g,f,h=[],l="max"===c,n="min"===c,x=p.isArray(a);for(e in a)if(a.hasOwnProperty(e)){c=a[e];f=kb(c,b,a,x?[c,parseInt(e),a]:[]);if(N(f))throw new TypeError("Cannot compare with undefined");if(f===g)h.push(c);else if(N(g)||l&&f>g||n&&f<g)h=[c],g=f}x||(h=rb(h,1));return d?h:h[0]}
function ub(a,b){var c,d,e,g,f=0,h=0;c=p[xb];d=p[yb];var l=p[zb],n=p[Ab],x=p[Bb];a=Cb(a,c,d);b=Cb(b,c,d);do c=a.charAt(f),e=l[c]||c,c=b.charAt(f),g=l[c]||c,c=e?n.indexOf(e):null,d=g?n.indexOf(g):null,-1===c||-1===d?(c=a.charCodeAt(f)||null,d=b.charCodeAt(f)||null,x&&((c>=Ea&&c<=Fa||c>=Ga&&c<=Ha)&&(d>=Ea&&d<=Fa||d>=Ga&&d<=Ha))&&(c=Oa(a.slice(f)),d=Oa(b.slice(f)))):(e=e!==a.charAt(f),g=g!==b.charAt(f),e!==g&&0===h&&(h=e-g)),f+=1;while(null!=c&&null!=d&&c===d);return c===d?h:c-d}
function Cb(a,b,c){z(a)||(a=s(a));c&&(a=a.toLowerCase());b&&(a=a.replace(b,""));return a}var Ab="AlphanumericSortOrder",xb="AlphanumericSortIgnore",yb="AlphanumericSortIgnoreCase",zb="AlphanumericSortEquivalents",Bb="AlphanumericSortNatural";H(p,!1,!0,{create:function(){var a=[];L(arguments,function(b){if(!ua(b)&&"length"in b&&("[object Arguments]"===v.call(b)||b.callee)||!ua(b)&&"length"in b&&!z(b)&&!va(b))b=p.prototype.slice.call(b,0);a=a.concat(b)});return a}});
H(p,!0,!1,{find:function(a,b){ta(a);return mb(this,a,0,!1,!1,b)},findIndex:function(a,b){var c;ta(a);c=mb(this,a,0,!1,!0,b);return N(c)?-1:c}});
H(p,!0,!0,{findFrom:function(a,b,c){return mb(this,a,b,c)},findIndexFrom:function(a,b,c){b=mb(this,a,b,c,!0);return N(b)?-1:b},findAll:function(a,b,c){var d=[],e;0<this.length&&(e=ib(a),V(this,function(a,b,c){e(a,b,c)&&d.push(a)},b,c));return d},count:function(a){return N(a)?this.length:this.findAll(a).length},removeAt:function(a,b){if(N(a))return this;N(b)&&(b=a);this.splice(a,b-a+1);return this},include:function(a,b){return this.clone().add(a,b)},exclude:function(){return p.prototype.remove.apply(this.clone(),
arguments)},clone:function(){return xa([],this)},unique:function(a){return nb(this,a)},flatten:function(a){return rb(this,a)},union:function(){return nb(this.concat(sb(arguments)))},intersect:function(){return pb(this,sb(arguments),!1)},subtract:function(a){return pb(this,sb(arguments),!0)},at:function(){return Wa(this,arguments)},first:function(a){if(N(a))return this[0];0>a&&(a=0);return this.slice(0,a)},last:function(a){return N(a)?this[this.length-1]:this.slice(0>this.length-a?0:this.length-a)},
from:function(a){return this.slice(a)},to:function(a){N(a)&&(a=this.length);return this.slice(0,a)},min:function(a,b){return tb(this,a,"min",b)},max:function(a,b){return tb(this,a,"max",b)},least:function(a,b){return tb(this.groupBy.apply(this,[a]),"length","min",b)},most:function(a,b){return tb(this.groupBy.apply(this,[a]),"length","max",b)},sum:function(a){a=a?this.map(a):this;return 0<a.length?a.reduce(function(a,c){return a+c}):0},average:function(a){a=a?this.map(a):this;return 0<a.length?a.sum()/
a.length:0},inGroups:function(a,b){var c=1<arguments.length,d=this,e=[],g=Aa(this.length/a);wa(a,function(a){a*=g;var h=d.slice(a,a+g);c&&h.length<g&&wa(g-h.length,function(){h=h.add(b)});e.push(h)});return e},inGroupsOf:function(a,b){var c=[],d=this.length,e=this,g;if(0===d||0===a)return e;N(a)&&(a=1);N(b)&&(b=null);wa(Aa(d/a),function(d){for(g=e.slice(a*d,a*d+a);g.length<a;)g.push(b);c.push(g)});return c},isEmpty:function(){return 0==this.compact().length},sortBy:function(a,b){var c=this.clone();
c.sort(function(d,e){var g,f;g=kb(d,a,c,[d]);f=kb(e,a,c,[e]);return(z(g)&&z(f)?ub(g,f):g<f?-1:g>f?1:0)*(b?-1:1)});return c},randomize:function(){for(var a=this.concat(),b=a.length,c,d;b;)c=u.random()*b|0,d=a[--b],a[b]=a[c],a[c]=d;return a},zip:function(){var a=L(arguments);return this.map(function(b,c){return[b].concat(a.map(function(a){return c in a?a[c]:null}))})},sample:function(a){var b=this.randomize();return 0<arguments.length?b.slice(0,a):b[0]},each:function(a,b,c){V(this,a,b,c);return this},
add:function(a,b){if(!y(t(b))||isNaN(b))b=this.length;p.prototype.splice.apply(this,[b,0].concat(a));return this},remove:function(){var a=this;L(arguments,function(b){var c=0;for(b=ib(b);c<a.length;)b(a[c],c,a)?a.splice(c,1):c++});return a},compact:function(a){var b=[];V(this,function(c){A(c)?b.push(c.compact()):a&&c?b.push(c):a||(null==c||c.valueOf()!==c.valueOf())||b.push(c)});return b},groupBy:function(a,b){var c=this,d={},e;V(c,function(b,f){e=kb(b,a,c,[b,f,c]);d[e]||(d[e]=[]);d[e].push(b)});
b&&I(d,b);return d},none:function(){return!this.any.apply(this,arguments)}});H(p,!0,!0,{all:p.prototype.every,any:p.prototype.some,insert:p.prototype.add});function Db(a,b){K(m,!1,!0,a,function(a,d){a[d]=function(a,c,f){var h=m.keys(ya(a)),l;b||(l=ib(c,!0));f=p.prototype[d].call(h,function(d){var f=a[d];return b?kb(f,c,a,[d,f,a]):l(f,d,a)},f);A(f)&&(f=f.reduce(function(b,c){b[c]=a[c];return b},{}));return f}});Ya(a,O)}
H(m,!1,!0,{map:function(a,b){var c={},d,e;for(d in a)J(a,d)&&(e=a[d],c[d]=kb(e,b,a,[d,e,a]));return c},reduce:function(a){var b=m.keys(ya(a)).map(function(b){return a[b]});return b.reduce.apply(b,L(arguments,null,1))},each:function(a,b){ta(b);I(a,b);return a},size:function(a){return m.keys(ya(a)).length}});var Eb="any all none count find findAll isEmpty".split(" "),Fb="sum average min max least most".split(" "),Gb=["map","reduce","size"],Hb=Eb.concat(Fb).concat(Gb);
(function(){function a(){var a=arguments;return 0<a.length&&!F(a[0])}var b=p.prototype.map;K(p,!0,a,"every,all,some,filter,any,none,find,findIndex",function(a,b){var e=p.prototype[b];a[b]=function(a){var b=ib(a);return e.call(this,function(a,c){return b(a,c,this)})}});H(p,!0,a,{map:function(a){return b.call(this,function(b,e){return kb(b,a,this,[b,e,this])})}})})();
(function(){p[Ab]="A\u00c1\u00c0\u00c2\u00c3\u0104BC\u0106\u010c\u00c7D\u010e\u00d0E\u00c9\u00c8\u011a\u00ca\u00cb\u0118FG\u011eH\u0131I\u00cd\u00cc\u0130\u00ce\u00cfJKL\u0141MN\u0143\u0147\u00d1O\u00d3\u00d2\u00d4PQR\u0158S\u015a\u0160\u015eT\u0164U\u00da\u00d9\u016e\u00db\u00dcVWXY\u00ddZ\u0179\u017b\u017d\u00de\u00c6\u0152\u00d8\u00d5\u00c5\u00c4\u00d6".split("").map(function(a){return a+a.toLowerCase()}).join("");var a={};V("A\u00c1\u00c0\u00c2\u00c3\u00c4 C\u00c7 E\u00c9\u00c8\u00ca\u00cb I\u00cd\u00cc\u0130\u00ce\u00cf O\u00d3\u00d2\u00d4\u00d5\u00d6 S\u00df U\u00da\u00d9\u00db\u00dc".split(" "),
function(b){var c=b.charAt(0);V(b.slice(1).split(""),function(b){a[b]=c;a[b.toLowerCase()]=c.toLowerCase()})});p[Bb]=!0;p[yb]=!0;p[zb]=a})();Db(Eb);Db(Fb,!0);Ya(Gb,O);p.AlphanumericSort=ub;
"use strict";
var W,Ib,Jb="ampm hour minute second ampm utc offset_sign offset_hours offset_minutes ampm".split(" "),Kb="({t})?\\s*(\\d{1,2}(?:[,.]\\d+)?)(?:{h}([0-5]\\d(?:[,.]\\d+)?)?{m}(?::?([0-5]\\d(?:[,.]\\d+)?){s})?\\s*(?:({t})|(Z)|(?:([+-])(\\d{2,2})(?::?(\\d{2,2}))?)?)?|\\s*({t}))",Lb={},Mb,Nb,Ob,Pb=[],Qb={},X={yyyy:function(a){return U(a,"FullYear")},yy:function(a){return U(a,"FullYear")%100},ord:function(a){a=U(a,"Date");return a+Pa(a)},tz:function(a){return a.getUTCOffset()},isotz:function(a){return a.getUTCOffset(!0)},
Z:function(a){return a.getUTCOffset()},ZZ:function(a){return a.getUTCOffset().replace(/(\d{2})$/,":$1")}},Rb=[{name:"year",method:"FullYear",k:!0,b:function(a){return 864E5*(365+(a?a.isLeapYear()?1:0:0.25))}},{name:"month",error:0.919,method:"Month",k:!0,b:function(a,b){var c=30.4375,d;a&&(d=a.daysInMonth(),b<=d.days()&&(c=d));return 864E5*c}},{name:"week",method:"ISOWeek",b:aa(6048E5)},{name:"day",error:0.958,method:"Date",k:!0,b:aa(864E5)},{name:"hour",method:"Hours",b:aa(36E5)},{name:"minute",
method:"Minutes",b:aa(6E4)},{name:"second",method:"Seconds",b:aa(1E3)},{name:"millisecond",method:"Milliseconds",b:aa(1)}],Sb={};function Tb(a){xa(this,a);this.g=Pb.concat()}
Tb.prototype={getMonth:function(a){return y(a)?a-1:this.months.indexOf(a)%12},getWeekday:function(a){return this.weekdays.indexOf(a)%7},addFormat:function(a,b,c,d,e){var g=c||[],f=this,h;a=a.replace(/\s+/g,"[,. ]*");a=a.replace(/\{([^,]+?)\}/g,function(a,b){var d,e,h,B=b.match(/\?$/);h=b.match(/^(\d+)\??$/);var k=b.match(/(\d)(?:-(\d))?/),E=b.replace(/[^a-z]+$/,"");h?d=f.tokens[h[1]]:f[E]?d=f[E]:f[E+"s"]&&(d=f[E+"s"],k&&(e=[],d.forEach(function(a,b){var c=b%(f.units?8:d.length);c>=k[1]&&c<=(k[2]||
k[1])&&e.push(a)}),d=e),d=Ub(d));h?h="(?:"+d+")":(c||g.push(E),h="("+d+")");B&&(h+="?");return h});b?(b=Vb(f,e),e=["t","[\\s\\u3000]"].concat(f.timeMarker),h=a.match(/\\d\{\d,\d\}\)+\??$/),Wb(f,"(?:"+b+")[,\\s\\u3000]+?"+a,Jb.concat(g),d),Wb(f,a+"(?:[,\\s]*(?:"+e.join("|")+(h?"+":"*")+")"+b+")?",g.concat(Jb),d)):Wb(f,a,g,d)}};
function Xb(a,b,c){var d,e,g=b[0],f=b[1],h=b[2];b=a[c]||a.relative;if(F(b))return b.call(a,g,f,h,c);e=a.units[8*(a.plural&&1<g?1:0)+f]||a.units[f];a.capitalizeUnit&&(e=Yb(e));d=a.modifiers.filter(function(a){return"sign"==a.name&&a.value==(0<h?1:-1)})[0];return b.replace(/\{(.*?)\}/g,function(a,b){switch(b){case "num":return g;case "unit":return e;case "sign":return d.src}})}function Zb(a,b){b=b||a.code;return"en"===b||"en-US"===b?!0:a.variant}
function $b(a,b){return b.replace(q(a.num,"g"),function(b){return ac(a,b)||""})}function ac(a,b){var c;return y(b)?b:b&&-1!==(c=a.numbers.indexOf(b))?(c+1)%10:1}function Y(a,b){var c;z(a)||(a="");c=Sb[a]||Sb[a.slice(0,2)];if(!1===b&&!c)throw new TypeError("Invalid locale.");return c||Ib}
function bc(a,b){function c(a){var b=h[a];z(b)?h[a]=b.split(","):b||(h[a]=[])}function d(a,b){a=a.split("+").map(function(a){return a.replace(/(.+):(.+)$/,function(a,b,c){return c.split("|").map(function(a){return b+a}).join("|")})}).join("|");a.split("|").forEach(b)}function e(a,b,c){var e=[];h[a].forEach(function(a,f){b&&(a+="+"+a.slice(0,3));d(a,function(a,b){e[b*c+f]=a.toLowerCase()})});h[a]=e}function g(a,b,c){a="\\d{"+a+","+b+"}";c&&(a+="|(?:"+Ub(h.numbers)+")+");return a}function f(a,b){h[a]=
h[a]||b}var h,l;h=new Tb(b);c("modifiers");"months weekdays units numbers articles tokens timeMarker ampm timeSuffixes dateParse timeParse".split(" ").forEach(c);l=!h.monthSuffix;e("months",l,12);e("weekdays",l,7);e("units",!1,8);e("numbers",!1,10);f("code",a);f("date",g(1,2,h.digitDate));f("year","'\\d{2}|"+g(4,4));f("num",function(){var a=["-?\\d+"].concat(h.articles);h.numbers&&(a=a.concat(h.numbers));return Ub(a)}());(function(){var a=[];h.i={};h.modifiers.push({name:"day",src:"yesterday",value:-1});
h.modifiers.push({name:"day",src:"today",value:0});h.modifiers.push({name:"day",src:"tomorrow",value:1});h.modifiers.forEach(function(b){var c=b.name;d(b.src,function(d){var e=h[c];h.i[d]=b;a.push({name:c,src:d,value:b.value});h[c]=e?e+"|"+d:d})});h.day+="|"+Ub(h.weekdays);h.modifiers=a})();h.monthSuffix&&(h.month=g(1,2),h.months="1 2 3 4 5 6 7 8 9 10 11 12".split(" ").map(function(a){return a+h.monthSuffix}));h.full_month=g(1,2)+"|"+Ub(h.months);0<h.timeSuffixes.length&&h.addFormat(Vb(h),!1,Jb);
h.addFormat("{day}",!0);h.addFormat("{month}"+(h.monthSuffix||""));h.addFormat("{year}"+(h.yearSuffix||""));h.timeParse.forEach(function(a){h.addFormat(a,!0)});h.dateParse.forEach(function(a){h.addFormat(a)});return Sb[a]=h}function Wb(a,b,c,d){a.g.unshift({r:d,locale:a,q:q("^"+b+"$","i"),to:c})}function Yb(a){return a.slice(0,1).toUpperCase()+a.slice(1)}function Ub(a){return a.filter(function(a){return!!a}).join("|")}function cc(){var a=r.SugarNewDate;return a?a():new r}
function dc(a,b){var c;if(G(a[0]))return a;if(y(a[0])&&!y(a[1]))return[a[0]];if(z(a[0])&&b)return[ec(a[0]),a[1]];c={};Nb.forEach(function(b,e){c[b.name]=a[e]});return[c]}function ec(a){var b,c={};if(a=a.match(/^(\d+)?\s?(\w+?)s?$/i))N(b)&&(b=parseInt(a[1])||1),c[a[2].toLowerCase()]=b;return c}function fc(a,b,c){var d;N(c)&&(c=Ob.length);for(b=b||0;b<c&&(d=Ob[b],!1!==a(d.name,d,b));b++);}
function gc(a,b){var c={},d,e;b.forEach(function(b,f){d=a[f+1];N(d)||""===d||("year"===b&&(c.t=d.replace(/'/,"")),e=parseFloat(d.replace(/'/,"").replace(/,/,".")),c[b]=isNaN(e)?d.toLowerCase():e)});return c}function hc(a){a=a.trim().replace(/^just (?=now)|\.+$/i,"");return ic(a)}
function ic(a){return a.replace(Mb,function(a,c,d){var e=0,g=1,f,h;if(c)return a;d.split("").reverse().forEach(function(a){a=Lb[a];var b=9<a;b?(f&&(e+=g),g*=a/(h||1),h=a):(!1===f&&(g*=10),e+=g*a);f=b});f&&(e+=g);return e})}
function jc(a,b,c,d){function e(a){vb.push(a)}function g(){vb.forEach(function(a){a.call()})}function f(){var a=n.getWeekday();n.setWeekday(7*(k.num-1)+(a>Ba?Ba+7:Ba))}function h(){var a=B.i[k.edge];fc(function(a){if(M(k[a]))return E=a,!1},4);if("year"===E)k.e="month";else if("month"===E||"week"===E)k.e="day";n[(0>a.value?"endOf":"beginningOf")+Yb(E)]();-2===a.value&&n.reset()}function l(){var a;fc(function(b,c,d){"day"===b&&(b="date");if(M(k[b])){if(d>=wb)return n.setTime(NaN),!1;a=a||{};a[b]=k[b];
delete k[b]}});a&&e(function(){n.set(a,!0)})}var n,x,ha,vb,B,k,E,wb,Ba,ra,ca;n=cc();vb=[];n.utc(d);C(a)?n.utc(a.isUTC()).setTime(a.getTime()):y(a)?n.setTime(a):G(a)?(n.set(a,!0),k=a):z(a)&&(ha=Y(b),a=hc(a),ha&&I(ha.o?[ha.o].concat(ha.g):ha.g,function(c,d){var g=a.match(d.q);if(g){B=d.locale;k=gc(g,d.to);B.o=d;k.utc&&n.utc();if(k.timestamp)return k=k.timestamp,!1;d.r&&(!z(k.month)&&(z(k.date)||Zb(ha,b)))&&(ca=k.month,k.month=k.date,k.date=ca);k.year&&2===k.t.length&&(k.year=100*R(U(cc(),"FullYear")/
100)-100*R(k.year/100)+k.year);k.month&&(k.month=B.getMonth(k.month),k.shift&&!k.unit&&(k.unit=B.units[7]));k.weekday&&k.date?delete k.weekday:k.weekday&&(k.weekday=B.getWeekday(k.weekday),k.shift&&!k.unit&&(k.unit=B.units[5]));k.day&&(ca=B.i[k.day])?(k.day=ca.value,n.reset(),x=!0):k.day&&-1<(Ba=B.getWeekday(k.day))&&(delete k.day,k.num&&k.month?(e(f),k.day=1):k.weekday=Ba);k.date&&!y(k.date)&&(k.date=$b(B,k.date));k.ampm&&k.ampm===B.ampm[1]&&12>k.hour?k.hour+=12:k.ampm===B.ampm[0]&&12===k.hour&&
(k.hour=0);if("offset_hours"in k||"offset_minutes"in k)n.utc(),k.offset_minutes=k.offset_minutes||0,k.offset_minutes+=60*k.offset_hours,"-"===k.offset_sign&&(k.offset_minutes*=-1),k.minute-=k.offset_minutes;k.unit&&(x=!0,ra=ac(B,k.num),wb=B.units.indexOf(k.unit)%8,E=W.units[wb],l(),k.shift&&(ra*=(ca=B.i[k.shift])?ca.value:0),k.sign&&(ca=B.i[k.sign])&&(ra*=ca.value),M(k.weekday)&&(n.set({weekday:k.weekday},!0),delete k.weekday),k[E]=(k[E]||0)+ra);k.edge&&e(h);"-"===k.year_sign&&(k.year*=-1);fc(function(a,
b,c){b=k[a];var d=b%1;d&&(k[Ob[c-1].name]=R(d*("second"===a?1E3:60)),k[a]=Q(b))},1,4);return!1}}),k?x?n.advance(k):(n._utc&&n.reset(),kc(n,k,!0,!1,c)):("now"!==a&&(n=new r(a)),d&&n.addMinutes(-n.getTimezoneOffset())),g(),n.utc(!1));return{c:n,set:k}}function lc(a){var b,c=P(a),d=c,e=0;fc(function(a,f,h){b=Q(Da(c/f.b(),1));1<=b&&(d=b,e=h)},1);return[d,e,a]}
function mc(a){var b=lc(a.millisecondsFromNow());if(6===b[1]||5===b[1]&&4===b[0]&&a.daysFromNow()>=cc().daysInMonth())b[0]=P(a.monthsFromNow()),b[1]=6;return b}function nc(a,b,c){function d(a,c){var d=U(a,"Month");return Y(c).months[d+12*b]}Z(a,d,c);Z(Yb(a),d,c,1)}function Z(a,b,c,d){X[a]=function(a,g){var f=b(a,g);c&&(f=f.slice(0,c));d&&(f=f.slice(0,d).toUpperCase()+f.slice(d));return f}}
function oc(a,b,c){X[a]=b;X[a+a]=function(a,c){return T(b(a,c),2)};c&&(X[a+a+a]=function(a,c){return T(b(a,c),3)},X[a+a+a+a]=function(a,c){return T(b(a,c),4)})}function pc(a){var b=a.match(/(\{\w+\})|[^{}]+/g);Qb[a]=b.map(function(a){a.replace(/\{(\w+)\}/,function(b,e){a=X[e]||e;return e});return a})}
function qc(a,b,c,d){var e;if(!a.isValid())return"Invalid Date";Date[b]?b=Date[b]:F(b)&&(e=mc(a),b=b.apply(a,e.concat(Y(d))));if(!b&&c)return e=e||mc(a),0===e[1]&&(e[1]=1,e[0]=1),a=Y(d),Xb(a,e,0<e[2]?"future":"past");b=b||"long";if("short"===b||"long"===b||"full"===b)b=Y(d)[b];Qb[b]||pc(b);var g,f;e="";b=Qb[b];g=0;for(c=b.length;g<c;g++)f=b[g],e+=F(f)?f(a,d):f;return e}
function rc(a,b,c,d,e){var g,f,h,l=0,n=0,x=0;g=jc(b,c,null,e);0<d&&(n=x=d,f=!0);if(!g.c.isValid())return!1;if(g.set&&g.set.e){Rb.forEach(function(b){b.name===g.set.e&&(l=b.b(g.c,a-g.c)-1)});b=Yb(g.set.e);if(g.set.edge||g.set.shift)g.c["beginningOf"+b]();"month"===g.set.e&&(h=g.c.clone()["endOf"+b]().getTime());!f&&(g.set.sign&&"millisecond"!=g.set.e)&&(n=50,x=-50)}f=a.getTime();b=g.c.getTime();h=sc(a,b,h||b+l);return f>=b-n&&f<=h+x}
function sc(a,b,c){b=new r(b);a=(new r(c)).utc(a.isUTC());23!==U(a,"Hours")&&(b=b.getTimezoneOffset(),a=a.getTimezoneOffset(),b!==a&&(c+=(a-b).minutes()));return c}
function kc(a,b,c,d,e){function g(a){return M(b[a])?b[a]:b[a+"s"]}function f(a){return M(g(a))}var h;if(y(b)&&d)b={milliseconds:b};else if(y(b))return a.setTime(b),a;M(b.date)&&(b.day=b.date);fc(function(d,e,g){var l="day"===d;if(f(d)||l&&f("weekday"))return b.e=d,h=+g,!1;!c||("week"===d||l&&f("week"))||Sa(a,e.method,l?1:0)});Rb.forEach(function(c){var e=c.name;c=c.method;var h;h=g(e);N(h)||(d?("week"===e&&(h=(b.day||0)+7*h,c="Date"),h=h*d+U(a,c)):"month"===e&&f("day")&&Sa(a,"Date",15),Sa(a,c,h),
d&&"month"===e&&(e=h,0>e&&(e=e%12+12),e%12!=U(a,"Month")&&Sa(a,"Date",0)))});d||(f("day")||!f("weekday"))||a.setWeekday(g("weekday"));var l;a:{switch(e){case -1:l=a>cc();break a;case 1:l=a<cc();break a}l=void 0}l&&fc(function(b,c){if((c.k||"week"===b&&f("weekday"))&&!(f(b)||"day"===b&&f("weekday")))return a[c.j](e),!1},h+1);return a}
function Vb(a,b){var c=Kb,d={h:0,m:1,s:2},e;a=a||W;return c.replace(/{([a-z])}/g,function(c,f){var h=[],l="h"===f,n=l&&!b;if("t"===f)return a.ampm.join("|");l&&h.push(":");(e=a.timeSuffixes[d[f]])&&h.push(e+"\\s*");return 0===h.length?"":"(?:"+h.join("|")+")"+(n?"":"?")})}function tc(a,b,c){var d,e;y(a[1])?d=dc(a)[0]:(d=a[0],e=a[1]);return jc(d,e,b,c).c}
H(r,!1,!0,{create:function(){return tc(arguments)},past:function(){return tc(arguments,-1)},future:function(){return tc(arguments,1)},addLocale:function(a,b){return bc(a,b)},setLocale:function(a){var b=Y(a,!1);Ib=b;a&&a!=b.code&&(b.code=a);return b},getLocale:function(a){return a?Y(a,!1):Ib},addFormat:function(a,b,c){Wb(Y(c),a,b)}});
H(r,!0,!0,{set:function(){var a=dc(arguments);return kc(this,a[0],a[1])},setWeekday:function(a){if(!N(a))return Sa(this,"Date",U(this,"Date")+a-U(this,"Day"))},setISOWeek:function(a){var b=U(this,"Day")||7;if(!N(a))return this.set({month:0,date:4}),this.set({weekday:1}),1<a&&this.addWeeks(a-1),1!==b&&this.advance({days:b-1}),this.getTime()},getISOWeek:function(){var a;a=this.clone();var b=U(a,"Day")||7;a.addDays(4-b).reset();return 1+Q(a.daysSince(a.clone().beginningOfYear())/7)},beginningOfISOWeek:function(){var a=
this.getDay();0===a?a=-6:1!==a&&(a=1);this.setWeekday(a);return this.reset()},endOfISOWeek:function(){0!==this.getDay()&&this.setWeekday(7);return this.endOfDay()},getUTCOffset:function(a){var b=this._utc?0:this.getTimezoneOffset(),c=!0===a?":":"";return!b&&a?"Z":T(Q(-b/60),2,!0)+c+T(P(b%60),2)},utc:function(a){oa(this,"_utc",!0===a||0===arguments.length);return this},isUTC:function(){return!!this._utc||0===this.getTimezoneOffset()},advance:function(){var a=dc(arguments,!0);return kc(this,a[0],a[1],
1)},rewind:function(){var a=dc(arguments,!0);return kc(this,a[0],a[1],-1)},isValid:function(){return!isNaN(this.getTime())},isAfter:function(a,b){return this.getTime()>r.create(a).getTime()-(b||0)},isBefore:function(a,b){return this.getTime()<r.create(a).getTime()+(b||0)},isBetween:function(a,b,c){var d=this.getTime();a=r.create(a).getTime();var e=r.create(b).getTime();b=Ca(a,e);a=S(a,e);c=c||0;return b-c<d&&a+c>d},isLeapYear:function(){var a=U(this,"FullYear");return 0===a%4&&0!==a%100||0===a%400},
daysInMonth:function(){return 32-U(new r(U(this,"FullYear"),U(this,"Month"),32),"Date")},format:function(a,b){return qc(this,a,!1,b)},relative:function(a,b){z(a)&&(b=a,a=null);return qc(this,a,!0,b)},is:function(a,b,c){var d,e;if(this.isValid()){if(z(a))switch(a=a.trim().toLowerCase(),e=this.clone().utc(c),!0){case "future"===a:return this.getTime()>cc().getTime();case "past"===a:return this.getTime()<cc().getTime();case "weekday"===a:return 0<U(e,"Day")&&6>U(e,"Day");case "weekend"===a:return 0===
U(e,"Day")||6===U(e,"Day");case -1<(d=W.weekdays.indexOf(a)%7):return U(e,"Day")===d;case -1<(d=W.months.indexOf(a)%12):return U(e,"Month")===d}return rc(this,a,null,b,c)}},reset:function(a){var b={},c;a=a||"hours";"date"===a&&(a="days");c=Rb.some(function(b){return a===b.name||a===b.name+"s"});b[a]=a.match(/^days?/)?1:0;return c?this.set(b,!0):this},clone:function(){var a=new r(this.getTime());a.utc(!!this._utc);return a}});
H(r,!0,!0,{iso:function(){return this.toISOString()},getWeekday:r.prototype.getDay,getUTCWeekday:r.prototype.getUTCDay});function uc(a,b){function c(){return R(this*b)}function d(){return tc(arguments)[a.j](this)}function e(){return tc(arguments)[a.j](-this)}var g=a.name,f={};f[g]=c;f[g+"s"]=c;f[g+"Before"]=e;f[g+"sBefore"]=e;f[g+"Ago"]=e;f[g+"sAgo"]=e;f[g+"After"]=d;f[g+"sAfter"]=d;f[g+"FromNow"]=d;f[g+"sFromNow"]=d;t.extend(f)}H(t,!0,!0,{duration:function(a){a=Y(a);return Xb(a,lc(this),"duration")}});
W=Ib=r.addLocale("en",{plural:!0,timeMarker:"at",ampm:"am,pm",months:"January,February,March,April,May,June,July,August,September,October,November,December",weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",units:"millisecond:|s,second:|s,minute:|s,hour:|s,day:|s,week:|s,month:|s,year:|s",numbers:"one,two,three,four,five,six,seven,eight,nine,ten",articles:"a,an,the",tokens:"the,st|nd|rd|th,of","short":"{Month} {d}, {yyyy}","long":"{Month} {d}, {yyyy} {h}:{mm}{tt}",full:"{Weekday} {Month} {d}, {yyyy} {h}:{mm}:{ss}{tt}",
past:"{num} {unit} {sign}",future:"{num} {unit} {sign}",duration:"{num} {unit}",modifiers:[{name:"sign",src:"ago|before",value:-1},{name:"sign",src:"from now|after|from|in|later",value:1},{name:"edge",src:"last day",value:-2},{name:"edge",src:"end",value:-1},{name:"edge",src:"first day|beginning",value:1},{name:"shift",src:"last",value:-1},{name:"shift",src:"the|this",value:0},{name:"shift",src:"next",value:1}],dateParse:["{month} {year}","{shift} {unit=5-7}","{0?} {date}{1}","{0?} {edge} of {shift?} {unit=4-7?}{month?}{year?}"],
timeParse:"{num} {unit} {sign};{sign} {num} {unit};{0} {num}{1} {day} of {month} {year?};{weekday?} {month} {date}{1?} {year?};{date} {month} {year};{date} {month};{shift} {weekday};{shift} week {weekday};{weekday} {2?} {shift} week;{num} {unit=4-5} {sign} {day};{0?} {date}{1} of {month};{0?}{month?} {date?}{1?} of {shift} {unit=6-7}".split(";")});Ob=Rb.concat().reverse();Nb=Rb.concat();Nb.splice(2,1);
K(r,!0,!0,Rb,function(a,b,c){function d(a){a/=f;var c=a%1,d=b.error||0.999;c&&P(c%1)>d&&(a=R(a));return 0>a?Aa(a):Q(a)}var e=b.name,g=Yb(e),f=b.b(),h,l;b.j="add"+g+"s";h=function(a,b){return d(this.getTime()-r.create(a,b).getTime())};l=function(a,b){return d(r.create(a,b).getTime()-this.getTime())};a[e+"sAgo"]=l;a[e+"sUntil"]=l;a[e+"sSince"]=h;a[e+"sFromNow"]=h;a[b.j]=function(a,b){var c={};c[e]=a;return this.advance(c,b)};uc(b,f);3>c&&["Last","This","Next"].forEach(function(b){a["is"+b+g]=function(){return rc(this,
b+" "+e,"en")}});4>c&&(a["beginningOf"+g]=function(){var a={};switch(e){case "year":a.year=U(this,"FullYear");break;case "month":a.month=U(this,"Month");break;case "day":a.day=U(this,"Date");break;case "week":a.weekday=0}return this.set(a,!0)},a["endOf"+g]=function(){var a={hours:23,minutes:59,seconds:59,milliseconds:999};switch(e){case "year":a.month=11;a.day=31;break;case "month":a.day=this.daysInMonth();break;case "week":a.weekday=6}return this.set(a,!0)})});
W.addFormat("([+-])?(\\d{4,4})[-.]?{full_month}[-.]?(\\d{1,2})?",!0,["year_sign","year","month","date"],!1,!0);W.addFormat("(\\d{1,2})[-.\\/]{full_month}(?:[-.\\/](\\d{2,4}))?",!0,["date","month","year"],!0);W.addFormat("{full_month}[-.](\\d{4,4})",!1,["month","year"]);W.addFormat("\\/Date\\((\\d+(?:[+-]\\d{4,4})?)\\)\\/",!1,["timestamp"]);W.addFormat(Vb(W),!1,Jb);Pb=W.g.slice(0,7).reverse();W.g=W.g.slice(7).concat(Pb);oc("f",function(a){return U(a,"Milliseconds")},!0);
oc("s",function(a){return U(a,"Seconds")});oc("m",function(a){return U(a,"Minutes")});oc("h",function(a){return U(a,"Hours")%12||12});oc("H",function(a){return U(a,"Hours")});oc("d",function(a){return U(a,"Date")});oc("M",function(a){return U(a,"Month")+1});(function(){function a(a,c){var d=U(a,"Hours");return Y(c).ampm[Q(d/12)]||""}Z("t",a,1);Z("tt",a);Z("T",a,1,1);Z("TT",a,null,2)})();
(function(){function a(a,c){var d=U(a,"Day");return Y(c).weekdays[d]}Z("dow",a,3);Z("Dow",a,3,1);Z("weekday",a);Z("Weekday",a,null,1)})();nc("mon",0,3);nc("month",0);nc("month2",1);nc("month3",2);X.ms=X.f;X.milliseconds=X.f;X.seconds=X.s;X.minutes=X.m;X.hours=X.h;X["24hr"]=X.H;X["12hr"]=X.h;X.date=X.d;X.day=X.d;X.year=X.yyyy;K(r,!0,!0,"short,long,full",function(a,b){a[b]=function(a){return qc(this,b,!1,a)}});
"\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07".split("").forEach(function(a,b){9<b&&(b=za(10,b-9));Lb[a]=b});xa(Lb,Ka);Mb=q("([\u671f\u9031\u5468])?([\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07"+Ja+"]+)(?!\u6628)","g");
(function(){var a=W.weekdays.slice(0,7),b=W.months.slice(0,12);K(r,!0,!0,"today yesterday tomorrow weekday weekend future past".split(" ").concat(a).concat(b),function(a,b){a["is"+Yb(b)]=function(a){return this.is(b,0,a)}})})();r.utc||(r.utc={create:function(){return tc(arguments,0,!0)},past:function(){return tc(arguments,-1,!0)},future:function(){return tc(arguments,1,!0)}});
H(r,!1,!0,{RFC1123:"{Dow}, {dd} {Mon} {yyyy} {HH}:{mm}:{ss} {tz}",RFC1036:"{Weekday}, {dd}-{Mon}-{yy} {HH}:{mm}:{ss} {tz}",ISO8601_DATE:"{yyyy}-{MM}-{dd}",ISO8601_DATETIME:"{yyyy}-{MM}-{dd}T{HH}:{mm}:{ss}.{fff}{isotz}"});
"use strict";function Range(a,b){this.start=vc(a);this.end=vc(b)}function vc(a){return C(a)?new r(a.getTime()):null==a?a:C(a)?a.getTime():a.valueOf()}function wc(a){a=null==a?a:C(a)?a.getTime():a.valueOf();return!!a||0===a}
function xc(a,b){var c,d,e,g;if(y(b))return new r(a.getTime()+b);c=b[0];d=b[1];e=U(a,d);g=new r(a.getTime());Sa(g,d,e+c);return g}function yc(a,b){return s.fromCharCode(a.charCodeAt(0)+b)}function zc(a,b){return a+b}Range.prototype.toString=function(){return this.isValid()?this.start+".."+this.end:"Invalid Range"};
H(Range,!0,!0,{isValid:function(){return wc(this.start)&&wc(this.end)&&typeof this.start===typeof this.end},span:function(){return this.isValid()?P((z(this.end)?this.end.charCodeAt(0):this.end)-(z(this.start)?this.start.charCodeAt(0):this.start))+1:NaN},contains:function(a){return null==a?!1:a.start&&a.end?a.start>=this.start&&a.start<=this.end&&a.end>=this.start&&a.end<=this.end:a>=this.start&&a<=this.end},every:function(a,b){var c,d=this.start,e=this.end,g=e<d,f=d,h=0,l=[];F(a)&&(b=a,a=null);a=
a||1;y(d)?c=zc:z(d)?c=yc:C(d)&&(c=a,y(c)?a=c:(d=c.toLowerCase().match(/^(\d+)?\s?(\w+?)s?$/i),c=parseInt(d[1])||1,d=d[2].slice(0,1).toUpperCase()+d[2].slice(1),d.match(/hour|minute|second/i)?d+="s":"Year"===d?d="FullYear":"Day"===d&&(d="Date"),a=[c,d]),c=xc);for(g&&0<a&&(a*=-1);g?f>=e:f<=e;)l.push(f),b&&b(f,h),f=c(f,a),h++;return l},union:function(a){return new Range(this.start<a.start?this.start:a.start,this.end>a.end?this.end:a.end)},intersect:function(a){return a.start>this.end||a.end<this.start?
new Range(NaN,NaN):new Range(this.start>a.start?this.start:a.start,this.end<a.end?this.end:a.end)},clone:function(){return new Range(this.start,this.end)},clamp:function(a){var b=this.start,c=this.end,d=c<b?c:b,b=b>c?b:c;return vc(a<d?d:a>b?b:a)}});[t,s,r].forEach(function(a){H(a,!1,!0,{range:function(b,c){a.create&&(b=a.create(b),c=a.create(c));return new Range(b,c)}})});
H(t,!0,!0,{upto:function(a,b,c){return t.range(this,a).every(c,b)},clamp:function(a,b){return(new Range(a,b)).clamp(this)},cap:function(a){return this.clamp(void 0,a)}});H(t,!0,!0,{downto:t.prototype.upto});H(p,!1,function(a){return a instanceof Range},{create:function(a){return a.every()}});
"use strict";function Ac(a,b,c,d,e){Infinity!==b&&(a.timers||(a.timers=[]),y(b)||(b=1),a.n=!1,a.timers.push(setTimeout(function(){a.n||c.apply(d,e||[])},b)))}
H(Function,!0,!0,{lazy:function(a,b,c){function d(){g.length<c-(f&&b?1:0)&&g.push([this,arguments]);f||(f=!0,b?h():Ac(d,l,h));return x}var e=this,g=[],f=!1,h,l,n,x;a=a||1;c=c||Infinity;l=Aa(a);n=R(l/a)||1;h=function(){var a=g.length,b;if(0!=a){for(b=S(a-n,0);a>b;)x=Function.prototype.apply.apply(e,g.shift()),a--;Ac(d,l,function(){f=!1;h()})}};return d},throttle:function(a){return this.lazy(a,!0,1)},debounce:function(a){function b(){b.cancel();Ac(b,a,c,this,arguments)}var c=this;return b},delay:function(a){var b=
L(arguments,null,1);Ac(this,a,this,this,b);return this},every:function(a){function b(){c.apply(c,d);Ac(c,a,b)}var c=this,d=arguments,d=1<d.length?L(d,null,1):[];Ac(c,a,b);return c},cancel:function(){var a=this.timers,b;if(A(a))for(;b=a.shift();)clearTimeout(b);this.n=!0;return this},after:function(a){var b=this,c=0,d=[];if(!y(a))a=1;else if(0===a)return b.call(),b;return function(){var e;d.push(L(arguments));c++;if(c==a)return e=b.call(this,d),c=0,d=[],e}},once:function(){return this.throttle(Infinity,
!0)},fill:function(){var a=this,b=L(arguments);return function(){var c=L(arguments);b.forEach(function(a,b){(null!=a||b>=c.length)&&c.splice(b,0,a)});return a.apply(this,c)}}});
"use strict";function Bc(a,b,c,d,e,g){var f=a.toFixed(20),h=f.search(/\./),f=f.search(/[1-9]/),h=h-f;0<h&&(h-=1);e=S(Ca(Q(h/3),!1===e?c.length:e),-d);d=c.charAt(e+d-1);-9>h&&(e=-3,b=P(h)-9,d=c.slice(0,1));c=g?za(2,10*e):za(10,3*e);return Da(a/c,b||0).format()+d.trim()}
H(t,!1,!0,{random:function(a,b){var c,d;1==arguments.length&&(b=a,a=0);c=Ca(a||0,N(b)?1:b);d=S(a||0,N(b)?1:b)+1;return Q(u.random()*(d-c)+c)}});
H(t,!0,!0,{log:function(a){return u.log(this)/(a?u.log(a):1)},abbr:function(a){return Bc(this,a,"kmbt",0,4)},metric:function(a,b){return Bc(this,a,"n\u03bcm kMGTPE",4,N(b)?1:b)},bytes:function(a,b){return Bc(this,a,"kMGTPE",0,N(b)?4:b,!0)+"B"},isInteger:function(){return 0==this%1},isOdd:function(){return!isNaN(this)&&!this.isMultipleOf(2)},isEven:function(){return this.isMultipleOf(2)},isMultipleOf:function(a){return 0===this%a},format:function(a,b,c){var d,e,g,f="";N(b)&&(b=",");N(c)&&(c=".");d=
(y(a)?Da(this,a||0).toFixed(S(a,0)):this.toString()).replace(/^-/,"").split(".");e=d[0];g=d[1];for(d=e.length;0<d;d-=3)d<e.length&&(f=b+f),f=e.slice(S(0,d-3),d)+f;g&&(f+=c+Na("0",(a||0)-g.length)+g);return(0>this?"-":"")+f},hex:function(a){return this.pad(a||1,!1,16)},times:function(a){if(a)for(var b=0;b<this;b++)a.call(this,b);return this.toNumber()},chr:function(){return s.fromCharCode(this)},pad:function(a,b,c){return T(this,a,b,c)},ordinalize:function(){var a=P(this),a=parseInt(a.toString().slice(-2));
return this+Pa(a)},toNumber:function(){return parseFloat(this,10)}});(function(){function a(a){return function(c){return c?Da(this,c,a):a(this)}}H(t,!0,!0,{ceil:a(Aa),round:a(R),floor:a(Q)});K(t,!0,!0,"abs,pow,sin,asin,cos,acos,tan,atan,exp,pow,sqrt",function(a,c){a[c]=function(a,b){return u[c](this,a,b)}})})();
"use strict";var Cc=["isObject","isNaN"],Dc="keys values select reject each merge clone equal watch tap has toQueryString".split(" ");
function Ec(a,b,c,d){var e,g,f;(g=b.match(/^(.+?)(\[.*\])$/))?(f=g[1],b=g[2].replace(/^\[|\]$/g,"").split("]["),b.forEach(function(b){e=!b||b.match(/^\d+$/);!f&&A(a)&&(f=a.length);J(a,f)||(a[f]=e?[]:{});a=a[f];f=b}),!f&&e&&(f=a.length.toString()),Ec(a,f,c,d)):a[b]=d&&"true"===c?!0:d&&"false"===c?!1:c}function Fc(a,b){var c;return A(b)||G(b)&&b.toString===v?(c=[],I(b,function(b,e){a&&(b=a+"["+b+"]");c.push(Fc(b,e))}),c.join("&")):a?Gc(a)+"="+(C(b)?b.getTime():Gc(b)):""}
function Gc(a){return a||!1===a||0===a?encodeURIComponent(a).replace(/%20/g,"+"):""}function Hc(a,b,c){var d,e=a instanceof O?new O:{};I(a,function(a,f){d=!1;sa(b,function(b){(D(b)?b.test(a):G(b)?b[a]===f:a===s(b))&&(d=!0)},1);d===c&&(e[a]=f)});return e}H(m,!1,!0,{watch:function(a,b,c){if(ea){var d=a[b];m.defineProperty(a,b,{enumerable:!0,configurable:!0,get:function(){return d},set:function(e){d=c.call(a,b,d,e)}})}}});
H(m,!1,function(){return 1<arguments.length},{keys:function(a,b){var c=m.keys(a);c.forEach(function(c){b.call(a,c,a[c])});return c}});
H(m,!1,!0,{isObject:function(a){return va(a)},isNaN:function(a){return y(a)&&a.valueOf()!==a.valueOf()},equal:function(a,b){return Ua(a,b)},extended:function(a){return new O(a)},merge:function(a,b,c,d){var e,g,f,h,l,n,x;if(a&&"string"!==typeof b)for(e in b)if(J(b,e)&&a){h=b[e];l=a[e];n=M(l);g=G(h);f=G(l);x=n&&!1===d?l:h;n&&F(d)&&(x=d.call(b,e,l,h));if(c&&(g||f))if(C(h))x=new r(h.getTime());else if(D(h))x=new q(h.source,Qa(h));else{f||(a[e]=p.isArray(h)?[]:{});m.merge(a[e],h,c,d);continue}a[e]=x}return a},
values:function(a,b){var c=[];I(a,function(d,e){c.push(e);b&&b.call(a,e)});return c},clone:function(a,b){var c;if(!G(a))return a;c=v.call(a);if(C(a,c)&&a.clone)return a.clone();if(C(a,c)||D(a,c))return new a.constructor(a);if(a instanceof O)c=new O;else if(A(a,c))c=[];else if(va(a,c))c={};else throw new TypeError("Clone must be a basic data type.");return m.merge(c,a,b)},fromQueryString:function(a,b){var c=m.extended();a=a&&a.toString?a.toString():"";a.replace(/^.*?\?/,"").split("&").forEach(function(a){a=
a.split("=");2===a.length&&Ec(c,a[0],decodeURIComponent(a[1]),b)});return c},toQueryString:function(a,b){return Fc(b,a)},tap:function(a,b){var c=b;F(b)||(c=function(){if(b)a[b]()});c.call(a,a);return a},has:function(a,b){return J(a,b)},select:function(a){return Hc(a,arguments,!0)},reject:function(a){return Hc(a,arguments,!1)}});K(m,!1,!0,w,function(a,b){var c="is"+b;Cc.push(c);a[c]=ia[b]});
H(m,!1,function(){return 0===arguments.length},{extend:function(){var a=Cc.concat(Dc);"undefined"!==typeof Hb&&(a=a.concat(Hb));Ya(a,m)}});Ya(Dc,O);
"use strict";H(q,!1,!0,{escape:function(a){return Ra(a)}});H(q,!0,!0,{getFlags:function(){return Qa(this)},setFlags:function(a){return q(this.source,a)},addFlag:function(a){return this.setFlags(Qa(this,a))},removeFlag:function(a){return this.setFlags(Qa(this).replace(a,""))}});
"use strict";
function Ic(a){a=+a;if(0>a||Infinity===a)throw new RangeError("Invalid number");return a}function Jc(a,b){return Na(M(b)?b:" ",a)}function Kc(a,b,c,d,e){var g;if(a.length<=b)return a.toString();d=N(d)?"...":d;switch(c){case "left":return a=e?Lc(a,b,!0):a.slice(a.length-b),d+a;case "middle":return c=Aa(b/2),g=Q(b/2),b=e?Lc(a,c):a.slice(0,c),a=e?Lc(a,g,!0):a.slice(a.length-g),b+d+a;default:return b=e?Lc(a,b):a.slice(0,b),b+d}}
function Lc(a,b,c){if(c)return Lc(a.reverse(),b).reverse();c=q("(?=["+Ma()+"])");var d=0;return a.split(c).filter(function(a){d+=a.length;return d<=b}).join("")}function Mc(a,b,c){z(b)&&(b=a.indexOf(b),-1===b&&(b=c?a.length:0));return b}var Nc,Oc;H(s,!0,!1,{repeat:function(a){a=Ic(a);return Na(this,a)}});
H(s,!0,function(a){return D(a)||2<arguments.length},{startsWith:function(a){var b=arguments,c=b[1],b=b[2],d=this;c&&(d=d.slice(c));N(b)&&(b=!0);c=D(a)?a.source.replace("^",""):Ra(a);return q("^"+c,b?"":"i").test(d)},endsWith:function(a){var b=arguments,c=b[1],b=b[2],d=this;M(c)&&(d=d.slice(0,c));N(b)&&(b=!0);c=D(a)?a.source.replace("$",""):Ra(a);return q(c+"$",b?"":"i").test(d)}});
H(s,!0,!0,{escapeRegExp:function(){return Ra(this)},escapeURL:function(a){return a?encodeURIComponent(this):encodeURI(this)},unescapeURL:function(a){return a?decodeURI(this):decodeURIComponent(this)},escapeHTML:function(){return this.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")},unescapeHTML:function(){return this.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(///g,
"/").replace(/&/g,"&")},encodeBase64:function(){return Nc(unescape(encodeURIComponent(this)))},decodeBase64:function(){return decodeURIComponent(escape(Oc(this)))},each:function(a,b){var c,d,e;F(a)?(b=a,a=/[\s\S]/g):a?z(a)?a=q(Ra(a),"gi"):D(a)&&(a=q(a.source,Qa(a,"g"))):a=/[\s\S]/g;c=this.match(a)||[];if(b)for(d=0,e=c.length;d<e;d++)c[d]=b.call(this,c[d],d,c)||c[d];return c},shift:function(a){var b="";a=a||0;this.codes(function(c){b+=s.fromCharCode(c+a)});return b},codes:function(a){var b=[],
c,d;c=0;for(d=this.length;c<d;c++){var e=this.charCodeAt(c);b.push(e);a&&a.call(this,e,c)}return b},chars:function(a){return this.each(a)},words:function(a){return this.trim().each(/\S+/g,a)},lines:function(a){return this.trim().each(/^.*$/gm,a)},paragraphs:function(a){var b=this.trim().split(/[\r\n]{2,}/);return b=b.map(function(b){if(a)var d=a.call(b);return d?d:b})},isBlank:function(){return 0===this.trim().length},has:function(a){return-1!==this.search(D(a)?a:Ra(a))},add:function(a,b){b=N(b)?
this.length:b;return this.slice(0,b)+a+this.slice(b)},remove:function(a){return this.replace(a,"")},reverse:function(){return this.split("").reverse().join("")},compact:function(){return this.trim().replace(/([\r\n\s\u3000])+/g,function(a,b){return"\u3000"===b?b:" "})},at:function(){return Wa(this,arguments,!0)},from:function(a){return this.slice(Mc(this,a,!0))},to:function(a){N(a)&&(a=this.length);return this.slice(0,Mc(this,a))},dasherize:function(){return this.underscore().replace(/_/g,"-")},underscore:function(){return this.replace(/[-\s]+/g,
"_").replace(s.Inflector&&s.Inflector.acronymRegExp,function(a,b){return(0<b?"_":"")+a.toLowerCase()}).replace(/([A-Z\d]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()},camelize:function(a){return this.underscore().replace(/(^|_)([^_]+)/g,function(b,c,d,e){b=(b=s.Inflector)&&b.acronyms[d];b=z(b)?b:void 0;e=!1!==a||0<e;return b?e?b:b.toLowerCase():e?d.capitalize():d})},spacify:function(){return this.underscore().replace(/_/g," ")},stripTags:function(){var a=this;sa(0<arguments.length?
arguments:[""],function(b){a=a.replace(q("</?"+Ra(b)+"[^<>]*>","gi"),"")});return a},removeTags:function(){var a=this;sa(0<arguments.length?arguments:["\\S+"],function(b){b=q("<("+b+")[^<>]*(?:\\/>|>.*?<\\/\\1>)","gi");a=a.replace(b,"")});return a},truncate:function(a,b,c){return Kc(this,a,b,c)},truncateOnWord:function(a,b,c){return Kc(this,a,b,c,!0)},pad:function(a,b){var c,d;a=Ic(a);c=S(0,a-this.length)/2;d=Q(c);c=Aa(c);return Jc(d,b)+this+Jc(c,b)},padLeft:function(a,b){a=Ic(a);return Jc(S(0,a-
this.length),b)+this},padRight:function(a,b){a=Ic(a);return this+Jc(S(0,a-this.length),b)},first:function(a){N(a)&&(a=1);return this.substr(0,a)},last:function(a){N(a)&&(a=1);return this.substr(0>this.length-a?0:this.length-a)},toNumber:function(a){return Oa(this,a)},capitalize:function(a){var b;return this.toLowerCase().replace(a?/[^']/g:/^\S/,function(a){var d=a.toUpperCase(),e;e=b?a:d;b=d!==a;return e})},assign:function(){var a={};sa(arguments,function(b,c){G(b)?xa(a,b):a[c+1]=b});return this.replace(/\{([^{]+?)\}/g,
function(b,c){return J(a,c)?a[c]:b})}});H(s,!0,!0,{insert:s.prototype.add});
(function(a){if(ba.btoa)Nc=ba.btoa,Oc=ba.atob;else{var b=/[^A-Za-z0-9\+\/\=]/g;Nc=function(b){var d="",e,g,f,h,l,n,x=0;do e=b.charCodeAt(x++),g=b.charCodeAt(x++),f=b.charCodeAt(x++),h=e>>2,e=(e&3)<<4|g>>4,l=(g&15)<<2|f>>6,n=f&63,isNaN(g)?l=n=64:isNaN(f)&&(n=64),d=d+a.charAt(h)+a.charAt(e)+a.charAt(l)+a.charAt(n);while(x<b.length);return d};Oc=function(c){var d="",e,g,f,h,l,n=0;if(c.match(b))throw Error("String contains invalid base64 characters");c=c.replace(/[^A-Za-z0-9\+\/\=]/g,"");do e=a.indexOf(c.charAt(n++)),
g=a.indexOf(c.charAt(n++)),h=a.indexOf(c.charAt(n++)),l=a.indexOf(c.charAt(n++)),e=e<<2|g>>4,g=(g&15)<<4|h>>2,f=(h&3)<<6|l,d+=s.fromCharCode(e),64!=h&&(d+=s.fromCharCode(g)),64!=l&&(d+=s.fromCharCode(f));while(n<c.length);return d}}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=");})(); | 372.234848 | 609 | 0.624239 |
f6cc49631bff87524e560955b255a9abd1ce0cf2 | 2,505 | js | JavaScript | hw3/upload/lab3-1854116-code/lab3_files/mod_f2513f1.js | zmzfpc/HCI | 454e13099485d7d2028daa81cf989686fc1fa3b2 | [
"Apache-2.0"
] | null | null | null | hw3/upload/lab3-1854116-code/lab3_files/mod_f2513f1.js | zmzfpc/HCI | 454e13099485d7d2028daa81cf989686fc1fa3b2 | [
"Apache-2.0"
] | null | null | null | hw3/upload/lab3-1854116-code/lab3_files/mod_f2513f1.js | zmzfpc/HCI | 454e13099485d7d2028daa81cf989686fc1fa3b2 | [
"Apache-2.0"
] | null | null | null | !function(n){var e,t,r=window.sugar||{},a=document.getElementsByTagName("head")[0],o={},i={},c={},s={},u={},l={},f=function(n,t){for(var r=document.createDocumentFragment(),o=0,i=n.length;i>o;o++){var c=n[o].id,u=n[o].url;if(!(u in s)){s[u]=!0;var l=document.createElement("script");t&&!function(n,r){var a=setTimeout(function(){t(r)},e.timeout);n.onerror=function(){clearTimeout(a),t(r)};var o=function(){clearTimeout(a)};"onload"in n?n.onload=o:n.onreadystatechange=function(){("loaded"===this.readyState||"complete"===this.readyState)&&o()}}(l,c),l.type="text/javascript",l.src=u,r.appendChild(l)}}a.appendChild(r)},d=function(n,e,t){for(var r=[],a=0,i=n.length;i>a;a++){var c=n[a],s=o[c]||(o[c]=[]);s.push(e);var d,p=u[c]||u[c+".js"]||{},h=p.pkg;d=h?l[h].url||l[h].uri:p.url||p.uri||c,r.push({id:c,url:d})}f(r,t)},p=function(n){var e=o[n];if(e){for(var t=0,r=e.length;r>t;t++)e[t]();delete o[n]}};t=function(n,t){if(n=n.replace(/\.js$/i,""),i[n]=t,~t.toString().indexOf("__mod__async__load")){var r={exports:{}};i[n]={deffer:!0,callbacks:[],loaded:!1,load:function(){}},t.apply(r,[e,r.exports,r]);var a=r.exports.__mod__async__load;i[n].load=function(){this.loaded||(this.loaded=!0,a(function(e){var t=i[n].callbacks;i[n]=function(){return e},t.forEach(function(n){n()}),p(n)}))},o[n]&&o[n].length&&i[n].load()}else p(n)},e=function(n){if(n&&n.splice)return e.async.apply(this,arguments);n=e.alias(n);var t=c[n];if(t)return t.exports;var r=i[n];if(!r)throw"[ModJS] Cannot find module `"+n+"`";t=c[n]={exports:{}};var a="function"==typeof r?r.apply(t,[e,t.exports,t]):r;return a&&(t.exports=a),t.exports},e.async=function(t,r,a){function o(n){for(var t,r=0,a=n.length;a>r;r++){var d=e.alias(n[r]);d in s||(s[d]=!0,d in i?(i[d]&&i[d].deffer&&(l++,i[d].callbacks.push(c),i[d].load()),t=u[d]||u[d+".js"],t&&"deps"in t&&o(t.deps)):(f.push(d),l++,t=u[d]||u[d+".js"],t&&"deps"in t&&o(t.deps)))}}function c(){if(0===l--){for(var a=[],o=0,i=t.length;i>o;o++)a[o]=e(t[o]);r&&r.apply(n,a)}}"string"==typeof t&&(t=[t]);var s={},l=0,f=[];o(t),d(f,c,a),c()},e.ensure=function(n,t){e.async(n,function(){t&&t.call(this,e)})},e.resourceMap=function(n){var e,t;t=n.res;for(e in t)t.hasOwnProperty(e)&&(u[e]=t[e]);t=n.pkg;for(e in t)t.hasOwnProperty(e)&&(l[e]=t[e])},e.loadJs=function(n){if(!(n in s)){s[n]=!0;var e=document.createElement("script");return e.type="text/javascript",e.src=n,a.appendChild(e),e}},e.alias=function(n){return n.replace(/\.js$/i,"")},e.timeout=5e3,r.require=e,r.define=t,window.sugar=r}(this); | 2,505 | 2,505 | 0.626347 |
f6cca40198ab8db4691999e0e04efa0253ae01b2 | 2,519 | js | JavaScript | static/js/controllers/websocket-chat.js | tkerspp007/python-chat | b66cad5b82d7809d61bbf9f02487797ef10a4529 | [
"MIT"
] | 45 | 2015-01-30T02:38:22.000Z | 2020-04-28T06:09:01.000Z | static/js/controllers/websocket-chat.js | tkerspp007/python-chat | b66cad5b82d7809d61bbf9f02487797ef10a4529 | [
"MIT"
] | 3 | 2015-04-20T03:59:07.000Z | 2017-02-21T08:54:43.000Z | static/js/controllers/websocket-chat.js | TheWaWaR/python-chat | b66cad5b82d7809d61bbf9f02487797ef10a4529 | [
"MIT"
] | 19 | 2015-04-07T07:14:32.000Z | 2021-03-26T08:59:29.000Z | // Generated by CoffeeScript 1.6.3
var chatApp, ws;
ws = null;
chatApp = angular.module("chatApp", []);
chatApp.factory("ChatService", function() {
var service;
service = {};
service.setOnmessage = function(callback) {
return service.onmessage = callback;
};
service.setOnopen = function(callback) {
return service.onopen = callback;
};
service.connect = function() {
if (service.ws) {
return;
}
ws = new WebSocket("ws://" + location.host + "/api");
ws.onopen = function(event) {
return service.onopen(event);
};
ws.onmessage = function(event) {
return service.onmessage(event);
};
return service.ws = ws;
};
return service;
});
chatApp.controller("Ctrl", [
'$scope', 'ChatService', function($scope, ChatService) {
$scope.templateUrl = "/static/partials/chat.html";
$scope.messages = [];
$scope.cids = [];
$scope.members = {};
ChatService.setOnopen(function() {
return console.log('Opened');
});
ChatService.setOnmessage(function(event) {
var data, msg, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
data = JSON.parse(event.data);
console.log('data', data);
switch (data.type) {
case 'online':
_ref = data.messages;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
msg = _ref[_i];
$scope.cids.push(msg.cid);
$scope.members[msg.cid] = {
'datetime': msg.datetime
};
}
break;
case 'offline':
_ref1 = data.messages;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
msg = _ref1[_j];
$scope.cids.splice($scope.cids.indexOf(msg.cid), 1);
delete $scope.members[msg.cid];
}
break;
case 'message':
_ref2 = data.messages;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
msg = _ref2[_k];
$scope.messages.push(msg);
}
}
$scope.$apply();
if (data.type === 'message') {
return $('#logs').stop().animate({
scrollTop: $('#logs')[0].scrollHeight
}, "300", "swing");
}
});
ChatService.connect();
return 'ok';
}
]);
$(document).ready(function() {
return $('form').submit(function(event) {
var msg;
msg = $('#message-input').val();
if (msg.length > 0) {
ws.send(msg);
$('#message-input').val("");
}
return false;
});
});
| 26.515789 | 72 | 0.530369 |
f6cceb6de8609fe961892c5d233e266d6799368d | 5,884 | js | JavaScript | public/js/gservice.js | dchen101/GMap | d2da2a7ac8cdbce10a4661a5c918038804b9fe03 | [
"MIT"
] | null | null | null | public/js/gservice.js | dchen101/GMap | d2da2a7ac8cdbce10a4661a5c918038804b9fe03 | [
"MIT"
] | null | null | null | public/js/gservice.js | dchen101/GMap | d2da2a7ac8cdbce10a4661a5c918038804b9fe03 | [
"MIT"
] | null | null | null | // Creates the gservice factory. This will be the primary means by which we interact with Google Maps
angular.module('gservice', [])
.factory('gservice', function($rootScope, $http){
// Update Broadcasted Variable (lets the panels know to change their lat, long values)
// Initialize Variables
// -------------------------------------------------------------
// Service our factory will return
var googleMapService = {};
// Array of locations obtained from API calls
var locations = [];
// Selected Location (initialize to center of America)
var selectedLat = 39.50;
var selectedLong = -98.35;
// Handling Clicks and location selection
googleMapService.clickLat = 0;
googleMapService.clickLong = 0;
// Functions
// --------------------------------------------------------------
// Refresh the Map with new data. Function will take new latitude and longitude coordinates.
googleMapService.refresh = function(latitude, longitude){
// Clears the holding array of locations
locations = [];
// Set the selected lat and long equal to the ones provided on the refresh() call
selectedLat = latitude;
selectedLong = longitude;
// Perform an AJAX call to get all of the records in the db.
$http.get('/users').success(function(response){
// Convert the results into Google Map Format
locations = convertToMapPoints(response);
// Then initialize the map.
initialize(latitude, longitude);
}).error(function(){});
};
// Private Inner Functions
// --------------------------------------------------------------
// Convert a JSON of users into map points
var convertToMapPoints = function(response){
// Clear the locations holder
var locations = [];
// Loop through all of the JSON entries provided in the response
for(var i= 0; i < response.length; i++) {
var user = response[i];
// Create popup windows for each record
var contentString =
'<p><b>Username</b>: ' + user.username +
'<br><b>Age</b>: ' + user.age +
'<br><b>Gender</b>: ' + user.gender +
'<br><b>Favorite Language</b>: ' + user.favlang +
'</p>';
// Converts each of the JSON records into Google Maps Location format (Note [Lat, Lng] format).
locations.push({
latlon: new google.maps.LatLng(user.location[1], user.location[0]),
message: new google.maps.InfoWindow({
content: contentString,
maxWidth: 320
}),
username: user.username,
gender: user.gender,
age: user.age,
favlang: user.favlang
});
}
// location is now an array populated with records in Google Maps format
return locations;
};
// Initializes the map
var initialize = function(latitude, longitude) {
// Uses the selected lat, long as starting point
var myLatLng = {lat: selectedLat, lng: selectedLong};
// If map has not been created already...
if (!map){
// Create a new map and place in the index.html page
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: myLatLng
});
}
// Loop through each location in the array and place a marker
locations.forEach(function(n, i){
var marker = new google.maps.Marker({
position: n.latlon,
map: map,
title: "Big Map",
icon: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png",
});
// For each marker created, add a listener that checks for clicks
google.maps.event.addListener(marker, 'click', function(e){
// When clicked, open the selected marker's message
currentSelectedMarker = n;
n.message.open(map, marker);
});
});
// Set initial location as a bouncing red marker
var initialLocation = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: initialLocation,
animation: google.maps.Animation.BOUNCE,
map: map,
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
});
// Bouncing Red Marker Logic
// ...
// Function for moving to a selected location
map.panTo(new google.maps.LatLng(latitude, longitude));
// Clicking on the Map moves the bouncing red marker
google.maps.event.addListener(map, 'click', function(e){
var marker = new google.maps.Marker({
position: e.latLng,
animation: google.maps.Animation.BOUNCE,
map: map,
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
});
// When a new spot is selected, delete the old red bouncing marker
if(lastMarker){
lastMarker.setMap(null);
}
// Create a new red bouncing marker and move to it
lastMarker = marker;
map.panTo(marker.position);
googleMapService.clickLat = marker.getPosition().lat();
googleMapService.clickLong = marker.getPosition().lng();
$rootScope.$broadcast("clicked");
});
lastMarker = marker;
};
// Refresh the page upon window load. Use the initial latitude and longitude
google.maps.event.addDomListener(window, 'load',
googleMapService.refresh(selectedLat, selectedLong));
return googleMapService;
});
| 35.445783 | 111 | 0.558124 |
f6ccf9c28a22ea629dae95f8911a76b151f67d7f | 2,159 | js | JavaScript | test/integration/test-errors.js | marcelovani/amphtml | e35426b5fe632134a2c772ea9addbd5ead9c37e5 | [
"Apache-2.0"
] | 1 | 2016-07-07T14:45:23.000Z | 2016-07-07T14:45:23.000Z | test/integration/test-errors.js | marcelovani/amphtml | e35426b5fe632134a2c772ea9addbd5ead9c37e5 | [
"Apache-2.0"
] | 1 | 2019-03-28T10:38:44.000Z | 2019-03-28T10:38:44.000Z | test/integration/test-errors.js | marcelovani/amphtml | e35426b5fe632134a2c772ea9addbd5ead9c37e5 | [
"Apache-2.0"
] | 12 | 2017-01-04T08:34:17.000Z | 2018-11-26T10:42:08.000Z | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
createFixtureIframe,
poll,
expectBodyToBecomeVisible,
} from '../../testing/iframe.js';
describe('error page', () => {
let fixture;
beforeEach(() => {
return createFixtureIframe('test/fixtures/errors.html', 500, win => {
// Trigger dev mode.
try {
win.history.pushState({}, '', 'test2.html#development=1');
} catch (e) {
// Some browsers do not allow this.
win.AMP_DEV_MODE = true;
}
console.error('updated', win.location.hash);
}).then(f => {
fixture = f;
return poll('errors to happen', () => {
return fixture.doc.querySelectorAll('[error-message]').length >= 2;
}, () => {
return new Error('Failed to find errors. HTML\n' +
fixture.doc.documentElement./*TEST*/innerHTML);
});
});
});
it.skipper().skipFirefox().run('should show the body in error test', () => {
return expectBodyToBecomeVisible(fixture.win);
});
function shouldFail(id) {
// Skip for issue #110
it.skipper().skipFirefox().run('should fail to load #' + id, () => {
const e = fixture.doc.getElementById(id);
expect(fixture.errors.join('\n')).to.contain(
e.getAttribute('data-expectederror'));
expect(e.getAttribute('error-message')).to.contain(
e.getAttribute('data-expectederror'));
expect(e.className).to.contain('-amp-element-error');
});
}
// Add cases to fixtures/errors.html and add them here.
shouldFail('yt0');
shouldFail('iframe0');
});
| 32.712121 | 78 | 0.637332 |
f6cd5e21badce267ad66eac7d4ce55c66e9ebf9f | 1,103 | js | JavaScript | src/js/elements/Spring.js | jonathanching/text-particles | f3df05a3a1068bf4740123074e7ad20ac30f9db2 | [
"MIT"
] | 1 | 2020-04-14T08:38:47.000Z | 2020-04-14T08:38:47.000Z | src/js/elements/Spring.js | jonathanching/text-particles | f3df05a3a1068bf4740123074e7ad20ac30f9db2 | [
"MIT"
] | 4 | 2021-03-09T19:17:02.000Z | 2022-02-12T22:01:53.000Z | src/js/elements/Spring.js | jonathanching/text-particles | f3df05a3a1068bf4740123074e7ad20ac30f9db2 | [
"MIT"
] | 1 | 2020-05-19T05:49:08.000Z | 2020-05-19T05:49:08.000Z | /**
* ==================================================================================
* Spring element
*
* ==================================================================================
**/
import Vector2 from '../libs/Vector2.js';
export default class Spring {
constructor(x, y, stiffness, offset) {
this.position = new Vector2(x, y);
this.stiffness = stiffness;
this.offset = offset;
}
/**
* ==================================================================================
* @Methods
* ==================================================================================
**/
//
/**
* ==================================================================================
* @Getter/Setter
* ==================================================================================
**/
//
/**
* ==================================================================================
* @Checker
* ==================================================================================
**/
//
}
| 24.511111 | 89 | 0.165911 |
f6cd87ca64451963c990d54982de6f4b53fd2652 | 65 | js | JavaScript | app/components/tab-bar-item.js | AriasBros/ember-material | a9131e07502bb7886f017f604a734742b9738fe2 | [
"MIT"
] | null | null | null | app/components/tab-bar-item.js | AriasBros/ember-material | a9131e07502bb7886f017f604a734742b9738fe2 | [
"MIT"
] | null | null | null | app/components/tab-bar-item.js | AriasBros/ember-material | a9131e07502bb7886f017f604a734742b9738fe2 | [
"MIT"
] | null | null | null | export { default } from 'ember-material/components/tab-bar-item'; | 65 | 65 | 0.769231 |
f6cd8cdccf813fcc0cd37f2223438df1dc732b9d | 276 | js | JavaScript | server/app.js | JaxTheWolf/clicker-gamev2 | 39e082e88d5dc81aec5ac7b9d2970b9695ce8ab8 | [
"MIT"
] | 1 | 2020-04-24T11:34:38.000Z | 2020-04-24T11:34:38.000Z | server/app.js | JaxTheWolf/clicker-gamev2 | 39e082e88d5dc81aec5ac7b9d2970b9695ce8ab8 | [
"MIT"
] | 1 | 2021-05-10T22:04:45.000Z | 2021-05-10T22:04:45.000Z | server/app.js | JaxTheWolf/clicker-gamev2 | 39e082e88d5dc81aec5ac7b9d2970b9695ce8ab8 | [
"MIT"
] | null | null | null | var express=require("express"),$jscomp$destructuring$var0=require("path"),join=$jscomp$destructuring$var0.join,app=express();app.get("/click",function(b,a){a.sendFile(join(__dirname,"index.html"))});app.use("/public",express.static(join(__dirname,"public")));app.listen(6969); | 276 | 276 | 0.753623 |
f6cf23c406a61d194e36e6cbc8377a6986bd7d58 | 218 | js | JavaScript | packages/df-client/config/index.js | mvachhar/dineforward | 9acfdd08043a264b9fff5b70686d9f76532f843f | [
"MIT"
] | 4 | 2020-03-17T22:41:18.000Z | 2021-08-18T07:13:30.000Z | packages/df-client/config/index.js | mvachhar/dineforward | 9acfdd08043a264b9fff5b70686d9f76532f843f | [
"MIT"
] | 10 | 2020-03-18T23:22:32.000Z | 2021-05-11T09:12:34.000Z | packages/df-client/config/index.js | mvachhar/dineforward | 9acfdd08043a264b9fff5b70686d9f76532f843f | [
"MIT"
] | 5 | 2020-03-17T22:41:35.000Z | 2020-06-24T19:43:44.000Z | const config = {
BUNDLE_ANALYZE: process.env.BUNDLE_ANALYZE,
NODE_ENV: process.env.NODE_ENV,
CUSTOM_ENV: process.env.CUSTOM_ENV,
IS_PROD: process.env.NODE_ENV === 'production',
};
module.exports = config;
| 24.222222 | 49 | 0.729358 |
f6d02292570888d13af360bf018294ab43704e9e | 478 | js | JavaScript | webpack/webpack.config.server.development.js | tanglie1993/react-native.cn | 8dcc2dc5eae55b05d030f8181aa4978e465fefcf | [
"BSD-3-Clause"
] | 651 | 2015-09-25T12:22:03.000Z | 2022-03-25T14:02:16.000Z | webpack/webpack.config.server.development.js | tanglie1993/react-native.cn | 8dcc2dc5eae55b05d030f8181aa4978e465fefcf | [
"BSD-3-Clause"
] | 97 | 2015-12-06T04:31:14.000Z | 2021-06-06T14:33:29.000Z | webpack/webpack.config.server.development.js | tanglie1993/react-native.cn | 8dcc2dc5eae55b05d030f8181aa4978e465fefcf | [
"BSD-3-Clause"
] | 767 | 2015-11-21T10:26:56.000Z | 2022-02-12T06:01:39.000Z | import base_configuration from './webpack.config.server'
import application_configuration from './application_configuration'
// Network path for static files: fetch all statics from webpack development server
base_configuration.output.publicPath = `http://${application_configuration.development.webpack.development_server.host}:${application_configuration.development.webpack.development_server.port}${base_configuration.output.publicPath}`
export default base_configuration | 59.75 | 232 | 0.853556 |
f6d03cee0ddcf0cfbcbdbe5ccf3c87f472332ea0 | 473 | js | JavaScript | src/Web/FitnessBuddy.Web/wwwroot/lib/signalr/dist/esm/Polyfills.min.js | beshev/FitnessBuddy | 00c3dc0f398c601cbe117db80d4b088ddb5a4243 | [
"MIT"
] | 4 | 2022-02-17T21:09:00.000Z | 2022-03-30T07:22:08.000Z | src/Web/FitnessBuddy.Web/wwwroot/lib/signalr/dist/esm/Polyfills.min.js | beshev/FitnessBuddy | 00c3dc0f398c601cbe117db80d4b088ddb5a4243 | [
"MIT"
] | null | null | null | src/Web/FitnessBuddy.Web/wwwroot/lib/signalr/dist/esm/Polyfills.min.js | beshev/FitnessBuddy | 00c3dc0f398c601cbe117db80d4b088ddb5a4243 | [
"MIT"
] | null | null | null | /**
* Skipped minification because the original files appears to be already minified.
* Original file: /npm/@microsoft/signalr@6.0.1/dist/esm/Polyfills.js
*
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
*/
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
export {};
//# sourceMappingURL=Polyfills.js.map | 47.3 | 123 | 0.758985 |
f6d0f82636f1ca42bdb6fdac17a408b7c4c076df | 5,590 | js | JavaScript | frontend/src/components/Home/index.js | wjuanps/new-antares | 1a5d84970c42384f4e4cac091fd5d98135cf7d6c | [
"MIT"
] | 1 | 2020-04-10T16:54:55.000Z | 2020-04-10T16:54:55.000Z | frontend/src/components/Home/index.js | wjuanps/new-antares | 1a5d84970c42384f4e4cac091fd5d98135cf7d6c | [
"MIT"
] | 3 | 2020-04-10T17:00:28.000Z | 2021-03-10T14:21:01.000Z | frontend/src/components/Home/index.js | wjuanps/new-antares | 1a5d84970c42384f4e4cac091fd5d98135cf7d6c | [
"MIT"
] | null | null | null | import React, { useState } from "react";
import Header from "../Header";
const Home = () => {
const [c, co] = useState(0);
return (
<>
<Header />
<section
className="features-icons text-center"
style={{ backgroundColor: "#ffffff" }}
>
<div className="container">
<div className="row text-center">
<div className="col-md-12 mb-3">
<h2 className="text-uppercase">Mais pesquisados</h2>
</div>
</div>
<div className="row">
<div className="col-lg-4">
<div className="features-icons-item mx-auto mb-5 mb-lg-0 mb-lg-3">
<div className="features-icons-icon d-flex">
<a className=" m-auto text-primary" href="">
<i className="fa fa-external-link"></i>
</a>
</div>
<h3>Samsung note 10 plus</h3>
<p className="lead mb-0">55 consultas nas últimas 4 semanas</p>
</div>
</div>
<div className="col-lg-4">
<div className="features-icons-item mx-auto mb-5 mb-lg-0 mb-lg-3">
<div className="features-icons-icon d-flex">
<a className=" m-auto text-primary" href="">
<i className="fa fa-external-link"></i>
</a>
</div>
<h3>Mi note 10</h3>
<p className="lead mb-0">43 consultas nas últimas 4 semanas</p>
</div>
</div>
<div className="col-lg-4">
<div className="features-icons-item mx-auto mb-0 mb-lg-3">
<div className="features-icons-icon d-flex">
<a className=" m-auto text-primary" href="">
<i className="fa fa-external-link"></i>
</a>
</div>
<h3>Iphone 11 pro max</h3>
<p className="lead mb-0">41 consultas nas últimas 4 semanas</p>
</div>
</div>
</div>
</div>
</section>
<section className="features-icons bg-light text-center">
<div className="container">
<div className="row">
<div className="col-md-12">
<h1 style={{ color: "#275E7C" }}>Como funciona o Antares</h1>
</div>
</div>
</div>
</section>
<section className="showcase">
<div className="container-fluid p-0">
<div className="row no-gutters">
<div className="col-lg-6 order-lg-2 text-white showcase-img showcase-1"></div>
<div className="col-lg-6 order-lg-1 my-auto showcase-text">
<h2>Input dos dados</h2>
<p className="lead mb-0">
O processo se inicia com a partir da entrada de qualquer
produto, serviço ou empresa informada pelo usuário ou pela
escolha entre os termos mais pesquisados.
</p>
</div>
</div>
<div className="row no-gutters">
<div className="col-lg-6 text-white showcase-img showcase-2"></div>
<div className="col-lg-6 my-auto showcase-text">
<h2>Cálculo do Sentimento</h2>
<p className="lead mb-0">
Com base na pesquisa do usuário, o Antares faz uma busca nas
redes sociais e utilizando Machine Learning faz cáculos
heurísticos para verificar a tendencia de cada sentimento
presente nos textos coletados.
</p>
</div>
</div>
<div className="row no-gutters">
<div className="col-lg-6 order-lg-2 text-white showcase-img showcase-3"></div>
<div className="col-lg-6 order-lg-1 my-auto showcase-text">
<h2>Visualização dos resultados</h2>
<p className="lead mb-0">
Ao fim de todas as etapas, o sistema exibe ao usuário os
resultados de todo o processo em forma de gráficos e tabelas com
um resumo dos textos encontrados, bem como o sentimento atrelado
a cada um deles.
</p>
</div>
</div>
</div>
</section>
<section className="call-to-action text-white text-center">
<div className="overlay"></div>
<div className="container">
<div className="row">
<div className="col-xl-9 mx-auto">
<h2 className="mb-4">Pronto para começar? Faça sua busca!</h2>
</div>
<div className="col-md-10 col-lg-8 col-xl-7 mx-auto">
<form method="get" action="/sentiment-analysis">
<div className="form-row">
<div className="col-12 col-md-9 mb-2 mb-md-0">
<input
name="q"
type="text"
className="form-control form-control-lg"
placeholder="Pesquisar por..."
required
/>
</div>
<div className="col-12 col-md-3">
<button
type="submit"
className="btn btn-block btn-lg btn-primary"
>
Buscar
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
</>
);
};
export default Home;
| 38.287671 | 90 | 0.480322 |
f6d12abf0f89ff991a4b1e0ee4dc348f8a7756c8 | 843 | js | JavaScript | src/services/CharacterService.js | nrgaposok/smashcombos | 73d2cf6bd6a09ed9c0d5b52bcd800be48011b7ec | [
"MIT"
] | null | null | null | src/services/CharacterService.js | nrgaposok/smashcombos | 73d2cf6bd6a09ed9c0d5b52bcd800be48011b7ec | [
"MIT"
] | null | null | null | src/services/CharacterService.js | nrgaposok/smashcombos | 73d2cf6bd6a09ed9c0d5b52bcd800be48011b7ec | [
"MIT"
] | null | null | null | import axios from "axios";
import uuid from "uuid/v4";
const URL_BASE = "https://smashcombos.xyz";
export class CharacterService {
static async editProfile(name, description, tags) {
const url = `${URL_BASE}/characters/${name}/profile`;
const { data } = await axios.post(url, {
description,
tags
});
return data.success;
}
static async addCombo(name, combo) {
const url = `${URL_BASE}/characters/${name}/combos`;
const { data } = await axios.post(url, {
combo: {
...combo,
uuid: uuid()
}
});
return data.success;
}
static async editCombo(name, uuid, combo) {
const url = `${URL_BASE}/characters/${name}/combos/${uuid}`;
const { data } = await axios.post(url, {
combo
});
return data.success;
}
}
export default CharacterService;
| 21.075 | 64 | 0.604982 |
f6d18b8bb41b1b67a891ca6c99bc581c1b824177 | 7,374 | js | JavaScript | simple-schema-context.js | quantilope/meteor-simple-schema | abf51400f4069c77a6ee6237974fcbd11056d266 | [
"MIT"
] | null | null | null | simple-schema-context.js | quantilope/meteor-simple-schema | abf51400f4069c77a6ee6237974fcbd11056d266 | [
"MIT"
] | null | null | null | simple-schema-context.js | quantilope/meteor-simple-schema | abf51400f4069c77a6ee6237974fcbd11056d266 | [
"MIT"
] | null | null | null | /* global SimpleSchema */
/* global SimpleSchemaValidationContext:true */
/* global doValidation1 */
/* global doValidation2 */
function doValidation(obj, isModifier, isUpsert, keyToValidate, ss, extendedCustomContext) {
var useOld = true; //for now this can be manually changed to try the experimental method, which doesn't yet work properly
var func = useOld ? doValidation1 : doValidation2;
return func(obj, isModifier, isUpsert, keyToValidate, ss, extendedCustomContext);
}
/*
* PUBLIC API
*/
SimpleSchemaValidationContext = function SimpleSchemaValidationContext(ss) {
var self = this;
self._simpleSchema = ss;
self._schema = ss.schema();
self._schemaKeys = _.keys(self._schema);
self._invalidKeys = [];
//set up validation dependencies
self._deps = {};
self._depsAny = new Deps.Dependency();
_.each(self._schemaKeys, function(name) {
self._deps[name] = new Deps.Dependency();
});
};
//validates the object against the simple schema and sets a reactive array of error objects
SimpleSchemaValidationContext.prototype.validate = function simpleSchemaValidationContextValidate(doc, options) {
var self = this;
options = _.extend({
modifier: false,
upsert: false,
extendedCustomContext: {}
}, options || {});
//on the client we can add the userId if not already in the custom context
if (Meteor.isClient && options.extendedCustomContext.userId === void 0) {
options.extendedCustomContext.userId = (Meteor.userId && Meteor.userId()) || null;
}
var invalidKeys = doValidation(doc, options.modifier, options.upsert, null, self._simpleSchema, options.extendedCustomContext);
//now update self._invalidKeys and dependencies
//note any currently invalid keys so that we can mark them as changed
//due to new validation (they may be valid now, or invalid in a different way)
var removedKeys = _.pluck(self._invalidKeys, "name");
//update
self._invalidKeys = invalidKeys;
//add newly invalid keys to changedKeys
var addedKeys = _.pluck(self._invalidKeys, "name");
//mark all changed keys as changed
var changedKeys = _.union(addedKeys, removedKeys);
self._markKeysChanged(changedKeys);
// Return true if it was valid; otherwise, return false
return self._invalidKeys.length === 0;
};
//validates doc against self._schema for one key and sets a reactive array of error objects
SimpleSchemaValidationContext.prototype.validateOne = function simpleSchemaValidationContextValidateOne(doc, keyName, options) {
var self = this, i, ln, k;
options = _.extend({
modifier: false,
upsert: false,
extendedCustomContext: {}
}, options || {});
//on the client we can add the userId if not already in the custom context
if (Meteor.isClient && options.extendedCustomContext.userId === void 0) {
options.extendedCustomContext.userId = (Meteor.userId && Meteor.userId()) || null;
}
var invalidKeys = doValidation(doc, options.modifier, options.upsert, keyName, self._simpleSchema, options.extendedCustomContext);
//now update self._invalidKeys and dependencies
//remove objects from self._invalidKeys where name = keyName
var newInvalidKeys = [];
for (i = 0, ln = self._invalidKeys.length; i < ln; i++) {
k = self._invalidKeys[i];
if (k.name !== keyName) {
newInvalidKeys.push(k);
}
}
self._invalidKeys = newInvalidKeys;
//merge invalidKeys into self._invalidKeys
for (i = 0, ln = invalidKeys.length; i < ln; i++) {
k = invalidKeys[i];
self._invalidKeys.push(k);
}
//mark key as changed due to new validation (they may be valid now, or invalid in a different way)
self._markKeysChanged([keyName]);
// Return true if it was valid; otherwise, return false
return !self._keyIsInvalid(keyName);
};
//reset the invalidKeys array
SimpleSchemaValidationContext.prototype.resetValidation = function simpleSchemaValidationContextResetValidation() {
var self = this;
var removedKeys = _.pluck(self._invalidKeys, "name");
self._invalidKeys = [];
self._markKeysChanged(removedKeys);
};
SimpleSchemaValidationContext.prototype.isValid = function simpleSchemaValidationContextIsValid() {
var self = this;
self._depsAny.depend();
return !self._invalidKeys.length;
};
SimpleSchemaValidationContext.prototype.invalidKeys = function simpleSchemaValidationContextInvalidKeys() {
var self = this;
self._depsAny.depend();
return self._invalidKeys;
};
SimpleSchemaValidationContext.prototype.addInvalidKeys = function simpleSchemaValidationContextAddInvalidKeys(errors) {
var self = this;
if (!errors || !errors.length) {
return;
}
var changedKeys = [];
_.each(errors, function (errorObject) {
changedKeys.push(errorObject.name);
self._invalidKeys.push(errorObject);
});
self._markKeysChanged(changedKeys);
};
SimpleSchemaValidationContext.prototype._markKeysChanged = function simpleSchemaValidationContextMarkKeysChanged(keys) {
var self = this;
if (!keys || !keys.length) {
return;
}
_.each(keys, function(name) {
var genericName = self._simpleSchema.makeGeneric(name);
if (genericName in self._deps) {
self._deps[genericName].changed();
}
});
self._depsAny.changed();
};
SimpleSchemaValidationContext.prototype._getInvalidKeyObject = function simpleSchemaValidationContextGetInvalidKeyObject(name, genericName) {
var self = this;
genericName = genericName || self._simpleSchema.makeGeneric(name);
var errorObj = _.findWhere(self._invalidKeys, {name: name});
if (!errorObj) {
errorObj = _.findWhere(self._invalidKeys, {name: genericName});
}
return errorObj;
};
SimpleSchemaValidationContext.prototype._keyIsInvalid = function simpleSchemaValidationContextKeyIsInvalid(name, genericName) {
return !!this._getInvalidKeyObject(name, genericName);
};
// Like the internal one, but with deps
SimpleSchemaValidationContext.prototype.keyIsInvalid = function simpleSchemaValidationContextKeyIsInvalid(name) {
var self = this;
var genericName = self._simpleSchema.makeGeneric(name);
self._deps[genericName] && self._deps[genericName].depend();
return self._keyIsInvalid(name, genericName);
};
SimpleSchemaValidationContext.prototype.keyErrorMessage = function simpleSchemaValidationContextKeyErrorMessage(name) {
var self = this;
var genericName = self._simpleSchema.makeGeneric(name);
self._deps[genericName] && self._deps[genericName].depend();
var errorObj = self._getInvalidKeyObject(name, genericName);
if (!errorObj) {
return "";
}
return self._simpleSchema.messageForError(errorObj.type, errorObj.name, null, errorObj.value);
};
SimpleSchemaValidationContext.prototype.getErrorObject = function simpleSchemaValidationContextGetErrorObject() {
var self = this, message, invalidKeys = this._invalidKeys;
if (invalidKeys.length) {
message = self.keyErrorMessage(invalidKeys[0].name);
// We add `message` prop to the invalidKeys.
invalidKeys = _.map(invalidKeys, function (o) {
return _.extend({message: self.keyErrorMessage(o.name)}, o);
});
} else {
message = "Failed validation";
}
var error = new Error(message);
error.invalidKeys = invalidKeys;
// If on the server, we add a sanitized error, too, in case we're
// called from a method.
if (Meteor.isServer) {
error.sanitizedError = new Meteor.Error(400, message);
}
return error;
};
| 34.138889 | 141 | 0.736913 |
f6d1a8e4833ee473bc9e55b48cfdf66608415038 | 885 | js | JavaScript | config/typography.js | astutespruce/astutespruce.com | 955ad32812da32613f00d87b83fb04bda4a566b8 | [
"MIT"
] | null | null | null | config/typography.js | astutespruce/astutespruce.com | 955ad32812da32613f00d87b83fb04bda4a566b8 | [
"MIT"
] | null | null | null | config/typography.js | astutespruce/astutespruce.com | 955ad32812da32613f00d87b83fb04bda4a566b8 | [
"MIT"
] | null | null | null | import Typography from 'typography'
import { theme } from 'style/theme'
const typography = new Typography({
title: 'Mediterranean',
baseFontSize: '20px',
baseLineHeight: 1.45,
headerFontFamily: ['Cinzel'],
bodyFontFamily: ['Lato'],
scaleRatio: 2.441,
headerWeight: 700,
headerColor: theme.colors.grey[900],
bodyColor: theme.colors.grey[900],
overrideStyles: () => ({
html: {
height: '100%',
overflowY: 'auto',
minWidth: '440px',
},
body: {
height: '100%',
},
a: {
color: theme.colors.accent[700],
textDecoration: 'none',
},
'a:hover': {
textDecoration: 'underline',
},
blockquote: {
color: theme.colors.grey[900],
background: theme.colors.grey[100],
padding: '1rem',
fontStyle: 'italic',
borderRadius: '0.5rem',
},
}),
})
export default typography
| 21.071429 | 41 | 0.59322 |
f6d22049d686bbb83ea33745e130be2196fd5cfc | 778 | js | JavaScript | posts-server/src/index.js | kevinvoduy/discor | 0b92bf2e64d89b8b5ae088f4296e4dfd7a0800fc | [
"MIT"
] | null | null | null | posts-server/src/index.js | kevinvoduy/discor | 0b92bf2e64d89b8b5ae088f4296e4dfd7a0800fc | [
"MIT"
] | null | null | null | posts-server/src/index.js | kevinvoduy/discor | 0b92bf2e64d89b8b5ae088f4296e4dfd7a0800fc | [
"MIT"
] | 1 | 2018-06-05T09:13:26.000Z | 2018-06-05T09:13:26.000Z | import http from 'http';
import SocketIO from 'socket.io';
import App from './config/express';
// dynamo: prod
// import './config/dynamo';
// mongodb: dev
import './config/mongo';
// if (process.env.NODE_ENV !== 'production') {
// require('babel-register');
// require('babel-polyfill');
// }
const app = App.express;
const server = http.Server(app);
const io = SocketIO(server);
const PORT = process.env.PORT || 3030;
io.on('connection', socket => {
console.log('Client Connected');
socket.on('new__post', post => {
console.log('posts - broadcasting new post');
socket.broadcast.emit('new__posts', post);
});
});
server.listen(PORT, err => {
if (err) throw new Error;
else console.log('successfully connected to posts server:', PORT);
});
export default app; | 22.882353 | 67 | 0.672237 |
f6d23592bc89a0cb69134c59b9c9e5885b435cf7 | 7,813 | js | JavaScript | src/views/dashboard/Dashboard.js | abhaykvincent/firefly | 7f50f5d5bd7dc2b433488abaca753059949d8a61 | [
"MIT"
] | null | null | null | src/views/dashboard/Dashboard.js | abhaykvincent/firefly | 7f50f5d5bd7dc2b433488abaca753059949d8a61 | [
"MIT"
] | null | null | null | src/views/dashboard/Dashboard.js | abhaykvincent/firefly | 7f50f5d5bd7dc2b433488abaca753059949d8a61 | [
"MIT"
] | null | null | null | import React, { useState,useEffect } from 'react'
import { Link,Switch, Route, useRouteMatch } from 'react-router-dom'
import $ from 'jquery'
import './dashboard.scss'
import Logo from '../../images/app-images/logo.svg'
import NewContactForm from '../contacts/NewContact.js'
const Dashboard = () => {
let match = useRouteMatch();
return (
<div className="dashboard">
<div className="sidebar">
<div className="logo"><Link to="/dashboard">
<img src={Logo} alt="" srcset=""/>
</Link></div>
<div className="quick-actions">
<Link to="/dashboard/new/contact">
<div className="action contacts">
<div className="count">
<div className="count-display">25</div>
</div>
<div className="label">Contacts</div>
<div className="add">
<div className="add-button">+</div>
</div>
</div>
</Link>
<Link to="/dashboard/new/connection">
<div className="action connections">
<div className="count">
<div className="count-display">25</div>
</div>
<div className="label">Connections</div>
<div className="add">
<div className="add-button">+</div>
</div>
</div>
</Link>
</div>
<div className="quick-displays">
<div className="quick-display future-connections">
<div className="display-label">Future Connections</div>
<div className="content">
<div className="content-label">Today</div>
<div className="content-list list">
<div className="list-item contact-name">Myra Baker</div>
<div className="list-item contact-name">Peterson</div>
</div>
<div className="see-all">See All</div>
</div>
<div className="content">
<div className="content-label">This Week</div>
<div className="content-list list">
<div className="list-item contact-name">Myra Baker</div>
<div className="list-item contact-name">Peterson</div>
</div>
<div className="see-all">See All</div>
</div>
</div>
<div className="quick-display future-connections">
<div className="display-label">Top Connections</div>
<div className="content">
<div className="content-label">Today</div>
<div className="content-list list">
<div className="list-item contact-name">Myra Baker</div>
<div className="list-item contact-name">Peterson</div>
</div>
<div className="see-all">See All</div>
</div>
<div className="content">
<div className="content-label">This Week</div>
<div className="content-list list">
<div className="list-item contact-name">Myra Baker</div>
<div className="list-item contact-name">Peterson</div>
</div>
<div className="see-all">See All</div>
</div>
</div>
</div>
</div>
<main>
<header>
<div className="search">Search...</div>
<div className="settings-panel">
<div className="notifications"></div>
<div className="profile">
<div className="profile-name">Alice Moron</div>
<div className="profile-image"></div>
</div>
</div>
</header>
<div className="main-panel">
<section className="title">
<h1>Winning Relations never stop Connections</h1>
</section>
<section className="flexible-tile">flexible-tile</section>
<section className="contacts">
<div className="section-label">Contacts</div>
<div className="content-list list">
<div className="list-item contact-name">Myra Baker</div>
<div className="list-item contact-name">Peterson</div>
</div>
</section>
<section className="timeline">
<div className="section-label">Timeline</div>
<div className="content-list list">
<div className="list-item contact-name">Myra Baker</div>
<div className="list-item contact-name">Peterson</div>
</div>
</section>
<section className="additional-panel">
<Route path={`${match.path}/new/contact`}>
<NewContact />
</Route>
<Route path={`${match.path}/new/connection`}>
<NewConnection />
</Route>
</section>
<div className="loading">
<div className="value"></div>
</div>
</div>
</main>
<div className="testing-tools">
<div className="button-test" onClick={() => {
if($('.main-panel').hasClass('with-additional-panel')){
console.log('deactivating Panel....')
$('.main-panel').removeClass('with-additional-panel');
}
else{
console.log('activating Panel....')
$('.main-panel').addClass('with-additional-panel');
}
}}>Toggle additional Panel</div>
</div>
</div>
)
}
export default Dashboard
function NewContact() {
useEffect(() => {
setTimeout(function(){
$('.main-panel').addClass('with-additional-panel');
$('.main-panel').removeClass('with-additional-panel__middleanimation');
$('.loading').removeClass('active');
}, 1000);
});
useEffect(() => {
return () => {
$('.main-panel').addClass('with-additional-panel__middleanimation');
$('.loading').addClass('active');
}
}, [])
return (
<div className="option-control change-name">
<NewContactForm/>
</div>
)
}
function NewConnection() {
useEffect(() => {
setTimeout(function(){
$('.main-panel').addClass('with-additional-panel');
$('.main-panel').removeClass('with-additional-panel__middleanimation');
$('.loading').removeClass('active');
}, 1000);
});
useEffect(() => {
return () => {
$('.main-panel').addClass('with-additional-panel__middleanimation');
$('.loading').addClass('active');
}
}, [])
return (
<div className="option-control change-name">
h1 New Connection
</div>
)
}
| 38.678218 | 84 | 0.446563 |
f6d291a92229990ec15a81339ed03f48244649ca | 958 | js | JavaScript | script.js | rajanraj5585/vftvk-Simple-Interest-Calculator | 0e0dcd9ee6d9351796e522894d19170c22fdc2c2 | [
"Apache-2.0"
] | null | null | null | script.js | rajanraj5585/vftvk-Simple-Interest-Calculator | 0e0dcd9ee6d9351796e522894d19170c22fdc2c2 | [
"Apache-2.0"
] | null | null | null | script.js | rajanraj5585/vftvk-Simple-Interest-Calculator | 0e0dcd9ee6d9351796e522894d19170c22fdc2c2 | [
"Apache-2.0"
] | null | null | null | function calculateTip()
{
var billamt = document.getElementById("billamt").value;
var serviceQual = document.getElementById("serviceQual").value;
var intrate = document.getElementById("intrate").value;
if(billamt==="" || serviceQual==0 )
{
alert("please enter values");
reture;
}
if(billamt==0 || billamt<0 )
{
alert("please enter positive no.");
reture;
}
else
{
document.getElementById("each").style.display="block";
}
var total=(billamt*serviceQual*intrate)/100;
//total=Math.round(total);
document.getElementById("totalTip").style.display="block";
document.getElementById("tip").innerHTML=total;
}
document.getElementById("totalTip").style.display="none";
document.getElementById("totalTip").style.display="none";
document.getElementById("calculate").onclick=function()
{
calculateTip();
}
| 26.611111 | 68 | 0.623173 |
f6d2bd3d31c0a494086855a40c263b5abaf58d6d | 2,463 | js | JavaScript | src/components/Footer.js | Build-Week-Water-My-Plants-033/front-end | d8a5217d557859aa28bf180bbd4b5e1db5b8f53f | [
"MIT"
] | null | null | null | src/components/Footer.js | Build-Week-Water-My-Plants-033/front-end | d8a5217d557859aa28bf180bbd4b5e1db5b8f53f | [
"MIT"
] | 3 | 2022-02-04T22:05:02.000Z | 2022-02-04T22:43:04.000Z | src/components/Footer.js | Build-Week-Water-My-Plants-033/front-end | d8a5217d557859aa28bf180bbd4b5e1db5b8f53f | [
"MIT"
] | null | null | null | import React from 'react'
import {FaGithub, FaTwitter, FaYoutube, FaLinkedin} from 'react-icons/fa';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
// Styles
const FooterContainer = styled.footer`
background: white;
display:flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
max-width: 1100px;
margin: auto;
`;
const SocialMedia = styled.section`
max-width: 1000px;
width: 100%;
`;
const SocialMediaWrap = styled.div`
display:flex;
justify-content: space-between;
align-items: center;
max-width: 1100px;
margin: 40px auto 0 auto;
@media screen and (max-width: 820px) {
flex-direction:column;
}
`;
const SocialLogo =styled(Link)`
color: green;
cursor: pointer;
text-decoration: none;
font-size: 1.5rem;
display: flex;
align-items: start;
margin-bottom: 16px;
font-weight: bold;
`;
const WebsiteRights = styled.small`
color: green;
margin-bottom: 16px;
`;
const SocialIcons = styled.div`
display:flex;
justify-content: space-between;
width: 240px;
`;
const SocialIconLink = styled.a`
color: green;
font-size: 24px;
`;
// End of Styles
const Footer = () => {
return (
<FooterContainer>
<SocialMedia>
<SocialMediaWrap>
<SocialLogo to='/'>WATER MY PLANTS</SocialLogo>
<WebsiteRights> Water My Plants © {new Date().getFullYear()} All rights reserved. </WebsiteRights>
<SocialIcons>
<SocialIconLink href="https://github.com/Build-Week-Water-My-Plants-033" target="_blank" aria-label="Github"><FaGithub/></SocialIconLink>
<SocialIconLink href="//www.twitter.com/bloomtech" target="_blank" aria-label="Twitter"><FaTwitter/></SocialIconLink>
<SocialIconLink href="//www.youtube.com/watch?v=JRXtVE5Cct8&ab_channel=BloomInstituteofTechnology" target="_blank" aria-label="Youtube"><FaYoutube/></SocialIconLink>
<SocialIconLink href="https://www.linkedin.com/school/bloominstituteoftechnology/" target="_blank" aria-label="Linkedin"><FaLinkedin/></SocialIconLink>
</SocialIcons>
</SocialMediaWrap>
</SocialMedia>
</FooterContainer>
)
}
export default Footer | 28.310345 | 193 | 0.618352 |
f6d324e6c8cd6352e4bb5d658439135ad23b1fd9 | 1,776 | js | JavaScript | Libs/scripts/npc/2041000.js | eu84567955/MapleStory-v120-Server-Eimulator | 6967d1e03ad7857d45594130135ee524783d2303 | [
"MIT"
] | 74 | 2016-12-21T07:49:49.000Z | 2022-03-30T04:52:58.000Z | Libs/scripts/npc/2041000.js | eu84567955/MapleStory-v120-Server-Eimulator | 6967d1e03ad7857d45594130135ee524783d2303 | [
"MIT"
] | 24 | 2016-12-25T15:33:36.000Z | 2021-01-16T11:21:37.000Z | Libs/scripts/npc/2041000.js | eu84567955/MapleStory-v120-Server-Eimulator | 6967d1e03ad7857d45594130135ee524783d2303 | [
"MIT"
] | 56 | 2016-12-19T10:50:43.000Z | 2022-01-23T10:11:49.000Z | /* Author: Xterminator
NPC Name: Tian
Map(s): Ludibrium: Station<Orbis> (220000110)
Description: Ludibrium Ticketing Usher
*/
var status = 0;
function start() {
status = -1;
train = cm.getEventManager("Trains");
action(1, 0, 0);
}
function action(mode, type, selection) {
status++;
if(mode == 0) {
cm.sendNext("You must have some business to take care of here, right?");
cm.dispose();
return;
}
if (status == 0) {
if(train == null) {
cm.sendNext("Event error, please restart your server for solution");
cm.dispose();
} else if(train.getProperty("entry").equals("true")) {
cm.sendYesNo("It looks like there's plenty of room for this ride. Please have your ticket ready so I can let you in, The ride will be long, but you'll get to your destination just fine. What do you think? Do you want to get on this ride?");
} else if(train.getProperty("entry").equals("false") && train.getProperty("docked").equals("true")) {
cm.sendNext("The train is getting ready for takeoff. I'm sorry, but you'll have to get on the next ride. The ride schedule is available through the usher at the ticketing booth.");
cm.dispose();
} else {
cm.sendNext("We will begin boarding 1 minutes before the takeoff. Please be patient and wait for a few minutes. Be aware that the subway will take off on time, and we stop receiving tickets 1 minute before that, so please make sure to be here on time.");
cm.dispose();
}
} else if(status == 1) {
if(!cm.haveItem(4031045)) {
cm.sendNext("Oh no ... I don't think you have the ticket with you. I can't let you in without it. Please buy the ticket at the ticketing booth.");
} else {
cm.gainItem(4031045, -1);
cm.warp(220000111, 0);
}
cm.dispose();
}
} | 41.302326 | 259 | 0.670608 |
f6d3b3a39bf3fc0374daad2a407508a57185e8fb | 1,048 | js | JavaScript | src/pages/account.js | jwsearch1/jwsearch | 274a6a071e5eb6d1b7a4be9f37063e85c5c3aaff | [
"MIT"
] | null | null | null | src/pages/account.js | jwsearch1/jwsearch | 274a6a071e5eb6d1b7a4be9f37063e85c5c3aaff | [
"MIT"
] | 10 | 2021-03-01T20:49:03.000Z | 2022-02-26T01:43:41.000Z | src/pages/account.js | alexanderfountain/jw | d3c6c546728201e43494a72c2e23119093294cd4 | [
"MIT"
] | null | null | null | import React from "react"
import { Router } from "@reach/router"
import { login, logout, isAuthenticated, getProfile } from "../utils/auth"
import { Link } from "gatsby"
const Home = ({ user }) => {
return <p>Hi, {user.name ? user.name : "friend"}!</p>
}
const Settings = () => <p>Settings</p>
const Billing = () => <p>Billing</p>
const Account = () => {
if (!isAuthenticated()) {
login()
return <p>Redirecting to login...</p>
}
const user = getProfile()
return (
<>
<nav>
<Link to="/account">Home</Link>{" "}
<Link to="/account/settings">Settings</Link>{" "}
<Link to="/account/billing">Billing</Link>{" "}
<a
href="#logout"
onClick={e => {
logout()
e.preventDefault()
}}
>
Log Out
</a>
</nav>
<Router>
<Home path="/account" user={user} />
<Settings path="/account/settings" />
<Billing path="/account/billing" />
</Router>
</>
)
}
export default Account | 23.288889 | 74 | 0.516221 |
f6d43e41b5a9f029ff14bbcb4e404da9512d7216 | 14,628 | js | JavaScript | public_html/nextcloud/lib/l10n/sq.js | uttej4u4ever/uttejpalavai | 23dd52f1d10235142a2e1117f5887ffdc7d9d9c5 | [
"CC-BY-3.0"
] | null | null | null | public_html/nextcloud/lib/l10n/sq.js | uttej4u4ever/uttejpalavai | 23dd52f1d10235142a2e1117f5887ffdc7d9d9c5 | [
"CC-BY-3.0"
] | null | null | null | public_html/nextcloud/lib/l10n/sq.js | uttej4u4ever/uttejpalavai | 23dd52f1d10235142a2e1117f5887ffdc7d9d9c5 | [
"CC-BY-3.0"
] | null | null | null | OC.L10N.register(
"lib",
{
"Cannot write into \"config\" directory!" : "Nuk shkruhet dot te drejtoria \"config\"!",
"See %s" : "Shihni %s",
"Sample configuration detected" : "U gjet formësim shembull",
"It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php" : "U pa se është kopjuar shembulli për formësime. Kjo mund të prishë instalimin tuaj dhe nuk mbulohet. Ju lutemi, lexoni dokumentimin, përpara se të kryeni ndryshime te config.php",
"%1$s and %2$s" : "%1$s dhe %2$s",
"%1$s, %2$s and %3$s" : "%1$s, %2$s dhe %3$s",
"%1$s, %2$s, %3$s and %4$s" : "%1$s, %2$s, %3$s dhe %4$s",
"%1$s, %2$s, %3$s, %4$s and %5$s" : "%1$s, %2$s, %3$s, %4$s dhe %5$s",
"Education Edition" : "Variant Edukativ",
"Enterprise bundle" : "Pakoja e ndërmarrjeve",
"Groupware bundle" : "Pako groupware",
"Social sharing bundle" : "Pakoja e ndarjes sociale",
"PHP %s or higher is required." : "Kërkohet PHP %s ose më sipër.",
"PHP with a version lower than %s is required." : "Lypset PHP me një version më të ulët se sa %s.",
"%sbit or higher PHP required." : "Lypset PHP %sbit ose më i ri.",
"The command line tool %s could not be found" : "Mjeti rresht urdhrash %s s’u gjet dot",
"The library %s is not available." : "Libraria %s s’është e passhme.",
"Server version %s or higher is required." : "Versioni i serverit kërkohet %s ose më lartë",
"Server version %s or lower is required." : "Versioni i serverit kërkohet %s ose më poshtë",
"Authentication" : "Mirëfilltësim",
"Unknown filetype" : "Lloj i panjohur skedari",
"Invalid image" : "Figurë e pavlefshme",
"Avatar image is not square" : "Imazhi avatar nuk është katror",
"today" : "sot",
"yesterday" : "dje",
"_%n day ago_::_%n days ago_" : ["%n ditë më parë","%n ditë më parë"],
"last month" : "muajin e shkuar",
"_%n month ago_::_%n months ago_" : ["%n muaj më parë","%n muaj më parë"],
"last year" : "vitin e shkuar",
"_%n year ago_::_%n years ago_" : ["%n vit më parë","%n vjet më parë"],
"_%n hour ago_::_%n hours ago_" : ["%n orë më parë","%n orë më parë"],
"_%n minute ago_::_%n minutes ago_" : ["%n minutë më parë","%n minuta më parë"],
"seconds ago" : "sekonda më parë",
"Module with ID: %s does not exist. Please enable it in your apps settings or contact your administrator." : "Moduli me ID: %s nuk ekziston. Ju lutem aktivizojeni atë në konfigurimet e aplikacionit tuaj ose kontaktoni administratorin tuaj.",
"File name is a reserved word" : "Emri i kartelës është një emër i rezervuar",
"File name contains at least one invalid character" : "Emri i kartelës përmban të paktën një shenjë të pavlefshme",
"File name is too long" : "Emri i kartelës është shumë i gjatë",
"Dot files are not allowed" : "Nuk lejohen kartela të fshehura",
"Empty filename is not allowed" : "Nuk lejohen emra të zbrazët kartelash",
"App \"%s\" cannot be installed because appinfo file cannot be read." : "Aplikacioni \"%s\" s’mund të instalohet, ngaqë s’lexohet dot kartela appinfo.",
"App \"%s\" cannot be installed because it is not compatible with this version of the server." : "Aplikacioni \"%s\" nuk mund të instalohet sepse nuk përputhet me këtë version të serverit.",
"__language_name__" : "Shqip",
"This is an automatically sent email, please do not reply." : "Ky është një email i dërguar automatikisht, ju lutem mos u përgjigjni.",
"Help" : "Ndihmë",
"Apps" : "Aplikacione",
"Settings" : "Konfigurime",
"Log out" : "Shkyçu",
"Users" : "Përdorues",
"Unknown user" : "Përdorues i panjohur",
"Additional settings" : "Konfigurime shtesë",
"%s enter the database username and name." : "%s jepni emrin e bazës së të dhënave dhe emrin e përdoruesit për të.",
"%s enter the database username." : "%s jepni emrin e përdoruesit të bazës së të dhënave.",
"%s enter the database name." : "%s jepni emrin e bazës së të dhënave.",
"%s you may not use dots in the database name" : "%s s’mund të përdorni pika te emri i bazës së të dhënave",
"You need to enter details of an existing account." : "Duhet të futni detajet e një llogarie ekzistuese.",
"Oracle connection could not be established" : "S’u vendos dot lidhje me Oracle",
"Oracle username and/or password not valid" : "Emër përdoruesi dhe/ose fjalëkalim Oracle-i i pavlefshëm",
"PostgreSQL username and/or password not valid" : "Emër përdoruesi dhe/ose fjalëkalim PostgreSQL jo të vlefshëm",
"Mac OS X is not supported and %s will not work properly on this platform. Use it at your own risk! " : "Mac OS X nuk mbulohet dhe %s s’do të funksionojë si duhet në këtë platformë. Përdoreni nën përgjegjësinë tuaj! ",
"For the best results, please consider using a GNU/Linux server instead." : "Për përfundimet më të mira, ju lutemi, më mirë konsideroni përdorimin e një shërbyesi GNU/Linux.",
"It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. This will lead to problems with files over 4 GB and is highly discouraged." : "Duket se kjo instancë %s xhiron një mjedis PHP 32-bitësh dhe open_basedir është e formësuar, te php.ini. Kjo do të shpjerë në probleme me kartela më të mëdha se 4 GB dhe këshillohet me forcë të mos ndodhë.",
"Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP." : "Ju lutemi, hiqeni rregullimin open_basedir nga php.ini juaj ose hidhuni te PHP për 64-bit.",
"Set an admin username." : "Caktoni një emër përdoruesi për përgjegjësin.",
"Set an admin password." : "Caktoni një fjalëkalim për përgjegjësin.",
"Sharing backend %s must implement the interface OCP\\Share_Backend" : "Mekanizmi i shërbimit për ndarje %s duhet të sendërtojë ndërfaqen OCP\\Share_Backend",
"Sharing backend %s not found" : "S’u gjet mekanizmi i shërbimit për ndarje %s",
"Sharing backend for %s not found" : "S’u gjet mekanizmi i shërbimit për ndarje për %s",
"Open »%s«" : "Hap»1 %s«",
"You are not allowed to share %s" : "Nuk ju lejohet ta ndani %s me të tjerët",
"Expiration date is in the past" : "Data e skadimit bie në të kaluarën",
"Click the button below to open it." : "Kliko butonin më poshtë për të hapur atë.",
"The requested share does not exist anymore" : "Ndarja e kërkuar nuk ekziston më",
"Could not find category \"%s\"" : "S’u gjet kategori \"%s\"",
"Sunday" : "E Dielë",
"Monday" : "E Hënë",
"Tuesday" : "E Martë",
"Wednesday" : "E Mërkurë",
"Thursday" : "E Enjte",
"Friday" : "E Premte",
"Saturday" : "E Shtunë",
"Sun." : "Die.",
"Mon." : "Hën.",
"Tue." : "Mar.",
"Wed." : "Mër.",
"Thu." : "Enj.",
"Fri." : "Pre.",
"Sat." : "Sht.",
"Su" : "Di",
"Mo" : "Hë",
"Tu" : "Ma",
"We" : "Ne",
"Th" : "En",
"Fr" : "Pr",
"Sa" : "Sh",
"January" : "Janar",
"February" : "Shkurt",
"March" : "Mars",
"April" : "Prill",
"May" : "Maj",
"June" : "Qershor",
"July" : "Korrik",
"August" : "Gusht",
"September" : "Shtator",
"October" : "Tetor",
"November" : "Nëntor",
"December" : "Dhjetor",
"Jan." : "Jan.",
"Feb." : "Shk.",
"Mar." : "Mar.",
"Apr." : "Pri.",
"May." : "Maj.",
"Jun." : "Qer.",
"Jul." : "Kor.",
"Aug." : "Gus.",
"Sep." : "Sht.",
"Oct." : "Tet.",
"Nov." : "Nën.",
"Dec." : "Dhj.",
"Only the following characters are allowed in a username: \"a-z\", \"A-Z\", \"0-9\", and \"_.@-'\"" : "Në një emër përdoruesi lejohen vetëm shenjat vijuese: \"a-z\", \"A-Z\", \"0-9\", dhe \"_.@-\"",
"A valid username must be provided" : "Duhet dhënë një emër i vlefshëm përdoruesi",
"Username contains whitespace at the beginning or at the end" : "Emri i përdoruesit përmban hapësirë në fillim ose në fund",
"Username must not consist of dots only" : "Emri i përdoruesit nuk duhet të përbëhet vetëm nga pika",
"A valid password must be provided" : "Duhet dhënë një fjalëkalim i vlefshëm",
"The username is already being used" : "Emri i përdoruesit është tashmë i përdorur",
"User disabled" : "Përdorues i çaktivizuar",
"Login canceled by app" : "Hyrja u anulua nga aplikacioni",
"a safe home for all your data" : "Një shtëpi e sigurt për të dhënat e tua",
"File is currently busy, please try again later" : "Kartela tani është e zënë, ju lutemi, riprovoni më vonë.",
"Application is not enabled" : "Aplikacioni s’është aktivizuar",
"Authentication error" : "Gabim mirëfilltësimi",
"Token expired. Please reload page." : "Token-i ka skaduar. Ju lutem ringarkoni faqen.",
"No database drivers (sqlite, mysql, or postgresql) installed." : "S’ka baza të dhënash (sqlite, mysql, ose postgresql) të instaluara.",
"Cannot write into \"config\" directory" : "S’shkruhet dot te drejtoria \"config\"",
"This can usually be fixed by giving the webserver write access to the config directory. See %s" : "Kjo zakonisht mund të rregullohet duke i dhënë serverit të web-it akses shkrimi tek direktoria config. Shih %s",
"Cannot write into \"apps\" directory" : "S’shkruhet dot te drejtoria \"apps\"",
"Cannot create \"data\" directory" : "Nuk mund të krijohet direktoria \"data\"",
"This can usually be fixed by giving the webserver write access to the root directory. See %s" : "Kjo zakonisht mund të rregullohet duke i dhënë serverit të web-it akses shkrimi tek direktoria rrënjë. Shih %s",
"Permissions can usually be fixed by giving the webserver write access to the root directory. See %s." : "Zakonisht lejet mund të rregullohen duke i dhënë serverit të web-it akses shkrimi tek direktoria rrënjë. Shih %s.",
"Setting locale to %s failed" : "Caktimi i gjuhës si %s dështoi",
"Please install one of these locales on your system and restart your webserver." : "Ju lutemi, instaloni te sistemi juaj një prej këtyre vendoreve dhe rinisni shërbyesin tuaj web.",
"PHP module %s not installed." : "Moduli PHP %s s’është i instaluar.",
"Please ask your server administrator to install the module." : "Ju lutemi, kërkojini përgjegjësit të shërbyesit ta instalojë modulin.",
"PHP setting \"%s\" is not set to \"%s\"." : "Rregullimi PHP \"%s\" s’është vënë si \"%s\".",
"Adjusting this setting in php.ini will make Nextcloud run again" : "Përshtatja e këtij konfigurimi në php.ini do e bëjë Nextcloud të punoj përsëri",
"mbstring.func_overload is set to \"%s\" instead of the expected value \"0\"" : "mbstring.func_overload është caktuar si \"%s\", në vend të vlerës së pritshme \"0\"",
"To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini" : "Për ta ndrequr këtë problem, caktoni për <code>mbstring.func_overload</code> vlerën <code>0</code> te php.ini juaj",
"libxml2 2.7.0 is at least required. Currently %s is installed." : "Lypset të paktën libxml2 2.7.0. Hëpërhë e instaluar është %s.",
"To fix this issue update your libxml2 version and restart your web server." : "Për të ndrequr këtë problem, përditësoni libxml2 dhe rinisni shërbyesin tuaj web.",
"PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible." : "Me sa duket, PHP-ja është rregulluar që të heqë blloqe të brendshëm dokumentimi. Kjo do t’i nxjerrë nga funksionimi disa aplikacione bazë.",
"This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Kjo ka gjasa të jetë shkaktuar nga një fshehtinë/përshpejtues i tillë si Zend OPcache ose eAccelerator.",
"PHP modules have been installed, but they are still listed as missing?" : "Modulet PHP janë instaluar, por tregohen ende sikur mungojnë?",
"Please ask your server administrator to restart the web server." : "Ju lutemi, kërkojini përgjegjësit të shërbyesit tuaj të rinisë shërbyesin web.",
"PostgreSQL >= 9 required" : "Lypset PostgreSQL >= 9",
"Please upgrade your database version" : "Ju lutemi, përmirësoni bazën tuaj të të dhënave me një version më të ri.",
"Your data directory is readable by other users" : "Direktoria juaj e të dhënave është e lexueshme nga përdorues të tjerë",
"Please change the permissions to 0770 so that the directory cannot be listed by other users." : "Ju lutemi, kalojani lejet në 0770, që kështu atë drejtori të mos mund ta shfaqin përdorues të tjerë.",
"Your data directory must be an absolute path" : "Direktoria juaj e të dhënave duhet të jetë një path absolut",
"Check the value of \"datadirectory\" in your configuration" : "Kontrolloni vlerën e \"datadirectory\" te formësimi juaj",
"Your data directory is invalid" : "Direktoria juaj e të dhënave është i pavlefshëm",
"Ensure there is a file called \".ocdata\" in the root of the data directory." : "Sigurohu që ekziston një skedar i quajtur \".ocdata\" në rrënjën e direktorisë së të dhënave.",
"Could not obtain lock type %d on \"%s\"." : "S’u mor dot lloj kyçjeje %d në \"%s\".",
"Storage unauthorized. %s" : "Depozitë e paautorizuar. %s",
"Storage incomplete configuration. %s" : "Formësim jo i plotë i depozitës. %s",
"Storage connection error. %s" : "Gabim lidhje te depozita. %s",
"Storage is temporarily not available" : "Hapsira ruajtëse nuk është në dispozicion përkohësisht",
"Storage connection timeout. %s" : "Mbarim kohe lidhjeje për depozitën. %s",
"This can usually be fixed by giving the webserver write access to the config directory" : "Zakonisht kjo mund të ndreqet duke i akorduar shërbyesit web të drejta shkrimi mbi drejtorinë e formësimeve",
"Following databases are supported: %s" : "Mbulohen bazat vijuese të të dhënave: %s",
"Following platforms are supported: %s" : "Mbulohen platformat vijuese: %s",
"Can't create or write into the data directory %s" : "S’e krijon ose s’shkruan dot te drejtoria e të dhënave %s",
"Invalid Federated Cloud ID" : "ID Federated Cloud e pavlefshme",
"Can’t increase permissions of %s" : "Nuk mund të shtohen lejet e %s",
"Files can’t be shared with delete permissions" : "Skedarët nuk mund të ndahen me leje të fshira",
"Files can’t be shared with create permissions" : "matchSkedarët nuk mund të ndahen me leje të krijuara",
"Can’t set expiration date more than %s days in the future" : "Nuk mund të caktohet data e skadimit më shumë se %s ditë në të ardhmen",
"Can't read file" : "S'lexohet dot kartela"
},
"nplurals=2; plural=(n != 1);");
| 80.373626 | 414 | 0.678562 |
f6d4f9c67225bcb8c9507465d16c787c1df7739b | 1,961 | js | JavaScript | pages/api/mindmaps/[key]/timeline.js | ksj18/hivemind | 7ab59f20ef3f471cf653be4c0a53f6076ce27d18 | [
"Apache-2.0"
] | null | null | null | pages/api/mindmaps/[key]/timeline.js | ksj18/hivemind | 7ab59f20ef3f471cf653be4c0a53f6076ce27d18 | [
"Apache-2.0"
] | null | null | null | pages/api/mindmaps/[key]/timeline.js | ksj18/hivemind | 7ab59f20ef3f471cf653be4c0a53f6076ce27d18 | [
"Apache-2.0"
] | null | null | null | import { aql } from 'arangojs'
import db, {rg} from '../../../../utils/arangoWrapper'
import { verifyIdToken } from '../../../../utils/auth/firebaseAdmin'
const skeletonGraph = `${process.env.ARANGO_SVC_MOUNT_POINT}_skeleton`
const svPrefix = `${skeletonGraph}_vertices`
function createNodeBracepath (nodeGroups) {
const pathSegments = nodeGroups.map(group => {
let pathSegment = `${group.coll}/`
const keys = group.keys
if (keys.length > 1) {
pathSegment += `{${keys.join(',')}}`
}
else {
pathSegment += keys[0]
}
return pathSegment
})
let path = '/n/'
if (pathSegments.length > 1) {
path += `{${pathSegments.join(',')}}`
}
else if (pathSegments.length === 1) {
path += pathSegments[0]
}
return path
}
const TimelineAPI = async (req, res) => {
const { token } = req.headers
try {
await verifyIdToken(token)
const { key } = req.query
let response
switch (req.method) {
case 'GET':
const svSuffix = `mindmaps.${key}`
const svid = `${svPrefix}/${svSuffix}`
let query = aql`
for v, e, p in 0..${Number.MAX_SAFE_INTEGER}
any ${svid}
graph ${skeletonGraph}
prune v.collection == 'access'
options {uniqueVertices: 'global', bfs: true}
filter v.collection not in ['access', 'links']
collect coll = v.collection into keys = v.meta.key
return {coll, keys}
`
let cursor = await db.query(query)
const groups = await cursor.all()
const path = createNodeBracepath(groups)
response = await rg.post('/event/log', {path}, {sort: 'asc'})
return res.status(response.statusCode).json(response.body)
}
}
catch (error) {
console.error(error.message, error.stack)
return res.status(401).json({ message: 'Access Denied.' })
}
}
export default TimelineAPI
| 24.822785 | 70 | 0.578786 |
f6d50d9ff93705aa7001cb7afe30426bbc486749 | 1,289 | js | JavaScript | client/src/pages/About.js | cmarshman/shoestring | 09773c63f73a4033da0be2aa1006c48710ca1869 | [
"MIT"
] | 5 | 2020-03-13T00:20:09.000Z | 2020-07-05T23:22:25.000Z | client/src/pages/About.js | cmarshman/shoestring | 09773c63f73a4033da0be2aa1006c48710ca1869 | [
"MIT"
] | 4 | 2020-03-31T23:21:57.000Z | 2020-08-05T23:57:33.000Z | client/src/pages/About.js | cmarshman/shoestring | 09773c63f73a4033da0be2aa1006c48710ca1869 | [
"MIT"
] | 4 | 2020-03-18T23:52:29.000Z | 2020-09-02T23:44:52.000Z | import React from 'react';
import Navbar from '../components/navbar';
import AppScreens from './../images/AppScreens/user-wallet.png';
import TheTeam from './../components/TheTeam';
import Playstore from './../components/Playstore';
function About() {
return (
<>
<Navbar />
<br />
<br />
<div className="tile is-ancestor">
<div className="tile is vertical is-10 is-clearfix columns" id="tile">
<div className="column">
<div className="column is-pulled-right">
<img id="appscreens" src={AppScreens} alt="appscreens" />
</div>
</div>
<div className="column is-three-fifths">
<p className="title">Meet the Team</p>
<br />
<TheTeam />
<br />
<p className="subtitle"><strong>Download our app</strong></p>
<div className="columns">
<Playstore />
</div>
</div>
</div>
</div>
<br />
</>
);
}
export default About; | 33.921053 | 86 | 0.427463 |
f6d5e15bb521f5b7c35b6f091b632fb1726e599a | 4,117 | js | JavaScript | packages/ckeditor5-image/tests/imageinsert/utils.js | groupvine/ckeditor5 | 503c623b39e9236ab8bdefc8709e4c4d26e2346d | [
"MIT"
] | 4 | 2021-04-14T02:18:26.000Z | 2022-03-03T03:28:02.000Z | packages/ckeditor5-image/tests/imageinsert/utils.js | groupvine/ckeditor5 | 503c623b39e9236ab8bdefc8709e4c4d26e2346d | [
"MIT"
] | 1 | 2020-10-08T13:07:44.000Z | 2020-10-08T13:07:44.000Z | packages/ckeditor5-image/tests/imageinsert/utils.js | groupvine/ckeditor5 | 503c623b39e9236ab8bdefc8709e4c4d26e2346d | [
"MIT"
] | 8 | 2020-11-30T10:42:34.000Z | 2021-11-17T20:26:19.000Z | /**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/* globals document */
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
import Image from '../../src/image';
import ImageUploadUI from '../../src/imageinsert/imageinsertui';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import Link from '@ckeditor/ckeditor5-link/src/link';
import CKFinder from '@ckeditor/ckeditor5-ckfinder/src/ckfinder';
import { prepareIntegrations, createLabeledInputView } from '../../src/imageinsert/utils';
describe( 'Upload utils', () => {
describe( 'prepareIntegrations()', () => {
it( 'should return "insetImageViaUrl" and "openCKFinder" integrations', async () => {
const editorElement = document.createElement( 'div' );
document.body.appendChild( editorElement );
const editor = await ClassicEditor
.create( editorElement, {
plugins: [
CKFinder,
Paragraph,
Image,
ImageUploadUI
],
image: {
insert: {
integrations: [
'insertImageViaUrl',
'openCKFinder'
]
}
}
} );
const openCKFinderExtendedView = Object.values( prepareIntegrations( editor ) )[ 1 ];
expect( openCKFinderExtendedView.class ).contains( 'ck-image-insert__ck-finder-button' );
expect( openCKFinderExtendedView.label ).to.equal( 'Insert image or file' );
expect( openCKFinderExtendedView.withText ).to.be.true;
editor.destroy();
editorElement.remove();
} );
it( 'should return only "insertImageViaUrl" integration and throw warning ' +
'for "image-upload-integrations-invalid-view" error', async () => {
const editorElement = document.createElement( 'div' );
document.body.appendChild( editorElement );
const editor = await ClassicEditor
.create( editorElement, {
plugins: [
Paragraph,
Image,
ImageUploadUI
],
image: {
insert: {
integrations: [
'insertImageViaUrl',
'openCKFinder'
]
}
}
} );
expect( Object.values( prepareIntegrations( editor ) ).length ).to.equal( 1 );
editor.destroy();
editorElement.remove();
} );
it( 'should return only "link" integration', async () => {
const editorElement = document.createElement( 'div' );
document.body.appendChild( editorElement );
const editor = await ClassicEditor
.create( editorElement, {
plugins: [
Paragraph,
Link,
Image,
ImageUploadUI
],
image: {
insert: {
integrations: [
'link'
]
}
}
} );
expect( Object.values( prepareIntegrations( editor ) ).length ).to.equal( 1 );
expect( Object.values( prepareIntegrations( editor ) )[ 0 ].label ).to.equal( 'Link' );
expect( Object.values( prepareIntegrations( editor ) )[ 0 ] ).to.be.instanceOf( ButtonView );
editor.destroy();
editorElement.remove();
} );
it( 'should return "insertImageViaUrl" integration, when no integrations were configured', async () => {
const editorElement = document.createElement( 'div' );
document.body.appendChild( editorElement );
const editor = await ClassicEditor
.create( editorElement, {
plugins: [
Paragraph,
Image,
ImageUploadUI
]
} );
expect( Object.keys( prepareIntegrations( editor ) ).length ).to.equal( 1 );
editor.destroy();
editorElement.remove();
} );
} );
describe( 'createLabeledInputView()', () => {
describe( 'image URL input view', () => {
it( 'should have placeholder', () => {
const view = createLabeledInputView( { t: val => val } );
expect( view.fieldView.placeholder ).to.equal( 'https://example.com/src/image.png' );
} );
it( 'should have info text', () => {
const view = createLabeledInputView( { t: val => val } );
expect( view.infoText ).to.match( /^Paste the image source URL/ );
} );
} );
} );
} );
| 28.79021 | 106 | 0.640758 |
f6d6216f7969c5a0fbccf246a35e9dd7ff0621b1 | 2,382 | js | JavaScript | src/consts.js | pgm-sybrdebo/Developer_Quiz | bec68867c7af8a140204f58e68f63f4a653f48da | [
"Apache-2.0"
] | null | null | null | src/consts.js | pgm-sybrdebo/Developer_Quiz | bec68867c7af8a140204f58e68f63f4a653f48da | [
"Apache-2.0"
] | null | null | null | src/consts.js | pgm-sybrdebo/Developer_Quiz | bec68867c7af8a140204f58e68f63f4a653f48da | [
"Apache-2.0"
] | null | null | null | /**
* A File with app constants
*/
export const defaultFilter = {
category: 'Docker',
difficulty: 'Easy',
limit: 1,
};
export const APP_TITLE = 'Developer Quiz - Home';
export const QUIZ_TOKEN = 'SRDvAvU4LZV210qaM714AfSoJ8y38430Kx5AELfw';
export const QUIZ_API = `https://quizapi.io/api/v1/questions`;
export const categories = ['All', 'Docker', 'SQL', 'Code', 'DevOps', 'Linux', 'CMS', 'bash'];
export const difficulty = ['Easy', 'Medium', 'Hard'];
export const amountOfQuestions = {
min: 1,
max: 20,
};
export const maxTimeMinutes = 1;
export const home = '<svg viewBox="0 1 511 511.999"><path d="M498.7 222.695c-.016-.011-.028-.027-.04-.039L289.805 13.81C280.902 4.902 269.066 0 256.477 0c-12.59 0-24.426 4.902-33.332 13.809L14.398 222.55c-.07.07-.144.144-.21.215-18.282 18.386-18.25 48.218.09 66.558 8.378 8.383 19.44 13.235 31.273 13.746.484.047.969.07 1.457.07h8.32v153.696c0 30.418 24.75 55.164 55.168 55.164h81.711c8.285 0 15-6.719 15-15V376.5c0-13.879 11.293-25.168 25.172-25.168h48.195c13.88 0 25.168 11.29 25.168 25.168V497c0 8.281 6.715 15 15 15h81.711c30.422 0 55.168-24.746 55.168-55.164V303.14h7.719c12.586 0 24.422-4.903 33.332-13.813 18.36-18.367 18.367-48.254.027-66.633zm-21.243 45.422a17.03 17.03 0 01-12.117 5.024H442.62c-8.285 0-15 6.714-15 15v168.695c0 13.875-11.289 25.164-25.168 25.164h-66.71V376.5c0-30.418-24.747-55.168-55.169-55.168H232.38c-30.422 0-55.172 24.75-55.172 55.168V482h-66.71c-13.876 0-25.169-11.29-25.169-25.164V288.14c0-8.286-6.715-15-15-15H48a13.9 13.9 0 00-.703-.032c-4.469-.078-8.66-1.851-11.8-4.996-6.68-6.68-6.68-17.55 0-24.234.003 0 .003-.004.007-.008l.012-.012L244.363 35.02A17.003 17.003 0 01256.477 30c4.574 0 8.875 1.781 12.113 5.02l208.8 208.796.098.094c6.645 6.692 6.633 17.54-.031 24.207zm0 0"/></svg>';
export const leaderboardIcon = '<svg data-id="leaderboard" viewBox="0 -8 480 480"><path d="M440 448V296H320v152h-16V216H176v232h-16V264H40v184H0v16h480v-16zm0 0M304 16v66.742A87.673 87.673 0 00320 32V16zm0 0M176 16h-16v16a87.673 87.673 0 0016 50.742V80.88zm0 0M184 80.879a70.66 70.66 0 004.168 23.945 58.926 58.926 0 0038.039 37.246c.61.168 1.234.235 1.848.387a49.083 49.083 0 0025.777-.402A58.89 58.89 0 00291.84 104.8a70.995 70.995 0 003.824-17.235c.207-2.214.336-4.437.336-6.687V32h-64V16h64V0H184zM200 16h16v16h-16zm0 0M224 152v32h32v-32a134.498 134.498 0 01-32 0zm0 0M192 200v8h96v-16h-96zm0 0"/></svg>';
| 108.272727 | 1,220 | 0.721662 |
f6d67d66e02088bf11c080d422229d80a2f00667 | 13,021 | js | JavaScript | js/http_client/v1/test/api/ProjectsV1Api.spec.js | mouradmourafiq/polyaxon-client | 5fc32b9decc7305161561d404b0127f3e900c64a | [
"Apache-2.0"
] | null | null | null | js/http_client/v1/test/api/ProjectsV1Api.spec.js | mouradmourafiq/polyaxon-client | 5fc32b9decc7305161561d404b0127f3e900c64a | [
"Apache-2.0"
] | null | null | null | js/http_client/v1/test/api/ProjectsV1Api.spec.js | mouradmourafiq/polyaxon-client | 5fc32b9decc7305161561d404b0127f3e900c64a | [
"Apache-2.0"
] | 1 | 2021-12-03T07:12:03.000Z | 2021-12-03T07:12:03.000Z | // Copyright 2018-2022 Polyaxon, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Polyaxon SDKs and REST API specification.
* Polyaxon SDKs and REST API specification.
*
* The version of the OpenAPI document: 1.18.2
* Contact: contact@polyaxon.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', process.cwd()+'/src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require(process.cwd()+'/src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.PolyaxonSdk);
}
}(this, function(expect, PolyaxonSdk) {
'use strict';
var instance;
beforeEach(function() {
instance = new PolyaxonSdk.ProjectsV1Api();
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('ProjectsV1Api', function() {
describe('archiveProject', function() {
it('should call archiveProject successfully', function(done) {
//uncomment below and update the code to test archiveProject
//instance.archiveProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('bookmarkProject', function() {
it('should call bookmarkProject successfully', function(done) {
//uncomment below and update the code to test bookmarkProject
//instance.bookmarkProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('createProject', function() {
it('should call createProject successfully', function(done) {
//uncomment below and update the code to test createProject
//instance.createProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('createVersion', function() {
it('should call createVersion successfully', function(done) {
//uncomment below and update the code to test createVersion
//instance.createVersion(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('createVersionStage', function() {
it('should call createVersionStage successfully', function(done) {
//uncomment below and update the code to test createVersionStage
//instance.createVersionStage(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('deleteProject', function() {
it('should call deleteProject successfully', function(done) {
//uncomment below and update the code to test deleteProject
//instance.deleteProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('deleteVersion', function() {
it('should call deleteVersion successfully', function(done) {
//uncomment below and update the code to test deleteVersion
//instance.deleteVersion(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('disableProjectCI', function() {
it('should call disableProjectCI successfully', function(done) {
//uncomment below and update the code to test disableProjectCI
//instance.disableProjectCI(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('enableProjectCI', function() {
it('should call enableProjectCI successfully', function(done) {
//uncomment below and update the code to test enableProjectCI
//instance.enableProjectCI(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('getProject', function() {
it('should call getProject successfully', function(done) {
//uncomment below and update the code to test getProject
//instance.getProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('getProjectActivities', function() {
it('should call getProjectActivities successfully', function(done) {
//uncomment below and update the code to test getProjectActivities
//instance.getProjectActivities(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('getProjectSettings', function() {
it('should call getProjectSettings successfully', function(done) {
//uncomment below and update the code to test getProjectSettings
//instance.getProjectSettings(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('getProjectStats', function() {
it('should call getProjectStats successfully', function(done) {
//uncomment below and update the code to test getProjectStats
//instance.getProjectStats(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('getVersion', function() {
it('should call getVersion successfully', function(done) {
//uncomment below and update the code to test getVersion
//instance.getVersion(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('getVersionStages', function() {
it('should call getVersionStages successfully', function(done) {
//uncomment below and update the code to test getVersionStages
//instance.getVersionStages(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('listArchivedProjects', function() {
it('should call listArchivedProjects successfully', function(done) {
//uncomment below and update the code to test listArchivedProjects
//instance.listArchivedProjects(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('listBookmarkedProjects', function() {
it('should call listBookmarkedProjects successfully', function(done) {
//uncomment below and update the code to test listBookmarkedProjects
//instance.listBookmarkedProjects(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('listProjectNames', function() {
it('should call listProjectNames successfully', function(done) {
//uncomment below and update the code to test listProjectNames
//instance.listProjectNames(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('listProjects', function() {
it('should call listProjects successfully', function(done) {
//uncomment below and update the code to test listProjects
//instance.listProjects(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('listVersionNames', function() {
it('should call listVersionNames successfully', function(done) {
//uncomment below and update the code to test listVersionNames
//instance.listVersionNames(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('listVersions', function() {
it('should call listVersions successfully', function(done) {
//uncomment below and update the code to test listVersions
//instance.listVersions(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('patchProject', function() {
it('should call patchProject successfully', function(done) {
//uncomment below and update the code to test patchProject
//instance.patchProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('patchProjectSettings', function() {
it('should call patchProjectSettings successfully', function(done) {
//uncomment below and update the code to test patchProjectSettings
//instance.patchProjectSettings(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('patchVersion', function() {
it('should call patchVersion successfully', function(done) {
//uncomment below and update the code to test patchVersion
//instance.patchVersion(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('restoreProject', function() {
it('should call restoreProject successfully', function(done) {
//uncomment below and update the code to test restoreProject
//instance.restoreProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('transferVersion', function() {
it('should call transferVersion successfully', function(done) {
//uncomment below and update the code to test transferVersion
//instance.transferVersion(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('unbookmarkProject', function() {
it('should call unbookmarkProject successfully', function(done) {
//uncomment below and update the code to test unbookmarkProject
//instance.unbookmarkProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('updateProject', function() {
it('should call updateProject successfully', function(done) {
//uncomment below and update the code to test updateProject
//instance.updateProject(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('updateProjectSettings', function() {
it('should call updateProjectSettings successfully', function(done) {
//uncomment below and update the code to test updateProjectSettings
//instance.updateProjectSettings(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('updateVersion', function() {
it('should call updateVersion successfully', function(done) {
//uncomment below and update the code to test updateVersion
//instance.updateVersion(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
describe('uploadProjectArtifact', function() {
it('should call uploadProjectArtifact successfully', function(done) {
//uncomment below and update the code to test uploadProjectArtifact
//instance.uploadProjectArtifact(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
});
}));
| 34.44709 | 92 | 0.591045 |
f6d6e150e9bd3c18198f3331dbce14f790313511 | 942 | js | JavaScript | PCA_lib/documentation/html/search/variables_12.js | Anny-Moon/PCA | eb82538c320a01e753351c39be5ec848a00530d6 | [
"Apache-2.0"
] | null | null | null | PCA_lib/documentation/html/search/variables_12.js | Anny-Moon/PCA | eb82538c320a01e753351c39be5ec848a00530d6 | [
"Apache-2.0"
] | null | null | null | PCA_lib/documentation/html/search/variables_12.js | Anny-Moon/PCA | eb82538c320a01e753351c39be5ec848a00530d6 | [
"Apache-2.0"
] | 1 | 2019-06-25T07:54:21.000Z | 2019-06-25T07:54:21.000Z | var searchData=
[
['s',['s',['../class_p_c_a_1_1_polymer_scaling_1_1_scaling_param.html#a56665ea41c05361e104d28e6dd440f9b',1,'PCA::PolymerScaling::ScalingParam']]],
['square',['square',['../scaling_movie_8m.html#ac4497e2392e94d73eff636b15d8defc4',1,'square(): scalingMovie.m'],['../scaling_picture_8m.html#ac4497e2392e94d73eff636b15d8defc4',1,'square(): scalingPicture.m']]],
['string',['string',['../scaling_movie_8m.html#a1f352d323788a945d0cae6a0905e6635',1,'string(): scalingMovie.m'],['../scaling_movie__new_8m.html#a1f352d323788a945d0cae6a0905e6635',1,'string(): scalingMovie_new.m'],['../scaling_picture_8m.html#a338951b7e7607b65262fb051e7804d91',1,'string(): scalingPicture.m'],['../scaling_picture__new_8m.html#a1f352d323788a945d0cae6a0905e6635',1,'string(): scalingPicture_new.m']]],
['sweeps',['sweeps',['../scaling_picture_8m.html#a1702adc370b9c1923d62b231a219b90d',1,'scalingPicture.m']]]
];
| 117.75 | 438 | 0.768577 |
f6d6f605ab412c17dfda3c18f82acc4241c92dc8 | 44,588 | js | JavaScript | src/webui/app/controllers.js | djdhm/mesos | c67d6b716dfd197ae39089726814fd97dbaf9655 | [
"Apache-2.0"
] | null | null | null | src/webui/app/controllers.js | djdhm/mesos | c67d6b716dfd197ae39089726814fd97dbaf9655 | [
"Apache-2.0"
] | 19 | 2018-09-26T14:18:14.000Z | 2021-11-30T17:29:23.000Z | src/webui/app/controllers.js | djdhm/mesos | c67d6b716dfd197ae39089726814fd97dbaf9655 | [
"Apache-2.0"
] | 7 | 2020-01-29T15:31:06.000Z | 2021-08-22T22:24:59.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function() {
'use strict';
var mesosApp = angular.module('mesos');
function hasSelectedText() {
if (window.getSelection) { // All browsers except IE before version 9.
var range = window.getSelection();
return range.toString().length > 0;
}
return false;
}
// Returns the URL prefix for an agent, there are two cases
// to consider:
//
// (1) Some endpoints for the agent process itself require
// the agent PID.name (processId) in the path, this is
// to ensure that the webui works correctly when running
// against mesos-local or other instances of multiple agents
// running within the same "host:port":
//
// //hostname:port/slave(1)
// //hostname:port/slave(2)
// ...
//
// (2) Some endpoints for other components in the agent
// do not require the agent PID.name in the path, since
// a single endpoint serves multiple agents within the
// same process. In this case we just return:
//
// //hostname:port
//
// Note that there are some clashing issues in mesos-local
// (e.g., hosting '/slave/log' for each agent log, we don't
// namespace metrics within '/metrics/snapshot', etc).
function agentURLPrefix(agent, includeProcessId) {
var port = agent.pid.substring(agent.pid.lastIndexOf(':') + 1);
var processId = agent.pid.substring(0, agent.pid.indexOf('@'));
var url = '//' + agent.hostname + ':' + port;
if (includeProcessId) {
url += '/' + processId;
}
return url;
}
function leadingMasterURLPrefix(leader_info) {
if (leader_info) {
return '//' + leader_info.hostname + ':' + leader_info.port;
}
// If we do not have `leader_info` available (e.g. the first
// time we are retrieving state), fallback to the current master.
return '';
}
// Invokes the pailer, building the endpoint URL with the specified urlPrefix
// and path.
function pailer(urlPrefix, path, window_title) {
var url = urlPrefix + '/files/read?path=' + path;
// The randomized `storageKey` is removed from `localStorage` once the
// pailer window loads the URL into its `sessionStorage`, therefore
// the probability of collisions is low and we do not use a uuid.
var storageKey = Math.random().toString(36).substr(2, 8);
// Store the target URL in `localStorage` which is
// accessed by the pailer window when opened.
localStorage.setItem(storageKey, url);
var pailer =
window.open('app/shared/pailer.html', storageKey, 'width=580px, height=700px');
// Need to use window.onload instead of document.ready to make
// sure the title doesn't get overwritten.
pailer.onload = function() {
pailer.document.title = window_title;
};
}
function updateInterval(num_agents) {
// TODO(bmahler): Increasing the update interval for large clusters
// is done purely to mitigate webui performance issues. Ideally we can
// keep a consistently fast rate for updating statistical information.
// For the full system state updates, it may make sense to break
// it up using pagination and/or splitting the endpoint.
if (num_agents < 500) {
return 10000;
} else if (num_agents < 1000) {
return 20000;
} else if (num_agents < 5000) {
return 60000;
} else if (num_agents < 10000) {
return 120000;
} else if (num_agents < 15000) {
return 240000;
} else if (num_agents < 20000) {
return 480000;
} else {
return 960000;
}
}
// Set the task sandbox directory for use by the WebUI.
function setTaskSandbox(executor) {
_.each(
[executor.tasks, executor.queued_tasks, executor.completed_tasks],
function(tasks) {
_.each(tasks, function(task) {
if (executor.type === 'DEFAULT') {
task.directory = executor.directory + '/tasks/' + task.id;
} else {
task.directory = executor.directory;
}
});
});
}
// Update the outermost scope with the new state.
function updateState($scope, $timeout, state) {
// Don't do anything if the state hasn't changed.
if ($scope.state == state) {
return true; // Continue polling.
}
$scope.state = state;
// A cluster is named if the state returns a non-empty string name.
// Track whether this cluster is named in a Boolean for display purposes.
$scope.clusterNamed = !!$scope.state.cluster;
// Check for selected text, and allow up to 20 seconds to pass before
// potentially wiping the user highlighted text.
// TODO(bmahler): This is to avoid the annoying loss of highlighting when
// the tables update. Once we can have tighter granularity control on the
// angular.js dynamic table updates, we should remove this hack.
$scope.time_since_update += $scope.delay;
if (hasSelectedText() && $scope.time_since_update < 20000) {
return true;
}
// Pass this pollTime to all relativeDate calls to make them all relative to
// the same moment in time.
//
// If relativeDate is called without a reference time, it instantiates a new
// Date to be the reference. Since there can be hundreds of dates on a given
// page, they would all be relative to slightly different moments in time.
$scope.pollTime = new Date();
// Update the maps.
$scope.agents = {};
$scope.frameworks = {};
$scope.offers = {};
$scope.completed_frameworks = {};
$scope.active_tasks = [];
$scope.unreachable_tasks = [];
$scope.completed_tasks = [];
// Update the stats.
$scope.cluster = $scope.state.cluster;
$scope.total_cpus = 0;
$scope.total_gpus = 0;
$scope.total_mem = 0;
$scope.total_disk = 0;
$scope.total_network_bandwidth = 0;
$scope.used_cpus = 0;
$scope.used_gpus = 0;
$scope.used_mem = 0;
$scope.used_disk = 0;
$scope.used_network_bandwidth = 0;
$scope.offered_cpus = 0;
$scope.offered_gpus = 0;
$scope.offered_mem = 0;
$scope.offered_disk = 0;
$scope.offered_network_bandwidth = 0;
$scope.activated_agents = $scope.state.activated_slaves;
$scope.deactivated_agents = $scope.state.deactivated_slaves;
$scope.unreachable_agents = $scope.state.unreachable_slaves;
_.each($scope.state.slaves, function(agent) {
// Calculate the agent "state" from activation and drain state.
if (!agent.deactivated) {
agent.state = "Active";
} else if (agent.drain_info) {
// Transform the drain state so only the first letter is capitalized.
var s = agent.drain_info.state;
agent.state = s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
} else {
agent.state = "Deactivated";
}
$scope.agents[agent.id] = agent;
$scope.total_cpus += agent.resources.cpus;
$scope.total_gpus += agent.resources.gpus;
$scope.total_mem += agent.resources.mem;
$scope.total_disk += agent.resources.disk;
$scope.total_network_bandwidth += agent.resources.network_bandwidth;
});
var setTaskMetadata = function(task) {
if (!task.executor_id) {
task.executor_id = task.id;
}
if (task.statuses.length > 0) {
var firstStatus = task.statuses[0];
if (!isStateTerminal(firstStatus.state)) {
task.start_time = firstStatus.timestamp * 1000;
}
var lastStatus = task.statuses[task.statuses.length - 1];
if (isStateTerminal(task.state)) {
task.finish_time = lastStatus.timestamp * 1000;
}
task.healthy = lastStatus.healthy;
}
};
var isStateTerminal = function(taskState) {
var terminalStates = [
'TASK_ERROR',
'TASK_FAILED',
'TASK_FINISHED',
'TASK_KILLED',
'TASK_LOST',
'TASK_DROPPED',
'TASK_GONE',
'TASK_GONE_BY_OPERATOR'
];
return terminalStates.indexOf(taskState) > -1;
};
_.each($scope.state.frameworks, function(framework) {
$scope.frameworks[framework.id] = framework;
// Fill in the `roles` field for non-MULTI_ROLE schedulers.
if (framework.role) {
framework.roles = [framework.role];
}
_.each(framework.offers, function(offer) {
$scope.offers[offer.id] = offer;
$scope.offered_cpus += offer.resources.cpus;
$scope.offered_gpus += offer.resources.gpus;
$scope.offered_mem += offer.resources.mem;
$scope.offered_disk += offer.resources.disk;
$scope.offered_network_bandwidth += offer.resources.network_bandwidth;
offer.framework_name = $scope.frameworks[offer.framework_id].name;
offer.hostname = $scope.agents[offer.slave_id].hostname;
});
$scope.used_cpus += framework.resources.cpus;
$scope.used_gpus += framework.resources.gpus;
$scope.used_mem += framework.resources.mem;
$scope.used_disk += framework.resources.disk;
$scope.used_network_bandwidth += framework.resources.network_bandwidth;
framework.cpus_share = 0;
if ($scope.total_cpus > 0) {
framework.cpus_share = framework.used_resources.cpus / $scope.total_cpus;
}
framework.gpus_share = 0;
if ($scope.total_gpus > 0) {
framework.gpus_share = framework.used_resources.gpus / $scope.total_gpus;
}
framework.mem_share = 0;
if ($scope.total_mem > 0) {
framework.mem_share = framework.used_resources.mem / $scope.total_mem;
}
framework.disk_share = 0;
if ($scope.total_disk > 0) {
framework.disk_share = framework.used_resources.disk / $scope.total_disk;
}
framework.network_bandwidth_share = 0;
if ($scope.total_network_bandwidth > 0) {
framework.network_bandwidth_share = framework.used_resources.network_bandwidth / $scope.total_network_bandwidth;
}
framework.max_share = Math.max(
framework.cpus_share,
framework.gpus_share,
framework.mem_share,
framework.disk_share,
framework.network_bandwidth_share);
// If the executor ID is empty, this is a command executor with an
// internal executor ID generated from the task ID.
// TODO(brenden): Remove this once
// https://issues.apache.org/jira/browse/MESOS-527 is fixed.
_.each(framework.tasks, setTaskMetadata);
_.each(framework.unreachable_tasks, setTaskMetadata);
_.each(framework.completed_tasks, setTaskMetadata);
// TODO(bmahler): Add per-framework metrics to the master so that
// the webui does not need to loop over all tasks!
framework.running_tasks = 0;
framework.staging_tasks = 0;
framework.starting_tasks = 0;
framework.killing_tasks = 0;
_.each(framework.tasks, function(task) {
switch (task.state) {
case "TASK_STAGING": framework.staging_tasks += 1; break;
case "TASK_STARTING": framework.starting_tasks += 1; break;
case "TASK_RUNNING": framework.running_tasks += 1; break;
case "TASK_KILLING": framework.killing_tasks += 1; break;
default: break;
}
})
framework.finished_tasks = 0;
framework.killed_tasks = 0;
framework.failed_tasks = 0;
framework.lost_tasks = 0;
_.each(framework.completed_tasks, function(task) {
switch (task.state) {
case "TASK_FINISHED": framework.finished_tasks += 1; break;
case "TASK_KILLED": framework.killed_tasks += 1; break;
case "TASK_FAILED": framework.failed_tasks += 1; break;
case "TASK_LOST": framework.lost_tasks += 1; break;
default: break;
}
})
$scope.active_tasks = $scope.active_tasks.concat(framework.tasks);
$scope.unreachable_tasks = $scope.unreachable_tasks.concat(framework.unreachable_tasks);
$scope.completed_tasks =
$scope.completed_tasks.concat(framework.completed_tasks);
});
_.each($scope.state.completed_frameworks, function(framework) {
$scope.completed_frameworks[framework.id] = framework;
// Fill in the `roles` field for non-MULTI_ROLE schedulers.
if (framework.role) {
framework.roles = [framework.role];
}
_.each(framework.completed_tasks, setTaskMetadata);
});
$scope.used_cpus -= $scope.offered_cpus;
$scope.used_gpus -= $scope.offered_gpus;
$scope.used_mem -= $scope.offered_mem;
$scope.used_disk -= $scope.offered_disk;
$scope.used_network_bandwidth -= $scope.offered_network_bandwidth;
$scope.idle_cpus = $scope.total_cpus - ($scope.offered_cpus + $scope.used_cpus);
$scope.idle_gpus = $scope.total_gpus - ($scope.offered_gpus + $scope.used_gpus);
$scope.idle_mem = $scope.total_mem - ($scope.offered_mem + $scope.used_mem);
$scope.idle_disk = $scope.total_disk - ($scope.offered_disk + $scope.used_disk);
$scope.idle_network_bandwidth = $scope.total_network_bandwidth - ($scope.offered_network_bandwidth + $scope.used_network_bandwidth);
$scope.time_since_update = 0;
$scope.$broadcast('state_updated');
return true; // Continue polling.
}
// Update the outermost scope with the metrics/snapshot endpoint.
function updateMetrics($scope, $timeout, metrics) {
$scope.staging_tasks = metrics['master/tasks_staging'];
$scope.starting_tasks = metrics['master/tasks_starting'];
$scope.running_tasks = metrics['master/tasks_running'];
$scope.killing_tasks = metrics['master/tasks_killing'];
$scope.finished_tasks = metrics['master/tasks_finished'];
$scope.killed_tasks = metrics['master/tasks_killed'];
$scope.failed_tasks = metrics['master/tasks_failed'];
$scope.lost_tasks = metrics['master/tasks_lost'];
return true; // Continue polling.
}
// Main controller that can be used to handle "global" events. E.g.,:
// $scope.$on('$afterRouteChange', function() { ...; });
//
// In addition, the MainCtrl encapsulates the "view", allowing the
// active controller/view to easily access anything in scope (e.g.,
// the state).
mesosApp.controller('MainCtrl', [
'$scope', '$http', '$location', '$timeout', '$modal',
function($scope, $http, $location, $timeout, $modal) {
$scope.doneLoading = true;
// Adding bindings into scope so that they can be used from within
// AngularJS expressions.
$scope._ = _;
$scope.stringify = JSON.stringify;
$scope.encodeURIComponent = encodeURIComponent;
$scope.basename = function(path) {
// This is only a basic version of basename that handles the cases we care
// about, rather than duplicating unix basename functionality perfectly.
if (path === '/') {
return path; // Handle '/'.
}
// Strip a trailing '/' if present.
if (path.length > 0 && path.lastIndexOf('/') === (path.length - 1)) {
path = path.substr(0, path.length - 1);
}
return path.substr(path.lastIndexOf('/') + 1);
};
$scope.$location = $location;
$scope.delay = 2000;
$scope.retry = 0;
$scope.time_since_update = 0;
$scope.isErrorModalOpen = false;
// Ordered Array of path => activeTab mappings. On successful route changes,
// the `pathRegexp` values are matched against the current route. The first
// match will be used to set the active navbar tab.
var NAVBAR_PATHS = [
{
pathRegexp: /^\/agents/,
tab: 'agents'
},
{
pathRegexp: /^\/frameworks/,
tab: 'frameworks'
},
{
pathRegexp: /^\/roles/,
tab: 'roles'
},
{
pathRegexp: /^\/offers/,
tab: 'offers'
},
{
pathRegexp: /^\/maintenance/,
tab: 'maintenance'
}
];
// Set the active tab on route changes according to NAVBAR_PATHS.
$scope.$on('$routeChangeSuccess', function(event, current) {
var path = current.$$route.originalPath;
// Use _.some so the loop can exit on the first `pathRegexp` match.
var matched = _.some(NAVBAR_PATHS, function(nav) {
if (path.match(nav.pathRegexp)) {
$scope.navbarActiveTab = nav.tab;
return true;
}
});
if (!matched) $scope.navbarActiveTab = null;
});
var popupErrorModal = function() {
if ($scope.delay >= 128000) {
$scope.delay = 2000;
} else {
$scope.delay = $scope.delay * 2;
}
$scope.isErrorModalOpen = true;
var errorModal = $modal.open({
controller: function($scope, $modalInstance, scope) {
// Give the modal reference to the root scope so it can access the
// `retry` variable. It needs to be passed by reference, not by
// value, since its value is changed outside the scope of the
// modal.
$scope.rootScope = scope;
},
resolve: {
scope: function() { return $scope; }
},
templateUrl: "template/dialog/master-gone.html"
});
// Make it such that everytime we hide the error-modal, we stop the
// countdown and restart the polling.
errorModal.result.then(function() {
$scope.isErrorModalOpen = false;
if ($scope.countdown != null) {
if ($timeout.cancel($scope.countdown)) {
// Restart since they cancelled the countdown.
$scope.delay = 2000;
}
}
// Start polling again, but do it asynchronously (and wait at
// least a second because otherwise the error-modal won't get
// properly shown).
$timeout(pollState, 1000);
$timeout(pollMetrics, 1000);
});
$scope.retry = $scope.delay;
var countdown = function() {
if ($scope.retry === 0) {
errorModal.close();
} else {
$scope.retry = $scope.retry - 1000;
$scope.countdown = $timeout(countdown, 1000);
}
};
countdown();
};
var pollState = function() {
// When the current master is not the leader, the request is redirected to
// the leading master automatically. This would cause a CORS error if we
// use XMLHttpRequest here. To avoid the CORS error, we use JSONP as a
// workaround. Please refer to MESOS-5911 for further details.
//
// Note that `$scope.state` will not be defined during the first
// request.
var leader_info = $scope.state ? $scope.state.leader_info : null;
$http.jsonp(leadingMasterURLPrefix(leader_info) +
'/master/state?jsonp=JSON_CALLBACK')
.success(function(response) {
if (updateState($scope, $timeout, response)) {
$scope.delay = updateInterval(_.size($scope.agents));
$timeout(pollState, $scope.delay);
}
})
.error(function() {
if ($scope.isErrorModalOpen === false) {
popupErrorModal();
}
});
};
var pollMetrics = function() {
var leader_info = $scope.state ? $scope.state.leader_info : null;
$http.jsonp(leadingMasterURLPrefix(leader_info) +
'/metrics/snapshot?jsonp=JSON_CALLBACK')
.success(function(response) {
if (updateMetrics($scope, $timeout, response)) {
$scope.delay = updateInterval(_.size($scope.agents));
$timeout(pollMetrics, $scope.delay);
}
})
.error(function(message, code) {
if ($scope.isErrorModalOpen === false) {
// If return code is 401 or 403 the user is unauthorized to reach
// the endpoint, which is not a connection error.
if ([401, 403].indexOf(code) < 0) {
popupErrorModal();
}
}
});
};
pollState();
pollMetrics();
}]);
mesosApp.controller('HomeCtrl', function($scope) {
var hostname = $scope.$location.host() + ':' + $scope.$location.port();
var update = function() {
$scope.streamLogs = function(_$event) {
pailer(
leadingMasterURLPrefix($scope.state.leader_info),
'/master/log',
'Mesos Master (' + hostname + ')');
};
// Note that we always show the leader's log, which is why
// we examine the leader's flags to determine whether the
// log file is attached.
$scope.log_file_attached =
$scope.state.flags.external_log_file || $scope.state.flags.log_dir;
$scope.leader_url_prefix =
leadingMasterURLPrefix($scope.state.leader_info);
};
if ($scope.state) {
update();
}
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
});
mesosApp.controller('FrameworksCtrl', function() {});
mesosApp.controller('RolesCtrl', function($scope, $http) {
var update = function() {
$http.jsonp(leadingMasterURLPrefix($scope.state.leader_info) +
'/master/roles?jsonp=JSON_CALLBACK')
.success(function(response) {
$scope.roles = response;
})
.error(function() {
if ($scope.isErrorModalOpen === false) {
popupErrorModal();
}
});
};
if ($scope.state) {
update();
}
$scope.show_weight = false;
$scope.show_framework_count = false;
$scope.show_offered = false;
$scope.show_allocated = true;
$scope.show_reserved = true;
$scope.show_quota_consumption = true;
$scope.show_quota_guarantee = false;
$scope.show_quota_limit = true;
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
});
mesosApp.controller('OffersCtrl', function() {});
mesosApp.controller('MaintenanceCtrl', function($scope, $http) {
var update = function() {
$http.jsonp(leadingMasterURLPrefix($scope.state.leader_info) +
'/master/maintenance/schedule?jsonp=JSON_CALLBACK')
.success(function(response) {
$scope.maintenance = response;
})
.error(function() {
if ($scope.isErrorModalOpen === false) {
popupErrorModal();
}
});
};
if ($scope.state) {
update();
}
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
});
mesosApp.controller('FrameworkCtrl', function($scope, $routeParams) {
var update = function() {
if ($routeParams.id in $scope.completed_frameworks) {
$scope.framework = $scope.completed_frameworks[$routeParams.id];
$scope.alert_message = 'This framework has terminated!';
$('#alert').show();
$('#framework').show();
} else if ($routeParams.id in $scope.frameworks) {
$scope.framework = $scope.frameworks[$routeParams.id];
$('#framework').show();
} else {
$scope.alert_message = 'No framework found with ID: ' + $routeParams.id;
$('#alert').show();
}
};
if ($scope.state) {
update();
}
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
});
mesosApp.controller('AgentsCtrl', function() {});
mesosApp.controller('AgentCtrl', [
'$scope', '$routeParams', '$http', '$q', '$timeout', 'top',
function($scope, $routeParams, $http, $q, $timeout, $top) {
$scope.agent_id = $routeParams.agent_id;
var update = function() {
if (!($routeParams.agent_id in $scope.agents)) {
$scope.alert_message = 'No agent found with ID: ' + $routeParams.agent_id;
$('#alert').show();
return;
}
var agent = $scope.agents[$routeParams.agent_id];
$scope.streamLogs = function(_$event) {
pailer(agentURLPrefix(agent, false), '/slave/log', 'Mesos Agent (' + agent.id + ')');
};
// Set up polling for the monitor if this is the first update.
if (!$top.started()) {
$top.start(
agentURLPrefix(agent, true) + '/monitor/statistics?jsonp=JSON_CALLBACK',
$scope
);
}
$http.jsonp(agentURLPrefix(agent, true) + '/state?jsonp=JSON_CALLBACK')
.success(function(response) {
$scope.state = response;
$scope.agent = {};
$scope.agent.frameworks = {};
$scope.agent.completed_frameworks = {};
$scope.agent.resource_providers = {};
$scope.agent.url_prefix = agentURLPrefix(agent, false);
// The agent attaches a "/slave/log" file when either
// of these flags are set.
$scope.agent.log_file_attached = $scope.state.external_log_file || $scope.state.log_dir;
$scope.agent.drain_config = response.drain_config;
if (response.estimated_drain_start_time_seconds && response.drain_config.max_grace_period) {
$scope.agent.estimated_drain_end_time_seconds =
response.estimated_drain_start_time_seconds +
(response.drain_config.max_grace_period.nanoseconds / 1000000000);
}
// Convert the reserved resources map into an array for inclusion
// in an `ng-repeat` table.
$scope.agent.reserved_resources_as_array = _($scope.state.reserved_resources)
.map(function(reservation, role) {
reservation.role = role;
return reservation;
});
// Compute resource provider information.
_.each($scope.state.resource_providers, function(provider) {
// Store a summarized representation of the resource provider's
// total scalar resources in the `total_resources` field; the full
// original data is available under `total_resources_full`.
provider.total_resources_full = _.clone(provider.total_resources);
// provider.total_resources = {};
_.each(provider.total_resources_full, function(resource) {
if (resource.type != "SCALAR") {
return;
}
if (!provider.total_resources[resource.name]) {
provider.total_resources[resource.name] = 0;
}
provider.total_resources[resource.name] += resource.scalar.value;
});
$scope.agent.resource_providers[provider.resource_provider_info.id.value] = provider;
});
// Computes framework stats by setting new attributes on the 'framework'
// object.
function computeFrameworkStats(framework) {
framework.num_tasks = 0;
framework.cpus = 0;
framework.gpus = 0;
framework.mem = 0;
framework.disk = 0;
framework.network_bandwidth = 0;
_.each(framework.executors, function(executor) {
framework.num_tasks += _.size(executor.tasks);
framework.cpus += executor.resources.cpus;
framework.gpus += executor.resources.gpus;
framework.mem += executor.resources.mem;
framework.disk += executor.resources.disk;
framework.network_bandwidth += executor.resources.network_bandwidth;
});
}
// Compute framework stats and update agent's mappings of those
// frameworks.
_.each($scope.state.frameworks, function(framework) {
$scope.agent.frameworks[framework.id] = framework;
computeFrameworkStats(framework);
// Fill in the `roles` field for non-MULTI_ROLE schedulers.
if (framework.role) {
framework.roles = [framework.role];
}
});
_.each($scope.state.completed_frameworks, function(framework) {
$scope.agent.completed_frameworks[framework.id] = framework;
computeFrameworkStats(framework);
// Fill in the `roles` field for non-MULTI_ROLE schedulers.
if (framework.role) {
framework.roles = [framework.role];
}
});
$scope.state.allocated_resources = {};
$scope.state.allocated_resources.cpus = 0;
$scope.state.allocated_resources.gpus = 0;
$scope.state.allocated_resources.mem = 0;
$scope.state.allocated_resources.disk = 0;
$scope.state.allocated_resources.network_bandwidth = 0;
// Currently the agent does not expose the total allocated
// resources across all frameworks, so we sum manually.
_.each($scope.state.frameworks, function(framework) {
$scope.state.allocated_resources.cpus += framework.cpus;
$scope.state.allocated_resources.gpus += framework.gpus;
$scope.state.allocated_resources.mem += framework.mem;
$scope.state.allocated_resources.disk += framework.disk;
$scope.state.allocated_resources.network_bandwidth += framework.network_bandwidth;
});
$('#agent').show();
})
.error(function(reason) {
$scope.alert_message = 'Failed to get agent usage / state: ' + reason;
$('#alert').show();
});
$http.jsonp(agentURLPrefix(agent, false) + '/metrics/snapshot?jsonp=JSON_CALLBACK')
.success(function (response) {
$scope.staging_tasks = response['slave/tasks_staging'];
$scope.starting_tasks = response['slave/tasks_starting'];
$scope.running_tasks = response['slave/tasks_running'];
$scope.killing_tasks = response['slave/tasks_killing'];
$scope.finished_tasks = response['slave/tasks_finished'];
$scope.killed_tasks = response['slave/tasks_killed'];
$scope.failed_tasks = response['slave/tasks_failed'];
$scope.lost_tasks = response['slave/tasks_lost'];
})
.error(function(reason) {
$scope.alert_message = 'Failed to get agent metrics: ' + reason;
$('#alert').show();
});
};
if ($scope.state) {
update();
}
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
}]);
mesosApp.controller('AgentFrameworkCtrl', [
'$scope', '$routeParams', '$http', '$q', '$timeout', 'top',
function($scope, $routeParams, $http, $q, $timeout, $top) {
$scope.agent_id = $routeParams.agent_id;
$scope.framework_id = $routeParams.framework_id;
var update = function() {
if (!($routeParams.agent_id in $scope.agents)) {
$scope.alert_message = 'No agent found with ID: ' + $routeParams.agent_id;
$('#alert').show();
return;
}
var agent = $scope.agents[$routeParams.agent_id];
// Set up polling for the monitor if this is the first update.
if (!$top.started()) {
$top.start(
agentURLPrefix(agent, true) + '/monitor/statistics?jsonp=JSON_CALLBACK',
$scope
);
}
$http.jsonp(agentURLPrefix(agent, true) + '/state?jsonp=JSON_CALLBACK')
.success(function (response) {
$scope.state = response;
$scope.agent = {};
function matchFramework(framework) {
return $scope.framework_id === framework.id;
}
// Find the framework; it's either active or completed.
$scope.framework =
_.find($scope.state.frameworks, matchFramework) ||
_.find($scope.state.completed_frameworks, matchFramework);
if (!$scope.framework) {
$scope.alert_message = 'No framework found with ID: ' + $routeParams.framework_id;
$('#alert').show();
return;
}
// Fill in the `roles` field for non-MULTI_ROLE schedulers.
if ($scope.framework.role) {
$scope.framework.roles = [$scope.framework.role];
}
// Compute the framework stats.
$scope.framework.num_tasks = 0;
$scope.framework.cpus = 0;
$scope.framework.gpus = 0;
$scope.framework.mem = 0;
$scope.framework.disk = 0;
$scope.framework.network_bandwidth = 0;
_.each($scope.framework.executors, function(executor) {
$scope.framework.num_tasks += _.size(executor.tasks);
$scope.framework.cpus += executor.resources.cpus;
$scope.framework.gpus += executor.resources.gpus;
$scope.framework.mem += executor.resources.mem;
$scope.framework.disk += executor.resources.disk;
$scope.framework.network_bandwidth += executor.resources.network_bandwidth;
// If 'role' is not present in executor, we are talking
// to a non-MULTI_ROLE capable agent. This means that we
// can use the 'role' of the framework.
executor.role = executor.role || $scope.framework.role;
});
$('#agent').show();
})
.error(function (reason) {
$scope.alert_message = 'Failed to get agent usage / state: ' + reason;
$('#alert').show();
});
};
if ($scope.state) {
update();
}
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
}]);
mesosApp.controller('AgentExecutorCtrl', [
'$scope', '$routeParams', '$http', '$q', '$timeout', 'top',
function($scope, $routeParams, $http, $q, $timeout, $top) {
$scope.agent_id = $routeParams.agent_id;
$scope.framework_id = $routeParams.framework_id;
$scope.executor_id = $routeParams.executor_id;
var update = function() {
if (!($routeParams.agent_id in $scope.agents)) {
$scope.alert_message = 'No agent found with ID: ' + $routeParams.agent_id;
$('#alert').show();
return;
}
var agent = $scope.agents[$routeParams.agent_id];
// Set up polling for the monitor if this is the first update.
if (!$top.started()) {
$top.start(
agentURLPrefix(agent, true) + '/monitor/statistics?jsonp=JSON_CALLBACK',
$scope
);
}
$http.jsonp(agentURLPrefix(agent, true) + '/state?jsonp=JSON_CALLBACK')
.success(function (response) {
$scope.state = response;
$scope.agent = {};
function matchFramework(framework) {
return $scope.framework_id === framework.id;
}
// Find the framework; it's either active or completed.
$scope.framework =
_.find($scope.state.frameworks, matchFramework) ||
_.find($scope.state.completed_frameworks, matchFramework);
if (!$scope.framework) {
$scope.alert_message = 'No framework found with ID: ' + $routeParams.framework_id;
$('#alert').show();
return;
}
function matchExecutor(executor) {
return $scope.executor_id === executor.id;
}
function setRole(tasks) {
_.each(tasks, function(task) {
task.role = $scope.framework.role;
});
}
function setHealth(tasks) {
_.each(tasks, function(task) {
var lastStatus = _.last(task.statuses);
if (lastStatus) {
task.healthy = lastStatus.healthy;
}
})
}
// Look for the executor; it's either active or completed.
$scope.executor =
_.find($scope.framework.executors, matchExecutor) ||
_.find($scope.framework.completed_executors, matchExecutor);
if (!$scope.executor) {
$scope.alert_message = 'No executor found with ID: ' + $routeParams.executor_id;
$('#alert').show();
return;
}
// If 'role' is not present in the task, we are talking
// to a non-MULTI_ROLE capable agent. This means that we
// can use the 'role' of the framework.
if (!("role" in $scope.executor)) {
$scope.executor.role = $scope.framework.role;
setRole($scope.executor.tasks);
setRole($scope.executor.queued_tasks);
setRole($scope.executor.completed_tasks);
}
setHealth($scope.executor.tasks);
setTaskSandbox($scope.executor);
$('#agent').show();
})
.error(function (reason) {
$scope.alert_message = 'Failed to get agent usage / state: ' + reason;
$('#alert').show();
});
};
if ($scope.state) {
update();
}
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
}]);
// Reroutes requests like:
// * '/agents/:agent_id/frameworks/:framework_id/executors/:executor_id/browse'
// * '/agents/:agent_id/frameworks/:framework_id/executors/:executor_id/tasks/:task_id/browse'
// to the sandbox directory of the executor or the task respectively. This
// requires a second request because the directory to browse is known by the
// agent but not by the master. Request the directory from the agent, and then
// redirect to it.
//
// TODO(ssorallen): Add `executor.directory` to the master's state endpoint
// output so this controller of rerouting is no longer necessary.
mesosApp.controller('AgentTaskAndExecutorRerouterCtrl',
function($alert, $http, $location, $routeParams, $scope, $window) {
function goBack(flashMessageOrOptions) {
if (flashMessageOrOptions) {
$alert.danger(flashMessageOrOptions);
}
if ($window.history.length > 1) {
// If the browser has something in its history, just go back.
$window.history.back();
} else {
// Otherwise navigate to the framework page, which is likely the
// previous page anyway.
$location.path('/frameworks/' + $routeParams.framework_id).replace();
}
}
var reroute = function() {
var agent = $scope.agents[$routeParams.agent_id];
// If the agent doesn't exist, send the user back.
if (!agent) {
return goBack("Agent with ID '" + $routeParams.agent_id + "' does not exist.");
}
// Request agent details to get access to the route executor's "directory"
// to navigate directly to the executor's sandbox.
var url = agentURLPrefix(agent, true) + '/state?jsonp=JSON_CALLBACK';
$http.jsonp(url)
.success(function(response) {
function matchFramework(framework) {
return $routeParams.framework_id === framework.id;
}
var framework =
_.find(response.frameworks, matchFramework) ||
_.find(response.completed_frameworks, matchFramework);
if (!framework) {
return goBack(
"Framework with ID '" + $routeParams.framework_id +
"' does not exist on agent with ID '" + $routeParams.agent_id +
"'."
);
}
function matchExecutor(executor) {
return $routeParams.executor_id === executor.id;
}
var executor =
_.find(framework.executors, matchExecutor) ||
_.find(framework.completed_executors, matchExecutor);
if (!executor) {
return goBack(
"Executor with ID '" + $routeParams.executor_id +
"' does not exist on agent with ID '" + $routeParams.agent_id +
"'."
);
}
var sandboxDirectory = executor.directory;
function matchTask(task) {
return $routeParams.task_id === task.id;
}
// Continue to navigate to the task's sandbox if the task id is
// specified in route parameters.
if ($routeParams.task_id) {
setTaskSandbox(executor);
var task =
_.find(executor.tasks, matchTask) ||
_.find(executor.queued_tasks, matchTask) ||
_.find(executor.completed_tasks, matchTask);
if (!task) {
return goBack(
"Task with ID '" + $routeParams.task_id +
"' does not exist on agent with ID '" + $routeParams.agent_id +
"'."
);
}
sandboxDirectory = task.directory;
}
// Navigate to a path like '/agents/:id/browse?path=%2Ftmp%2F', the
// recognized "browse" endpoint for an agent.
$location.path('/agents/' + $routeParams.agent_id + '/browse')
.search({path: sandboxDirectory})
.replace();
})
.error(function(_response) {
$alert.danger({
bullets: [
"The agent is not accessible",
"The agent timed out or went offline"
],
message: "Potential reasons:",
title: "Failed to connect to agent '" + $routeParams.agent_id +
"' on '" + url + "'."
});
// Is the agent dead? Navigate home since returning to the agent might
// end up in an endless loop.
$location.path('/').replace();
});
};
// When navigating directly to this page, e.g. pasting the URL into the
// browser, the previous page is not a page in Mesos. The agents
// information may not ready when loading this page, we start to reroute
// the sandbox request after the agents information loaded.
if ($scope.state) {
reroute();
}
// `reroute` is expected to always route away from the current page
// and the listener would be removed after the first state update.
var removeListener = $scope.$on('state_updated', reroute);
$scope.$on('$routeChangeStart', removeListener);
});
mesosApp.controller('BrowseCtrl', function($scope, $routeParams, $http) {
var update = function() {
if ($routeParams.agent_id in $scope.agents && $routeParams.path) {
$scope.agent_id = $routeParams.agent_id;
$scope.path = $routeParams.path;
var agent = $scope.agents[$routeParams.agent_id];
// This variable is used in 'browse.html' to generate the '/files'
// links, so we have to pass `includeProcessId=false` (see
// `agentURLPrefix`for more details).
$scope.agent_url_prefix = agentURLPrefix(agent, false);
$scope.pail = function($event, path) {
pailer(
agentURLPrefix(agent, false),
path,
decodeURIComponent(path) + ' (' + agent.id + ')');
};
var url = agentURLPrefix(agent, false) + '/files/browse?jsonp=JSON_CALLBACK';
// TODO(bmahler): Try to get the error code / body in the error callback.
// This wasn't working with the current version of angular.
$http.jsonp(url, {params: {path: $routeParams.path}})
.success(function(data) {
$scope.listing = data;
$('#listing').show();
})
.error(function() {
$scope.alert_message = 'Error browsing path: ' + $routeParams.path;
$('#alert').show();
});
} else {
if (!($routeParams.agent_id in $scope.agents)) {
$scope.alert_message = 'No agent found with ID: ' + $routeParams.agent_id;
} else {
$scope.alert_message = 'Missing "path" request parameter.';
}
$('#alert').show();
}
};
if ($scope.state) {
update();
}
var removeListener = $scope.$on('state_updated', update);
$scope.$on('$routeChangeStart', removeListener);
});
})();
| 35.641886 | 136 | 0.604916 |
f6d74234b210d68cec606ae06f473457a4fc73dc | 100 | js | JavaScript | framework/PVRAssets/docs/html/search/classes_7.js | senthuran-ukr/Native_SDK | 2c7f0713cd1af5cb47e2351f83418fa8c7ff49bf | [
"MIT"
] | 13 | 2017-07-24T05:12:53.000Z | 2021-06-12T15:35:40.000Z | framework/PVRAssets/docs/html/search/classes_7.js | senthuran-ukr/Native_SDK | 2c7f0713cd1af5cb47e2351f83418fa8c7ff49bf | [
"MIT"
] | 1 | 2021-02-09T19:06:05.000Z | 2021-02-09T19:06:05.000Z | framework/PVRAssets/docs/html/search/classes_7.js | senthuran-ukr/Native_SDK | 2c7f0713cd1af5cb47e2351f83418fa8c7ff49bf | [
"MIT"
] | 5 | 2017-11-03T19:23:02.000Z | 2021-12-24T04:12:34.000Z | var searchData=
[
['light',['Light',['../classpvr_1_1assets_1_1_light.html',1,'pvr::assets']]]
];
| 20 | 78 | 0.65 |
f6d763d93807c60c2c05e4d913607b51296c78b7 | 306 | js | JavaScript | node_modules/zipkin/lib/tracer/noop.js | MJOAN/WatsonSSTWebApp | 07d635c8eccfbc17b216349aaf5e38b431aac4b4 | [
"MIT"
] | 1 | 2020-12-01T10:15:31.000Z | 2020-12-01T10:15:31.000Z | node_modules/zipkin/lib/tracer/noop.js | MJOAN/WatsonSSTWebApp | 07d635c8eccfbc17b216349aaf5e38b431aac4b4 | [
"MIT"
] | 2 | 2019-03-29T15:01:14.000Z | 2021-08-30T09:36:09.000Z | packages/zipkin/src/tracer/noop.js | byteshiva/zipkin-js-es5 | c6aa25b26aa19dcbc7be739deb04bbdabc5aeb3e | [
"MIT"
] | 1 | 2017-12-01T10:39:56.000Z | 2017-12-01T10:39:56.000Z | 'use strict';
var Tracer = require('./');
var ExplicitContext = require('../explicit-context');
module.exports = function createNoopTracer() {
var recorder = {
record: function record() {}
};
var ctxImpl = new ExplicitContext();
return new Tracer({ recorder: recorder, ctxImpl: ctxImpl });
}; | 25.5 | 62 | 0.673203 |
f6d778e16acf08c05549085b7bb7e330239bb4be | 2,747 | js | JavaScript | webpack.config.js | falkodev/cadavresky | 2e4a08490bc97859813cba4c44cc33c35e108e1f | [
"MIT"
] | null | null | null | webpack.config.js | falkodev/cadavresky | 2e4a08490bc97859813cba4c44cc33c35e108e1f | [
"MIT"
] | null | null | null | webpack.config.js | falkodev/cadavresky | 2e4a08490bc97859813cba4c44cc33c35e108e1f | [
"MIT"
] | null | null | null | var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.join(__dirname, 'node_modules');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = {
entry: setEntry(),
output: setOutput(),
plugins: setPlugins(),
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'app/Resources/js'),
exclude: node_modules_dir,
loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react&presets[]=stage-2'],
presets: ['es2015', 'react', 'stage-2']
},
{
test: /\.s?css$/,
loader: ExtractTextPlugin.extract('css!sass')
},
{
test: /\.jpe?g$|\.gif$|\.png$|\.svg$/,
loader: "file?name=images/[name].[ext]"
},
{
test: /\.woff$|\.woff2?$|\.ttf$|\.eot$/,
loader: "file?name=fonts/[name].[ext]"
}
]
}
};
function setEntry() {
var entry = [
'babel-polyfill',
'./app/Resources/js/app.js',
'./app/Resources/scss/style.scss'
];
if (process.env.NODE_ENV !== 'production') {
entry.push('webpack-dev-server/client?http://127.0.0.1:3000');
entry.push('webpack/hot/only-dev-server');
}
return entry;
}
function setOutput() {
var output = {
path: path.join(__dirname, 'web/dist'),
filename: 'bundle.js',
publicPath: 'http://www.cadavresky.com/web/dist/'
};
if (process.env.NODE_ENV !== 'production') {
output.publicPath = 'http://127.0.0.1:3000/static/';
} else if (process.env.localhost) {
output.publicPath = 'http://localhost/symfony-react/web/dist/';
}
return output;
}
function setPlugins() {
var plugins = [
new webpack.NoErrorsPlugin(),
new webpack.IgnorePlugin(/^(jquery)$/), //exclude jquery (included with Twitter Bootstrap by default)
new ExtractTextPlugin('style.css', { allChunks: true }),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
host: JSON.stringify(process.env.host),
localhost: JSON.stringify(process.env.localhost),
}
}),
];
if (process.env.NODE_ENV !== 'production') {
plugins.push(new webpack.HotModuleReplacementPlugin());
} else {
plugins.push(new webpack.optimize.OccurenceOrderPlugin());
plugins.push(new webpack.optimize.DedupePlugin());
plugins.push(new webpack.optimize.UglifyJsPlugin());
}
return plugins;
}
module.exports = config;
| 30.186813 | 109 | 0.549327 |
f6d79223606d981a96e0dafc41b7f4e401bf2e74 | 1,294 | js | JavaScript | widgets/Directions/setting/nls/Setting_id.js | daveism/testmap | 63c4da4c6ddf8f679f53f19cd7fcd1a852b9583c | [
"MIT"
] | null | null | null | widgets/Directions/setting/nls/Setting_id.js | daveism/testmap | 63c4da4c6ddf8f679f53f19cd7fcd1a852b9583c | [
"MIT"
] | null | null | null | widgets/Directions/setting/nls/Setting_id.js | daveism/testmap | 63c4da4c6ddf8f679f53f19cd7fcd1a852b9583c | [
"MIT"
] | null | null | null | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.15/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details.
//>>built
define({"widgets/Directions/setting/nls/strings":{routeUrl:"URL Rute",locatorUrl:"URL Geocoder",geocoderOptions:"Opsi Geocoder",autoComplete:"Selesaikan otomatis",maximumSuggestions:"Saran maksimal",minCharacters:"Karakter minimal",searchDelay:"Cari penangguhan",placeholder:"Placeholder",routeOptions:"Opsi rute",directionsLanguage:"Bahasa arahan",directionsLengthUnits:"Unit panjang arahan",directionsOutputType:"Tipe output arahan",impedanceAttribute:"Atribut impedansi",kilometers:"Kilometer",miles:"Mil",
meters:"Meter",feet:"Kaki",yards:"Yard",nauticalMiles:"Mil Laut",parametersTip:"Harap tetapkan parameter dengan benar !",complete:"Selesai",completeNoEvents:"Tidak Menyelesaikan Acara",instructionsOnly:"Khusus Instruksi",standard:"Standar",summaryOnly:"Khusus Ringkasan",travelModesUrl:"URL Mode Perjalanan",searchPlaceholder:"Temukan alamat atau tempat",trafficLayerUrl:"URL Layer Lalu Lintas",presetDestinations:"Perhentian prasetel",startPoint:"Titik mulai",endPoint:"Titik selesai",destinationHolder:"Alamat atau kordinat",
optional:"Opsional.",_localized:{}}}); | 215.666667 | 527 | 0.81221 |
f6d7b76eea7c768b0d9dd5bdff55e0e684c01e28 | 17,975 | js | JavaScript | src/js/jMonthCalendar.js | KyleLeneau/jMonthCalendar | 80e8d0aada086569c07ce6f7e613d0f6a962f2b3 | [
"MIT"
] | 7 | 2015-10-06T09:22:35.000Z | 2021-11-08T12:06:55.000Z | src/js/jMonthCalendar.js | lucoo01/jMonthCalendar | 80e8d0aada086569c07ce6f7e613d0f6a962f2b3 | [
"MIT"
] | null | null | null | src/js/jMonthCalendar.js | lucoo01/jMonthCalendar | 80e8d0aada086569c07ce6f7e613d0f6a962f2b3 | [
"MIT"
] | 10 | 2015-08-04T01:52:29.000Z | 2021-02-01T09:31:36.000Z | /*!
* Title: jMonthCalendar @VERSION
* Dependencies: jQuery 1.3.0 +
* Author: Kyle LeNeau
* Email: kyle.leneau@gmail.com
* Project Hompage: http://www.bytecyclist.com/projects/jmonthcalendar
* Source: http://github.com/KyleLeneau/jMonthCalendar
*
*/
(function($) {
var _beginDate;
var _endDate;
var _boxes = [];
var _eventObj = {};
var _workingDate = null;
var _daysInMonth = 0;
var _firstOfMonth = null;
var _lastOfMonth = null;
var _gridOffset = 0;
var _totalDates = 0;
var _gridRows = 0;
var _totalBoxes = 0;
var _dateRange = { startDate: null, endDate: null };
var cEvents = [];
var def = {
containerId: "#jMonthCalendar",
headerHeight: 50,
firstDayOfWeek: 0,
calendarStartDate:new Date(),
dragableEvents: true,
dragHoverClass: 'DateBoxOver',
navLinks: {
enableToday: true,
enableNextYear: true,
enablePrevYear: true,
p:'‹ Prev',
n:'Next ›',
t:'Today',
showMore: 'Show More'
},
onMonthChanging: function() {},
onMonthChanged: function() {},
onEventLinkClick: function() {},
onEventBlockClick: function() {},
onEventBlockOver: function() {},
onEventBlockOut: function() {},
onDayLinkClick: function() {},
onDayCellClick: function() {},
onDayCellDblClick: function() {},
onEventDropped: function() {},
onShowMoreClick: function() {}
};
$.jMonthCalendar = $.J = function() {};
var _getJSONDate = function(dateStr) {
//check conditions for different types of accepted dates
var tDt, k;
if (typeof dateStr == "string") {
// "2008-12-28T00:00:00.0000000"
var isoRegPlus = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{7})$/;
// "2008-12-28T00:00:00"
var isoReg = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})$/;
//"2008-12-28"
var yyyyMMdd = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
// "new Date(2009, 1, 1)"
// "new Date(1230444000000)
var newReg = /^new/;
// "\/Date(1234418400000-0600)\/"
var stdReg = /^\\\/Date\(([0-9]{13})-([0-9]{4})\)\\\/$/;
if (k = dateStr.match(isoRegPlus)) {
return new Date(k[1],k[2]-1,k[3],k[4],k[5],k[6]);
} else if (k = dateStr.match(isoReg)) {
return new Date(k[1],k[2]-1,k[3],k[4],k[5],k[6]);
} else if (k = dateStr.match(yyyyMMdd)) {
return new Date(k[1],k[2]-1,k[3]);
}
if (k = dateStr.match(stdReg)) {
return new Date(k[1]);
}
if (k = dateStr.match(newReg)) {
return eval('(' + dateStr + ')');
}
return tDt;
}
};
//This function will clean the JSON array, primaryly the dates and put the correct ones in the object. Intended to alwasy be called on event functions.
var _filterEventCollection = function() {
if (cEvents && cEvents.length > 0) {
var multi = [];
var single = [];
//Update and parse all the dates
$.each(cEvents, function(){
var ev = this;
//Date Parse the JSON to create a new Date to work with here
if(ev.StartDateTime) {
if (typeof ev.StartDateTime == 'object' && ev.StartDateTime.getDate) { this.StartDateTime = ev.StartDateTime; }
if (typeof ev.StartDateTime == 'string' && ev.StartDateTime.split) { this.StartDateTime = _getJSONDate(ev.StartDateTime); }
} else if(ev.Date) { // DEPRECATED
if (typeof ev.Date == 'object' && ev.Date.getDate) { this.StartDateTime = ev.Date; }
if (typeof ev.Date == 'string' && ev.Date.split) { this.StartDateTime = _getJSONDate(ev.Date); }
} else {
return; //no start date, or legacy date. no event.
}
if(ev.EndDateTime) {
if (typeof ev.EndDateTime == 'object' && ev.EndDateTime.getDate) { this.EndDateTime = ev.EndDateTime; }
if (typeof ev.EndDateTime == 'string' && ev.EndDateTime.split) { this.EndDateTime = _getJSONDate(ev.EndDateTime); }
} else {
this.EndDateTime = this.StartDateTime.clone();
}
if (this.StartDateTime.clone().clearTime().compareTo(this.EndDateTime.clone().clearTime()) == 0) {
single.push(this);
} else if (this.StartDateTime.clone().clearTime().compareTo(this.EndDateTime.clone().clearTime()) == -1) {
multi.push(this);
}
});
multi.sort(_eventSort);
single.sort(_eventSort);
cEvents = [];
$.merge(cEvents, multi);
$.merge(cEvents, single);
}
};
var _eventSort = function(a, b) {
return a.StartDateTime.compareTo(b.StartDateTime);
};
var _clearBoxes = function() {
_clearBoxEvents();
_boxes = [];
};
var _clearBoxEvents = function() {
for (var i = 0; i < _boxes.length; i++) {
_boxes[i].clear();
}
_eventObj = {};
};
var _initDates = function(dateIn) {
var today = def.calendarStartDate;
if(dateIn == undefined) {
_workingDate = new Date(today.getFullYear(), today.getMonth(), 1);
} else {
_workingDate = dateIn;
_workingDate.setDate(1);
}
_daysInMonth = _workingDate.getDaysInMonth();
_firstOfMonth = _workingDate.clone().moveToFirstDayOfMonth();
_lastOfMonth = _workingDate.clone().moveToLastDayOfMonth();
_gridOffset = _firstOfMonth.getDay() - def.firstDayOfWeek;
_totalDates = _gridOffset + _daysInMonth;
_gridRows = Math.ceil(_totalDates / 7);
_totalBoxes = _gridRows * 7;
_dateRange.startDate = _firstOfMonth.clone().addDays((-1) * _gridOffset);
_dateRange.endDate = _lastOfMonth.clone().addDays(_totalBoxes - (_daysInMonth + _gridOffset));
};
var _initHeaders = function() {
// Create Previous Month link for later
var prevMonth = _workingDate.clone().addMonths(-1);
var prevMLink = $('<div class="MonthNavPrev"><a class="link-prev">'+ def.navLinks.p +'</a></div>').click(function() {
$.J.ChangeMonth(prevMonth);
return false;
});
//Create Next Month link for later
var nextMonth = _workingDate.clone().addMonths(1);
var nextMLink = $('<div class="MonthNavNext"><a class="link-next">'+ def.navLinks.n +'</a></div>').click(function() {
$.J.ChangeMonth(nextMonth);
return false;
});
//Create Previous Year link for later
var prevYear = _workingDate.clone().addYears(-1);
var prevYLink;
if(def.navLinks.enablePrevYear) {
prevYLink = $('<div class="YearNavPrev"><a>'+ prevYear.getFullYear() +'</a></div>').click(function() {
$.J.ChangeMonth(prevYear);
return false;
});
}
//Create Next Year link for later
var nextYear = _workingDate.clone().addYears(1);
var nextYLink;
if(def.navLinks.enableNextYear) {
nextYLink = $('<div class="YearNavNext"><a>'+ nextYear.getFullYear() +'</a></div>').click(function() {
$.J.ChangeMonth(nextYear);
return false;
});
}
var todayLink;
if(def.navLinks.enableToday) {
//Create Today link for later
todayLink = $('<div class="TodayLink"><a class="link-today">'+ def.navLinks.t +'</a></div>').click(function() {
$.J.ChangeMonth(new Date());
return false;
});
}
//Build up the Header first, Navigation
var navRow = $('<tr><td colspan="7"><div class="FormHeader MonthNavigation"></div></td></tr>');
var navHead = $('.MonthNavigation', navRow);
navHead.append(prevMLink, nextMLink);
if(def.navLinks.enableToday) { navHead.append(todayLink); }
navHead.append($('<div class="MonthName"></div>').append(Date.CultureInfo.monthNames[_workingDate.getMonth()] + " " + _workingDate.getFullYear()));
if(def.navLinks.enablePrevYear) { navHead.append(prevYLink); }
if(def.navLinks.enableNextYear) { navHead.append(nextYLink); }
// Days
var headRow = $("<tr></tr>");
for (var i = def.firstDayOfWeek; i < def.firstDayOfWeek+7; i++) {
var weekday = i % 7;
var wordday = Date.CultureInfo.dayNames[weekday];
headRow.append('<th title="' + wordday + '" class="DateHeader' + (weekday == 0 || weekday == 6 ? ' Weekend' : '') + '"><span>' + wordday + '</span></th>');
}
headRow = $("<thead id=\"CalendarHead\"></thead>").css({ "height" : def.headerHeight + "px" }).append(headRow);
headRow = headRow.prepend(navRow);
return headRow;
};
$.J.DrawCalendar = function(dateIn){
var now = new Date();
now.clearTime();
var today = def.calendarStartDate;
_clearBoxes();
_initDates(dateIn);
var headerRow = _initHeaders();
//properties
var isCurrentMonth = (_workingDate.getMonth() == today.getMonth() && _workingDate.getFullYear() == today.getFullYear());
var containerHeight = $(def.containerId).outerHeight();
var rowHeight = (containerHeight - def.headerHeight) / _gridRows;
var row = null;
//Build up the Body
var tBody = $('<tbody id="CalendarBody"></tbody>');
for (var i = 0; i < _totalBoxes; i++) {
var currentDate = _dateRange.startDate.clone().addDays(i);
if (i % 7 == 0 || i == 0) {
row = $("<tr></tr>");
row.css({ "height" : rowHeight + "px" });
tBody.append(row);
}
var weekday = (def.firstDayOfWeek + i) % 7;
var atts = {'class':"DateBox" + (weekday == 0 || weekday == 6 ? ' Weekend ' : ''),
'date':currentDate.toString("M/d/yyyy")
};
//dates outside of month range.
if (currentDate.compareTo(_firstOfMonth) == -1 || currentDate.compareTo(_lastOfMonth) == 1) {
atts['class'] += ' Inactive';
}
//check to see if current date rendering is today
if (currentDate.compareTo(now) == 0) {
atts['class'] += ' Today';
}
//DateBox Events
var dateLink = $('<div class="DateLabel"><a>' + currentDate.getDate() + '</a></div>');
dateLink.bind('click', { Date: currentDate.clone() }, def.onDayLinkClick);
var dateBox = $("<td></td>").attr(atts).append(dateLink);
dateBox.bind('dblclick', { Date: currentDate.clone() }, def.onDayCellDblClick);
dateBox.bind('click', { Date: currentDate.clone() }, def.onDayCellClick);
if (def.dragableEvents) {
dateBox.droppable({
hoverClass: def.dragHoverClass,
tolerance: 'pointer',
drop: function(ev, ui) {
var eventId = ui.draggable.attr("eventid")
var newDate = new Date($(this).attr("date")).clearTime();
var event;
$.each(cEvents, function() {
if (this.EventID == eventId) {
var days = new TimeSpan(newDate - this.StartDateTime).days;
this.StartDateTime.addDays(days);
this.EndDateTime.addDays(days);
event = this;
}
});
$.J.ClearEventsOnCalendar();
_drawEventsOnCalendar();
def.onEventDropped.call(this, event, newDate);
}
});
}
_boxes.push(new CalendarBox(i, currentDate, dateBox, dateLink));
row.append(dateBox);
}
tBody.append(row);
var a = $(def.containerId);
var cal = $('<table class="MonthlyCalendar" cellpadding="0" tablespacing="0"></table>').append(headerRow, tBody);
a.hide();
a.html(cal);
a.fadeIn("normal");
_drawEventsOnCalendar();
}
var _drawEventsOnCalendar = function() {
//filter the JSON array for proper dates
_filterEventCollection();
_clearBoxEvents();
if (cEvents && cEvents.length > 0) {
var container = $(def.containerId);
$.each(cEvents, function(){
var ev = this;
//alert("eventID: " + ev.EventID + ", start: " + ev.StartDateTime + ",end: " + ev.EndDateTime);
var tempStartDT = ev.StartDateTime.clone().clearTime();
var tempEndDT = ev.EndDateTime.clone().clearTime();
var startI = new TimeSpan(tempStartDT - _dateRange.startDate).days;
var endI = new TimeSpan(tempEndDT - _dateRange.startDate).days;
//alert("start I: " + startI + " end I: " + endI);
var istart = (startI < 0) ? 0 : startI;
var iend = (endI > _boxes.length - 1) ? _boxes.length - 1 : endI;
//alert("istart: " + istart + " iend: " + iend);
for (var i = istart; i <= iend; i++) {
var b = _boxes[i];
var startBoxCompare = tempStartDT.compareTo(b.date);
var endBoxCompare = tempEndDT.compareTo(b.date);
var continueEvent = ((i != 0 && startBoxCompare == -1 && endBoxCompare >= 0 && b.weekNumber != _boxes[i - 1].weekNumber) || (i == 0 && startBoxCompare == -1));
var toManyEvents = (startBoxCompare == 0 || (i == 0 && startBoxCompare == -1) ||
continueEvent || (startBoxCompare == -1 && endBoxCompare >= 0)) && b.vOffset >= (b.getCellBox().height() - b.getLabelHeight() - 32);
//alert("b.vOffset: " + b.vOffset + ", cell height: " + (b.getCellBox().height() - b.getLabelHeight() - 32));
//alert(continueEvent);
//alert(toManyEvents);
if (toManyEvents) {
if (!b.isTooManySet) {
var moreDiv = $('<div class="MoreEvents" id="ME_' + i + '">' + def.navLinks.showMore + '</div>');
var pos = b.getCellPosition();
var index = i;
moreDiv.css({
"top" : (pos.top + (b.getCellBox().height() - b.getLabelHeight())),
"left" : pos.left,
"width" : (b.getLabelWidth() - 7),
"position" : "absolute" });
moreDiv.click(function(e) { _showMoreClick(e, index); });
_eventObj[moreDiv.attr("id")] = moreDiv;
b.isTooManySet = true;
} //else update the +more to show??
b.events.push(ev);
} else if (startBoxCompare == 0 || (i == 0 && startBoxCompare == -1) || continueEvent) {
var block = _buildEventBlock(ev, b.weekNumber);
var pos = b.getCellPosition();
block.css({
"top" : (pos.top + b.getLabelHeight() + b.vOffset),
"left" : pos.left,
"width" : (b.getLabelWidth() - 7),
"position" : "absolute" });
b.vOffset += 19;
if (continueEvent) {
block.prepend($('<span />').addClass("ui-icon").addClass("ui-icon-triangle-1-w"));
var e = _eventObj['Event_' + ev.EventID + '_' + (b.weekNumber - 1)];
if (e) { e.prepend($('<span />').addClass("ui-icon").addClass("ui-icon-triangle-1-e")); }
}
_eventObj[block.attr("id")] = block;
b.events.push(ev);
} else if (startBoxCompare == -1 && endBoxCompare >= 0) {
var e = _eventObj['Event_' + ev.EventID + '_' + b.weekNumber];
if (e) {
var w = e.css("width")
e.css({ "width" : (parseInt(w) + b.getLabelWidth() + 1) });
b.vOffset += 19;
b.events.push(ev);
}
}
//end of month continue
if (i == iend && endBoxCompare > 0) {
var e = _eventObj['Event_' + ev.EventID + '_' + b.weekNumber];
if (e) { e.prepend($('<span />').addClass("ui-icon").addClass("ui-icon-triangle-1-e")); }
}
}
});
for (var o in _eventObj) {
_eventObj[o].hide();
container.append(_eventObj[o]);
_eventObj[o].show();
}
}
}
var _buildEventBlock = function(ev, weekNumber) {
var block = $('<div class="Event" id="Event_' + ev.EventID + '_' + weekNumber + '" eventid="' + ev.EventID +'"></div>');
if(ev.CssClass) { block.addClass(ev.CssClass) }
block.bind('click', { Event: ev }, def.onEventBlockClick);
block.bind('mouseover', { Event: ev }, def.onEventBlockOver);
block.bind('mouseout', { Event: ev }, def.onEventBlockOut);
if (def.dragableEvents) {
_dragableEvent(ev, block, weekNumber);
}
var link;
if (ev.URL && ev.URL.length > 0) {
link = $('<a href="' + ev.URL + '">' + ev.Title + '</a>');
} else {
link = $('<a>' + ev.Title + '</a>');
}
link.bind('click', { Event: ev }, def.onEventLinkClick);
block.append(link);
return block;
}
var _dragableEvent = function(event, block, weekNumber) {
block.draggable({
zIndex: 4,
delay: 50,
opacity: 0.5,
revertDuration: 1000,
cursorAt: { left: 5 },
start: function(ev, ui) {
//hide any additional event parts
for (var i = 0; i <= _gridRows; i++) {
if (i == weekNumber) {
continue;
}
var e = _eventObj['Event_' + event.EventID + '_' + i];
if (e) { e.hide(); }
}
}
});
}
var _showMoreClick = function(e, boxIndex) {
var box = _boxes[boxIndex];
def.onShowMoreClick.call(this, box.events);
e.stopPropagation();
}
$.J.ClearEventsOnCalendar = function() {
_clearBoxEvents();
$(".Event", $(def.containerId)).remove();
$(".MoreEvents", $(def.containerId)).remove();
}
$.J.AddEvents = function(eventCollection) {
if(eventCollection) {
if(eventCollection.length > 0) {
$.merge(cEvents, eventCollection);
} else {
cEvents.push(eventCollection);
}
$.J.ClearEventsOnCalendar();
_drawEventsOnCalendar();
}
}
$.J.ReplaceEventCollection = function(eventCollection) {
if(eventCollection) {
cEvents = [];
cEvents = eventCollection;
}
$.J.ClearEventsOnCalendar();
_drawEventsOnCalendar();
}
$.J.ChangeMonth = function(dateIn) {
var returned = def.onMonthChanging.call(this, dateIn);
if (!returned) {
$.J.DrawCalendar(dateIn);
def.onMonthChanged.call(this, dateIn);
}
}
$.J.Initialize = function(options, events) {
var today = new Date();
options = $.extend(def, options);
if (events) {
$.J.ClearEventsOnCalendar();
cEvents = events;
}
$.J.DrawCalendar();
};
function CalendarBox(id, boxDate, cell, label) {
this.id = id;
this.date = boxDate;
this.cell = cell;
this.label = label;
this.weekNumber = Math.floor(id / 7);
this.events= [];
this.isTooManySet = false;
this.vOffset = 0;
this.echo = function() {
alert("Date: " + this.date + " WeekNumber: " + this.weekNumber + " ID: " + this.id);
}
this.clear = function() {
this.events = [];
this.isTooManySet = false;
this.vOffset = 0;
}
this.getCellPosition = function() {
if (this.cell) {
return this.cell.position();
}
return;
}
this.getCellBox = function() {
if (this.cell) {
return this.cell;
}
return;
}
this.getLabelWidth = function() {
if (this.label) {
return this.label.innerWidth();
}
return;
}
this.getLabelHeight = function() {
if (this.label) {
return this.label.height();
}
return;
}
this.getDate = function() {
return this.date;
}
}
})(jQuery); | 29.809287 | 164 | 0.599722 |
f6d7b86e92d219436768a6a808c54c1aa1c2de03 | 295 | js | JavaScript | client/src/js/actions/fuelSavingsActions.js | ziyadparekh/relay-services | 29cd10972d539b89c3073420ee86ced311e29863 | [
"MIT"
] | null | null | null | client/src/js/actions/fuelSavingsActions.js | ziyadparekh/relay-services | 29cd10972d539b89c3073420ee86ced311e29863 | [
"MIT"
] | null | null | null | client/src/js/actions/fuelSavingsActions.js | ziyadparekh/relay-services | 29cd10972d539b89c3073420ee86ced311e29863 | [
"MIT"
] | null | null | null | import * as types from 'constants/ActionTypes';
export function saveFuelSavings(settings) {
return { type: types.SAVE_FUEL_SAVINGS, settings };
}
export function calculateFuelSavings(settings, fieldName, value) {
return { type: types.CALCULATE_FUEL_SAVINGS, settings, fieldName, value };
} | 32.777778 | 76 | 0.776271 |
f6d7cfe200bd1f70ba934c60e2418695c7a0eba5 | 6,316 | js | JavaScript | static/portfolioWeb/data/slide12.js | Hearwindsaying/zihong | 1dd11155548ba8cc93e2073f2cbc262294dc4b41 | [
"MIT"
] | null | null | null | static/portfolioWeb/data/slide12.js | Hearwindsaying/zihong | 1dd11155548ba8cc93e2073f2cbc262294dc4b41 | [
"MIT"
] | null | null | null | static/portfolioWeb/data/slide12.js | Hearwindsaying/zihong | 1dd11155548ba8cc93e2073f2cbc262294dc4b41 | [
"MIT"
] | null | null | null | (function(){var loadHandler=window['sl_{103DB3B4-68ED-409A-BA38-8947414ABB49}'];loadHandler&&loadHandler(11, '<div id="spr0_2027248b"><div id="spr1_2027248b" class="kern slide"><img id="img7_2027248b" src="data/img1.png" width="960px" height="540px" alt="" style="left:0px;top:0px;"/><div id="svg0_2027248b" style="left:0px;top:0px;"><svg width="64" height="99" viewBox="0 0 64 99"><path fill="#cfe2f3" d="M0,0 h63.833 v98.5 h-63.833 Z"/></svg></div><div id="svg1_2027248b" style="left:-1.5px;top:107.167px;"><svg width="12" height="962" viewBox="0 0 12 962"><path fill="#000000" d="M0,0 h11.333 v961.5 h-11.333 Z"/></svg></div><div id="svg2_2027248b" style="left:63.833px;"><svg width="12" height="540" viewBox="0 0 12 540"><path fill="#000000" d="M0,0 h11.333 v540 h-11.333 Z"/></svg></div></div><div id="spr2_2027248b" class="kern slide"><div id="spr3_2027248b" style="left:546.5px;top:131.5px;"><div style="width:0px;"><span id="txt0_2027248b" data-width="65.781334" style="left:9.598px;top:-3.517px;">Features</span></div><div style="width:0px;"><span id="txt1_2027248b" class="nokern" data-width="98.046669" style="left:9.598px;top:36.083px;">Light Transport</span></div><div style="width:0px;"><span id="txt2_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:52.269px;">•</span> <span id="txt3_2027248b" class="nokern relpos" data-width="93.676003" style="left:24.297px;top:50.739px;">Direct Lighting</span></div><div style="width:0px;"><span id="txt4_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:69.869px;">•</span> <span id="txt5_2027248b" class="nokern relpos" data-width="166.833344" style="left:24.297px;top:68.339px;">Unidirectional Path Tracing</span></div><div style="width:0px;"><span id="txt6_2027248b" class="nokern" data-width="110.674660" style="left:9.598px;top:106.483px;">Reflection Models</span></div><div style="width:0px;"><span id="txt7_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:122.669px;">•</span> <span id="txt8_2027248b" class="nokern relpos" data-width="113.417343" style="left:24.297px;top:121.139px;">Lambertian BRDF</span></div><div style="width:0px;"><span id="txt9_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:140.269px;">•</span> <span id="txt10_2027248b" class="nokern relpos" data-width="194.010651" style="left:24.297px;top:138.739px;">Specular BRDF (Perfect Mirror)</span></div><div style="width:0px;"><span id="txt11_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:157.869px;">•</span> <span id="txt12_2027248b" class="nokern relpos" data-width="183.670670" style="left:24.297px;top:156.339px;">Specular BSDF (Perfect Glass)</span></div><div style="width:0px;"><span id="txt13_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:175.469px;">•</span> <span id="txt14_2027248b" class="nokern relpos" data-width="254.026611" style="left:24.297px;top:173.939px;">Ashikhmin-Shirley BRDF (Rough Plastic)</span></div><div style="width:0px;"><span id="txt15_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:193.069px;">•</span> <span id="txt16_2027248b" class="nokern relpos" data-width="267.886627" style="left:24.297px;top:191.539px;">GGX Microfacet BRDF (Rough Conductor)</span></div><div style="width:0px;"><span id="txt17_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:210.669px;">•</span> <span id="txt18_2027248b" class="nokern relpos" data-width="259.321289" style="left:24.297px;top:209.139px;">GGX Microfacet BSDF (Rough Dielectric)</span></div><div style="width:0px;"><span id="txt19_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:228.269px;">•</span> <span id="txt20_2027248b" class="nokern relpos" data-width="252.163956" style="left:24.297px;top:226.739px;">Dielectric-Couductor Two Layered BSDF</span></div><div style="width:0px;"><span id="txt21_2027248b" class="nokern" data-width="49.661335" style="left:9.598px;top:264.883px;">Sampler</span></div><div style="width:0px;"><span id="txt22_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:281.069px;">•</span> <span id="txt23_2027248b" class="nokern relpos" data-width="127.482658" style="left:24.297px;top:279.539px;">Independent Sampler</span></div><div style="width:0px;"><span id="txt24_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:298.669px;">•</span> <span id="txt25_2027248b" class="nokern relpos" data-width="306.591949" style="left:24.297px;top:297.139px;">Halton QMC Sampler (Fast Random Permutation)</span></div><div style="width:0px;"><span id="txt26_2027248b" class="nokern relpos" dir="auto" style="left:9.63px;top:316.269px;">•</span> <span id="txt27_2027248b" class="nokern relpos" data-width="127.189339" style="left:24.297px;top:314.739px;">Sobol QMC Sampler</span></div></div><div id="spr4_2027248b" style="left:87px;top:56.5px;"><div style="width:0px;"><span id="txt28_2027248b" class="nokern" data-width="493.468750" style="left:9.598px;top:-4.244px;">Gallery and Features for Colvillea</span></div></div><div id="spr5_2027248b" style="left:100.833px;top:148px;"><img id="img0_2027248b" src="data/img11.png" width="135" height="134.531" alt="" style="top:-0.007px;"/></div><div id="spr6_2027248b" style="left:238.5px;top:148px;"><img id="img1_2027248b" src="data/img12.png" width="152.344" height="134.531" alt="" style="left:-0.042px;top:-0.007px;"/></div><div id="spr7_2027248b" style="left:393.167px;top:148px;"><img id="img2_2027248b" src="data/img13.png" width="139.688" height="134.531" alt="" style="left:0.034px;top:-0.007px;"/></div><div id="spr8_2027248b" style="left:247.5px;top:290.5px;"><img id="img3_2027248b" src="data/img14.png" width="134.063" height="134.531" alt="" style="left:0.024px;top:-0.007px;"/></div><div id="spr9_2027248b" style="left:101.5px;top:290.5px;"><img id="img4_2027248b" src="data/img15.png" width="134.531" height="134.531" alt="" style="left:-0.007px;top:-0.007px;"/></div><div id="spr10_2027248b" style="left:393.167px;top:290.5px;"><img id="img5_2027248b" src="data/img16.png" width="134.531" height="134.531" alt="" style="left:-0.007px;top:-0.007px;"/></div><div id="spr11_2027248b" style="left:556.406px;top:146.719px;"><img id="img6_2027248b" src="data/img17.png" width="382.031" height="9.375" alt=""/></div></div></div>', '{"s":[]}');})(); | 6,316 | 6,316 | 0.713426 |
f6d7da29f59eaadd7f9723cf2f06863f5d71bb58 | 3,087 | js | JavaScript | test/options.spec.js | ix4/videojs-wavesurfer | fba0d77d14430d75083fefb301ca3018e812fee7 | [
"MIT"
] | 289 | 2015-01-08T10:21:12.000Z | 2022-03-18T14:35:38.000Z | test/options.spec.js | collab-project/videojs-wavesurfer | 7b41e2d736ecc90b355ae9f77978fe60b039631a | [
"MIT"
] | 136 | 2015-02-05T13:51:51.000Z | 2022-03-20T04:18:39.000Z | test/options.spec.js | ix4/videojs-wavesurfer | fba0d77d14430d75083fefb301ca3018e812fee7 | [
"MIT"
] | 60 | 2015-03-13T00:16:00.000Z | 2022-03-08T17:12:36.000Z | /**
* @since 2.0.0
*/
import host from "@jsdevtools/host-environment";
import Event from '../src/js/event.js';
import TestHelpers from './test-helpers.js';
let player;
function ws_options_test(backend) {
/** @test {Wavesurfer} */
it('accepts waveformHeight option', (done) => {
let height = 139;
// create player
player = TestHelpers.makePlayer({
plugins: {
wavesurfer: {
backend: backend,
waveformHeight: height
}
}
});
player.one(Event.WAVE_READY, () => {
expect(player.wavesurfer().surfer.getHeight()).toEqual(height);
done();
});
// load file
player.src(TestHelpers.EXAMPLE_AUDIO_SRC);
});
/** @test {Wavesurfer} */
it('accepts splitChannels option', (done) => {
player = TestHelpers.makePlayer({
height: 100,
plugins: {
wavesurfer: {
backend: backend,
splitChannels: true
}
}
});
player.one(Event.WAVE_READY, () => {
expect(player.wavesurfer().surfer.getHeight()).toEqual(35);
done();
});
// load file
player.src(TestHelpers.EXAMPLE_AUDIO_SRC);
});
/** @test {Wavesurfer} */
it('accepts autoplay option', (done) => {
player = TestHelpers.makePlayer({
autoplay: true,
plugins: {
wavesurfer: {
backend: backend
}
}
});
// skip test in firefox until autoplay in headless browser is figured out
if (host.browser.firefox) {
done();
}
player.one(Event.ERROR, (element, error) => {
fail(error);
});
player.one(Event.ENDED, done);
// load file
player.src(TestHelpers.EXAMPLE_AUDIO_SRC);
});
/** @test {Wavesurfer} */
it('accepts formatTime option', (done) => {
player = TestHelpers.makePlayer({
height: 100,
plugins: {
wavesurfer: {
backend: backend,
formatTime: (seconds, guide) => `foo:${seconds}:${guide}`
}
}
});
player.one(Event.WAVE_READY, () => {
expect(player.controlBar.currentTimeDisplay.formattedTime_).toEqual('foo:0:0');
expect(player.controlBar.durationDisplay.formattedTime_.substring(0, 5)).toEqual('foo:0');
done();
});
// load file
player.src(TestHelpers.EXAMPLE_AUDIO_SRC);
});
}
/** @test {Wavesurfer} */
describe('Wavesurfer options', () => {
afterEach(() => {
// delete player
player.dispose();
});
// run tests for each wavesurfer.js backend
ws_options_test(TestHelpers.MEDIA_ELEMENT_BACKEND);
ws_options_test(TestHelpers.MEDIA_ELEMENT_WEB_AUDIO_BACKEND);
ws_options_test(TestHelpers.WEB_AUDIO_BACKEND);
}); | 25.941176 | 102 | 0.512796 |
f6d85eb8f32372e5bd0ccce074dc68556810c14b | 1,368 | es6 | JavaScript | das-console-static/src/model/sync/GroupSyncModel.es6 | wanglei2659297/das | f251d36a7cbf2b7cc27c26a048709e6ddb0384c2 | [
"Apache-2.0"
] | 170 | 2019-10-14T05:41:51.000Z | 2022-03-11T06:17:39.000Z | das-console-static/src/model/sync/GroupSyncModel.es6 | wanglei2659297/das | f251d36a7cbf2b7cc27c26a048709e6ddb0384c2 | [
"Apache-2.0"
] | 11 | 2019-11-06T09:44:08.000Z | 2021-01-25T08:20:58.000Z | das-console-static/src/model/sync/GroupSyncModel.es6 | wanglei2659297/das | f251d36a7cbf2b7cc27c26a048709e6ddb0384c2 | [
"Apache-2.0"
] | 56 | 2019-10-18T07:56:28.000Z | 2022-03-25T07:21:08.000Z | import {Model} from 'ea-react-dm-v14'
@Model('GroupSyncModel')
export default class GroupSyncModel {
static rs
static list = []
static searchInfo = {
totalCount: 0,
page: 1,
pageSize: 10,
sort: 'id'
}
static states = {
editeVisible: false,
checkVisible: false
}
static columnInfo = {
column: [
{
name: 'Team 名称',
width: 20,
key: 'group_name',
sort: true
},
{
name: '备注',
width: 30,
key: 'group_comment'
},
{
name: '创建时间',
width: 10,
key: 'insert_time',
sort: true,
search: false
},
{
name: '操作人',
width: 20,
key: 'userRealName',
sort: true,
search: false,
sortKey: 'user_real_name'
},
{
name: '操作',
width: 10,
key: null,
button: {sync: true, syncTitle: '同步数据到当前环境,可重复操作'}
}
]
}
static group = {
id: 0,
group_name: '',
group_comment: ''
}
static tree = []
} | 20.727273 | 66 | 0.365497 |
f6d8bd02b16f8f7f19ffadc3ff73cbf04ac634e8 | 1,336 | js | JavaScript | api/models/Author.js | EstelleZhang1009/Extents_master1 | 9b8a813959c07b4be036584927e11002ff1409a2 | [
"Apache-2.0"
] | 118 | 2016-02-18T03:47:38.000Z | 2021-03-23T07:18:18.000Z | api/models/Author.js | EstelleZhang1009/Extents_master1 | 9b8a813959c07b4be036584927e11002ff1409a2 | [
"Apache-2.0"
] | 189 | 2016-02-18T03:49:10.000Z | 2017-11-28T11:48:08.000Z | api/models/Author.js | EstelleZhang1009/Extents_master1 | 9b8a813959c07b4be036584927e11002ff1409a2 | [
"Apache-2.0"
] | 56 | 2016-02-27T16:57:28.000Z | 2021-04-02T12:43:20.000Z | /**
* Author.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
/* tests (many) <-> authors (many)
* tests and authors have a many to many relationship
* - a test can be assigned with one or more authors
* - a author can have one or more tests
* In Waterline, from the Author model, to find tests:
* Author.find().populate('tests')..
*/
tests: {
collection: 'test',
via: 'authors'
},
project: {
model: 'project'
},
/* Owner
* A report can have one or more authors
* There is a one-to-many relationship between report and author
* In Waterline, from the Report model, it is possible to do:
* Report.find().populate('authors')..
*/
report: {
model: 'report'
},
testName: 'string',
name: 'string',
status: 'string'
},
getDistinctNames: function(cb) {
Author.native(function(err, collection) {
collection.distinct('name', function(err, result) {
if (err) console.log(err);
else cb(result);
});
});
},
};
| 25.207547 | 108 | 0.544162 |
f6da75413c2887943c1eb8a7b1de35b11827aa9d | 19,078 | js | JavaScript | src/three/TilesRenderer.js | ligaofeng0901/3DTilesRendererJS | 1a2dd7058f55facc63b2d9bece80ce32fe4e1ff2 | [
"Apache-2.0"
] | null | null | null | src/three/TilesRenderer.js | ligaofeng0901/3DTilesRendererJS | 1a2dd7058f55facc63b2d9bece80ce32fe4e1ff2 | [
"Apache-2.0"
] | null | null | null | src/three/TilesRenderer.js | ligaofeng0901/3DTilesRendererJS | 1a2dd7058f55facc63b2d9bece80ce32fe4e1ff2 | [
"Apache-2.0"
] | null | null | null | import { TilesRendererBase } from '../base/TilesRendererBase.js';
import { B3DMLoader } from './B3DMLoader.js';
import { PNTSLoader } from './PNTSLoader.js';
import { I3DMLoader } from './I3DMLoader.js';
import { CMPTLoader } from './CMPTLoader.js';
import { TilesGroup } from './TilesGroup.js';
import {
Matrix4,
Box3,
Sphere,
Vector3,
Vector2,
Frustum,
LoadingManager
} from 'three';
import { raycastTraverse, raycastTraverseFirstHit } from './raycastTraverse.js';
const INITIAL_FRUSTUM_CULLED = Symbol( 'INITIAL_FRUSTUM_CULLED' );
const tempMat = new Matrix4();
const tempMat2 = new Matrix4();
const tempVector = new Vector3();
const vecX = new Vector3();
const vecY = new Vector3();
const vecZ = new Vector3();
const X_AXIS = new Vector3( 1, 0, 0 );
const Y_AXIS = new Vector3( 0, 1, 0 );
function updateFrustumCulled( object, toInitialValue ) {
object.traverse( c => {
c.frustumCulled = c[ INITIAL_FRUSTUM_CULLED ] && toInitialValue;
} );
}
export class TilesRenderer extends TilesRendererBase {
get autoDisableRendererCulling() {
return this._autoDisableRendererCulling;
}
set autoDisableRendererCulling( value ) {
if ( this._autoDisableRendererCulling !== value ) {
super._autoDisableRendererCulling = value;
this.forEachLoadedModel( ( scene ) => {
updateFrustumCulled( scene, ! value );
} );
}
}
constructor( ...args ) {
super( ...args );
this.group = new TilesGroup( this );
this.cameras = [];
this.cameraMap = new Map();
this.cameraInfo = [];
this.activeTiles = new Set();
this.visibleTiles = new Set();
this._autoDisableRendererCulling = true;
this.optimizeRaycast = true;
this.onLoadTileSet = null;
this.onLoadModel = null;
this.onDisposeModel = null;
this.onTileVisibilityChange = null;
const manager = new LoadingManager();
manager.setURLModifier( url => {
if ( this.preprocessURL ) {
return this.preprocessURL( url );
} else {
return url;
}
} );
this.manager = manager;
// Setting up the override raycasting function to be used by
// 3D objects created by this renderer
const tilesRenderer = this;
this._overridenRaycast = function ( raycaster, intersects ) {
if ( ! tilesRenderer.optimizeRaycast ) {
Object.getPrototypeOf( this ).raycast.call( this, raycaster, intersects );
}
};
}
/* Public API */
getBounds( box ) {
if ( ! this.root ) {
return false;
}
const cached = this.root.cached;
const boundingBox = cached.box;
const obbMat = cached.boxTransform;
if ( boundingBox ) {
box.copy( boundingBox );
box.applyMatrix4( obbMat );
return true;
} else {
return false;
}
}
getOrientedBounds( box, matrix ) {
if ( ! this.root ) {
return false;
}
const cached = this.root.cached;
const boundingBox = cached.box;
const obbMat = cached.boxTransform;
if ( boundingBox ) {
box.copy( boundingBox );
matrix.copy( obbMat );
return true;
} else {
return false;
}
}
getBoundingSphere( sphere ) {
if ( ! this.root ) {
return false;
}
const boundingSphere = this.root.cached.sphere;
if ( boundingSphere ) {
sphere.copy( boundingSphere );
return true;
} else {
return false;
}
}
forEachLoadedModel( callback ) {
this.traverse( tile => {
const scene = tile.cached.scene;
if ( scene ) {
callback( scene, tile );
}
} );
}
raycast( raycaster, intersects ) {
if ( ! this.root ) {
return;
}
if ( raycaster.firstHitOnly ) {
const hit = raycastTraverseFirstHit( this.root, this.group, this.activeTiles, raycaster );
if ( hit ) {
intersects.push( hit );
}
} else {
raycastTraverse( this.root, this.group, this.activeTiles, raycaster, intersects );
}
}
hasCamera( camera ) {
return this.cameraMap.has( camera );
}
setCamera( camera ) {
const cameras = this.cameras;
const cameraMap = this.cameraMap;
if ( ! cameraMap.has( camera ) ) {
cameraMap.set( camera, new Vector2() );
cameras.push( camera );
return true;
}
return false;
}
setResolution( camera, xOrVec, y ) {
const cameraMap = this.cameraMap;
if ( ! cameraMap.has( camera ) ) {
return false;
}
if ( xOrVec instanceof Vector2 ) {
cameraMap.get( camera ).copy( xOrVec );
} else {
cameraMap.get( camera ).set( xOrVec, y );
}
return true;
}
setResolutionFromRenderer( camera, renderer ) {
const cameraMap = this.cameraMap;
if ( ! cameraMap.has( camera ) ) {
return false;
}
const resolution = cameraMap.get( camera );
renderer.getSize( resolution );
resolution.multiplyScalar( renderer.getPixelRatio() );
return true;
}
deleteCamera( camera ) {
const cameras = this.cameras;
const cameraMap = this.cameraMap;
if ( cameraMap.has( camera ) ) {
const index = cameras.indexOf( camera );
cameras.splice( index, 1 );
cameraMap.delete( camera );
return true;
}
return false;
}
/* Overriden */
fetchTileSet( url, ...rest ) {
const pr = super.fetchTileSet( url, ...rest );
pr.then( json => {
if ( this.onLoadTileSet ) {
// Push this onto the end of the event stack to ensure this runs
// after the base renderer has placed the provided json where it
// needs to be placed and is ready for an update.
Promise.resolve().then( () => {
this.onLoadTileSet( json, url );
} );
}
} );
return pr;
}
update() {
const group = this.group;
const cameras = this.cameras;
const cameraMap = this.cameraMap;
const cameraInfo = this.cameraInfo;
if ( cameras.length === 0 ) {
console.warn( 'TilesRenderer: no cameras defined. Cannot update 3d tiles.' );
return;
}
// automatically scale the array of cameraInfo to match the cameras
while ( cameraInfo.length > cameras.length ) {
cameraInfo.pop();
}
while ( cameraInfo.length < cameras.length ) {
cameraInfo.push( {
frustum: new Frustum(),
isOrthographic: false,
sseDenominator: - 1, // used if isOrthographic:false
position: new Vector3(),
invScale: - 1,
pixelSize: 0, // used if isOrthographic:true
} );
}
// extract scale of group container
tempMat2.copy( group.matrixWorld ).invert();
let invScale;
tempVector.setFromMatrixScale( tempMat2 );
invScale = tempVector.x;
if ( Math.abs( Math.max( tempVector.x - tempVector.y, tempVector.x - tempVector.z ) ) > 1e-6 ) {
console.warn( 'ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.' );
}
// store the camera cameraInfo in the 3d tiles root frame
for ( let i = 0, l = cameraInfo.length; i < l; i ++ ) {
const camera = cameras[ i ];
const info = cameraInfo[ i ];
const frustum = info.frustum;
const position = info.position;
const resolution = cameraMap.get( camera );
if ( resolution.width === 0 || resolution.height === 0 ) {
console.warn( 'TilesRenderer: resolution for camera error calculation is not set.' );
}
// Read the calculated projection matrix directly to support custom Camera implementations
const projection = camera.projectionMatrix.elements;
// The last element of the projection matrix is 1 for orthographic, 0 for perspective
info.isOrthographic = projection[ 15 ] === 1;
if ( info.isOrthographic ) {
// See OrthographicCamera.updateProjectionMatrix and Matrix4.makeOrthographic:
// the view width and height are used to populate matrix elements 0 and 5.
const w = 2 / projection[ 0 ];
const h = 2 / projection[ 5 ];
info.pixelSize = Math.max( h / resolution.height, w / resolution.width );
} else {
// See PerspectiveCamera.updateProjectionMatrix and Matrix4.makePerspective:
// the vertical FOV is used to populate matrix element 5.
info.sseDenominator = ( 2 / projection[ 5 ] ) / resolution.height;
}
info.invScale = invScale;
// get frustum in group root frame
tempMat.copy( group.matrixWorld );
tempMat.premultiply( camera.matrixWorldInverse );
tempMat.premultiply( camera.projectionMatrix );
frustum.setFromProjectionMatrix( tempMat );
// get transform position in group root frame
position.set( 0, 0, 0 );
position.applyMatrix4( camera.matrixWorld );
position.applyMatrix4( tempMat2 );
}
super.update();
}
preprocessNode( tile, parentTile, tileSetDir ) {
super.preprocessNode( tile, parentTile, tileSetDir );
const transform = new Matrix4();
if ( tile.transform ) {
const transformArr = tile.transform;
for ( let i = 0; i < 16; i ++ ) {
transform.elements[ i ] = transformArr[ i ];
}
} else {
transform.identity();
}
if ( parentTile ) {
transform.premultiply( parentTile.cached.transform );
}
const transformInverse = new Matrix4().copy( transform ).invert();
let box = null;
let boxTransform = null;
let boxTransformInverse = null;
if ( 'box' in tile.boundingVolume ) {
const data = tile.boundingVolume.box;
box = new Box3();
boxTransform = new Matrix4();
boxTransformInverse = new Matrix4();
// get the extents of the bounds in each axis
vecX.set( data[ 3 ], data[ 4 ], data[ 5 ] );
vecY.set( data[ 6 ], data[ 7 ], data[ 8 ] );
vecZ.set( data[ 9 ], data[ 10 ], data[ 11 ] );
const scaleX = vecX.length();
const scaleY = vecY.length();
const scaleZ = vecZ.length();
vecX.normalize();
vecY.normalize();
vecZ.normalize();
// handle the case where the box has a dimension of 0 in one axis
if ( scaleX === 0 ) {
vecX.crossVectors( vecY, vecZ );
}
if ( scaleY === 0 ) {
vecY.crossVectors( vecX, vecZ );
}
if ( scaleZ === 0 ) {
vecZ.crossVectors( vecX, vecY );
}
// create the oriented frame that the box exists in
boxTransform.set(
vecX.x, vecY.x, vecZ.x, data[ 0 ],
vecX.y, vecY.y, vecZ.y, data[ 1 ],
vecX.z, vecY.z, vecZ.z, data[ 2 ],
0, 0, 0, 1
);
boxTransform.premultiply( transform );
boxTransformInverse.copy( boxTransform ).invert();
// scale the box by the extents
box.min.set( - scaleX, - scaleY, - scaleZ );
box.max.set( scaleX, scaleY, scaleZ );
}
let sphere = null;
if ( 'sphere' in tile.boundingVolume ) {
const data = tile.boundingVolume.sphere;
sphere = new Sphere();
sphere.center.set( data[ 0 ], data[ 1 ], data[ 2 ] );
sphere.radius = data[ 3 ];
sphere.applyMatrix4( transform );
} else if ( 'box' in tile.boundingVolume ) {
const data = tile.boundingVolume.box;
sphere = new Sphere();
box.getBoundingSphere( sphere );
sphere.center.set( data[ 0 ], data[ 1 ], data[ 2 ] );
sphere.applyMatrix4( transform );
}
let region = null;
if ( 'region' in tile.boundingVolume ) {
console.warn( 'ThreeTilesRenderer: region bounding volume not supported.' );
}
tile.cached = {
loadIndex: 0,
transform,
transformInverse,
active: false,
inFrustum: [],
box,
boxTransform,
boxTransformInverse,
sphere,
region,
scene: null,
geometry: null,
material: null,
};
}
parseTile( buffer, tile, extension ) {
tile._loadIndex = tile._loadIndex || 0;
tile._loadIndex ++;
const uri = tile.content.uri;
const uriSplits = uri.split( /[\\\/]/g );
uriSplits.pop();
const workingPath = uriSplits.join( '/' );
const fetchOptions = this.fetchOptions;
const manager = this.manager;
const loadIndex = tile._loadIndex;
let promise = null;
switch ( extension ) {
case 'b3dm':
const loader = new B3DMLoader( manager );
loader.workingPath = workingPath;
loader.fetchOptions = fetchOptions;
promise = loader
.parse( buffer )
.then( res => res.scene );
break;
case 'pnts':
promise = Promise.resolve( new PNTSLoader( manager ).parse( buffer ).scene );
break;
case 'i3dm': {
const loader = new I3DMLoader( manager );
loader.workingPath = workingPath;
loader.fetchOptions = fetchOptions;
promise = loader
.parse( buffer )
.then( res => res.scene );
break;
}
case 'cmpt': {
const loader = new CMPTLoader( manager );
loader.workingPath = workingPath;
loader.fetchOptions = fetchOptions;
promise = loader
.parse( buffer )
.then( res => res.scene );
break;
}
default:
console.warn( `TilesRenderer: Content type "${ extension }" not supported.` );
promise = Promise.resolve( null );
break;
}
return promise.then( scene => {
if ( tile._loadIndex !== loadIndex ) {
return;
}
const upAxis = this.rootTileSet.asset && this.rootTileSet.asset.gltfUpAxis || 'y';
const cached = tile.cached;
const cachedTransform = cached.transform;
switch ( upAxis.toLowerCase() ) {
case 'x':
tempMat.makeRotationAxis( Y_AXIS, - Math.PI / 2 );
break;
case 'y':
tempMat.makeRotationAxis( X_AXIS, Math.PI / 2 );
break;
case 'z':
tempMat.identity();
break;
}
// ensure the matrix is up to date in case the scene has a transform applied
scene.updateMatrix();
// apply the local up-axis correction rotation
// GLTFLoader seems to never set a transformation on the root scene object so
// any transformations applied to it can be assumed to be applied after load
// (such as applying RTC_CENTER) meaning they should happen _after_ the z-up
// rotation fix which is why "multiply" happens here.
if ( extension !== 'pnts' ) {
scene.matrix.multiply( tempMat );
}
scene.matrix.premultiply( cachedTransform );
scene.matrix.decompose( scene.position, scene.quaternion, scene.scale );
scene.traverse( c => {
c[ INITIAL_FRUSTUM_CULLED ] = c.frustumCulled;
} );
updateFrustumCulled( scene, ! this.autoDisableRendererCulling );
cached.scene = scene;
// We handle raycasting in a custom way so remove it from here
scene.traverse( c => {
c.raycast = this._overridenRaycast;
} );
const materials = [];
const geometry = [];
const textures = [];
scene.traverse( c => {
if ( c.geometry ) {
geometry.push( c.geometry );
}
if ( c.material ) {
const material = c.material;
materials.push( c.material );
for ( const key in material ) {
const value = material[ key ];
if ( value && value.isTexture ) {
textures.push( value );
}
}
}
} );
cached.materials = materials;
cached.geometry = geometry;
cached.textures = textures;
if ( this.onLoadModel ) {
this.onLoadModel( scene, tile );
}
} );
}
disposeTile( tile ) {
// This could get called before the tile has finished downloading
const cached = tile.cached;
if ( cached.scene ) {
const materials = cached.materials;
const geometry = cached.geometry;
const textures = cached.textures;
for ( let i = 0, l = geometry.length; i < l; i ++ ) {
geometry[ i ].dispose();
}
for ( let i = 0, l = materials.length; i < l; i ++ ) {
materials[ i ].dispose();
}
for ( let i = 0, l = textures.length; i < l; i ++ ) {
const texture = textures[ i ];
texture.dispose();
}
if ( this.onDisposeModel ) {
this.onDisposeModel( cached.scene, tile );
}
cached.scene = null;
cached.materials = null;
cached.textures = null;
cached.geometry = null;
}
tile._loadIndex ++;
}
setTileVisible( tile, visible ) {
const scene = tile.cached.scene;
const visibleTiles = this.visibleTiles;
const group = this.group;
if ( visible ) {
group.add( scene );
visibleTiles.add( tile );
scene.updateMatrixWorld( true );
} else {
group.remove( scene );
visibleTiles.delete( tile );
}
if ( this.onTileVisibilityChange ) {
this.onTileVisibilityChange( scene, tile, visible );
}
}
setTileActive( tile, active ) {
const activeTiles = this.activeTiles;
if ( active ) {
activeTiles.add( tile );
} else {
activeTiles.delete( tile );
}
}
calculateError( tile ) {
const cached = tile.cached;
const inFrustum = cached.inFrustum;
const cameras = this.cameras;
const cameraInfo = this.cameraInfo;
// TODO: Use the content bounding volume here?
// TODO: We should use the largest distance to the tile between
// all available bounding volume types.
const boundingVolume = tile.boundingVolume;
if ( 'box' in boundingVolume || 'sphere' in boundingVolume ) {
const boundingSphere = cached.sphere;
const boundingBox = cached.box;
const boxTransformInverse = cached.boxTransformInverse;
const transformInverse = cached.transformInverse;
const useBox = boundingBox && boxTransformInverse;
let maxError = - Infinity;
let minDistance = Infinity;
for ( let i = 0, l = cameras.length; i < l; i ++ ) {
if ( ! inFrustum[ i ] ) {
continue;
}
// transform camera position into local frame of the tile bounding box
const info = cameraInfo[ i ];
const invScale = info.invScale;
let error;
if ( info.isOrthographic ) {
const pixelSize = info.pixelSize;
error = tile.geometricError / ( pixelSize * invScale );
} else {
tempVector.copy( info.position );
let distance;
if ( useBox ) {
tempVector.applyMatrix4( boxTransformInverse );
distance = boundingBox.distanceToPoint( tempVector );
} else {
tempVector.applyMatrix4( transformInverse );
// Sphere#distanceToPoint is negative inside the sphere, whereas Box3#distanceToPoint is
// zero inside the box. Clipping the distance to a minimum of zero ensures that both
// types of bounding volume behave the same way.
distance = Math.max( boundingSphere.distanceToPoint( tempVector ), 0 );
}
const scaledDistance = distance * invScale;
const sseDenominator = info.sseDenominator;
error = tile.geometricError / ( scaledDistance * sseDenominator );
minDistance = Math.min( minDistance, scaledDistance );
}
maxError = Math.max( maxError, error );
}
tile.__distanceFromCamera = minDistance;
tile.__error = maxError;
} else if ( 'region' in boundingVolume ) {
// unsupported
console.warn( 'ThreeTilesRenderer : Region bounds not supported.' );
}
}
tileInView( tile ) {
// TODO: we should use the more precise bounding volumes here if possible
// cache the root-space planes
// Use separating axis theorem for frustum and obb
const cached = tile.cached;
const sphere = cached.sphere;
const inFrustum = cached.inFrustum;
if ( sphere ) {
const cameraInfo = this.cameraInfo;
let inView = false;
for ( let i = 0, l = cameraInfo.length; i < l; i ++ ) {
// Track which camera frustums this tile is in so we can use it
// to ignore the error calculations for cameras that can't see it
const frustum = cameraInfo[ i ].frustum;
if ( frustum.intersectsSphere( sphere ) ) {
inView = true;
inFrustum[ i ] = true;
} else {
inFrustum[ i ] = false;
}
}
return inView;
}
return true;
}
}
| 20.103267 | 134 | 0.643464 |
f6dc21859c46549ffdac962a3c52af97438710ac | 5,516 | js | JavaScript | tests/integration/services/ajax-test.js | muyueh/Ghost-Admin | 8f39c12b83d01fcd5ff3fac3ef18763d1338ec8d | [
"MIT"
] | 2 | 2020-04-01T07:17:04.000Z | 2022-02-10T08:17:25.000Z | tests/integration/services/ajax-test.js | muyueh/Ghost-Admin | 8f39c12b83d01fcd5ff3fac3ef18763d1338ec8d | [
"MIT"
] | 1 | 2022-02-14T12:48:00.000Z | 2022-02-14T12:48:00.000Z | tests/integration/services/ajax-test.js | muyueh/Ghost-Admin | 8f39c12b83d01fcd5ff3fac3ef18763d1338ec8d | [
"MIT"
] | 1 | 2020-10-16T17:07:27.000Z | 2020-10-16T17:07:27.000Z | import Pretender from 'pretender';
import config from 'ghost-admin/config/environment';
import {describe, it} from 'mocha';
import {expect} from 'chai';
import {
isAjaxError,
isUnauthorizedError
} from 'ember-ajax/errors';
import {
isMaintenanceError,
isRequestEntityTooLargeError,
isUnsupportedMediaTypeError,
isVersionMismatchError
} from 'ghost-admin/services/ajax';
import {setupTest} from 'ember-mocha';
function stubAjaxEndpoint(server, response = {}, code = 200) {
server.get('/test/', function () {
return [
code,
{'Content-Type': 'application/json'},
JSON.stringify(response)
];
});
}
describe('Integration: Service: ajax', function () {
setupTest('service:ajax', {
integration: true
});
let server;
beforeEach(function () {
server = new Pretender();
});
afterEach(function () {
server.shutdown();
});
it('adds Ghost version header to requests', function (done) {
let {version} = config.APP;
let ajax = this.subject();
stubAjaxEndpoint(server, {});
ajax.request('/test/').then(() => {
let [request] = server.handledRequests;
expect(request.requestHeaders['X-Ghost-Version']).to.equal(version);
done();
});
});
it('correctly parses single message response text', function (done) {
let error = {message: 'Test Error'};
stubAjaxEndpoint(server, error, 500);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true();
}).catch((error) => {
expect(error.payload.errors.length).to.equal(1);
expect(error.payload.errors[0].message).to.equal('Test Error');
done();
});
});
it('correctly parses single error response text', function (done) {
let error = {error: 'Test Error'};
stubAjaxEndpoint(server, error, 500);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true();
}).catch((error) => {
expect(error.payload.errors.length).to.equal(1);
expect(error.payload.errors[0].message).to.equal('Test Error');
done();
});
});
it('correctly parses multiple error messages', function (done) {
let error = {errors: ['First Error', 'Second Error']};
stubAjaxEndpoint(server, error, 500);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true();
}).catch((error) => {
expect(error.payload.errors.length).to.equal(2);
expect(error.payload.errors[0].message).to.equal('First Error');
expect(error.payload.errors[1].message).to.equal('Second Error');
done();
});
});
it('returns default error object for non built-in error', function (done) {
stubAjaxEndpoint(server, {}, 500);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true;
}).catch((error) => {
expect(isAjaxError(error)).to.be.true;
done();
});
});
it('handles error checking for built-in errors', function (done) {
stubAjaxEndpoint(server, '', 401);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true;
}).catch((error) => {
expect(isUnauthorizedError(error)).to.be.true;
done();
});
});
it('handles error checking for VersionMismatchError', function (done) {
server.get('/test/', function () {
return [
400,
{'Content-Type': 'application/json'},
JSON.stringify({
errors: [{
errorType: 'VersionMismatchError',
statusCode: 400
}]
})
];
});
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true;
}).catch((error) => {
expect(isVersionMismatchError(error)).to.be.true;
done();
});
});
it('handles error checking for RequestEntityTooLargeError on 413 errors', function (done) {
stubAjaxEndpoint(server, {}, 413);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true;
}).catch((error) => {
expect(isRequestEntityTooLargeError(error)).to.be.true;
done();
});
});
it('handles error checking for UnsupportedMediaTypeError on 415 errors', function (done) {
stubAjaxEndpoint(server, {}, 415);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true;
}).catch((error) => {
expect(isUnsupportedMediaTypeError(error)).to.be.true;
done();
});
});
it('handles error checking for MaintenanceError on 503 errors', function (done) {
stubAjaxEndpoint(server, {}, 503);
let ajax = this.subject();
ajax.request('/test/').then(() => {
expect(false).to.be.true;
}).catch((error) => {
expect(isMaintenanceError(error)).to.be.true;
done();
});
});
});
| 29.031579 | 95 | 0.531907 |
f6dcee167b15c4a6d8883af53581c2c3fc9d43ff | 371 | js | JavaScript | packages/frontend/src/store/modules/auth.js | i62navpm/fireabaseWorkPart | cac3902b0d26f3d1066536a31a38284b9f6d418f | [
"MIT"
] | null | null | null | packages/frontend/src/store/modules/auth.js | i62navpm/fireabaseWorkPart | cac3902b0d26f3d1066536a31a38284b9f6d418f | [
"MIT"
] | null | null | null | packages/frontend/src/store/modules/auth.js | i62navpm/fireabaseWorkPart | cac3902b0d26f3d1066536a31a38284b9f6d418f | [
"MIT"
] | 1 | 2020-05-16T18:05:51.000Z | 2020-05-16T18:05:51.000Z | import { db } from '@/plugins/firebase/db'
export default {
state: {
user: null,
},
mutations: {
setUser: (state, user) => (state.user = user),
},
actions: {
setUser: ({ commit }, user) => commit('setUser', user),
createUser: (_, email) => db.collection('users').doc(email).set({}),
},
getters: {
getUser: (state) => state.user,
},
}
| 20.611111 | 72 | 0.555256 |
f6de512d27665f15ee94a4aae2eae8b58b066b41 | 310 | js | JavaScript | packages/customWidgets/signature-web/cypress/integration/Signature.spec.js | sirazmillath/widgets-resources | aa8871f96a1945e35a2817a37bd5cdbd0ce50d1e | [
"Apache-2.0"
] | null | null | null | packages/customWidgets/signature-web/cypress/integration/Signature.spec.js | sirazmillath/widgets-resources | aa8871f96a1945e35a2817a37bd5cdbd0ce50d1e | [
"Apache-2.0"
] | null | null | null | packages/customWidgets/signature-web/cypress/integration/Signature.spec.js | sirazmillath/widgets-resources | aa8871f96a1945e35a2817a37bd5cdbd0ce50d1e | [
"Apache-2.0"
] | null | null | null | describe("Signature", () => {
it("renders canvas", () => {
cy.visit("/");
cy.get(".widget-signature-canvas").should("be.visible");
});
it("renders grid", () => {
cy.visit("/p/GridSize");
cy.get(".widget-signature-grid").get("svg").should("be.visible");
});
});
| 25.833333 | 73 | 0.496774 |
f6de5e1bc5f1b15ac6ac2a4f4dd68786215b3d9b | 2,451 | js | JavaScript | __test__/test_helpers.js | gracecarey/Spoke | 17fcc5326be3c41b42a77147e4058d797ed6df7c | [
"MIT"
] | 2 | 2018-10-10T21:00:03.000Z | 2020-02-13T21:41:22.000Z | __test__/test_helpers.js | AFSCME/Spoke | c3129e6ef7789c911ce2c58690de27be95d8bee8 | [
"MIT"
] | null | null | null | __test__/test_helpers.js | AFSCME/Spoke | c3129e6ef7789c911ce2c58690de27be95d8bee8 | [
"MIT"
] | null | null | null | import {createLoaders, r} from '../src/server/models/'
import { sleep } from '../src/workers/lib'
export async function setupTest() {
createLoaders()
let i = 0
while (i++ < 4) {
const results = [await r.knex.schema.hasTable('assignment'),
await r.knex.schema.hasTable('campaign'),
await r.knex.schema.hasTable('campaign_contact'),
await r.knex.schema.hasTable('canned_response'),
await r.knex.schema.hasTable('interaction_step'),
await r.knex.schema.hasTable('invite'),
await r.knex.schema.hasTable('job_request'),
await r.knex.schema.hasTable('log'),
await r.knex.schema.hasTable('message'),
await r.knex.schema.hasTable('migrations'),
await r.knex.schema.hasTable('opt_out'),
await r.knex.schema.hasTable('organization'),
await r.knex.schema.hasTable('pending_message_part'),
await r.knex.schema.hasTable('question_response'),
await r.knex.schema.hasTable('user'),
await r.knex.schema.hasTable('user_cell'),
await r.knex.schema.hasTable('user_organization'),
await r.knex.schema.hasTable('zip_code')]
if (results.some((element) => !element)) {
await sleep(i * 1000)
}
else {
break
}
}
}
export async function cleanupTest() {
// Drop tables in an order that drops foreign keys before dependencies
await r.knex.schema.dropTableIfExists('log')
await r.knex.schema.dropTableIfExists('zip_code')
await r.knex.schema.dropTableIfExists('message')
await r.knex.schema.dropTableIfExists('user_cell')
await r.knex.schema.dropTableIfExists('user_organization')
await r.knex.schema.dropTableIfExists('canned_response')
await r.knex.schema.dropTableIfExists('invite')
await r.knex.schema.dropTableIfExists('job_request')
await r.knex.schema.dropTableIfExists('migrations')
await r.knex.schema.dropTableIfExists('opt_out')
await r.knex.schema.dropTableIfExists('question_response')
await r.knex.schema.dropTableIfExists('interaction_step')
await r.knex.schema.dropTableIfExists('campaign_contact')
await r.knex.schema.dropTableIfExists('assignment')
await r.knex.schema.dropTableIfExists('campaign')
await r.knex.schema.dropTableIfExists('organization')
await r.knex.schema.dropTableIfExists('pending_message_part')
await r.knex.schema.dropTableIfExists('user')
}
export function getContext(context) {
return {
...context,
req: {},
loaders: createLoaders(),
}
}
| 37.136364 | 72 | 0.716034 |
f6de61a08969460104a5779f404cbc01f1046b81 | 662 | js | JavaScript | src/components/Main.js | jer0701/gallery-by-react | d529c6bd8c1e8bbb6c691583b3322f84c7c8b361 | [
"MIT"
] | null | null | null | src/components/Main.js | jer0701/gallery-by-react | d529c6bd8c1e8bbb6c691583b3322f84c7c8b361 | [
"MIT"
] | null | null | null | src/components/Main.js | jer0701/gallery-by-react | d529c6bd8c1e8bbb6c691583b3322f84c7c8b361 | [
"MIT"
] | null | null | null | require('normalize.css/normalize.css');
require('styles/App.css');
import React from 'react';
import ReactDOM from 'react-dom';
import ReactCSSTransitionGroup from "react-addons-css-transition-group" ;
var AppComponent = React.createClass({
render() {
return (
<ReactCSSTransitionGroup className="content" component="div" transitionName="example" transitionEnterTimeout={1000} transitionLeaveTimeout={500}
>
{React.cloneElement(this.props.children, {
key: this.props.location.pathname
})}
</ReactCSSTransitionGroup>
);
}
});
AppComponent.defaultProps = {
};
export default AppComponent;
| 25.461538 | 154 | 0.691843 |
f6dece897b81f8255397c8e30cf12d947841668e | 83 | js | JavaScript | src/containers/index.js | soyjavi/watchman | ff032d814775ee7e9d48422fc16a7c5d9255a451 | [
"MIT"
] | 1 | 2018-04-08T18:58:01.000Z | 2018-04-08T18:58:01.000Z | src/containers/index.js | soyjavi/cryptos-bar | 9a27ba6ec87f6cf1e1580e794d2fefdc63055f68 | [
"MIT"
] | null | null | null | src/containers/index.js | soyjavi/cryptos-bar | 9a27ba6ec87f6cf1e1580e794d2fefdc63055f68 | [
"MIT"
] | null | null | null | import Menu from './Menu';
import Tray from './Tray';
export {
Menu,
Tray,
};
| 10.375 | 26 | 0.60241 |
f6df4f245ae027f160dbba6a315edb3253cbf4e1 | 152 | js | JavaScript | src/store/modules/cart/state.js | hassanAwanAlvi/COVID-19inventoryFrontENd | ba55983bf2c2e006f48704bf25a22ee3f127ef59 | [
"MIT"
] | null | null | null | src/store/modules/cart/state.js | hassanAwanAlvi/COVID-19inventoryFrontENd | ba55983bf2c2e006f48704bf25a22ee3f127ef59 | [
"MIT"
] | 3 | 2021-03-10T13:33:05.000Z | 2022-01-22T11:24:26.000Z | src/store/modules/cart/state.js | hassanAwanAlvi/COVID-19inventoryFrontENd | ba55983bf2c2e006f48704bf25a22ee3f127ef59 | [
"MIT"
] | null | null | null | const cartState = {
cart:
{
cart_item_count: 0,
cart_item: [],
total_price: 0
}
}
export { cartState }
| 13.818182 | 29 | 0.460526 |
f6e015aa6f4542dcaae376f07eea4e88487f5e49 | 1,908 | js | JavaScript | dist/rollup-plugin-extension-mapper.js | franklin-ross/rollup-plugin-extension-mapper | 5e2bc26f1d84c80679d6deb020eae16db16ccba5 | [
"0BSD"
] | null | null | null | dist/rollup-plugin-extension-mapper.js | franklin-ross/rollup-plugin-extension-mapper | 5e2bc26f1d84c80679d6deb020eae16db16ccba5 | [
"0BSD"
] | null | null | null | dist/rollup-plugin-extension-mapper.js | franklin-ross/rollup-plugin-extension-mapper | 5e2bc26f1d84c80679d6deb020eae16db16ccba5 | [
"0BSD"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = plugin;
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function plugin(options = {}) {
//List of transform functions to try for each path. The first which returns a value wins.
const transformers = [];
//Ensures the provided string begins with a period and adds one if not.
const ensureHasLeadingDot = ext => ext.startsWith(".") ? ext : "." + ext;
//Builds a list of transform functions.
for (let extension in options) if (options.hasOwnProperty(extension)) {
const value = options[extension];
extension = ensureHasLeadingDot(extension);
let transform;
if (typeof value === "function") {
transform = value;
} else if (typeof value === "string") {
const newExtension = ensureHasLeadingDot(value);
const oldExtension = extension;
transform = (importee, importer) => {
const newFileName = importee.substr(0, importee.length - oldExtension.length) + newExtension;
const importDir = _path2.default.dirname(importer);
return _path2.default.resolve(importDir, newFileName);
};
} else {
console.warn(`rollup-plugin-extension-mapper expects the value of options.${extension} to be a string or a function`);
continue;
}
transformers.push((importee, importer) => {
if (typeof importee === "string" && importee.endsWith(extension)) {
return transform(importee, importer);
}
return undefined;
});
}
return {
resolveId(importee, importer) {
for (let transformer of transformers) {
const result = transformer(importee, importer);
if (result) {
return result;
}
}
return undefined;
}
};
}
| 30.774194 | 124 | 0.654088 |
f6e090b49f2295b2593728f01b77f11b5805ae57 | 1,112 | js | JavaScript | i18n/zh-CN.js | skyydq/uniapp-admin | 320fd05593a3c376414e73dde2d8d27ddd61e037 | [
"Apache-2.0"
] | 312 | 2019-10-26T23:46:16.000Z | 2022-03-27T05:08:35.000Z | i18n/zh-CN.js | gaecom/uniapp-admin | 75dc1f3de5fa9573a38b989e07109c0ae7472b17 | [
"Apache-2.0"
] | 7 | 2020-04-04T11:47:05.000Z | 2021-06-19T01:27:35.000Z | i18n/zh-CN.js | gaecom/uniapp-admin | 75dc1f3de5fa9573a38b989e07109c0ae7472b17 | [
"Apache-2.0"
] | 115 | 2019-10-27T01:54:34.000Z | 2022-02-17T06:56:43.000Z | export default {
'ProjectApproval': '项目审批',
'ProjectAdjust': '项目调整',
'UserApproval': '用户审批',
'FilePreview': '文件预览',
'Project': '项目',
'YzCloud': '永中云服务',
'YzDocPreview': '永中云预览',
'YzDocEdit': '永中云编辑',
'YzDocPreviewEdit': '永中云预览/云编辑',
'DocUpload': '文档上传',
'ProjectDetail': '项目详细',
'Statistics': '统计',
'Profile': '我的',
'ToDo': '待办',
'Language': '语言',
'Empty': '空',
'HardLoading': '努力加载中',
'NoMore': '没有了',
'BasicInfo': '基本信息',
'UserName': '用户名',
'Name': '姓名',
'Role': '角色',
'RegisteredUser': '注册用户',
'ProjectThisMonth': '本月项目',
'Ok': '确认',
'ClearSearchHistory': '清空搜索历史',
'Settings': '软件设置',
'SignOut': '退出登录',
'ChangePassword': '修改密码',
'Upgrade': '软件升级',
'System': '跟随系统',
'English': '英文',
'Chinese': '中文',
'en': '英文',
'zh-CN': '中文',
'Theme': '主题',
'BluishGreen': '青碧',
'Blush': '酡颜',
'Volcano': '火山',
'Orange': '橘黄',
'IndigoBlue': '靛青',
'Indigo': '靛蓝',
'Verdant': '苍翠',
'Water': '水色',
'Grey': '灰色',
'PinkGold': '赤金',
'Dim': '黯',
'Verdigris': '铜绿',
'DeepBlack': '玄青',
'AgateGreen': '湖绿',
'DarkGreen': '苍色',
'DarkMode': '深色模式',
'Dark': '暗黑',
'ToLogin': '去登录'
}
| 19.508772 | 33 | 0.556655 |
f6e13671d7bea78eae855abfdd63826f003265f1 | 6,165 | js | JavaScript | node_modules/angular-calendar/esm5/modules/week/calendar-week-view-hour-segment.component.js | bmkarthik610/ambipalm | eeace84443869f3950c1cfa6700cfbc8f50a1f88 | [
"OML",
"RSA-MD"
] | null | null | null | node_modules/angular-calendar/esm5/modules/week/calendar-week-view-hour-segment.component.js | bmkarthik610/ambipalm | eeace84443869f3950c1cfa6700cfbc8f50a1f88 | [
"OML",
"RSA-MD"
] | 4 | 2021-05-11T19:50:39.000Z | 2022-02-27T08:05:15.000Z | node_modules/angular-calendar/esm5/modules/week/calendar-week-view-hour-segment.component.js | bmkarthik610/ambipalm | eeace84443869f3950c1cfa6700cfbc8f50a1f88 | [
"OML",
"RSA-MD"
] | null | null | null | import * as tslib_1 from "tslib";
import { Component, Input, TemplateRef } from '@angular/core';
var CalendarWeekViewHourSegmentComponent = /** @class */ (function () {
function CalendarWeekViewHourSegmentComponent() {
}
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", Object)
], CalendarWeekViewHourSegmentComponent.prototype, "segment", void 0);
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", Number)
], CalendarWeekViewHourSegmentComponent.prototype, "segmentHeight", void 0);
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", String)
], CalendarWeekViewHourSegmentComponent.prototype, "locale", void 0);
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", Boolean)
], CalendarWeekViewHourSegmentComponent.prototype, "isTimeLabel", void 0);
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", Number)
], CalendarWeekViewHourSegmentComponent.prototype, "daysInWeek", void 0);
tslib_1.__decorate([
Input(),
tslib_1.__metadata("design:type", TemplateRef)
], CalendarWeekViewHourSegmentComponent.prototype, "customTemplate", void 0);
CalendarWeekViewHourSegmentComponent = tslib_1.__decorate([
Component({
selector: 'mwl-calendar-week-view-hour-segment',
template: "\n <ng-template\n #defaultTemplate\n let-segment=\"segment\"\n let-locale=\"locale\"\n let-segmentHeight=\"segmentHeight\"\n let-isTimeLabel=\"isTimeLabel\"\n let-daysInWeek=\"daysInWeek\"\n >\n <div\n [attr.aria-hidden]=\"\n {}\n | calendarA11y\n : (daysInWeek === 1\n ? 'hideDayHourSegment'\n : 'hideWeekHourSegment')\n \"\n class=\"cal-hour-segment\"\n [style.height.px]=\"segmentHeight\"\n [class.cal-hour-start]=\"segment.isStart\"\n [class.cal-after-hour-start]=\"!segment.isStart\"\n [ngClass]=\"segment.cssClass\"\n >\n <div class=\"cal-time\" *ngIf=\"isTimeLabel\">\n {{\n segment.displayDate\n | calendarDate\n : (daysInWeek === 1 ? 'dayViewHour' : 'weekViewHour')\n : locale\n }}\n </div>\n </div>\n </ng-template>\n <ng-template\n [ngTemplateOutlet]=\"customTemplate || defaultTemplate\"\n [ngTemplateOutletContext]=\"{\n segment: segment,\n locale: locale,\n segmentHeight: segmentHeight,\n isTimeLabel: isTimeLabel,\n daysInWeek: daysInWeek\n }\"\n >\n </ng-template>\n "
})
], CalendarWeekViewHourSegmentComponent);
return CalendarWeekViewHourSegmentComponent;
}());
export { CalendarWeekViewHourSegmentComponent };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2FsZW5kYXItd2Vlay12aWV3LWhvdXItc2VnbWVudC5jb21wb25lbnQuanMiLCJzb3VyY2VSb290Ijoibmc6Ly9hbmd1bGFyLWNhbGVuZGFyLyIsInNvdXJjZXMiOlsibW9kdWxlcy93ZWVrL2NhbGVuZGFyLXdlZWstdmlldy1ob3VyLXNlZ21lbnQuY29tcG9uZW50LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxPQUFPLEVBQUUsU0FBUyxFQUFFLEtBQUssRUFBRSxXQUFXLEVBQUUsTUFBTSxlQUFlLENBQUM7QUFtRDlEO0lBQUE7SUFZQSxDQUFDO0lBWFU7UUFBUixLQUFLLEVBQUU7O3lFQUE4QjtJQUU3QjtRQUFSLEtBQUssRUFBRTs7K0VBQXVCO0lBRXRCO1FBQVIsS0FBSyxFQUFFOzt3RUFBZ0I7SUFFZjtRQUFSLEtBQUssRUFBRTs7NkVBQXNCO0lBRXJCO1FBQVIsS0FBSyxFQUFFOzs0RUFBb0I7SUFFbkI7UUFBUixLQUFLLEVBQUU7MENBQWlCLFdBQVc7Z0ZBQU07SUFYL0Isb0NBQW9DO1FBaERoRCxTQUFTLENBQUM7WUFDVCxRQUFRLEVBQUUscUNBQXFDO1lBQy9DLFFBQVEsRUFBRSxzeENBNENUO1NBQ0YsQ0FBQztPQUNXLG9DQUFvQyxDQVloRDtJQUFELDJDQUFDO0NBQUEsQUFaRCxJQVlDO1NBWlksb0NBQW9DIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgQ29tcG9uZW50LCBJbnB1dCwgVGVtcGxhdGVSZWYgfSBmcm9tICdAYW5ndWxhci9jb3JlJztcbmltcG9ydCB7IFdlZWtWaWV3SG91clNlZ21lbnQgfSBmcm9tICdjYWxlbmRhci11dGlscyc7XG5cbkBDb21wb25lbnQoe1xuICBzZWxlY3RvcjogJ213bC1jYWxlbmRhci13ZWVrLXZpZXctaG91ci1zZWdtZW50JyxcbiAgdGVtcGxhdGU6IGBcbiAgICA8bmctdGVtcGxhdGVcbiAgICAgICNkZWZhdWx0VGVtcGxhdGVcbiAgICAgIGxldC1zZWdtZW50PVwic2VnbWVudFwiXG4gICAgICBsZXQtbG9jYWxlPVwibG9jYWxlXCJcbiAgICAgIGxldC1zZWdtZW50SGVpZ2h0PVwic2VnbWVudEhlaWdodFwiXG4gICAgICBsZXQtaXNUaW1lTGFiZWw9XCJpc1RpbWVMYWJlbFwiXG4gICAgICBsZXQtZGF5c0luV2Vlaz1cImRheXNJbldlZWtcIlxuICAgID5cbiAgICAgIDxkaXZcbiAgICAgICAgW2F0dHIuYXJpYS1oaWRkZW5dPVwiXG4gICAgICAgICAge31cbiAgICAgICAgICAgIHwgY2FsZW5kYXJBMTF5XG4gICAgICAgICAgICAgIDogKGRheXNJbldlZWsgPT09IDFcbiAgICAgICAgICAgICAgICAgID8gJ2hpZGVEYXlIb3VyU2VnbWVudCdcbiAgICAgICAgICAgICAgICAgIDogJ2hpZGVXZWVrSG91clNlZ21lbnQnKVxuICAgICAgICBcIlxuICAgICAgICBjbGFzcz1cImNhbC1ob3VyLXNlZ21lbnRcIlxuICAgICAgICBbc3R5bGUuaGVpZ2h0LnB4XT1cInNlZ21lbnRIZWlnaHRcIlxuICAgICAgICBbY2xhc3MuY2FsLWhvdXItc3RhcnRdPVwic2VnbWVudC5pc1N0YXJ0XCJcbiAgICAgICAgW2NsYXNzLmNhbC1hZnRlci1ob3VyLXN0YXJ0XT1cIiFzZWdtZW50LmlzU3RhcnRcIlxuICAgICAgICBbbmdDbGFzc109XCJzZWdtZW50LmNzc0NsYXNzXCJcbiAgICAgID5cbiAgICAgICAgPGRpdiBjbGFzcz1cImNhbC10aW1lXCIgKm5nSWY9XCJpc1RpbWVMYWJlbFwiPlxuICAgICAgICAgIHt7XG4gICAgICAgICAgICBzZWdtZW50LmRpc3BsYXlEYXRlXG4gICAgICAgICAgICAgIHwgY2FsZW5kYXJEYXRlXG4gICAgICAgICAgICAgICAgOiAoZGF5c0luV2VlayA9PT0gMSA/ICdkYXlWaWV3SG91cicgOiAnd2Vla1ZpZXdIb3VyJylcbiAgICAgICAgICAgICAgICA6IGxvY2FsZVxuICAgICAgICAgIH19XG4gICAgICAgIDwvZGl2PlxuICAgICAgPC9kaXY+XG4gICAgPC9uZy10ZW1wbGF0ZT5cbiAgICA8bmctdGVtcGxhdGVcbiAgICAgIFtuZ1RlbXBsYXRlT3V0bGV0XT1cImN1c3RvbVRlbXBsYXRlIHx8IGRlZmF1bHRUZW1wbGF0ZVwiXG4gICAgICBbbmdUZW1wbGF0ZU91dGxldENvbnRleHRdPVwie1xuICAgICAgICBzZWdtZW50OiBzZWdtZW50LFxuICAgICAgICBsb2NhbGU6IGxvY2FsZSxcbiAgICAgICAgc2VnbWVudEhlaWdodDogc2VnbWVudEhlaWdodCxcbiAgICAgICAgaXNUaW1lTGFiZWw6IGlzVGltZUxhYmVsLFxuICAgICAgICBkYXlzSW5XZWVrOiBkYXlzSW5XZWVrXG4gICAgICB9XCJcbiAgICA+XG4gICAgPC9uZy10ZW1wbGF0ZT5cbiAgYFxufSlcbmV4cG9ydCBjbGFzcyBDYWxlbmRhcldlZWtWaWV3SG91clNlZ21lbnRDb21wb25lbnQge1xuICBASW5wdXQoKSBzZWdtZW50OiBXZWVrVmlld0hvdXJTZWdtZW50O1xuXG4gIEBJbnB1dCgpIHNlZ21lbnRIZWlnaHQ6IG51bWJlcjtcblxuICBASW5wdXQoKSBsb2NhbGU6IHN0cmluZztcblxuICBASW5wdXQoKSBpc1RpbWVMYWJlbDogYm9vbGVhbjtcblxuICBASW5wdXQoKSBkYXlzSW5XZWVrOiBudW1iZXI7XG5cbiAgQElucHV0KCkgY3VzdG9tVGVtcGxhdGU6IFRlbXBsYXRlUmVmPGFueT47XG59XG4iXX0= | 158.076923 | 3,278 | 0.818005 |
f6e1503e5cd84fee82422258be8ec354ecad3144 | 1,051 | js | JavaScript | jslint-xml.js | edklimov/ring-ui | 5e0364909285b305eba0731ebaff434e058318de | [
"Apache-2.0"
] | 3,080 | 2017-08-02T14:16:01.000Z | 2022-03-31T09:24:10.000Z | jslint-xml.js | edklimov/ring-ui | 5e0364909285b305eba0731ebaff434e058318de | [
"Apache-2.0"
] | 1,209 | 2017-08-05T01:26:35.000Z | 2022-03-31T10:45:01.000Z | jslint-xml.js | edklimov/ring-ui | 5e0364909285b305eba0731ebaff434e058318de | [
"Apache-2.0"
] | 202 | 2017-08-03T12:55:12.000Z | 2022-03-31T09:47:44.000Z | // eslint-disable-next-line no-control-regex
const xmlEscape = s => (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/g, c => {
switch (c) {
case '<':
return '<';
case '>':
return '>';
case '&':
return '&';
case '"':
return '"';
case '\'':
return ''';
default:
return `&#${c.charCodeAt(0)};`;
}
});
module.exports = results => {
const files = results.map(file => {
const warnings = file.warnings.map(({column, line, text}) => {
const css = file._postcssResult && file._postcssResult.css;
const lines = css && css.split('\n') || [];
const evidence = lines[line - 1];
return [
`<issue line="${line}"`,
` char="${column}"`,
` evidence="${evidence ? xmlEscape(evidence) : ''}"`,
` reason="${xmlEscape(text)}" />`
].join('');
});
return `<file name="${file.source}">${warnings.join('')}</file>`;
});
return `<?xml version="1.0" encoding="utf-8"?><jslint>${files.join('')}</jslint>`;
};
| 26.948718 | 84 | 0.504282 |
f6e17b024335c9b812c98c4252945a89db649579 | 26,357 | js | JavaScript | docs/yoda-release-notes.js | LaudateCorpus1/yoda | 4d92a242d8747f5b5791650ea67709f993f8c3eb | [
"MIT"
] | 76 | 2018-03-07T20:52:36.000Z | 2022-03-28T04:38:21.000Z | docs/yoda-release-notes.js | LaudateCorpus1/yoda | 4d92a242d8747f5b5791650ea67709f993f8c3eb | [
"MIT"
] | 17 | 2018-02-02T15:59:26.000Z | 2022-01-04T07:45:59.000Z | docs/yoda-release-notes.js | LaudateCorpus1/yoda | 4d92a242d8747f5b5791650ea67709f993f8c3eb | [
"MIT"
] | 30 | 2018-03-07T20:55:24.000Z | 2022-01-11T08:21:05.000Z | // Copyright 2018 Hewlett Packard Enterprise Development LP
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT.
//
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Global variable controlling whether bars should be stacked or not.
// If stacked, then tool will not do a "totals" line and a corresponding right axis.
var ALL_MILESTONES = -1;
var repoList = []; // selected repos
var repoMilestones = []; // Double-array of repos,milestone (full structure) for selected repos
var commonMilestones = []; // Options for milestone selection (milestones in all repos).
var milestoneList = []; // selected milestones just the title
var milestoneListComplete = []; // selected milestones, full structure.
var repoIssues = []; // List of issues. Full structure as returned from github.
var download = false; // global - a bit of a hack.
function addIfNotDefault(params, field) {
var defaultValue = $("#" + field).prop('defaultValue');
// Hack. Make sure no real newlines into default value.
defaultValue = defaultValue.replace(/\n/g, "");
var value = $("#" + field).val();
if (value != defaultValue) {
console.log("value: " + value);
console.log("defa : " + defaultValue);
return params + "&" + field + "=" + value;
} else {
return params;
}
}
function getUrlParams() {
var params = "owner=" + $("#owner").val();
if ($("#repolist").val() != "")
params += "&repolist=" + $("#repolist").val();
if ($("#milestonelist").val() != "")
params += "&milestonelist=" + $("#milestonelist").val();
params = addIfNotDefault(params, "labelfilter");
params = addIfNotDefault(params, "rnlabeltypes");
params = addIfNotDefault(params, "rnknownlabeltypes");
params = addIfNotDefault(params, "rnskiplabel");
params = addIfNotDefault(params, "rnmetalabel");
params = addIfNotDefault(params, "rnknownlabel");
params = addIfNotDefault(params, "hlformat");
params = addIfNotDefault(params, "sformat");
params = addIfNotDefault(params, "ssformat");
params = addIfNotDefault(params, "listformat");
params = addIfNotDefault(params, "catformat");
params = addIfNotDefault(params, "rnformat");
params = addIfNotDefault(params, "catlabel");
if (yoda.getEstimateInIssues() != "inbody")
params += "&estimate=" + yoda.getEstimateInIssues();
var outputFormat = $('input:radio[name="outputformat"]:checked').val();
if (outputFormat != "html")
params += "&outputformat=" + outputFormat;
if ($('#closedmilestones').is(":checked")) {
params += "&closedmilestones=true";
}
if (!$('#tablelayout').is(":checked")) {
params += "&tablelayout=false";
}
if ($('#estimatecategory').is(":checked")) {
params += "&estimatecategory=true";
}
if ($('#estimateissue').is(":checked")) {
params += "&estimateissue=true";
}
return params;
}
function copy_text(element) {
//Before we copy, we are going to select the text.
var text = document.getElementById(element);
var selection = window.getSelection();
selection.removeAllRanges();
var range = document.createRange();
range.selectNodeContents(text);
selection.addRange(range);
// Now that we've selected element, execute the copy command
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy to clipboard command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy to clipboard');
}
// Remove selection. TBD: Remove, when copy works.
// selection.removeAllRanges();
}
// Remove elements in array that have duplicates based on a given field.
function uniqueArray(arr, field) {
return arr.filter(function(element, index, array, thisArg) {return array.findIndex(function(e, i, a, t)
{if (index != i && element[field] == e[field]) return true; else return false;}) == -1;});
}
// --------
// Add issues, making sure to avoid duplicates.
function addIssues(oldIssues, newIssues) {
return uniqueArray(oldIssues.concat(newIssues), "url");
}
function getFormat(formatArray, index) {
var f = formatArray[index];
f = f.replace(/\\n/g, '\n');
return f;
}
//Parse RN markdown to HTML (if any)
function parseRNMarkdown(markdown) {
// console.log(markdown);
var markdownUrl = yoda.getGithubUrl() + "markdown";
markdown = markdown.replace(/<br>/g, '<br>\n'); // A bit of a hack, but best way to handle that sometimes people have done lists using markdown, other times with bullets.
// console.log("markdownUrl: " + markdownUrl);
var urlData = {
"text": markdown
};
var result = "";
$.ajax({
url: markdownUrl,
type: 'POST',
async: false,
data: JSON.stringify(urlData),
success: function(data) { result = data;},
error: function() { yoda.showSnackbarError("Failed to translate Markdown"); },
complete: function(jqXHR, textStatus) { }
});
// console.log(result);
return result;
}
//Create a List node to based on the given issue.
function formatIssueRN(issue) {
var rnFormat = $("#rnformat").val();
var repo = yoda.getUrlRepo(issue.url);
if ($('input:radio[name="outputformat"]:checked').val()== "html")
var newLine = "<br>";
else
var newLine = "<br>";
var issueText = "";
var line = yoda.extractKeywordField(issue.body, "RNT", "single", newLine);
// console.log("line:" + line + ":");
if (line != "")
var title = line;
else
var title = issue.title;
var rnText = yoda.extractKeywordField(issue.body, "RN", "paragraph", newLine);
// console.log("rnText:" + rnText + ":");
// HTML?
var mdChars = /[*`_~>]+/;
if ($('input:radio[name="outputformat"]:checked').val()== "html" && rnText != "" && mdChars.test(rnText))
rnText = parseRNMarkdown(rnText);
if ($('input:radio[name="outputformat"]:checked').val()== "html" && title != "" && mdChars.test(title))
title = parseRNMarkdown(title);
// substitude into template
issueText = rnFormat;
// issueText = issueText.replaceAll(/\\n/g, "\n");
issueText = issueText.replace(/%t/, title);
issueText = issueText.replace(/%d/, repo + "#" + issue.number);
issueText = issueText.replace(/%n/, issue.number);
issueText = issueText.replace(/%r/, rnText);
var estimate = yoda.getBodyEstimate(issue.body);
if (estimate == null)
estimate = "";
issueText = issueText.replace(/%e/, estimate);
if (rnText != "") {
issueText = issueText.replace(/%y/, rnText);
// Don't add newLines if there is already a paragraph.
if (rnText.indexOf("<p>") == -1)
issueText = issueText.replace(/%x/, newLine + newLine + rnText);
else
issueText = issueText.replace(/%x/, rnText);
console.log(":" + issueText + ":");
} else {
issueText = issueText.replace(/%x/, "");
issueText = issueText.replace(/%y/, title);
}
return issueText;
}
function makeRN(headline, changesOrKnown, draw) {
var rn = document.getElementById("RN");
var repoList = $("#repolist").val();
var rnText = "";
// T2 - Enhancements|Added Features,T1 - Defect|Solved Issues
if (draw == "known")
var rnLabelTypes = $("#rnknownlabeltypes").val();
else
var rnLabelTypes = $("#rnlabeltypes").val();
var rnLabelTypesList = rnLabelTypes.split(",");
// Skip label
var rnSkipLabel = $("#rnskiplabel").val();
// Will be something like...
// var issueTypeList = ["T2 - Enhancement", "T1 - Defect"];
// var issueTypeHeading = ["Added Features", "Solved Issues"];
// Get formatting
var hlFormat = $("#hlformat").val().split(",");
var sFormat = $("#sformat").val().split(",");
var ssFormat = $("#ssformat").val().split(",");
var listFormat = $("#listformat").val().split(",");
var catFormat = $("#catformat").val();
// Headline - if present. Otherwise skip.
if ($("#hlformat").val().indexOf(",") != -1)
rnText += getFormat(hlFormat, 0) + headline + $("#milestonelist").val() + getFormat(hlFormat, 1);
// Categories. First build list based on regular expression (if any)
var categories = [];
var catLabel = $("#catlabel").val().split(",");
if (catLabel.length == 2) {
var catReg = new RegExp(catLabel[1]);
for (var i = 0; i < repoIssues.length; i++) {
for (var l=0; l < repoIssues[i].labels.length; l++) {
var labelName = repoIssues[i].labels[l].name;
var res = labelName.match(catReg);
if (res != null) {
catName = labelName;
if (res[1] != undefined)
catName = res[1];
if (categories.findIndex(function(c) {return (c.labelName == labelName)}) == -1) {
console.log("Found new category: " + catName);
categories.push({labelName: labelName, catName: catName});
}
}
}
}
// Sort the labels (before generic) alphabetically
categories = categories.sort(function(a,b) {return (a.catName < b.catName?-1:1);});
// Add fallback category
categories.push({labelName: "_FALLBACK_", catName: catLabel[0]});
console.log("List of categories:");
console.log(categories);
} else {
// Synthesize a category (hack to allow looping overit below).
categories.push({labelName: "_DUMMY_"});
}
// Loop over repos
for (var r = 0; r < repoList.length; r++) {
// Section - if present. Otherwise skip.
if ($("#sformat").val().indexOf(",") != -1)
rnText += getFormat(sFormat, 0) + changesOrKnown + repoList[r] + getFormat(sFormat, 1);
// Loop over labelTypes (typically Defects, Fixes)
for (var t = 0; t < rnLabelTypesList.length; t++) {
var rnList = "";
// Loop over categories (possibly the single _DUMMY_ entry - see above
for (var c = 0; c < categories.length; c++) {
var categoryEstimate = 0;
var categoryHeader = "";
if (categories[c].labelName != "_DUMMY_") {
categoryHeader = getFormat(listFormat, 2) + catFormat + getFormat(listFormat, 3);
categoryHeader = categoryHeader.replace(/%c/, categories[c].catName);
}
var issuesInCategory = 0;
// Loop over the issues putting into the right categories.
for (var i = 0; i < repoIssues.length; i++) {
// Match repo?.
var repository = repoIssues[i].repository_url.split("/").splice(-1); // Repo name is last element in the url
if (repository != repoList[r])
continue;
// Match issue type (in label)
if (!yoda.isLabelInIssue(repoIssues[i], rnLabelTypesList[t].split("|")[0]))
continue;
// Match category (if using categories at all)
// What if several labels match- suggest we add them in both/all places where there is a match.
if (!yoda.isLabelInIssue(repoIssues[i], categories[c].labelName) &&
categories[c].labelName != "_FALLBACK_" && categories[c].labelName != "_DUMMY_")
continue;
// FALLBACK handling
if (categories[c].labelName == "_FALLBACK_") {
var otherFound = false;
// Check if labels match any of the categories.
for (var c1 = 0; c1 < categories.length; c1++)
if (c != c1 && yoda.isLabelInIssue(repoIssues[i], categories[c1].labelName))
otherFound = true;
if (otherFound)
continue;
}
// Should issue be skipped
if (yoda.isLabelInIssue(repoIssues[i], rnSkipLabel))
continue;
if (issuesInCategory++ == 0)
rnList += categoryHeader;
var issueEstimate = yoda.getBodyEstimate(repoIssues[i].body);
if (issueEstimate != null)
categoryEstimate += issueEstimate;
rnList += getFormat(listFormat, 2) + formatIssueRN(repoIssues[i]) + getFormat(listFormat, 3);
}
// Update category total
rnList = rnList.replace(/%z/, categoryEstimate);
}
if (rnList != "" ) {
// Put header and list, but only if non-empty.
// If ssformat is blank, forget starting over, skip the header
if ($("#ssformat").val().indexOf(",") != -1)
rnText += getFormat(ssFormat, 0) + rnLabelTypesList[t].split("|")[1] + getFormat(ssFormat, 1);
rnText += getFormat(listFormat, 0) + rnList + getFormat(listFormat, 1);
}
}
}
if ($('input:radio[name="outputformat"]:checked').val() == "html") {
rn.innerHTML = rnText;
} else {
rn.innerHTML = "<pre>" + rnText + "</pre>";
}
// Download?
if (download) {
var fileName = $("#filename").val() + "." + $('input:radio[name="outputformat"]:checked').val();
console.log("Downloading to " + fileName);
var appType = "application/" + $('input:radio[name="outputformat"]:checked').val() + ";charset=utf-8;";
yoda.downloadFileWithType(appType, rnText, fileName);
}
// Copy to clipboard
copy_text("RN");
yoda.updateUrl(getUrlParams() + "&draw=" + draw);
}
// -----------
function startRN(_download) {
download = _download;
updateIssuesForRN();
}
function startKnown(_download) {
download = _download;
updateIssuesKnown();
}
// ---------------
function updateRepos() {
yoda.updateReposAndGUI($("#owner").val(), "#repolist", "repolist", "yoda.repolist", null, null);
}
// -------------
function storeMilestones(milestones, repoIndex) {
repoMilestones[repoIndex] = milestones;
updateMilestones(repoIndex + 1);
}
var firstMilestoneShow = true;
function updateMilestones(repoIndex) {
console.log("updateMilestones " + repoIndex);
if (repoIndex == undefined) {
repoIndex = 0;
}
if (repoIndex < repoList.length) {
if ($('#closedmilestones').is(":checked")) {
var getMilestonesUrl = yoda.getGithubUrl() + "repos/" + $("#owner").val() + "/" + repoList[repoIndex] + "/milestones?state=all";
} else {
var getMilestonesUrl = yoda.getGithubUrl() + "repos/" + $("#owner").val() + "/" + repoList[repoIndex] + "/milestones?state=open";
}
console.log("Milestone get URL: " + getMilestonesUrl);
yoda.getLoop(getMilestonesUrl, 1, [], function(data) {storeMilestones(data, repoIndex);}, null);
} else {
var selectMilestones = [];
if (firstMilestoneShow) {
firstMilestoneShow = false;
var urlMilestoneList = yoda.decodeUrlParam(null, "milestonelist");
if (urlMilestoneList != null)
selectMilestones = urlMilestoneList.split(",");
}
// Done getting milestones for all selected repos
// Next, find common milestones and update milestones selector.
$("#milestonelist").empty();
commonMilestones = [];
for (var r = 0; r < repoList.length; r++) {
for (var m = 0; m < repoMilestones[r].length; m++) {
var repoTitle = repoMilestones[r][m].title;
if (commonMilestones.indexOf(repoTitle) == -1) {
commonMilestones.push(repoTitle);
}
}
}
// Sort and add
commonMilestones.sort();
console.log("The common milestones are: " + commonMilestones);
var milestonesSelected = false;
for (var c = 0; c < commonMilestones.length; c++) {
var selectMilestone = false;
if (selectMilestones.indexOf(commonMilestones[c]) != -1) {
selectMilestone = true;
milestonesSelected = true;
}
var newOption = new Option(commonMilestones[c], commonMilestones[c], selectMilestone, selectMilestone);
$('#milestonelist').append(newOption);
}
if (milestonesSelected)
$('#milestonelist').trigger('change');
}
}
// -------------
function storeIssues(issues, milestoneIndex, myUpdateIssueActiveNo) {
if (myUpdateIssueActiveNo < updateIssueActiveNo) {
console.log("Update is not latest. Cancelling...");
// I'm out of date. cancel
return;
}
// repoIssues = repoIssues.concat(issues);
repoIssues = addIssues(repoIssues, issues);
console.log("total number of issues now: " + repoIssues.length);
updateIssueLoop(milestoneIndex + 1, myUpdateIssueActiveNo);
}
function updateMetaIssuesThenRN(metaIssuesList) {
if (metaIssuesList.length > 0) {
var getIssueUrl = metaIssuesList[0];
yoda.getLoop(getIssueUrl, -1, [], function(data) {repoIssues = addIssues(repoIssues, data); metaIssuesList.splice(0, 1); updateMetaIssuesThenRN(metaIssuesList);}, null);
} else {
// Let's sort issues on number. This may be required as we allow to retrieve issues from different milestones.
// Sort by repository, number
repoIssues.sort(function(a,b) {
if (a.repository_url == b.repository_url) {
return (a.number - b.number);
}
if (a.repository_url > b.repository_url) {
return 1;
} else {
return -1;
}
});
console.log("No issues (after filtering out pull requests): " + repoIssues.length);
yoda.showSnackbarOk("Succesfully retrived " + repoIssues.length + " issues.");
makeRN("Release notes for ", "Changes for ", "rn");
}
}
var updateIssueActiveNo = 0;
function updateIssueLoop(milestoneIndex, myUpdateIssueActiveNo) {
if (myUpdateIssueActiveNo < updateIssueActiveNo) {
console.log("Update is not latest. Cancelling...");
// I'm out of date. cancel
return;
}
console.log("UpdateIssueLoop: " + milestoneIndex);
if (milestoneIndex < milestoneListComplete.length) {
var milestone = milestoneListComplete[milestoneIndex];
var repo = yoda.getRepoFromMilestoneUrl(milestone.url);
var milestoneSearch = "&milestone=" + milestone.number;
console.log("milestone.number: " + milestone.number);
// Special situaton for milestone -1 (all milestones)
if (milestone.number == ALL_MILESTONES)
milestoneSearch = "";
var filterSearch = "";
if ($("#labelfilter").val() != "") {
filterSearch = "&labels=" + $("#labelfilter").val();
}
var getIssuesUrl = yoda.getGithubUrl() + "repos/" + $("#owner").val() + "/" + repo + "/issues?state=all&direction=asc" + milestoneSearch + filterSearch;
// console.log(getIssuesUrl);
yoda.getLoop(getIssuesUrl, 1, [], function(data) {storeIssues(data, milestoneIndex, myUpdateIssueActiveNo)}, null);
} else {
// Requested (and received all issues).
console.log("All issues (before filtering out pull requests): " + repoIssues.length);
yoda.filterPullRequests(repoIssues);
// Is this a good place to handle Meta-issues?
var metaIssuesList = [];
var rnMetaLabel = $("#rnmetalabel").val();
for (var i = 0; i < repoIssues.length; i++) {
// Meta issue? Special handling required
if (yoda.isLabelInIssue(repoIssues[i], rnMetaLabel)) {
console.log("Meta issue: " + repoIssues[i].number);
var metaStart = repoIssues[i].body.indexOf('> META ');
if (metaStart == -1) {
// No Meta-tag, let's try with '> contains'
var refLineReg = '(^([ ]*)-( \\[([ xX])\\])?[ ]*(((.*\/)?.*)?#[1-9][0-9]*)[ ]*(.*)|(..*)$)';
// Regexp for full block, ie. starting with e.g. "> contains (data, will be updated)" followed directly by n lines
// ^> contains[ ]*(.*)$((\r?\n)+^- \[([ xX])\][ ]*(((.*\/)?.*)?#[1-9][0-9]*)[ ]*(.*)$)*
var issueStart = new RegExp("^[ ]*> contains[ ]*(.*)$([\r]?[\n]?" + refLineReg + ")*", "mg");
var blockStart = issueStart.exec(repoIssues[i].body);
if (blockStart != null) {
var block = blockStart[0];
// Extract just the child part, i.e. take way contains issue reference lines (or text to remember).
var startChildBlock = block.indexOf('\n');
var childBlock = block.substr(startChildBlock);
// Let's loop the issues using the refLineReg regular expression..
var reg = new RegExp(refLineReg, 'mg');
do {
var res = reg.exec(childBlock);
if (res != null) {
var refEntry = {};
// Did we match a LOCAL issue reference?
if (res[0].trim().startsWith("-") && res[0].indexOf("#") != -1) {
var ref = res[5];
if (ref.startsWith("#")) {
var urlRef = repoIssues[i].url.replace(/\/[0-9]+$/g, "/" + ref.substr(1));
console.log("urlRef = " + urlRef);
metaIssuesList.push(urlRef);
} else {
// Non local.
repoSearch = "/repos/";
var repoIndex = repoIssues[i].url.indexOf(repoSearch);
if (repoIndex != -1) {
repoIndex += repoSearch.length;
var urlRef = repoIssues[i].url.substr(0, repoIndex) + ref.replace(/#/, "/issues/");
console.log("urlRef = " + urlRef);
metaIssuesList.push(urlRef);
}
}
}
}
} while (res != null);
}
} else {
// > META format...
var lineEnd = repoIssues[i].body.indexOf('\n', metaStart);
if (lineEnd == -1)
lineEnd = repoIssues[i].body.length;
var metaLine = repoIssues[i].body.substr(metaStart + 7, lineEnd);
var issuesRawList = metaLine.split(/\s+/);
console.log(issuesRawList);
for (var j = 0; j < issuesRawList.length; j++) {
if (issuesRawList[j].indexOf("#") == -1)
continue;
var ref = issuesRawList[j].trim().replace(/#/g, "");
var urlRef = repoIssues[i].url.replace(/\/[0-9]+$/g, "/" + ref);
console.log("urlRef = " + urlRef);
metaIssuesList.push(urlRef);
}
}
}
}
updateMetaIssuesThenRN(metaIssuesList);
}
}
function updateIssuesForRN() {
updateIssueActiveNo++;
console.log("UpdateIssueActive: " + updateIssueActiveNo);
// Ok, here we go. This is the tricky part.
// We will get issues for all selected milestones for all selected repos.
milestoneListComplete = [];
// Handle situation where no milestones are specified, but we do have a labelFilter. In this case, we will take all issues based on the filter
if (milestoneList.length == 0 && $("#labelfilter").val() != "") {
console.log("No milestones selected, but filter present. Getting all issues based on filter only.");
for (var r = 0; r < repoList.length; r++) {
// console.log(" For repo: " + repoList[r]);
milestoneListComplete.push({number: ALL_MILESTONES, url: yoda.getGithubUrl() + "repos/" + $("#owner").val() + "/" + repoList[r] + "/milestone/-1"}); // Dummy value
}
} else {
// Normal handling
for (var m = 0; m < milestoneList.length; m++) {
// console.log("Updating issues for milestone: " + milestoneList[m]);
for (var r = 0; r < repoList.length; r++) {
// console.log(" For repo: " + repoList[r]);
// Need to find the milestone (the number)..
for (var m1 = 0; m1 < repoMilestones[r].length; m1++) {
// console.log(repoMilestones[r][m1].title);
if (repoMilestones[r][m1].title == milestoneList[m]) {
console.log("Need to get issues for " + repoList[r] + ", " + milestoneList[m] + ", which has number: " + repoMilestones[r][m1].number);
milestoneListComplete.push(repoMilestones[r][m1]);
}
}
}
}
}
console.log("Total list of milestones for which to get issues");
console.log(milestoneListComplete);
repoIssues = [];
updateIssueLoop(0, updateIssueActiveNo);
}
// --------------
function updateIssuesKnownLoop(repoRemainList, issues) {
// repoIssues = repoIssues.concat(issues);
repoIssues = addIssues(repoIssues, issues);
console.log(repoRemainList);
if (repoRemainList.length == 0) {
makeRN("Known limitations and issues ", "Known issues for ", "known");
return;
}
var repo = repoRemainList[0];
var newRemain = repoRemainList.slice(0);
newRemain.splice(0, 1);
console.log(newRemain);
var getIssuesUrl = yoda.getGithubUrl() + "repos/" + $("#owner").val() + "/" + repo + "/issues?state=open&labels=" + $("#rnknownlabel").val();
yoda.getLoop(getIssuesUrl, 1, [], function(data) {updateIssuesKnownLoop(newRemain, data)}, null);
}
function updateIssuesKnown() {
repoIssues = [];
updateIssuesKnownLoop(repoList, []);
}
// --------------
function githubAuth() {
console.log("Github authentisation: " + $("#user").val() + ", token: " + $("#token").val());
yoda.gitAuth($("#user").val(), $("#token").val());
}
// --------------
function setDefaultAndValue(id, value) {
element = document.getElementById(id);
element.defaultValue = value;
element.value = value;
}
function changeOutput() {
value = $('input:radio[name="outputformat"]:checked').val();
if ($('#estimatecategory').is(":checked"))
cat = "%c (total %z)";
else
cat = "%c";
if ($('#estimateissue').is(":checked"))
iss = "%d (%e)"
else
iss = "%d";
switch (value) {
case "html":
if ($('#tablelayout').is(":checked")) {
// HPE SA format
setDefaultAndValue("hlformat", "<H1>,</H1>\\n");
setDefaultAndValue("sformat", "<H2>,</H2>\\n");
setDefaultAndValue("ssformat", "<H3>,</H3>\\n");
setDefaultAndValue("listformat", "<table><thead><tr><th width=10%>Number</th><th width=90%>Description</th></tr></thead><tbody>\n,</tbody></table>\n,<tr>\n,</tr>\n");
setDefaultAndValue("rnformat", "<td>" + iss + "</td><td>%t%x</td>");
setDefaultAndValue("catformat", '<td colspan=2 class="ic"><b>' + cat + '</b></td>');
} else {
setDefaultAndValue("hlformat", "<H1>,</H1>\\n");
setDefaultAndValue("sformat", "<H2>,</H2>\\n");
setDefaultAndValue("ssformat", "<H3>,</H3>\\n");
setDefaultAndValue("listformat", "<UL>\\n,</UL>\\n,<LI>\\n,</LI>\\n");
setDefaultAndValue("rnformat", "%t (" + iss + ")<BLOCKQUOTE>%r</BLOCKQUOTE>");
setDefaultAndValue("catformat", "<H4>" + cat + "</H4>");
}
break;
case "md":
case "rst": // Note: for now same as md
if ($('#tablelayout').is(":checked")) {
setDefaultAndValue("hlformat", "# ,\\n\\n");
setDefaultAndValue("sformat", "## ,\\n\\n");
setDefaultAndValue("ssformat", "### ,\\n\\n");
setDefaultAndValue("listformat", "Number | Description\\n--------|-------------\\n,\\n,,\\n");
setDefaultAndValue("rnformat", iss + " | %t%x");
setDefaultAndValue("catformat", "*" + cat + "*");
} else {
setDefaultAndValue("hlformat", "# ,\\n\\n");
setDefaultAndValue("sformat", "## ,\\n\\n");
setDefaultAndValue("ssformat", "### ,\\n\\n");
setDefaultAndValue("listformat", ",,- ,\\n\\n");
setDefaultAndValue("rnformat", "%t (" + iss + ")%x");
setDefaultAndValue("catformat", "*" + cat + "*");
}
break;
}
} | 34.817701 | 173 | 0.639223 |
f6e237eb99fb76de335101692860eaaf2c306052 | 157 | js | JavaScript | src/App.js | larissapissurno/tech-list | 3c3e4b0c446285de2d47242fca727c5fab785251 | [
"MIT"
] | null | null | null | src/App.js | larissapissurno/tech-list | 3c3e4b0c446285de2d47242fca727c5fab785251 | [
"MIT"
] | null | null | null | src/App.js | larissapissurno/tech-list | 3c3e4b0c446285de2d47242fca727c5fab785251 | [
"MIT"
] | null | null | null | import React from 'react';
import './App.css';
import TechList from './components/TechList';
function App() {
return <TechList />
}
export default App; | 14.272727 | 45 | 0.694268 |
f6e23db21827c03df0809b9f96743686a21480cc | 1,831 | js | JavaScript | docs/documentation/search/variables_a.js | mattateusb7/NamelessEngine | 14055477b6f873baab7b01ef8508f559a0b72fc0 | [
"MIT"
] | 2 | 2018-07-19T12:19:08.000Z | 2018-07-20T15:20:32.000Z | docs/documentation/search/variables_a.js | mattateusb7/NamelessEngine-Framework | 14055477b6f873baab7b01ef8508f559a0b72fc0 | [
"MIT"
] | null | null | null | docs/documentation/search/variables_a.js | mattateusb7/NamelessEngine-Framework | 14055477b6f873baab7b01ef8508f559a0b72fc0 | [
"MIT"
] | null | null | null | var searchData=
[
['layer',['Layer',['../class___n_l_1_1_core_1_1_u_i.html#ab2f89a111f22bf3aeacb065a2ed02179',1,'_NL::Core::UI']]],
['leftlight',['LeftLight',['../class_cockpit_controller.html#ac9afd897e2e2b0c8e13a4aad6e437355',1,'CockpitController']]],
['lifetime',['lifeTime',['../class___n_l_1_1_object_1_1_particle_obj.html#a1b841297a355a60dd63f0917e5ef7ce1',1,'_NL::Object::ParticleObj']]],
['lightcolor',['lightColor',['../struct___n_l_1_1_core_1_1_light_properties.html#aeaca2df1b5926b2bf7007cb5fd40d40d',1,'_NL::Core::LightProperties']]],
['lightdirection',['lightDirection',['../struct___n_l_1_1_core_1_1_light_properties.html#a8e3640ee106094082f118795447d1228',1,'_NL::Core::LightProperties']]],
['lightposition',['lightPosition',['../struct___n_l_1_1_core_1_1_light_properties.html#a434e0387480f888516841c9fecbe3d79',1,'_NL::Core::LightProperties']]],
['lightproperties',['LightProperties',['../class___n_l_1_1_object_1_1_light_object.html#a3d485913c418dad4ad459b0360486753',1,'_NL::Object::LightObject']]],
['lights',['Lights',['../class___n_l_1_1_engine_1_1_n_l_manager.html#ab68a26d6db7552bfeb300365c99d6ece',1,'_NL::Engine::NLManager']]],
['lightspotinnerangle',['lightSpotInnerAngle',['../struct___n_l_1_1_core_1_1_light_properties.html#a25f3a8e3914992a6bcc2a7a94d5db873',1,'_NL::Core::LightProperties']]],
['lightspotouterangle',['lightSpotOuterAngle',['../struct___n_l_1_1_core_1_1_light_properties.html#a1e0324453d71079ebcf2ff6a2e37db49',1,'_NL::Core::LightProperties']]],
['loadedtexture',['LoadedTexture',['../class___n_l_1_1_tools_1_1_texture_loader.html#a4cc0cf3f0f6fac66b241e15b21e32ed3',1,'_NL::Tools::TextureLoader']]],
['lookat',['LookAt',['../struct___n_l_1_1_object_1_1_camera_obj_1_1transform.html#a4a86f4becfda5b747a811b577c726644',1,'_NL::Object::CameraObj::transform']]]
];
| 114.4375 | 170 | 0.794102 |
f6e24e4a64693bb7d158db886155133bfd0443fc | 1,494 | js | JavaScript | app/scripts/modules/core/src/pipeline/config/pipelineConfig.module.js | scopely/deck | 3ac539e6f720985916c0d9c618bd4d08d4697b2e | [
"Apache-2.0"
] | 1 | 2018-04-17T14:30:01.000Z | 2018-04-17T14:30:01.000Z | app/scripts/modules/core/src/pipeline/config/pipelineConfig.module.js | scopely/deck | 3ac539e6f720985916c0d9c618bd4d08d4697b2e | [
"Apache-2.0"
] | 3 | 2020-09-04T03:41:36.000Z | 2021-03-11T04:39:10.000Z | app/scripts/modules/core/src/pipeline/config/pipelineConfig.module.js | scopely/deck | 3ac539e6f720985916c0d9c618bd4d08d4697b2e | [
"Apache-2.0"
] | 3 | 2018-08-31T06:41:23.000Z | 2021-01-07T09:35:33.000Z | 'use strict';
const angular = require('angular');
import { CREATE_PIPELINE_COMPONENT } from './createPipeline.component';
import { PIPELINE_GRAPH_COMPONENT } from './graph/pipeline.graph.component';
import { REQUIRED_FIELD_VALIDATOR } from './validation/requiredField.validator';
import { SERVICE_ACCOUNT_ACCESS_VALIDATOR } from './validation/serviceAccountAccess.validator';
import { STAGE_BEFORE_TYPE_VALIDATOR } from './validation/stageBeforeType.validator';
import { STAGE_OR_TRIGGER_BEFORE_TYPE_VALIDATOR } from './validation/stageOrTriggerBeforeType.validator';
import { TARGET_IMPEDANCE_VALIDATOR } from './validation/targetImpedance.validator';
import './pipelineConfig.less';
module.exports = angular.module('spinnaker.core.pipeline.config', [
CREATE_PIPELINE_COMPONENT,
require('./actions/actions.module.js').name,
PIPELINE_GRAPH_COMPONENT,
require('./stages/stage.module.js').name,
require('./stages/baseProviderStage/baseProviderStage.js').name,
require('./triggers/trigger.module.js').name,
require('./parameters/pipeline.module.js').name,
require('./pipelineConfig.controller.js').name,
require('./pipelineConfigView.js').name,
require('./pipelineConfigurer.js').name,
REQUIRED_FIELD_VALIDATOR,
TARGET_IMPEDANCE_VALIDATOR,
STAGE_OR_TRIGGER_BEFORE_TYPE_VALIDATOR,
STAGE_BEFORE_TYPE_VALIDATOR,
SERVICE_ACCOUNT_ACCESS_VALIDATOR,
require('./targetSelect.directive.js').name,
require('./health/stagePlatformHealthOverride.directive.js').name,
]);
| 43.941176 | 105 | 0.790495 |
f6e29432cb137316d5e4a3a68be06cce8e14b247 | 234 | js | JavaScript | database.js | NewmanFajardo/express-api-rest-cleaning-service | bd0008564a84d01df9d1edf67f63f5c1ef032751 | [
"MIT"
] | null | null | null | database.js | NewmanFajardo/express-api-rest-cleaning-service | bd0008564a84d01df9d1edf67f63f5c1ef032751 | [
"MIT"
] | null | null | null | database.js | NewmanFajardo/express-api-rest-cleaning-service | bd0008564a84d01df9d1edf67f63f5c1ef032751 | [
"MIT"
] | null | null | null | const mongoose = require('mongoose');
const URI = "mongodb://localhost/cleaningService";
mongoose.connect(URI)
.then(db => console.log('DB is connected'))
.catch(err => console.error(err));
module.exports = mongoose; | 29.25 | 51 | 0.675214 |
f6e2d575d48ac43e410a77fa2c709d74c2a0a779 | 677 | js | JavaScript | queries/teacherApp.js | PandaProgrammingHub/ls | 0e5d501b1bf7cc6b12bd917e896c2edb0cd3c0fc | [
"MIT",
"Unlicense"
] | null | null | null | queries/teacherApp.js | PandaProgrammingHub/ls | 0e5d501b1bf7cc6b12bd917e896c2edb0cd3c0fc | [
"MIT",
"Unlicense"
] | null | null | null | queries/teacherApp.js | PandaProgrammingHub/ls | 0e5d501b1bf7cc6b12bd917e896c2edb0cd3c0fc | [
"MIT",
"Unlicense"
] | null | null | null | var config = require('../knexfile');
var knex = require('knex')(config);
var configmysql = require('../knexfileGamma');
var knexmysql = require('knex')(configmysql);
exports.forTASClassDivisions = function(academic_year_id, school_user_id, school_id){
return knex.from('school_classes as sc')
.innerJoin('class_master as c', 'sc.class_id', 'c.id')
.innerJoin('division_id as d', 'sc.', 'd.id')
.select([
'sc.id as _id',
'sc.school_id as _schoolid',
'sc.class_id as _classid',
'sc.division_id as _divisionid',
'c.id as _class_id',
'c.name as _classs_name',
'c.class_type as _class_type',
'd.id as _divison'
])
} | 33.85 | 85 | 0.649926 |
f6e3061b44abb65e41499d1f1793674d575da0ce | 1,176 | js | JavaScript | src/App.js | deepaksing/covid19_Tracker_India | 738ccdb9e8b77c67514bbdad612f962a3b60caab | [
"MIT"
] | null | null | null | src/App.js | deepaksing/covid19_Tracker_India | 738ccdb9e8b77c67514bbdad612f962a3b60caab | [
"MIT"
] | null | null | null | src/App.js | deepaksing/covid19_Tracker_India | 738ccdb9e8b77c67514bbdad612f962a3b60caab | [
"MIT"
] | null | null | null | import React,{useState, useEffect} from 'react';
import axios from 'axios';
import Level from './Level';
import Tables from './Tables';
import './App.css';
import Header from './Header';
import Footer from './Footer';
const App = () => {
const [states, setStates] = useState([]);
const [stateDistrictWiseData, setStateDistrictWiseData] = useState({});
useEffect(() => {
getStates();
}, [])
const getStates = async() => {
const [
{data},
{data: stateDistrictWiseResponse},
] = await Promise.all([
axios.get('https://api.covid19india.org/data.json'),
axios.get('https://api.covid19india.org/state_district_wise.json'),
axios.get('https://api.covid19india.org/state_test_data.json'),
]);
setStates(data.statewise);
setStateDistrictWiseData(stateDistrictWiseResponse);
}
return (
<div clasName = "main">
<Header/>
<div className="content">
{states && <Level data = {states[0]}/>}
{states &&
<Tables
states={states}
district={stateDistrictWiseData}
/>
}
</div>
<Footer/>
</div>
)
}
export default App; | 24 | 75 | 0.596939 |
f6e348c750f6f880d97808a8df0f5cb315a7d2fb | 9,794 | js | JavaScript | js/bitso.js | morgwn-shaw/bttb | a0e8dac53f233f747ad1c50c13a1d4b2d0ca14a5 | [
"MIT"
] | 3 | 2017-11-19T22:08:29.000Z | 2018-02-21T11:14:41.000Z | js/bitso.js | morgwn-shaw/bttb | a0e8dac53f233f747ad1c50c13a1d4b2d0ca14a5 | [
"MIT"
] | null | null | null | js/bitso.js | morgwn-shaw/bttb | a0e8dac53f233f747ad1c50c13a1d4b2d0ca14a5 | [
"MIT"
] | null | null | null | "use strict";
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange')
const { ExchangeError } = require ('./base/errors')
// ---------------------------------------------------------------------------
module.exports = class bitso extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitso',
'name': 'Bitso',
'countries': 'MX', // Mexico
'rateLimit': 2000, // 30 requests per minute
'version': 'v3',
'hasCORS': true,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766335-715ce7aa-5ed5-11e7-88a8-173a27bb30fe.jpg',
'api': 'https://api.bitso.com',
'www': 'https://bitso.com',
'doc': 'https://bitso.com/api_info',
},
'api': {
'public': {
'get': [
'available_books',
'ticker',
'order_book',
'trades',
],
},
'private': {
'get': [
'account_status',
'balance',
'fees',
'fundings',
'fundings/{fid}',
'funding_destination',
'kyc_documents',
'ledger',
'ledger/trades',
'ledger/fees',
'ledger/fundings',
'ledger/withdrawals',
'mx_bank_codes',
'open_orders',
'order_trades/{oid}',
'orders/{oid}',
'user_trades',
'user_trades/{tid}',
'withdrawals/',
'withdrawals/{wid}',
],
'post': [
'bitcoin_withdrawal',
'debit_card_withdrawal',
'ether_withdrawal',
'orders',
'phone_number',
'phone_verification',
'phone_withdrawal',
'spei_withdrawal',
],
'delete': [
'orders/{oid}',
'orders/all',
],
},
},
});
}
async fetchMarkets () {
let markets = await this.publicGetAvailableBooks ();
let result = [];
for (let i = 0; i < markets['payload'].length; i++) {
let market = markets['payload'][i];
let id = market['book'];
let symbol = id.toUpperCase ().replace ('_', '/');
let [ base, quote ] = symbol.split ('/');
let limits = {
'amount': {
'min': parseFloat (market['minimum_amount']),
'max': parseFloat (market['maximum_amount']),
},
'price': {
'min': parseFloat (market['minimum_price']),
'max': parseFloat (market['maximum_price']),
},
'cost': {
'min': parseFloat (market['minimum_value']),
'max': parseFloat (market['maximum_value']),
},
};
let precision = {
'amount': this.precisionFromString (market['minimum_amount']),
'price': this.precisionFromString (market['minimum_price']),
};
let lot = limits['amount']['min'];
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
'lot': lot,
'limits': limits,
'precision': precision,
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privateGetBalance ();
let balances = response['payload']['balances'];
let result = { 'info': response };
for (let b = 0; b < balances.length; b++) {
let balance = balances[b];
let currency = balance['currency'].toUpperCase ();
let account = {
'free': parseFloat (balance['available']),
'used': parseFloat (balance['locked']),
'total': parseFloat (balance['total']),
};
result[currency] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, params = {}) {
await this.loadMarkets ();
let response = await this.publicGetOrderBook (this.extend ({
'book': this.marketId (symbol),
}, params));
let orderbook = response['payload'];
let timestamp = this.parse8601 (orderbook['updated_at']);
return this.parseOrderBook (orderbook, timestamp, 'bids', 'asks', 'price', 'amount');
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let response = await this.publicGetTicker (this.extend ({
'book': this.marketId (symbol),
}, params));
let ticker = response['payload'];
let timestamp = this.parse8601 (ticker['created_at']);
let vwap = parseFloat (ticker['vwap']);
let baseVolume = parseFloat (ticker['volume']);
let quoteVolume = baseVolume * vwap;
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': parseFloat (ticker['high']),
'low': parseFloat (ticker['low']),
'bid': parseFloat (ticker['bid']),
'ask': parseFloat (ticker['ask']),
'vwap': vwap,
'open': undefined,
'close': undefined,
'first': undefined,
'last': parseFloat (ticker['last']),
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
};
}
parseTrade (trade, market = undefined) {
let timestamp = this.parse8601 (trade['created_at']);
let symbol = undefined;
if (!market) {
if ('book' in trade)
market = this.markets_by_id[trade['book']];
}
if (market)
symbol = market['symbol'];
return {
'id': trade['tid'].toString (),
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'order': undefined,
'type': undefined,
'side': trade['maker_side'],
'price': parseFloat (trade['price']),
'amount': parseFloat (trade['amount']),
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetTrades (this.extend ({
'book': market['id'],
}, params));
return this.parseTrades (response['payload'], market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let order = {
'book': this.marketId (symbol),
'side': side,
'type': type,
'major': this.amountToPrecision (symbol, amount),
};
if (type == 'limit')
order['price'] = this.priceToPrecision (symbol, price);
let response = await this.privatePostOrders (this.extend (order, params));
return {
'info': response,
'id': response['payload']['oid'],
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
return await this.privateDeleteOrders ({ 'oid': id });
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let query = '/' + this.version + '/' + this.implodeParams (path, params);
let url = this.urls['api'] + query;
if (api == 'public') {
if (Object.keys (params).length)
url += '?' + this.urlencode (params);
} else {
let nonce = this.nonce ().toString ();
let request = [ nonce, method, query ].join ('');
if (Object.keys (params).length) {
body = this.json (params);
request += body;
}
let signature = this.hmac (this.encode (request), this.encode (this.secret));
let auth = this.apiKey + ':' + nonce + ':' + signature;
headers = {
'Authorization': "Bitso " + auth,
'Content-Type': 'application/json',
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let response = await this.fetch2 (path, api, method, params, headers, body);
if ('success' in response)
if (response['success'])
return response;
throw new ExchangeError (this.id + ' ' + this.json (response));
}
}
| 37.239544 | 126 | 0.445987 |
f6e4326de824cead262b6292fae6b169b255e4f7 | 401 | js | JavaScript | potion/js/8-yaml-front-matter.js | zeusricote/zeusricote.github.io | 183b8dc09c00810a6e206672e881a08b9287b808 | [
"MIT"
] | null | null | null | potion/js/8-yaml-front-matter.js | zeusricote/zeusricote.github.io | 183b8dc09c00810a6e206672e881a08b9287b808 | [
"MIT"
] | null | null | null | potion/js/8-yaml-front-matter.js | zeusricote/zeusricote.github.io | 183b8dc09c00810a6e206672e881a08b9287b808 | [
"MIT"
] | null | null | null | YAML.loadFront = function (text, name) {
name = name || '__content';
var re = /^-{3}([\w\W]+?)(-{3})([\w\W]*)*/
, results = re.exec(text)
, conf;
if(results) {
conf = YAML.parse(results[1]);
if(typeof results[3] !== 'undefined') conf[name] = results[3];
}
return conf;
};
YAML.createFront = function (data) {
var yaml = YAML.stringify(data);
return "---\n"+yaml+"---\n";
} | 25.0625 | 66 | 0.553616 |
f6e49e5b2df7c2b3ce2a871e3c218c935293a7f9 | 1,087 | js | JavaScript | core/modules/server/routes/put-tiddler.js | 8d1h/TiddlyWiki5 | 97dff042f752ee29cc2b08453652a74935ff2825 | [
"BSD-3-Clause"
] | 31 | 2020-06-11T08:21:54.000Z | 2022-02-07T13:31:26.000Z | core/modules/server/routes/put-tiddler.js | 8d1h/TiddlyWiki5 | 97dff042f752ee29cc2b08453652a74935ff2825 | [
"BSD-3-Clause"
] | 13 | 2020-06-12T15:12:30.000Z | 2021-12-16T06:54:11.000Z | core/modules/server/routes/put-tiddler.js | 8d1h/TiddlyWiki5 | 97dff042f752ee29cc2b08453652a74935ff2825 | [
"BSD-3-Clause"
] | 3 | 2020-06-23T02:37:11.000Z | 2021-01-01T15:49:19.000Z | /*\
title: $:/core/modules/server/routes/put-tiddler.js
type: application/javascript
module-type: route
PUT /recipes/default/tiddlers/:title
\*/
(function() {
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
exports.method = "PUT";
exports.path = /^\/recipes\/default\/tiddlers\/(.+)$/;
exports.handler = function(request,response,state) {
var title = decodeURIComponent(state.params[0]),
fields = JSON.parse(state.data);
// Pull up any subfields in the `fields` object
if(fields.fields) {
$tw.utils.each(fields.fields,function(field,name) {
fields[name] = field;
});
delete fields.fields;
}
// Remove any revision field
if(fields.revision) {
delete fields.revision;
}
state.wiki.addTiddler(new $tw.Tiddler(state.wiki.getCreationFields(),fields,{title: title},state.wiki.getModificationFields()));
var changeCount = state.wiki.getChangeCount(title).toString();
response.writeHead(204, "OK",{
Etag: "\"default/" + encodeURIComponent(title) + "/" + changeCount + ":\"",
"Content-Type": "text/plain"
});
response.end();
};
}());
| 25.27907 | 129 | 0.689052 |
f6e4f5f3a346a9c0a335acbfcfd177c696db2734 | 387 | js | JavaScript | src/js/herocalc/hero/heroOptionsArray.js | devilesk/hero-calculator | dc2e79b50056531f2e7f3665a7d60337f33056cf | [
"0BSD"
] | 9 | 2016-12-13T22:31:11.000Z | 2021-06-25T19:02:01.000Z | src/js/herocalc/hero/heroOptionsArray.js | devilesk/dota-hero-calculator | dc2e79b50056531f2e7f3665a7d60337f33056cf | [
"0BSD"
] | 1 | 2016-08-05T14:38:15.000Z | 2016-08-05T14:39:22.000Z | src/js/herocalc/hero/heroOptionsArray.js | devilesk/dota-hero-calculator | dc2e79b50056531f2e7f3665a7d60337f33056cf | [
"0BSD"
] | 2 | 2015-04-21T09:32:58.000Z | 2016-04-23T20:03:19.000Z | var HeroOption = require("./HeroOption");
var heroOptionsArray = {};
var init = function (heroData) {
heroOptionsArray.items = [];
for (var h in heroData) {
heroOptionsArray.items.push(new HeroOption(h.replace('npc_dota_hero_', ''), heroData[h].displayname));
}
return heroOptionsArray.items;
}
heroOptionsArray.init = init;
module.exports = heroOptionsArray; | 25.8 | 110 | 0.697674 |
f6e542128b566030fa7db0668987bffecd9c27a6 | 7,334 | js | JavaScript | Server/routes/visitorScheduler.js | edorrough/CLEAR | e6993304dedf4425e5bdd1d962e49f0fa8c47d0a | [
"MIT"
] | null | null | null | Server/routes/visitorScheduler.js | edorrough/CLEAR | e6993304dedf4425e5bdd1d962e49f0fa8c47d0a | [
"MIT"
] | null | null | null | Server/routes/visitorScheduler.js | edorrough/CLEAR | e6993304dedf4425e5bdd1d962e49f0fa8c47d0a | [
"MIT"
] | null | null | null | const mongoose = require('mongoose');
const validate = (data) => {
let errors = {};
if(data.title === '') errors.title = 'Title cannot be empty';
if(data.note === '') errors.note = 'Note cannot be empty';
if(data.startDate === '') errors.startDate = "Start date cannot be empty";
if(data.endDate === '') errors.endDate = "End date cannot be empty";
const isValid = Object.keys(errors).length === 0;
return { errors, isValid};
}
module.exports = (app, db) => {
app.get('/api/visitor-events', (req, res) => {
db.collection('visitorSchedule').find({}).toArray((err, schedules) => {
if(err) {
return res.status(500).json({ errors: { global: 'Something went wrong. Contact Administrator' }});
} else {
res.status(200).json({ schedules })
}
})
});
app.get('/api/visitor-events/:_id', (req, res) => {
db.collection('visitorSchedule').findOne({ _id: new mongoose.Types.ObjectId(req.params._id)}, (err, schedule) => {
if(err) throw err;
return res.status(200).json({ schedule })
})
});
app.put('/api/visitor-events/:_id', (req, res) => {
const { errors, isValid } = validate(req.body);
if(isValid) {
let {
title,
desc,
eventDone,
startDate,
endDate,
allDay,
location
} = req.body;
if(eventDone === 'true') {
eventDone = true
} else {
eventDone = false
}
if(allDay === 'false') {
allDay = false
} else {
allDay = true
}
let startDateParse = new Date(startDate)
let theStartDate = startDateParse.getFullYear() + '-' + (startDateParse.getMonth()+1) +'-'+ startDateParse.getDate();
let theStartTime = startDateParse.getHours() + ':' + (startDateParse.getMinutes() < 10 ? '0': '') + startDateParse.getMinutes();
let ampm = startDateParse.getHours() >= 12 ? 'PM' : 'AM';
let theStartDateTime = theStartDate + ' / ' + theStartTime + ' ' + ampm;
let endDateParse = new Date(endDate)
let theEndDate = endDateParse.getFullYear() + '-' + (endDateParse.getMonth() + 1) + '-' + endDateParse.getDate();
let theEndTime = endDateParse.getHours() + ':' + (endDateParse.getMinutes() < 10 ? '0' : '' ) + endDateParse.getMinutes();
let AMPM = endDateParse.getHours() >= 12 ? 'PM' : 'AM';
let theEndDateTime = theEndDate + ' / ' + theEndTime + ' ' + AMPM;
const today = new Date();
const compareDate = today.setDate(today.getDate());
db.collection('visitorSchedule').findOneAndUpdate(
{ _id: new mongoose.Types.ObjectId(req.params._id) },
{ $set: {
title,
desc,
eventDone,
showStartTime: theStartDateTime,
showEndTime: theEndDateTime,
start: startDate,
end: endDate,
allDay,
location,
comparedDate: compareDate, // This compares emaily to send emails weekly
eventsShowDateCompared: new Date(theEndDate) // This compares and displays in public page
},
},
{ returnOriginal: false }, // This is important
( err, newScheduler ) => {
// console.log("result in db.collection: ", result)
if(err) {
return res.status(500).json({ errors: { global: err } });
} else {
res.status(200).json({
schedule: newScheduler.value
})
}
}
)
} else {
return res.status(400).json({ errors })
}
});
app.post('/api/visitor-events', (req, res) => {
const { errors, isValid } = validate(req.body);
if(isValid) {
let {
title,
note,
eventDone,
startDate,
endDate,
allDay,
location
} = req.body;
if(eventDone === 'true') {
eventDone = true
} else {
eventDone = false
}
if(allDay === 'false') {
allDay = false
} else {
allDay = true
}
let startDateParse = new Date(startDate)
let theStartDate = startDateParse.getFullYear() + '-' + (startDateParse.getMonth()+1) +'-'+ startDateParse.getDate();
let theStartTime = startDateParse.getHours() + ':' + (startDateParse.getMinutes() < 10 ? '0': '') + startDateParse.getMinutes();
let ampm = startDateParse.getHours() >= 12 ? 'PM' : 'AM';
let theStartDateTime = theStartDate + ' / ' + theStartTime + ' ' + ampm;
let endDateParse = new Date(endDate)
let theEndDate = endDateParse.getFullYear() + '-' + (endDateParse.getMonth() + 1) + '-' + endDateParse.getDate();
let theEndTime = endDateParse.getHours() + ':' + (endDateParse.getMinutes() < 10 ? '0' : '' ) + endDateParse.getMinutes();
let AMPM = endDateParse.getHours() >= 12 ? 'PM' : 'AM';
let theEndDateTime = theEndDate + ' / ' + theEndTime + ' ' + AMPM;
const today = new Date();
const compareDate = today.setDate(today.getDate());
db.collection('visitorSchedule').insertOne({
title,
desc: note,
eventDone,
showStartTime: theStartDateTime,
showEndTime: theEndDateTime,
start: startDate,
end: endDate,
allDay,
location,
comparedDate: compareDate, // This compares emaily to send emails weekly
eventsShowDateCompared: new Date(theEndDate) // This compares and displays in public page
}, (err, result) => {
if(err) {
return res.status(500).json({ errors: { global: 'Something went wrong in database' }});
} else {
res.status(200).json({ schedule: result.ops[0] });
}
})
} else {
return res.status(400).json({ errors })
}
});
app.delete('/api/visitor-events/:_id', (req, res) => {
console.log(req.params._id)
db.collection('visitorSchedule').findOneAndDelete(
{ _id: new mongoose.Types.ObjectId(req.params._id) },
(err, schedule) => {
if(err) {
console.log("err in findOneAndDelete: ", err)
return res.status(500).json({ errors: { global: err } });
} else {
res.status(200).json({ message: 'successful' });
}
}
)
});
} | 39.858696 | 140 | 0.477229 |
f6e5d8727390898a8598a5c9a73c9137b7e356b8 | 1,666 | js | JavaScript | node_modules/office-ui-fabric-react/lib-es2015/components/Link/Link.js | gonadn/SPFxAngularCLIWithRouting | c42993755a18513c55be1157cea5e9f7b772d439 | [
"Apache-2.0"
] | 1 | 2020-06-01T12:54:01.000Z | 2020-06-01T12:54:01.000Z | node_modules/office-ui-fabric-react/lib-es2015/components/Link/Link.js | gonadn/SPFxAngularCLIWithRouting | c42993755a18513c55be1157cea5e9f7b772d439 | [
"Apache-2.0"
] | null | null | null | node_modules/office-ui-fabric-react/lib-es2015/components/Link/Link.js | gonadn/SPFxAngularCLIWithRouting | c42993755a18513c55be1157cea5e9f7b772d439 | [
"Apache-2.0"
] | null | null | null | import * as tslib_1 from "tslib";
import * as React from 'react';
import { BaseComponent, anchorProperties, autobind, buttonProperties, css, getNativeProps } from '../../Utilities';
import * as stylesImport from './Link.scss';
var styles = stylesImport;
var Link = /** @class */ (function (_super) {
tslib_1.__extends(Link, _super);
function Link() {
return _super !== null && _super.apply(this, arguments) || this;
}
Link.prototype.render = function () {
var _a = this.props, disabled = _a.disabled, children = _a.children, className = _a.className, href = _a.href;
return (href ? (React.createElement("a", tslib_1.__assign({}, getNativeProps(this.props, anchorProperties), { className: css('ms-Link', styles.root, className, disabled && ('is-disabled ' + styles.isDisabled), !disabled && styles.isEnabled), onClick: this._onClick, ref: this._resolveRef('_link'), target: this.props.target }), children)) : (React.createElement("button", tslib_1.__assign({}, getNativeProps(this.props, buttonProperties), { className: css('ms-Link', styles.root, className, disabled && ('is-disabled ' + styles.isDisabled)), onClick: this._onClick, ref: this._resolveRef('_link') }), children)));
};
Link.prototype.focus = function () {
if (this._link) {
this._link.focus();
}
};
Link.prototype._onClick = function (ev) {
var onClick = this.props.onClick;
if (onClick) {
onClick(ev);
}
};
tslib_1.__decorate([
autobind
], Link.prototype, "_onClick", null);
return Link;
}(BaseComponent));
export { Link };
//# sourceMappingURL=Link.js.map | 52.0625 | 621 | 0.65066 |
f6e5e5d18d3c33bba97d7b1c37c391dade3e7f74 | 622 | js | JavaScript | src/utils/pause-sandbox.js | andybee/deploy | c1b339bde027bd1e67f5c08f6fcd52343e43020e | [
"Apache-2.0"
] | 4 | 2019-10-12T03:02:57.000Z | 2022-01-22T13:39:25.000Z | src/utils/pause-sandbox.js | andybee/deploy | c1b339bde027bd1e67f5c08f6fcd52343e43020e | [
"Apache-2.0"
] | 146 | 2019-07-17T23:41:22.000Z | 2021-10-13T01:48:39.000Z | src/utils/pause-sandbox.js | andybee/deploy | c1b339bde027bd1e67f5c08f6fcd52343e43020e | [
"Apache-2.0"
] | 12 | 2019-07-11T13:41:55.000Z | 2022-03-26T15:45:41.000Z | let { existsSync, unlinkSync, writeFileSync } = require('fs')
let { join } = require('path')
let osPath = require('ospath')
let pauseFile = join(osPath.tmp(), '_pause-architect-sandbox-watcher')
module.exports = {
pause: () => {
try {
// Pause the Sandbox watcher so deploy ops don't do anything funky
if (!existsSync(pauseFile)) {
writeFileSync(pauseFile, '\n')
}
}
catch (err) { /* noop */ }
},
unpause: () => {
try {
// Cleanup after any past runs
if (existsSync(pauseFile)) {
unlinkSync(pauseFile)
}
}
catch (err) { /* noop */ }
}
}
| 23.923077 | 72 | 0.567524 |
f6e61b1b29dbd3be5e0c6075ec2311ad5a348879 | 178 | js | JavaScript | resources/js/admin.tab.js | Jatinpandey45/gdemy_web | 3d76ae7ac5f81de3c9ac30a27576a3ca13c8f56b | [
"MIT"
] | null | null | null | resources/js/admin.tab.js | Jatinpandey45/gdemy_web | 3d76ae7ac5f81de3c9ac30a27576a3ca13c8f56b | [
"MIT"
] | null | null | null | resources/js/admin.tab.js | Jatinpandey45/gdemy_web | 3d76ae7ac5f81de3c9ac30a27576a3ca13c8f56b | [
"MIT"
] | null | null | null | $(document).on('click', '.link-levelone ', function(e) {
if ($(this).hasClass('submenu')) {
e.preventDefault();
$(this).find('.submenu').slideDown();
}
}) | 29.666667 | 56 | 0.539326 |
f6e664caa08f79ab24cdca20df16a1599f831e84 | 11,238 | js | JavaScript | test/raw.js | danielrohers/bory | 6e807695c43d2e2f85dec44f0680941dbc9c4d74 | [
"MIT"
] | 4 | 2017-02-06T00:12:42.000Z | 2017-02-06T13:11:58.000Z | test/raw.js | danielrohers/bory | 6e807695c43d2e2f85dec44f0680941dbc9c4d74 | [
"MIT"
] | null | null | null | test/raw.js | danielrohers/bory | 6e807695c43d2e2f85dec44f0680941dbc9c4d74 | [
"MIT"
] | null | null | null | 'use strict';
const assert = require('assert');
const http = require('http');
const request = require('supertest');
const bory = require('..');
describe('bory.raw()', () => {
let server;
before(() => server = createServer());
it('should parse application/octet-stream', (done) => {
request(server)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('the user is daniel')
.expect(200, 'buf:74686520757365722069732064616e69656c', done);
});
it('should 400 when invalid content-length', (done) => {
const rawParser = bory.raw();
const server = createServer((req, res, next) => {
req.headers['content-length'] = '20'; // bad length
rawParser(req, res, next);
});
request(server)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('stuff')
.expect(400, /content length/, done);
});
it('should handle Content-Length: 0', (done) => {
request(server)
.post('/')
.set('Content-Type', 'application/octet-stream')
.set('Content-Length', '0')
.expect(200, 'buf:', done);
});
it('should handle empty message-body', (done) => {
request(server)
.post('/')
.set('Content-Type', 'application/octet-stream')
.set('Transfer-Encoding', 'chunked')
.send('')
.expect(200, 'buf:', done);
});
it('should handle duplicated middleware', (done) => {
const rawParser = bory.raw();
const server = createServer((req, res, next) => {
rawParser(req, res, (err) => {
if (err) return next(err);
rawParser(req, res, next);
});
});
request(server)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('the user is daniel')
.expect(200, 'buf:74686520757365722069732064616e69656c', done);
});
describe('with limit option', () => {
it('should 413 when over limit with Content-Length', (done) => {
const buf = allocBuffer(1028, '.');
const server = createServer({ limit: '1kb' });
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.set('Content-Length', '1028');
test.write(buf);
test.expect(413, done);
});
it('should 413 when over limit with chunked encoding', (done) => {
const buf = allocBuffer(1028, '.');
const server = createServer({ limit: '1kb' });
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.set('Transfer-Encoding', 'chunked');
test.write(buf);
test.expect(413, done);
});
it('should accept number of bytes', (done) => {
const buf = allocBuffer(1028, '.');
const server = createServer({ limit: 1024 });
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(buf);
test.expect(413, done);
});
it('should not change when options altered', (done) => {
const buf = allocBuffer(1028, '.');
const options = { limit: '1kb' };
const server = createServer(options);
options.limit = '100kb';
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(buf);
test.expect(413, done);
});
it('should not hang response', (done) => {
const buf = allocBuffer(10240, '.');
const server = createServer({ limit: '8kb' });
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(buf);
test.write(buf);
test.write(buf);
test.expect(413, done);
});
});
describe('with inflate option', () => {
describe('when false', () => {
let server;
before(() => server = createServer({ inflate: false }));
it('should not accept content-encoding', (done) => {
const test = request(server).post('/');
test.set('Content-Encoding', 'gzip');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'));
test.expect(415, 'content encoding unsupported', done);
});
});
describe('when true', () => {
let server;
before(() => server = createServer({ inflate: true }));
it('should accept content-encoding', (done) => {
const test = request(server).post('/');
test.set('Content-Encoding', 'gzip');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'));
test.expect(200, 'buf:6e616d653de8aeba', done);
});
});
});
describe('with type option', () => {
describe('when "application/vnd+octets"', () => {
let server;
before(() => server = createServer({ type: 'application/vnd+octets' }));
it('should parse for custom type', (done) => {
const test = request(server).post('/');
test.set('Content-Type', 'application/vnd+octets');
test.write(new Buffer('000102', 'hex'));
test.expect(200, 'buf:000102', done);
});
it('should ignore standard type', (done) => {
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('000102', 'hex'));
test.expect(200, '{}', done);
});
});
describe('when a function', () => {
it('should parse when truthy value returned', (done) => {
const server = createServer({ type: accept });
function accept(req) {
return req.headers['content-type'] === 'application/vnd.octet';
}
const test = request(server).post('/');
test.set('Content-Type', 'application/vnd.octet');
test.write(new Buffer('000102', 'hex'));
test.expect(200, 'buf:000102', done);
});
it('should work without content-type', (done) => {
const server = createServer({ type: accept });
function accept() {
return true;
}
const test = request(server).post('/');
test.write(new Buffer('000102', 'hex'));
test.expect(200, 'buf:000102', done);
});
it('should not invoke without a body', (done) => {
const server = createServer({ type: accept });
function accept() {
throw new Error('oops!');
}
request(server)
.get('/')
.expect(200, done);
});
});
});
describe('with verify option', () => {
it('should assert value is function', () => {
assert.throws(createServer.bind(null, { verify: 'lol' }), /TypeError: option verify must be function/);
});
it('should error from verify', (done) => {
const server = createServer({
verify: (req, res, buf) => {
if (buf[0] === 0x00) throw new Error('no leading null');
},
});
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('000102', 'hex'));
test.expect(403, 'no leading null', done);
});
it('should allow custom codes', (done) => {
const server = createServer({
verify: (req, res, buf) => {
if (buf[0] !== 0x00) return;
const err = new Error('no leading null');
err.status = 400;
throw err;
},
});
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('000102', 'hex'));
test.expect(400, 'no leading null', done);
});
it('should allow pass-through', (done) => {
const server = createServer({
verify: (req, res, buf) => {
if (buf[0] === 0x00) throw new Error('no leading null');
},
});
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('0102', 'hex'));
test.expect(200, 'buf:0102', done);
});
});
describe('charset', () => {
let server;
before(() => server = createServer());
it('should ignore charset', (done) => {
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream; charset=utf-8');
test.write(new Buffer('6e616d6520697320e8aeba', 'hex'));
test.expect(200, 'buf:6e616d6520697320e8aeba', done);
});
});
describe('encoding', () => {
let server;
before(() => server = createServer({ limit: '10kb' }));
it('should parse without encoding', (done) => {
const test = request(server).post('/');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('6e616d653de8aeba', 'hex'));
test.expect(200, 'buf:6e616d653de8aeba', done);
});
it('should support identity encoding', (done) => {
const test = request(server).post('/');
test.set('Content-Encoding', 'identity');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('6e616d653de8aeba', 'hex'));
test.expect(200, 'buf:6e616d653de8aeba', done);
});
it('should support gzip encoding', (done) => {
const test = request(server).post('/');
test.set('Content-Encoding', 'gzip');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'));
test.expect(200, 'buf:6e616d653de8aeba', done);
});
it('should support deflate encoding', (done) => {
const test = request(server).post('/');
test.set('Content-Encoding', 'deflate');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('789ccb4bcc4db57db16e17001068042f', 'hex'));
test.expect(200, 'buf:6e616d653de8aeba', done);
});
it('should be case-insensitive', (done) => {
const test = request(server).post('/');
test.set('Content-Encoding', 'GZIP');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'));
test.expect(200, 'buf:6e616d653de8aeba', done);
});
it('should fail on unknown encoding', (done) => {
const test = request(server).post('/');
test.set('Content-Encoding', 'nulls');
test.set('Content-Type', 'application/octet-stream');
test.write(new Buffer('000000000000', 'hex'));
test.expect(415, 'unsupported content encoding "nulls"', done);
});
});
});
function allocBuffer(size, fill) {
if (Buffer.alloc) {
return Buffer.alloc(size, fill);
}
const buf = new Buffer(size);
buf.fill(fill);
return buf;
}
function createServer(opts) {
const _bory = typeof opts !== 'function' ? bory.raw(opts) : opts;
return http.createServer((req, res) => {
_bory(req, res, (err) => {
if (err) {
res.statusCode = err.status || 500;
res.end(err.message);
return;
}
if (Buffer.isBuffer(req.body)) {
res.end(`buf:${req.body.toString('hex')}`);
return;
}
res.end(JSON.stringify(req.body));
});
});
}
| 31.835694 | 109 | 0.575992 |
f6e7e7f610750846e4e441061aa32afe86527e91 | 10,404 | js | JavaScript | aster-admin/src/main/resources/static/js/aster.js | lp1791803611/aster | 02a5879cefefa2d4ee148e0bd592b78efc82f4fb | [
"MIT"
] | 1 | 2021-08-14T16:19:29.000Z | 2021-08-14T16:19:29.000Z | aster-admin/src/main/resources/static/js/aster.js | lp1791803611/aster | 02a5879cefefa2d4ee148e0bd592b78efc82f4fb | [
"MIT"
] | null | null | null | aster-admin/src/main/resources/static/js/aster.js | lp1791803611/aster | 02a5879cefefa2d4ee148e0bd592b78efc82f4fb | [
"MIT"
] | null | null | null | /**
* 通用js方法封装处理
* Copyright (c) 2021 stranger
*/
// 获取ztree被选中的id值
var zTreeCheckedNodes = function (zTreeId) {
var zTree = $.fn.zTree.getZTreeObj(zTreeId);
var nodes = zTree.getCheckedNodes();
var ids = "";
for (var i = 0, l = nodes.length; i < l; i++) {
ids += "," + nodes[i].id;
}
return ids.substring(1);
};
(function ($) {
$.extend({
table: {
// 回显数据字典
showDictLabel: function(datas, value) {
if ($.common.isEmpty(datas) || $.common.isEmpty(value)) {
return '';
}
var actions = [];
$.each(datas, function(index, dict) {
if (dict.dictValue == ('' + value)) {
var bgColor = $.common.getBgColor(index);
var dictEL = '<span class="layui-badge '+ bgColor +'">' + dict.dictLabel + '</span>'
actions.push(dictEL);
return false;
}
});
return actions.join('');
}
},
// 通用方法封装处理
common: {
// 提交数据
submit: function(url, type, dataType, contentType, data, callback) {
var config = {
url: url,
type: type,
dataType: dataType,
contentType: contentType,
data: data,
success: function(result) {
if (typeof callback == "function") {
callback(result);
}
layer.msg(result.msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 404) {
window.location.href = ctx + "/404";
} else {
layer.msg("服务器好像出了点问题!请稍后试试");
}
}
};
$.ajax(config)
},
// post请求传输
postJSON: function(url, contentType, data, callback) {
$.common.submit(url, "post", "json", contentType, data, callback);
},
// post请求传输
post: function(url, data, callback) {
$.common.submit(url, "post", "json", "application/x-www-form-urlencoded", data, callback);
},
// get请求传输
get: function(url, callback) {
$.common.submit(url, "get", "json", "", callback);
},
// 获取背景色
getBgColor: function (value) {
var bgColors = ['layui-bg-gray','layui-bg-blue','layui-bg-green','layui-bg-red',
'layui-bg-orange','layui-bg-cyan','layui-bg-black'];
var bg_index = value % bgColors.length;
return bgColors[bg_index];
},
// 根据参数键名获取url中参数键值
getParam: function (paramName) {
var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
},
// 判断字符串是否为空
isEmpty: function (value) {
if (value == null || this.trim(value) == "") {
return true;
}
return false;
},
// 判断一个字符串是否为非空串
isNotEmpty: function (value) {
return !$.common.isEmpty(value);
},
// 空对象转字符串
nullToStr: function(value) {
if ($.common.isEmpty(value)) {
return "-";
}
return value;
},
// 是否显示数据 为空默认为显示
visible: function (value) {
if ($.common.isEmpty(value) || value == true) {
return true;
}
return false;
},
// 空格截取
trim: function (value) {
if (value == null) {
return "";
}
return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, "");
},
// 比较两个字符串(大小写敏感)
equals: function (str, that) {
return str == that;
},
// 比较两个字符串(大小写不敏感)
equalsIgnoreCase: function (str, that) {
return String(str).toUpperCase() === String(that).toUpperCase();
},
// 将字符串按指定字符分割
split: function (str, sep, maxLen) {
if ($.common.isEmpty(str)) {
return null;
}
var value = String(str).split(sep);
return maxLen ? value.slice(0, maxLen - 1) : value;
},
// 字符串格式化(%s )
sprintf: function (str) {
var args = arguments, flag = true, i = 1;
str = str.replace(/%s/g, function () {
var arg = args[i++];
if (typeof arg === 'undefined') {
flag = false;
return '';
}
return arg == null ? '' : arg;
});
return flag ? str : '';
},
// 日期格式化 时间戳 -> yyyy-MM-dd HH-mm-ss
dateFormat: function(date, format) {
var that = this;
if (that.isEmpty(date)) return "";
if (!date) return;
if (!format) format = "yyyy-MM-dd";
switch (typeof date) {
case "string":
date = new Date(date.replace(/-/, "/"));
break;
case "number":
date = new Date(date);
break;
}
if (!date instanceof Date) return;
var dict = {
"yyyy": date.getFullYear(),
"M": date.getMonth() + 1,
"d": date.getDate(),
"H": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"MM": ("" + (date.getMonth() + 101)).substr(1),
"dd": ("" + (date.getDate() + 100)).substr(1),
"HH": ("" + (date.getHours() + 100)).substr(1),
"mm": ("" + (date.getMinutes() + 100)).substr(1),
"ss": ("" + (date.getSeconds() + 100)).substr(1)
};
return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g,
function() {
return dict[arguments[0]];
});
},
// 获取节点数据,支持多层级访问
getItemField: function (item, field) {
var value = item;
if (typeof field !== 'string' || item.hasOwnProperty(field)) {
return item[field];
}
var props = field.split('.');
for (var p in props) {
value = value && value[props[p]];
}
return value;
},
// 指定随机数返回
random: function (min, max) {
return Math.floor((Math.random() * max) + min);
},
// 判断字符串是否是以start开头
startWith: function(value, start) {
var reg = new RegExp("^" + start);
return reg.test(value)
},
// 判断字符串是否是以end结尾
endWith: function(value, end) {
var reg = new RegExp(end + "$");
return reg.test(value)
},
// 数组去重
uniqueFn: function(array) {
var result = [];
var hashObj = {};
for (var i = 0; i < array.length; i++) {
if (!hashObj[array[i]]) {
hashObj[array[i]] = true;
result.push(array[i]);
}
}
return result;
},
// 数组中的所有元素放入一个字符串
join: function(array, separator) {
if ($.common.isEmpty(array)) {
return null;
}
return array.join(separator);
},
// 获取form下所有的字段并转换为json对象
formToJSON: function(formId) {
var json = {};
$.each($("#" + formId).serializeArray(), function(i, field) {
if(json[field.name]) {
json[field.name] += ("," + field.value);
} else {
json[field.name] = field.value;
}
});
return json;
},
// 获取obj对象长度
getLength: function(obj) {
var count = 0;
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
count++;
}
}
return count;
},
// 判断移动端
isMobile: function () {
return navigator.userAgent.match(/(Android|iPhone|SymbianOS|Windows Phone|iPad|iPod)/i);
},
// 数字正则表达式,只能为0-9数字
numValid : function(text){
var patten = new RegExp(/^[0-9]+$/);
return patten.test(text);
},
// 英文正则表达式,只能为a-z和A-Z字母
enValid : function(text){
var patten = new RegExp(/^[a-zA-Z]+$/);
return patten.test(text);
},
// 英文、数字正则表达式,必须包含(字母,数字)
enNumValid : function(text){
var patten = new RegExp(/^(?=.*[a-zA-Z]+)(?=.*[0-9]+)[a-zA-Z0-9]+$/);
return patten.test(text);
},
// 英文、数字、特殊字符正则表达式,必须包含(字母,数字,特殊字符!@#$%^&*()-=_+)
charValid : function(text){
var patten = new RegExp(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[~!@#\$%\^&\*\(\)\-=_\+])[A-Za-z\d~!@#\$%\^&\*\(\)\-=_\+]{6,}$/);
return patten.test(text);
}
}
});
})(jQuery); | 37.832727 | 134 | 0.380911 |
f6e8be156266d96819aa1181bc21fec46ecd7ee6 | 387 | js | JavaScript | __tests__/utils/extent.test.js | jordangehman/silky-charts | ff84d79cf9ac5f1bc3377e68616892ed5957ba98 | [
"MIT"
] | 1 | 2020-03-22T06:28:09.000Z | 2020-03-22T06:28:09.000Z | __tests__/utils/extent.test.js | jordangehman/silky-charts | ff84d79cf9ac5f1bc3377e68616892ed5957ba98 | [
"MIT"
] | null | null | null | __tests__/utils/extent.test.js | jordangehman/silky-charts | ff84d79cf9ac5f1bc3377e68616892ed5957ba98 | [
"MIT"
] | null | null | null | import { extent } from '../../src/utils';
test('return the min and max value in array', () => {
const [min, max] = extent([5, 9, 3, 13, 17, 10]);
expect(min).toEqual(3);
expect(max).toEqual(17);
});
test('return the min and max value in array', () => {
const [min, max] = extent(['a', 'h', 'X', '#', '5', 'r', 'O']);
expect(min).toEqual('#');
expect(max).toEqual('r');
});
| 27.642857 | 65 | 0.540052 |
f6e8e4f9259ff2d6837c974a90b20bff42c784a9 | 51 | js | JavaScript | src/shared/components/Icon/index.js | Gh0ysTschool/svelte-jira | 2597066ddd2a447f86c475c05464422689fd0dec | [
"MIT"
] | 1 | 2020-06-09T02:47:09.000Z | 2020-06-09T02:47:09.000Z | src/shared/components/Icon/index.js | Gh0ysTschool/svelte-jira | 2597066ddd2a447f86c475c05464422689fd0dec | [
"MIT"
] | 5 | 2020-07-21T01:40:52.000Z | 2022-03-15T20:23:09.000Z | src/shared/components/Icon/index.js | Gh0ysTschool/svelte-jira | 2597066ddd2a447f86c475c05464422689fd0dec | [
"MIT"
] | null | null | null | export { default as default } from './Icon.svelte'; | 51 | 51 | 0.705882 |
f6e921e82302bc5b0ba0c79236b6246cfd416016 | 515 | js | JavaScript | week15/App.js | AlyanaT/spring2021-mobiledevelopment | eed4c12c85b84d3c121658ea3dba0a06ee7e7fb2 | [
"MIT"
] | null | null | null | week15/App.js | AlyanaT/spring2021-mobiledevelopment | eed4c12c85b84d3c121658ea3dba0a06ee7e7fb2 | [
"MIT"
] | null | null | null | week15/App.js | AlyanaT/spring2021-mobiledevelopment | eed4c12c85b84d3c121658ea3dba0a06ee7e7fb2 | [
"MIT"
] | null | null | null | import React, { useReducer } from 'react';
import {state,reducer} from './components/ApplicationState';
import Lunge from './components/lunge';
import Squat from './components/squat'
function App() {
const [currentState, dispatch] = useReducer(reducer,state);
return (
<div className= "App">
<header className="App-header">
<Lunge state= {currentState} dispatch={dispatch}/>
<Squat state={currentState} dispatch={dispatch}/>
</header>
</div>
);
}
export default App; | 24.52381 | 61 | 0.664078 |
f6ea438d67dd62cdddbaa06cb89e794994ca3998 | 7,765 | js | JavaScript | src/pages/user/Sign-up.js | Freedgy/web-app | bccd387d93e7a24390b9901a8ec2f9b0a53a8ab9 | [
"RSA-MD"
] | null | null | null | src/pages/user/Sign-up.js | Freedgy/web-app | bccd387d93e7a24390b9901a8ec2f9b0a53a8ab9 | [
"RSA-MD"
] | null | null | null | src/pages/user/Sign-up.js | Freedgy/web-app | bccd387d93e7a24390b9901a8ec2f9b0a53a8ab9 | [
"RSA-MD"
] | null | null | null | import React from "react";
import { Form, Card, Row, Container, Col } from "react-bootstrap";
import Button from '@material-ui/core/Button';
import axios from 'axios';
import userContext from "../../context/user";
class Signup extends React.Component {
constructor(props) {
super(props);
this.state = {
mail: "",
name: "",
last_name: "",
pwd: "",
checked: false,
validated: false,
mailError: "",
nameError: "",
last_nameError: "",
passwordError: "",
};
}
componentDidMount() {
}
handleSubmit = (event) => {
const { signIn, setToken } = this.context
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
if (form.checkValidity() === true) {
var url = "http://back.freedgy.com:8080/user/register"
var data = {
name: this.state.name,
last_name: this.state.last_name,
password: this.state.pwd,
email: this.state.mail
}
axios.post(url, data)
.then((rep) => {
setToken("41df65b1df56r16er")
signIn({name: data.name, last_name : data.last_name, email: data.email})
window.location.href = "/"
}).catch(() => {
this.setState({
mailError: "user already exist",
})
});
// var data = {
// username: this.state.mail,
// fakeid: "156871568162",
// faketoken: "41df65b1df56r16er"
// }
// setToken(data.faketoken)
// signIn({user_name: data.username, id : data.fakeid})
// window.location.href = "/"
} else {
if (this.state.mail === "") {
this.setState({
mailError: "Field must not be empty!",
})
}
if (this.state.pwd === "") {
this.setState({
passwordError: "Field must not be empty!",
})
}
}
this.setState({validated:true})
};
handleCheck = (event) => {
this.setState({
checked: event.target.checked
});
};
render () {
const { mail, name, last_name, pwd, checked, validated, passwordError, mailError } = this.state;
return (
<Container className="vh-100">
<Row className="vh-100 justify-content-center align-items-center">
<Col lg={7}>
<Card className="shadow-small-dark mt-0 m-3 m-md-0 pt-1 pl-md-4 pl-1 pr-md-4 pr-1" style={{width: "100%"}}>
<Card.Body className="pb-0">
<Row className="justify-content-center">
<h3>Sign-up</h3>
</Row>
<Form noValidate validated={validated} onSubmit={this.handleSubmit}>
<Form.Group>
<Form.Label htmlFor="idmail">mail</Form.Label>
<Form.Control
required
id="idmail"
type="text"
placeholder="mail"
value={mail}
onChange={e => this.setState({mail: e.target.value, validated: false, mailError: ""})}
/>
{mailError}
</Form.Group>
<Form.Group>
<Form.Label htmlFor="idname">name</Form.Label>
<Form.Control
required
id="idname"
type="text"
placeholder="name"
value={name}
onChange={e => this.setState({name: e.target.value, validated: false, nameError: ""})}
/>
{mailError}
</Form.Group>
<Form.Group>
<Form.Label htmlFor="idmail">last_name</Form.Label>
<Form.Control
required
id="idlast_name"
type="text"
placeholder="last_name"
value={last_name}
onChange={e => this.setState({last_name: e.target.value, validated: false, last_nameError: ""})}
/>
{mailError}
</Form.Group>
<Form.Group>
<Form.Label htmlFor="idPassword">Password</Form.Label>
<Form.Control
required
id="idPassword"
type="password"
placeholder="Password"
value={pwd}
onChange={e => this.setState({pwd: e.target.value, validated: false, passwordError: ""})}
/>
{passwordError}
</Form.Group>
<Row className="justify-content-center mt-4">
<Form.Check
type="checkbox"
label="I agree with CGU"
required
checked={checked}
onChange={this.handleCheck}
/>
</Row>
<Row className="justify-content-center mt-4 mb-4">
<Button
variant="contained"
color="primary"
type="submit"
>
Sign-up
</Button>
</Row>
</Form>
<Row className="justify-content-center mt-4">
<a href="/user/Login">I already have an account</a>
</Row>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
)
}
}
Signup.contextType = userContext
export default Signup; | 44.119318 | 140 | 0.33651 |
f6ea65b0675be7a5b5f42333058ab9ae96f36f19 | 1,422 | js | JavaScript | lib/actions/action-list-provider.js | blueskyfish/heringsfish-cli | d37a1ca9e43e48ecfb5ff08bd04d56f886851e5f | [
"MIT"
] | 1 | 2016-04-21T18:04:16.000Z | 2016-04-21T18:04:16.000Z | lib/actions/action-list-provider.js | blueskyfish/heringsfish-cli | d37a1ca9e43e48ecfb5ff08bd04d56f886851e5f | [
"MIT"
] | 7 | 2016-02-24T21:36:15.000Z | 2019-01-15T13:04:29.000Z | lib/actions/action-list-provider.js | blueskyfish/heringsfish-cli | d37a1ca9e43e48ecfb5ff08bd04d56f886851e5f | [
"MIT"
] | 1 | 2016-04-21T18:04:35.000Z | 2016-04-21T18:04:35.000Z | /*
* heringsfish-cli - https://github.com/blueskyfish/heringsfish-cli.git
*
* The MIT License (MIT)
* Copyright (c) 2017 BlueSkyFish
*/
'use strict';
const Q = require('q');
const config = require('lib/config');
const logger = require('lib/logger');
const runner = require('lib/runner');
const asadmin = require('lib/server/asadmin');
/**
* @type {ActionInfo}
*/
const mInfo = {
action: 'list',
description: 'List the domains or application'
};
/**
* @type {ActionProvider}
*/
module.exports = {
run: function () {
return run_();
},
info: function () {
return mInfo;
}
};
function run_() {
return Q.fcall(function () {
logger.info('Execute "%s" (%s)', mInfo.action, mInfo.description);
return asadmin.getAsAdminSettingValues(true)
.then(function (asAdminSetting) {
if (config.isSetting('d', 'domain')) {
return _executeDomainList(asAdminSetting);
}
return _executeApplicationList(asAdminSetting);
});
});
}
function _executeDomainList(asAdminSetting) {
// build parameters
var params = [
'list-domains',
'--domaindir', asAdminSetting.domainHome
];
return runner.execute(asAdminSetting.asadmin, params);
}
function _executeApplicationList(asAdminSetting) {
var params = [
'list-applications',
'--port', asAdminSetting.adminPort
];
return runner.execute(asAdminSetting.asadmin, params);
}
| 20.608696 | 71 | 0.653305 |
f6eaf7baa9039360d3b8fb239d04e36e469544e2 | 2,660 | js | JavaScript | src/components/App.js | AdithyaBhat17/cgpa-calculator | 6a12ef4cc5fb588863bf3755e75681618b4fec08 | [
"Apache-2.0"
] | 2 | 2019-06-07T15:59:13.000Z | 2019-06-07T15:59:14.000Z | src/components/App.js | AdithyaBhat17/cgpa-calculator | 6a12ef4cc5fb588863bf3755e75681618b4fec08 | [
"Apache-2.0"
] | 11 | 2019-10-04T00:07:12.000Z | 2020-01-06T23:17:39.000Z | src/components/App.js | AdithyaBhat17/cgpa-calculator | 6a12ef4cc5fb588863bf3755e75681618b4fec08 | [
"Apache-2.0"
] | null | null | null | import React from 'react'
import { Form, Button, Container } from 'react-bootstrap'
import { Link } from 'react-router-dom'
import Nav from './Nav'
import Footer from './Footer'
function App(props) {
const [electiveNo, setElectiveNo] = React.useState(0)
const [mainNo, selectMainNo] = React.useState(0)
const [labNo, selectLabNo] = React.useState(0)
const [phase2, setPhase2] = React.useState(false)
React.useLayoutEffect(() => {
window.scrollTo(0, 0)
}, [])
return (
<div className="App">
<Container>
<Nav />
<h1>Hello there!</h1>
<p>Studying in a VTU college? Get your SGPA and CGPA scores here!</p>
<h5>SGPA Calculator</h5>
<Form>
<Form.Group>
<Form.Label>Number of Electives</Form.Label> <br/>
<Form.Control
name="electiveNo"
type="number"
min="0"
max="6"
required
onChange={(e) => setElectiveNo(e.target.value)}
/>
</Form.Group>
<Form.Group>
<Form.Label>Number of Main Subjects</Form.Label> <br/>
<Form.Control
name="mainNo"
type="number"
min="0"
max="6"
required
onChange={(e) => selectMainNo(e.target.value)}
/>
</Form.Group>
<Form.Group>
<Form.Label>Number of Labs ( + Project Phase 1 + Seminars + Internship)</Form.Label> <br/>
<Form.Control
name="mainNo"
type="number"
min="0"
max="3"
required
onChange={(e) => selectLabNo(e.target.value)}
/>
</Form.Group>
<Form.Group>
<Form.Check
style={{fontWeight: "bold"}}
checked={phase2}
onChange={() => setPhase2(!phase2)}
type="checkbox"
label="Project Phase 2?">
</Form.Check>
</Form.Group> <br/>
<Link to={{
pathname: '/sgpa',
state: {
electiveNo,
mainNo,
labNo,
phase2No: phase2 ? 1 : 0
}
}}>
<Button className="proceed">
Proceed
</Button>
</Link>
<p
onClick={() => props.history.push('/cgpa')}
style={{textAlign: 'center', marginTop: 10, color: '#6FBEDB'}}>
Calculate CGPA here!
</p>
</Form>
</Container>
<Container>
<Footer />
</Container>
</div>
);
}
export default App
| 28 | 102 | 0.472556 |
f6eb9decfb8d6cc98973be2f6f6e027095399e67 | 1,483 | js | JavaScript | dev-site-config/site.config.js | Mohib-hub/terra-ui | 5a052334c048ec12ad88af460917e503929c71cf | [
"Apache-2.0"
] | null | null | null | dev-site-config/site.config.js | Mohib-hub/terra-ui | 5a052334c048ec12ad88af460917e503929c71cf | [
"Apache-2.0"
] | 29 | 2020-08-20T15:49:58.000Z | 2021-02-20T01:02:53.000Z | dev-site-config/site.config.js | Mohib-hub/terra-ui | 5a052334c048ec12ad88af460917e503929c71cf | [
"Apache-2.0"
] | null | null | null | /* eslint-disable-next-line import/no-extraneous-dependencies */
const glob = require('glob');
const navConfig = require('./navigation.config');
const excludes = [
'node_modules/terra-doc-template',
'node_modules/terra-abstract-modal',
'node_modules/terra-dialog',
'node_modules/terra-dialog-modal',
'node_modules/terra-theme-context',
];
const patterns = glob.sync('node_modules/terra-*/lib/terra-dev-site').map(file => (
{ root: `node_modules/${file.split('/')[1]}`, dist: 'lib', entryPoint: 'terra-dev-site' }
)).filter(file => !excludes.includes(file.root));
const siteConfig = {
/* The navigation configuration. */
navConfig,
generatePages: {
searchPatterns: [
{
root: process.cwd(),
dist: 'src',
entryPoint: 'terra-dev-site',
},
...patterns,
],
},
hotReloading: false,
readMeContent: undefined,
sideEffectImports: [
'./initializeXFC.js',
'./IllustrationGrid.scss',
],
appConfig: {
/* The title for the site header. */
title: 'Terra',
themes: {
'Default Theme': '',
'Orion Fusion Theme': 'orion-fusion-theme',
},
extensions: [
{
iconPath: 'terra-icon/lib/icon/IconCompose',
key: 'terra-ui.issue-form',
text: 'Issue Form',
componentPath: '../src/terra-dev-site/IssueForm/Index',
size: 'huge',
},
],
},
filterSideMenu: true,
includeTestEvidence: false,
};
module.exports = siteConfig;
| 22.469697 | 91 | 0.61497 |
f6ec3c1230899fb47b4821e5e97b0d27ff882714 | 4,819 | js | JavaScript | src/selectors/progressSelectors.js | Fazer-Turvallisuuspeli/fazer-frontend | 7fa47f3763e718fa7ca624a4629f846583870679 | [
"MIT"
] | null | null | null | src/selectors/progressSelectors.js | Fazer-Turvallisuuspeli/fazer-frontend | 7fa47f3763e718fa7ca624a4629f846583870679 | [
"MIT"
] | 2 | 2019-11-25T07:35:43.000Z | 2019-11-28T11:47:53.000Z | src/selectors/progressSelectors.js | Fazer-Turvallisuuspeli/fazer-frontend | 7fa47f3763e718fa7ca624a4629f846583870679 | [
"MIT"
] | null | null | null | import { createSelector } from 'redux-starter-kit';
import {
selectCurrentCategoryId,
selectCategoriesData,
} from './categoriesSelectors';
import { selectCurrentQuestionId } from './questionsSelectors';
export const selectProgress = state => state.progress;
export const selectProgressPerCategory = createSelector(
[selectProgress],
progress => progress.perCategory
);
export const selectCurrectUncompletedQuestions = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId],
(perCategory, categoryId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].perQuestion
? Object.entries(perCategory[categoryId].perQuestion).filter(
question => question[1].isCompleted === false
)
: []
);
export const selectNthQuestion = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId],
(perCategory, categoryId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].nthQuestion
? perCategory[categoryId].nthQuestion
: 0
);
export const selectAmountOfQuestions = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId],
(perCategory, categoryId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].totalQuestions
? perCategory[categoryId].totalQuestions
: 0
);
export const selectIsSubmitting = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId, selectCurrentQuestionId],
(perCategory, categoryId, questionId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].isSubmitting &&
perCategory[categoryId].perQuestion[questionId].isSubmitting
? perCategory[categoryId].perQuestion[questionId].isSubmitting
: false
);
export const selectIsCategoryCompleted = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId],
(perCategory, categoryId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].isCompleted
? perCategory[categoryId].isCompleted
: false
);
export const selectProgressInitializationStatus = createSelector(
[selectProgress],
progress => progress.isInitialized
);
export const selectCheckedChoicesByQuestionId = (
state,
categoryId,
questionId
) =>
state.progress.perCategory[categoryId].perQuestion[questionId].checkedChoices;
export const selectCorrectAnswersByQuestionId = (state, questionId) =>
state.questions.data.find(question => question.id === questionId)
.correctChoiceId;
export const selectIsQuestionCompleted = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId, selectCurrentQuestionId],
(perCategory, categoryId, questionId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].perQuestion[questionId] &&
perCategory[categoryId].perQuestion[questionId].isCompleted
? perCategory[categoryId].perQuestion[questionId].isCompleted
: false
);
export const selectIsQuestionCorrect = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId, selectCurrentQuestionId],
(perCategory, categoryId, questionId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].perQuestion[questionId] &&
perCategory[categoryId].perQuestion[questionId].isCorrect
? perCategory[categoryId].perQuestion[questionId].isCorrect
: false
);
export const selectCurrentCheckedChoices = createSelector(
[selectProgressPerCategory, selectCurrentCategoryId, selectCurrentQuestionId],
(perCategory, categoryId, questionId) =>
perCategory &&
perCategory[categoryId] &&
perCategory[categoryId].perQuestion[questionId] &&
perCategory[categoryId].perQuestion[questionId].checkedChoices
? perCategory[categoryId].perQuestion[questionId].checkedChoices
: []
);
export const selectNextCategoryId = createSelector(
[selectCategoriesData, selectCurrentCategoryId],
(categories, categoryId) =>
categories &&
categoryId &&
categories[
categories.indexOf(
categories.find(category => category.id === categoryId)
) + 1
]
? categories[
categories.indexOf(
categories.find(category => category.id === categoryId)
) + 1
].id
: categories[0].id
);
export const selectCompletedCategories = createSelector(
[selectProgressPerCategory],
perCategory =>
perCategory &&
Object.keys(perCategory)
.filter(categoryId => perCategory[categoryId].isCompleted)
.map(id => Number(id))
);
export const selectUncompletedCategories = createSelector(
[selectProgressPerCategory],
perCategory =>
perCategory &&
Object.keys(perCategory)
.filter(categoryId => perCategory[categoryId].isCompleted === false)
.map(id => Number(id))
);
| 31.703947 | 80 | 0.738742 |