code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* ProductRepository
*
* This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
* repository methods below.
*/
class UserRepository extends EntityRepository
{
}
| YX11/timiya | src/AppBundle/Repository/UserRepository.php | PHP | mit | 277 |
import { combineReducers } from 'redux';
import { reducer as form } from 'redux-form';
import { list } from './list';
import { draw } from './draw';
const reducers = combineReducers({ list, draw, form });
export default reducers;
| ansonpellissier/gordon-shuffle-react | src/reducers/index.js | JavaScript | mit | 233 |
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
// Init module configuration options
var applicationModuleName = 'angleApp';
// var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils'];
var applicationModuleVendorDependencies = ['ngRoute', 'ngAnimate', 'ngStorage','ngTouch', 'ngCookies', 'pascalprecht.translate', 'ui.bootstrap', 'ui.router', 'oc.lazyLoad', 'cfp.loadingBar', 'ngSanitize', 'ngResource', 'ui.utils', 'angularFileUpload'];
// Add a new vertical module
var registerModule = function(moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName: applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule: registerModule
};
})();
'use strict';
//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
//Then define the init function for starting up the application
angular.element(document).ready(function() {
//Fixing facebook bug with redirect
if (window.location.hash === '#_=_') window.location.hash = '#!';
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('articles');
/*!
*
* Angle - Bootstrap Admin App + AngularJS
*
* Author: @themicon_co
* Website: http://themicon.co
* License: http://support.wrapbootstrap.com/knowledge_base/topics/usage-licenses
*
*/
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('core');
angular.module('core').run(["$rootScope", "$state", "$stateParams", '$window', '$templateCache',
function ($rootScope, $state, $stateParams, $window, $templateCache) {
// Set reference to access them from any scope
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.$storage = $window.localStorage;
// Uncomment this to disables template cache
/*$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if (typeof(toState) !== 'undefined'){
$templateCache.remove(toState.templateUrl);
}
});*/
// Scope Globals
// -----------------------------------
$rootScope.app = {
name: 'Alt Be Back',
description: 'Angular Bootstrap Admin Template',
year: ((new Date()).getFullYear()),
layout: {
isFixed: true,
isCollapsed: false,
isBoxed: false,
isRTL: false,
horizontal: false,
isFloat: false,
asideHover: false,
theme: null
},
useFullLayout: false,
hiddenFooter: false,
viewAnimation: 'ng-fadeInUp'
};
$rootScope.user = {
name: 'John',
job: 'ng-Dev',
picture: 'app/img/user/02.jpg'
};
}
]);
'use strict';
// Use application configuration module to register a new module
ApplicationConfiguration.registerModule('page');
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('users');
'use strict';
// Configuring the Articles module
angular.module('articles').run(['Menus',
function(Menus) {
// Set top bar menu items
Menus.addMenuItem('sidebar', 'Articles', 'articles', 'dropdown', '/articles(/.*)?', false, null, 20);
Menus.addSubMenuItem('sidebar', 'articles', 'List Articles', 'articles');
Menus.addSubMenuItem('sidebar', 'articles', 'New Article', 'articles/create');
}
]);
'use strict';
// Setting up route
angular.module('articles').config(['$stateProvider',
function($stateProvider) {
// Articles state routing
$stateProvider.
state('app.listArticles', {
url: '/articles',
templateUrl: 'modules/articles/views/list-articles.client.view.html'
}).
state('app.createArticle', {
url: '/articles/create',
templateUrl: 'modules/articles/views/create-article.client.view.html'
}).
state('app.viewArticle', {
url: '/articles/:articleId',
templateUrl: 'modules/articles/views/view-article.client.view.html',
controller: 'ArticlesController'
}).
state('app.editArticle', {
url: '/articles/:articleId/edit',
templateUrl: 'modules/articles/views/edit-article.client.view.html'
});
}
]);
'use strict';
angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles',
function($scope, $stateParams, $location, Authentication, Articles) {
$scope.authentication = Authentication;
$scope.create = function() {
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
$scope.title = '';
$scope.content = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.remove = function(article) {
if (article) {
article.$remove();
for (var i in $scope.articles) {
if ($scope.articles[i] === article) {
$scope.articles.splice(i, 1);
}
}
} else {
$scope.article.$remove(function() {
$location.path('articles');
});
}
};
$scope.update = function() {
var article = $scope.article;
article.$update(function() {
$location.path('articles/' + article._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.articles = Articles.query();
};
$scope.findOne = function() {
$scope.article = Articles.get({
articleId: $stateParams.articleId
});
};
}
]);
'use strict';
//Articles service used for communicating with the articles REST endpoints
angular.module('articles').factory('Articles', ['$resource',
function($resource) {
return $resource('articles/:articleId', {
articleId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
'use strict';
// Configuring the Core module
angular.module('core').run(['Menus',
function(Menus) {
// Add default menu entry
Menus.addMenuItem('sidebar', 'Home', 'home', null, '/home', true, null, null, 'icon-home');
}
]).config(['$ocLazyLoadProvider', 'APP_REQUIRES', function ($ocLazyLoadProvider, APP_REQUIRES) {
// Lazy Load modules configuration
$ocLazyLoadProvider.config({
debug: false,
events: true,
modules: APP_REQUIRES.modules
});
}]).config(['$controllerProvider', '$compileProvider', '$filterProvider', '$provide',
function ( $controllerProvider, $compileProvider, $filterProvider, $provide) {
// registering components after bootstrap
angular.module('core').controller = $controllerProvider.register;
angular.module('core').directive = $compileProvider.directive;
angular.module('core').filter = $filterProvider.register;
angular.module('core').factory = $provide.factory;
angular.module('core').service = $provide.service;
angular.module('core').constant = $provide.constant;
angular.module('core').value = $provide.value;
}]).config(['$translateProvider', function ($translateProvider) {
$translateProvider.useStaticFilesLoader({
prefix : 'modules/core/i18n/',
suffix : '.json'
});
$translateProvider.preferredLanguage('en');
$translateProvider.useLocalStorage();
}])
.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
cfpLoadingBarProvider.includeBar = true;
cfpLoadingBarProvider.includeSpinner = false;
cfpLoadingBarProvider.latencyThreshold = 500;
cfpLoadingBarProvider.parentSelector = '.wrapper > section';
}]);
/**=========================================================
* Module: constants.js
* Define constants to inject across the application
=========================================================*/
angular.module('core')
.constant('APP_COLORS', {
'primary': '#5d9cec',
'success': '#27c24c',
'info': '#23b7e5',
'warning': '#ff902b',
'danger': '#f05050',
'inverse': '#131e26',
'green': '#37bc9b',
'pink': '#f532e5',
'purple': '#7266ba',
'dark': '#3a3f51',
'yellow': '#fad732',
'gray-darker': '#232735',
'gray-dark': '#3a3f51',
'gray': '#dde6e9',
'gray-light': '#e4eaec',
'gray-lighter': '#edf1f2'
})
.constant('APP_MEDIAQUERY', {
'desktopLG': 1200,
'desktop': 992,
'tablet': 768,
'mobile': 480
})
.constant('APP_REQUIRES', {
// jQuery based and standalone scripts
scripts: {
'modernizr': ['/lib/modernizr/modernizr.js'],
'icons': ['/lib/fontawesome/css/font-awesome.min.css',
'/lib/simple-line-icons/css/simple-line-icons.css']
},
// Angular based script (use the right module name)
modules: [
// { name: 'toaster', files: ['/lib/angularjs-toaster/toaster.js','/lib/angularjs-toaster/toaster.css'] }
]
})
;
/**=========================================================
* Module: config.js
* App routes and resources configuration
=========================================================*/
angular.module('core').config(['$stateProvider', '$locationProvider', '$urlRouterProvider', 'RouteHelpersProvider',
function ($stateProvider, $locationProvider, $urlRouterProvider, helper) {
'use strict';
// Set the following to true to enable the HTML5 Mode
// You may have to set <base> tag in index and a routing configuration in your server
$locationProvider.html5Mode(false);
// default route
$urlRouterProvider.otherwise('/home');
//
// Application Routes
// -----------------------------------
$stateProvider
.state('app', {
// url: '/',
abstract: true,
templateUrl: 'modules/core/views/core.client.view.html',
resolve: helper.resolveFor('modernizr', 'icons', 'angularFileUpload')
})
.state('app.home', {
url: '/home',
templateUrl: 'modules/core/views/home.client.view.html'
})
//
// CUSTOM RESOLVES
// Add your own resolves properties
// following this object extend
// method
// -----------------------------------
// .state('app.someroute', {
// url: '/some_url',
// templateUrl: 'path_to_template.html',
// controller: 'someController',
// resolve: angular.extend(
// helper.resolveFor(), {
// // YOUR RESOLVES GO HERE
// }
// )
// })
;
}]);
/**=========================================================
* Module: main.js
* Main Application Controller
=========================================================*/
angular.module('core').controller('AppController',
['$rootScope', '$scope', '$state', '$translate', '$window', '$localStorage', '$timeout', 'toggleStateService', 'colors', 'browser', 'cfpLoadingBar', 'Authentication',
function($rootScope, $scope, $state, $translate, $window, $localStorage, $timeout, toggle, colors, browser, cfpLoadingBar, Authentication) {
"use strict";
// This provides Authentication context.
$scope.authentication = Authentication;
// Loading bar transition
// -----------------------------------
var thBar;
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if($('.wrapper > section').length) // check if bar container exists
thBar = $timeout(function() {
cfpLoadingBar.start();
}, 0); // sets a latency Threshold
});
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
event.targetScope.$watch("$viewContentLoaded", function () {
$timeout.cancel(thBar);
cfpLoadingBar.complete();
});
});
// Hook not found
$rootScope.$on('$stateNotFound',
function(event, unfoundState, fromState, fromParams) {
console.log(unfoundState.to); // "lazy.state"
console.log(unfoundState.toParams); // {a:1, b:2}
console.log(unfoundState.options); // {inherit:false} + default options
});
// Hook error
$rootScope.$on('$stateChangeError',
function(event, toState, toParams, fromState, fromParams, error){
console.log(error);
});
// Hook success
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
// display new view from top
$window.scrollTo(0, 0);
// Save the route title
$rootScope.currTitle = $state.current.title;
});
$rootScope.currTitle = $state.current.title;
$rootScope.pageTitle = function() {
return $rootScope.app.name + ' - ' + ($rootScope.currTitle || $rootScope.app.description);
};
// iPad may presents ghost click issues
// if( ! browser.ipad )
// FastClick.attach(document.body);
// Close submenu when sidebar change from collapsed to normal
$rootScope.$watch('app.layout.isCollapsed', function(newValue, oldValue) {
if( newValue === false )
$rootScope.$broadcast('closeSidebarMenu');
});
// Restore layout settings
if( angular.isDefined($localStorage.layout) )
$scope.app.layout = $localStorage.layout;
else
$localStorage.layout = $scope.app.layout;
$rootScope.$watch("app.layout", function () {
$localStorage.layout = $scope.app.layout;
}, true);
// Allows to use branding color with interpolation
// {{ colorByName('primary') }}
$scope.colorByName = colors.byName;
// Internationalization
// ----------------------
$scope.language = {
// Handles language dropdown
listIsOpen: false,
// list of available languages
available: {
'en': 'English',
'es_AR': 'Español'
},
// display always the current ui language
init: function () {
var proposedLanguage = $translate.proposedLanguage() || $translate.use();
var preferredLanguage = $translate.preferredLanguage(); // we know we have set a preferred one in app.config
$scope.language.selected = $scope.language.available[ (proposedLanguage || preferredLanguage) ];
},
set: function (localeId, ev) {
// Set the new idiom
$translate.use(localeId);
// save a reference for the current language
$scope.language.selected = $scope.language.available[localeId];
// finally toggle dropdown
$scope.language.listIsOpen = ! $scope.language.listIsOpen;
}
};
$scope.language.init();
// Restore application classes state
toggle.restoreState( $(document.body) );
// Applies animation to main view for the next pages to load
$timeout(function(){
$rootScope.mainViewAnimation = $rootScope.app.viewAnimation;
});
// cancel click event easily
$rootScope.cancel = function($event) {
$event.stopPropagation();
};
}]);
'use strict';
angular.module('core').controller('HeaderController', ['$scope', 'Authentication', 'Menus',
function($scope, Authentication, Menus) {
$scope.authentication = Authentication;
$scope.isCollapsed = false;
$scope.menu = Menus.getMenu('topbar');
$scope.toggleCollapsibleMenu = function() {
$scope.isCollapsed = !$scope.isCollapsed;
};
// Collapsing the menu after navigation
$scope.$on('$stateChangeSuccess', function() {
$scope.isCollapsed = false;
});
}
]);
'use strict';
angular.module('core').controller('SidebarController',
['$rootScope', '$scope', '$state', 'Authentication', 'Menus', 'Utils',
function($rootScope, $scope, $state, Authentication, Menus, Utils) {
$scope.authentication = Authentication;
$scope.menu = Menus.getMenu('sidebar');
var collapseList = [];
// demo: when switch from collapse to hover, close all items
$rootScope.$watch('app.layout.asideHover', function(oldVal, newVal){
if ( newVal === false && oldVal === true) {
closeAllBut(-1);
}
});
// Check item and children active state
var isActive = function(item) {
if(!item) return;
if( !item.sref || item.sref == '#') {
var foundActive = false;
angular.forEach(item.submenu, function(value, key) {
if(isActive(value)) foundActive = true;
});
return foundActive;
}
else
return $state.is(item.sref) || $state.includes(item.sref);
};
// Load menu from json file
// -----------------------------------
$scope.getMenuItemPropClasses = function(item) {
return (item.heading ? 'nav-heading' : '') +
(isActive(item) ? ' active' : '') ;
};
// Handle sidebar collapse items
// -----------------------------------
$scope.addCollapse = function($index, item) {
collapseList[$index] = $rootScope.app.layout.asideHover ? true : !isActive(item);
};
$scope.isCollapse = function($index) {
return (collapseList[$index]);
};
$scope.toggleCollapse = function($index, isParentItem) {
// collapsed sidebar doesn't toggle drodopwn
if( Utils.isSidebarCollapsed() || $rootScope.app.layout.asideHover ) return true;
// make sure the item index exists
if( angular.isDefined( collapseList[$index] ) ) {
collapseList[$index] = !collapseList[$index];
closeAllBut($index);
}
else if ( isParentItem ) {
closeAllBut(-1);
}
return true;
};
function closeAllBut(index) {
index += '';
for(var i in collapseList) {
if(index < 0 || index.indexOf(i) < 0)
collapseList[i] = true;
}
}
}
]);
/**=========================================================
* Module: navbar-search.js
* Navbar search toggler * Auto dismiss on ESC key
=========================================================*/
angular.module('core').directive('searchOpen', ['navSearch', function(navSearch) {
'use strict';
return {
restrict: 'A',
controller: ["$scope", "$element", function($scope, $element) {
$element
.on('click', function (e) { e.stopPropagation(); })
.on('click', navSearch.toggle);
}]
};
}]).directive('searchDismiss', ['navSearch', function(navSearch) {
'use strict';
var inputSelector = '.navbar-form input[type="text"]';
return {
restrict: 'A',
controller: ["$scope", "$element", function($scope, $element) {
$(inputSelector)
.on('click', function (e) { e.stopPropagation(); })
.on('keyup', function(e) {
if (e.keyCode == 27) // ESC
navSearch.dismiss();
});
// click anywhere closes the search
$(document).on('click', navSearch.dismiss);
// dismissable options
$element
.on('click', function (e) { e.stopPropagation(); })
.on('click', navSearch.dismiss);
}]
};
}]);
/**=========================================================
* Module: sidebar.js
* Wraps the sidebar and handles collapsed state
=========================================================*/
/* jshint -W026 */
angular.module('core').directive('sidebar', ['$rootScope', '$window', 'Utils', function($rootScope, $window, Utils) {
'use strict';
var $win = $($window);
var $body = $('body');
var $scope;
var $sidebar;
var currentState = $rootScope.$state.current.name;
return {
restrict: 'EA',
template: '<nav class="sidebar" ng-transclude></nav>',
transclude: true,
replace: true,
link: function(scope, element, attrs) {
$scope = scope;
$sidebar = element;
var eventName = Utils.isTouch() ? 'click' : 'mouseenter' ;
var subNav = $();
$sidebar.on( eventName, '.nav > li', function() {
if( Utils.isSidebarCollapsed() || $rootScope.app.layout.asideHover ) {
subNav.trigger('mouseleave');
subNav = toggleMenuItem( $(this) );
// Used to detect click and touch events outside the sidebar
sidebarAddBackdrop();
}
});
scope.$on('closeSidebarMenu', function() {
removeFloatingNav();
});
// Normalize state when resize to mobile
$win.on('resize', function() {
if( ! Utils.isMobile() )
$body.removeClass('aside-toggled');
});
// Adjustment on route changes
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
currentState = toState.name;
// Hide sidebar automatically on mobile
$('body.aside-toggled').removeClass('aside-toggled');
$rootScope.$broadcast('closeSidebarMenu');
});
// Allows to close
if ( angular.isDefined(attrs.sidebarAnyclickClose) ) {
$('.wrapper').on('click.sidebar', function(e){
// don't check if sidebar not visible
if( ! $body.hasClass('aside-toggled')) return;
// if not child of sidebar
if( ! $(e.target).parents('.aside').length ) {
$body.removeClass('aside-toggled');
}
});
}
}
};
function sidebarAddBackdrop() {
var $backdrop = $('<div/>', { 'class': 'dropdown-backdrop'} );
$backdrop.insertAfter('.aside-inner').on("click mouseenter", function () {
removeFloatingNav();
});
}
// Open the collapse sidebar submenu items when on touch devices
// - desktop only opens on hover
function toggleTouchItem($element){
$element
.siblings('li')
.removeClass('open')
.end()
.toggleClass('open');
}
// Handles hover to open items under collapsed menu
// -----------------------------------
function toggleMenuItem($listItem) {
removeFloatingNav();
var ul = $listItem.children('ul');
if( !ul.length ) return $();
if( $listItem.hasClass('open') ) {
toggleTouchItem($listItem);
return $();
}
var $aside = $('.aside');
var $asideInner = $('.aside-inner'); // for top offset calculation
// float aside uses extra padding on aside
var mar = parseInt( $asideInner.css('padding-top'), 0) + parseInt( $aside.css('padding-top'), 0);
var subNav = ul.clone().appendTo( $aside );
toggleTouchItem($listItem);
var itemTop = ($listItem.position().top + mar) - $sidebar.scrollTop();
var vwHeight = $win.height();
subNav
.addClass('nav-floating')
.css({
position: $scope.app.layout.isFixed ? 'fixed' : 'absolute',
top: itemTop,
bottom: (subNav.outerHeight(true) + itemTop > vwHeight) ? 0 : 'auto'
});
subNav.on('mouseleave', function() {
toggleTouchItem($listItem);
subNav.remove();
});
return subNav;
}
function removeFloatingNav() {
$('.dropdown-backdrop').remove();
$('.sidebar-subnav.nav-floating').remove();
$('.sidebar li.open').removeClass('open');
}
}]);
/**=========================================================
* Module: toggle-state.js
* Toggle a classname from the BODY Useful to change a state that
* affects globally the entire layout or more than one item
* Targeted elements must have [toggle-state="CLASS-NAME-TO-TOGGLE"]
* User no-persist to avoid saving the sate in browser storage
=========================================================*/
angular.module('core').directive('toggleState', ['toggleStateService', function(toggle) {
'use strict';
return {
restrict: 'A',
link: function(scope, element, attrs) {
var $body = $('body');
$(element)
.on('click', function (e) {
e.preventDefault();
var classname = attrs.toggleState;
if(classname) {
if( $body.hasClass(classname) ) {
$body.removeClass(classname);
if( ! attrs.noPersist)
toggle.removeState(classname);
}
else {
$body.addClass(classname);
if( ! attrs.noPersist)
toggle.addState(classname);
}
}
});
}
};
}]);
angular.module('core').service('browser', function(){
"use strict";
var matched, browser;
var uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(opr)[\/]([\w.]+)/.exec( ua ) ||
/(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
var platform_match = /(ipad)/.exec( ua ) ||
/(iphone)/.exec( ua ) ||
/(android)/.exec( ua ) ||
/(windows phone)/.exec( ua ) ||
/(win)/.exec( ua ) ||
/(mac)/.exec( ua ) ||
/(linux)/.exec( ua ) ||
/(cros)/i.exec( ua ) ||
[];
return {
browser: match[ 3 ] || match[ 1 ] || "",
version: match[ 2 ] || "0",
platform: platform_match[ 0 ] || ""
};
};
matched = uaMatch( window.navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
browser.versionNumber = parseInt(matched.version);
}
if ( matched.platform ) {
browser[ matched.platform ] = true;
}
// These are all considered mobile platforms, meaning they run a mobile browser
if ( browser.android || browser.ipad || browser.iphone || browser[ "windows phone" ] ) {
browser.mobile = true;
}
// These are all considered desktop platforms, meaning they run a desktop browser
if ( browser.cros || browser.mac || browser.linux || browser.win ) {
browser.desktop = true;
}
// Chrome, Opera 15+ and Safari are webkit based browsers
if ( browser.chrome || browser.opr || browser.safari ) {
browser.webkit = true;
}
// IE11 has a new token so we will assign it msie to avoid breaking changes
if ( browser.rv )
{
var ie = "msie";
matched.browser = ie;
browser[ie] = true;
}
// Opera 15+ are identified as opr
if ( browser.opr )
{
var opera = "opera";
matched.browser = opera;
browser[opera] = true;
}
// Stock Android browsers are marked as Safari on Android.
if ( browser.safari && browser.android )
{
var android = "android";
matched.browser = android;
browser[android] = true;
}
// Assign the name and platform variable
browser.name = matched.browser;
browser.platform = matched.platform;
return browser;
});
/**=========================================================
* Module: colors.js
* Services to retrieve global colors
=========================================================*/
angular.module('core').factory('colors', ['APP_COLORS', function(colors) {
'use strict';
return {
byName: function(name) {
return (colors[name] || '#fff');
}
};
}]);
'use strict';
//Menu service used for managing menus
angular.module('core').service('Menus', [
function() {
// Define a set of default roles
this.defaultRoles = ['*'];
// Define the menus object
this.menus = {};
// A private function for rendering decision
var shouldRender = function(user) {
if (user) {
if (!!~this.roles.indexOf('*')) {
return true;
} else {
for (var userRoleIndex in user.roles) {
for (var roleIndex in this.roles) {
if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
return true;
}
}
}
}
} else {
return this.isPublic;
}
return false;
};
// Validate menu existance
this.validateMenuExistance = function(menuId) {
if (menuId && menuId.length) {
if (this.menus[menuId]) {
return true;
} else {
throw new Error('Menu does not exists');
}
} else {
throw new Error('MenuId was not provided');
}
return false;
};
// Get the menu object by menu id
this.getMenu = function(menuId) {
// Validate that the menu exists
this.validateMenuExistance(menuId);
// Return the menu object
return this.menus[menuId];
};
// Add new menu object by menu id
this.addMenu = function(menuId, isPublic, roles) {
// Create the new menu
this.menus[menuId] = {
isPublic: isPublic || false,
roles: roles || this.defaultRoles,
items: [],
shouldRender: shouldRender
};
// Return the menu object
return this.menus[menuId];
};
// Remove existing menu object by menu id
this.removeMenu = function(menuId) {
// Validate that the menu exists
this.validateMenuExistance(menuId);
// Return the menu object
delete this.menus[menuId];
};
// Add menu item object
this.addMenuItem = function(menuId, menuItemTitle, menuItemURL, menuItemType, menuItemUIRoute, isPublic, roles, position,
iconClass, translateKey, alert) {
// Validate that the menu exists
this.validateMenuExistance(menuId);
// Push new menu item
this.menus[menuId].items.push({
title: menuItemTitle,
link: menuItemURL,
menuItemType: menuItemType || 'item',
menuItemClass: menuItemType,
uiRoute: menuItemUIRoute || ('/' + menuItemURL),
isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].isPublic : isPublic),
roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].roles : roles),
position: position || 0,
items: [],
shouldRender: shouldRender,
iconClass: iconClass || 'fa fa-file-o',
translate: translateKey,
alert: alert
});
// Return the menu object
return this.menus[menuId];
};
// Add submenu item object
this.addSubMenuItem = function(menuId, rootMenuItemURL, menuItemTitle, menuItemURL, menuItemUIRoute, isPublic, roles, position) {
// Validate that the menu exists
this.validateMenuExistance(menuId);
// Search for menu item
for (var itemIndex in this.menus[menuId].items) {
if (this.menus[menuId].items[itemIndex].link === rootMenuItemURL) {
// Push new submenu item
this.menus[menuId].items[itemIndex].items.push({
title: menuItemTitle,
link: menuItemURL,
uiRoute: menuItemUIRoute || ('/' + menuItemURL),
isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].items[itemIndex].isPublic : isPublic),
roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].items[itemIndex].roles : roles),
position: position || 0,
shouldRender: shouldRender
});
}
}
// Return the menu object
return this.menus[menuId];
};
// Remove existing menu object by menu id
this.removeMenuItem = function(menuId, menuItemURL) {
// Validate that the menu exists
this.validateMenuExistance(menuId);
// Search for menu item to remove
for (var itemIndex in this.menus[menuId].items) {
if (this.menus[menuId].items[itemIndex].link === menuItemURL) {
this.menus[menuId].items.splice(itemIndex, 1);
}
}
// Return the menu object
return this.menus[menuId];
};
// Remove existing menu object by menu id
this.removeSubMenuItem = function(menuId, submenuItemURL) {
// Validate that the menu exists
this.validateMenuExistance(menuId);
// Search for menu item to remove
for (var itemIndex in this.menus[menuId].items) {
for (var subitemIndex in this.menus[menuId].items[itemIndex].items) {
if (this.menus[menuId].items[itemIndex].items[subitemIndex].link === submenuItemURL) {
this.menus[menuId].items[itemIndex].items.splice(subitemIndex, 1);
}
}
}
// Return the menu object
return this.menus[menuId];
};
//Adding the topbar menu
this.addMenu('topbar');
//Adding the sidebar menu
this.addMenu('sidebar');
}
]);
/**=========================================================
* Module: nav-search.js
* Services to share navbar search functions
=========================================================*/
angular.module('core').service('navSearch', function() {
'use strict';
var navbarFormSelector = 'form.navbar-form';
return {
toggle: function() {
var navbarForm = $(navbarFormSelector);
navbarForm.toggleClass('open');
var isOpen = navbarForm.hasClass('open');
navbarForm.find('input')[isOpen ? 'focus' : 'blur']();
},
dismiss: function() {
$(navbarFormSelector)
.removeClass('open') // Close control
.find('input[type="text"]').blur() // remove focus
.val('') // Empty input
;
}
};
});
/**=========================================================
* Module: helpers.js
* Provides helper functions for routes definition
=========================================================*/
/* jshint -W026 */
/* jshint -W003 */
angular.module('core').provider('RouteHelpers', ['APP_REQUIRES', function (appRequires) {
"use strict";
// Set here the base of the relative path
// for all app views
this.basepath = function (uri) {
return 'app/views/' + uri;
};
// Generates a resolve object by passing script names
// previously configured in constant.APP_REQUIRES
this.resolveFor = function () {
var _args = arguments;
return {
deps: ['$ocLazyLoad','$q', function ($ocLL, $q) {
// Creates a promise chain for each argument
var promise = $q.when(1); // empty promise
for(var i=0, len=_args.length; i < len; i ++){
promise = andThen(_args[i]);
}
return promise;
// creates promise to chain dynamically
function andThen(_arg) {
// also support a function that returns a promise
if(typeof _arg == 'function')
return promise.then(_arg);
else
return promise.then(function() {
// if is a module, pass the name. If not, pass the array
var whatToLoad = getRequired(_arg);
// simple error check
if(!whatToLoad) return $.error('Route resolve: Bad resource name [' + _arg + ']');
// finally, return a promise
return $ocLL.load( whatToLoad );
});
}
// check and returns required data
// analyze module items with the form [name: '', files: []]
// and also simple array of script files (for not angular js)
function getRequired(name) {
if (appRequires.modules)
for(var m in appRequires.modules)
if(appRequires.modules[m].name && appRequires.modules[m].name === name)
return appRequires.modules[m];
return appRequires.scripts && appRequires.scripts[name];
}
}]};
}; // resolveFor
// not necessary, only used in config block for routes
this.$get = function(){};
}]);
/**=========================================================
* Module: toggle-state.js
* Services to share toggle state functionality
=========================================================*/
angular.module('core').service('toggleStateService', ['$rootScope', function($rootScope) {
'use strict';
var storageKeyName = 'toggleState';
// Helper object to check for words in a phrase //
var WordChecker = {
hasWord: function (phrase, word) {
return new RegExp('(^|\\s)' + word + '(\\s|$)').test(phrase);
},
addWord: function (phrase, word) {
if (!this.hasWord(phrase, word)) {
return (phrase + (phrase ? ' ' : '') + word);
}
},
removeWord: function (phrase, word) {
if (this.hasWord(phrase, word)) {
return phrase.replace(new RegExp('(^|\\s)*' + word + '(\\s|$)*', 'g'), '');
}
}
};
// Return service public methods
return {
// Add a state to the browser storage to be restored later
addState: function(classname){
var data = angular.fromJson($rootScope.$storage[storageKeyName]);
if(!data) {
data = classname;
}
else {
data = WordChecker.addWord(data, classname);
}
$rootScope.$storage[storageKeyName] = angular.toJson(data);
},
// Remove a state from the browser storage
removeState: function(classname){
var data = $rootScope.$storage[storageKeyName];
// nothing to remove
if(!data) return;
data = WordChecker.removeWord(data, classname);
$rootScope.$storage[storageKeyName] = angular.toJson(data);
},
// Load the state string and restore the classlist
restoreState: function($elem) {
var data = angular.fromJson($rootScope.$storage[storageKeyName]);
// nothing to restore
if(!data) return;
$elem.addClass(data);
}
};
}]);
/**=========================================================
* Module: utils.js
* Utility library to use across the theme
=========================================================*/
angular.module('core').service('Utils', ["$window", "APP_MEDIAQUERY", function($window, APP_MEDIAQUERY) {
'use strict';
var $html = angular.element("html"),
$win = angular.element($window),
$body = angular.element('body');
return {
// DETECTION
support: {
transition: (function() {
var transitionEnd = (function() {
var element = document.body || document.documentElement,
transEndEventNames = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
}, name;
for (name in transEndEventNames) {
if (element.style[name] !== undefined) return transEndEventNames[name];
}
}());
return transitionEnd && { end: transitionEnd };
})(),
animation: (function() {
var animationEnd = (function() {
var element = document.body || document.documentElement,
animEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
MozAnimation: 'animationend',
OAnimation: 'oAnimationEnd oanimationend',
animation: 'animationend'
}, name;
for (name in animEndEventNames) {
if (element.style[name] !== undefined) return animEndEventNames[name];
}
}());
return animationEnd && { end: animationEnd };
})(),
requestAnimationFrame: window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(callback){ window.setTimeout(callback, 1000/60); },
touch: (
('ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
(window.DocumentTouch && document instanceof window.DocumentTouch) ||
(window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints > 0) || //IE 10
(window.navigator.pointerEnabled && window.navigator.maxTouchPoints > 0) || //IE >=11
false
),
mutationobserver: (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver || null)
},
// UTILITIES
isInView: function(element, options) {
var $element = $(element);
if (!$element.is(':visible')) {
return false;
}
var window_left = $win.scrollLeft(),
window_top = $win.scrollTop(),
offset = $element.offset(),
left = offset.left,
top = offset.top;
options = $.extend({topoffset:0, leftoffset:0}, options);
if (top + $element.height() >= window_top && top - options.topoffset <= window_top + $win.height() &&
left + $element.width() >= window_left && left - options.leftoffset <= window_left + $win.width()) {
return true;
} else {
return false;
}
},
langdirection: $html.attr("dir") == "rtl" ? "right" : "left",
isTouch: function () {
return $html.hasClass('touch');
},
isSidebarCollapsed: function () {
return $body.hasClass('aside-collapsed');
},
isSidebarToggled: function () {
return $body.hasClass('aside-toggled');
},
isMobile: function () {
return $win.width() < APP_MEDIAQUERY.tablet;
}
};
}]);
'use strict';
// Setting up route
angular.module('page').config(['$stateProvider',
function($stateProvider) {
// Users state routing
$stateProvider.
state('page', {
url: '/page',
templateUrl: 'modules/page/views/page.client.view.html'
});
}
]);
'use strict';
// Config HTTP Error Handling
angular.module('users').config(['$httpProvider',
function($httpProvider) {
// Set the httpProvider "not authorized" interceptor
$httpProvider.interceptors.push(['$q', '$location', 'Authentication',
function($q, $location, Authentication) {
return {
responseError: function(rejection) {
switch (rejection.status) {
case 401:
// Deauthenticate the global user
Authentication.user = null;
// Redirect to signin page
$location.path('signin');
break;
case 403:
// Add unauthorized behaviour
break;
}
return $q.reject(rejection);
}
};
}
]);
}
]);
'use strict';
// Setting up route
angular.module('users').config(['$stateProvider',
function($stateProvider) {
// Users state routing
$stateProvider.
state('page.signin', {
url: '/signin',
templateUrl: 'modules/users/views/authentication/signin.client.view.html'
}).
state('page.signup', {
url: '/signup',
templateUrl: 'modules/users/views/authentication/signup.client.view.html'
}).
state('page.forgot', {
url: '/password/forgot',
templateUrl: 'modules/users/views/password/forgot-password.client.view.html'
}).
state('page.reset-invalid', {
url: '/password/reset/invalid',
templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html'
}).
state('page.reset-success', {
url: '/password/reset/success',
templateUrl: 'modules/users/views/password/reset-password-success.client.view.html'
}).
state('page.reset', {
url: '/password/reset/:token',
templateUrl: 'modules/users/views/password/reset-password.client.view.html'
}).
state('app.password', {
url: '/settings/password',
templateUrl: 'modules/users/views/settings/change-password.client.view.html'
}).
state('app.profile', {
url: '/settings/profile',
templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
}).
state('app.accounts', {
url: '/settings/accounts',
templateUrl: 'modules/users/views/settings/social-accounts.client.view.html'
});
}
]);
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
function($scope, $http, $location, Authentication) {
$scope.authentication = Authentication;
// If user is signed in then redirect back home
if ($scope.authentication.user) $location.path('/');
$scope.signup = function() {
$http.post('/auth/signup', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.signin = function() {
$http.post('/auth/signin', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
}
]);
'use strict';
angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$http', '$location', 'Authentication',
function($scope, $stateParams, $http, $location, Authentication) {
$scope.authentication = Authentication;
//If user is signed in then redirect back home
if ($scope.authentication.user) $location.path('/');
// Submit forgotten password account id
$scope.askForPasswordReset = function() {
$scope.success = $scope.error = null;
$http.post('/auth/forgot', $scope.credentials).success(function(response) {
// Show user success message and clear form
$scope.credentials = null;
$scope.success = response.message;
}).error(function(response) {
// Show user error message and clear form
$scope.credentials = null;
$scope.error = response.message;
});
};
// Change user password
$scope.resetUserPassword = function() {
$scope.success = $scope.error = null;
$http.post('/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function(response) {
// If successful show success message and clear form
$scope.passwordDetails = null;
// Attach user profile
Authentication.user = response;
// And redirect to the index page
$location.path('/password/reset/success');
}).error(function(response) {
$scope.error = response.message;
});
};
}
]);
'use strict';
angular.module('users').controller('SettingsController', ['$scope', '$http', '$location', 'Users', 'Authentication',
function($scope, $http, $location, Users, Authentication) {
$scope.user = Authentication.user;
// If user is not signed in then redirect back home
if (!$scope.user) $location.path('/');
// Check if there are additional accounts
$scope.hasConnectedAdditionalSocialAccounts = function(provider) {
for (var i in $scope.user.additionalProvidersData) {
return true;
}
return false;
};
// Check if provider is already in use with current user
$scope.isConnectedSocialAccount = function(provider) {
return $scope.user.provider === provider || ($scope.user.additionalProvidersData && $scope.user.additionalProvidersData[provider]);
};
// Remove a user social account
$scope.removeUserSocialAccount = function(provider) {
$scope.success = $scope.error = null;
$http.delete('/users/accounts', {
params: {
provider: provider
}
}).success(function(response) {
// If successful show success message and clear form
$scope.success = true;
$scope.user = Authentication.user = response;
}).error(function(response) {
$scope.error = response.message;
});
};
// Update a user profile
$scope.updateUserProfile = function(isValid) {
if (isValid) {
$scope.success = $scope.error = null;
var user = new Users($scope.user);
user.$update(function(response) {
$scope.success = true;
Authentication.user = response;
}, function(response) {
$scope.error = response.data.message;
});
} else {
$scope.submitted = true;
}
};
// Change user password
$scope.changeUserPassword = function() {
$scope.success = $scope.error = null;
$http.post('/users/password', $scope.passwordDetails).success(function(response) {
// If successful show success message and clear form
$scope.success = true;
$scope.passwordDetails = null;
}).error(function(response) {
$scope.error = response.message;
});
};
}
]);
'use strict';
// Authentication service for user variables
angular.module('users').factory('Authentication', [
function() {
var _this = this;
_this._data = {
user: window.user
};
return _this._data;
}
]);
'use strict';
// Users service used for communicating with the users REST endpoint
angular.module('users').factory('Users', ['$resource',
function($resource) {
return $resource('users', {}, {
update: {
method: 'PUT'
}
});
}
]); | andreilaza/alt-be-back-server | public/dist/application.js | JavaScript | mit | 50,852 |
/*!
* stepviz 0.1.0 (30-05-2016)
* https://github.com/suhaibkhan/stepviz
* MIT licensed
* Copyright (C) 2016 Suhaib Khan, http://suhaibkhan.github.io
*/
(function() {
'use strict';
// check for dependencies
if (typeof window.d3 === 'undefined') {
throw 'd3 library not found.';
}
// init namespaces
/**
* stepViz Namespace
*
* @namespace
*/
var ns = {
/**
* Components Namespace
*
* @namespace
* @memberof stepViz
*/
components: {},
/**
* Constants Namespace
*
* @namespace
* @memberof stepViz
*/
constants: {},
/**
* Configuration Namespace
*
* @namespace
* @memberof stepViz
*/
config: {},
/**
* Utility functions Namespace
*
* @namespace
* @memberof stepViz
*/
util: {}
};
// set as global
window.stepViz = ns;
}());
(function(ns) {
'use strict';
// Default Configuration
// Default theme
ns.config.themeCSSClass = 'default';
// CSS class used for highlighting
ns.config.highlightCSSClass = 'highlight';
// Default font size
ns.config.defaultFontSize = '12px';
}(window.stepViz));
(function(ns) {
'use strict';
ns.init = function(container, props) {
return new ns.components.Canvas(container, props);
};
ns.initStepExecutor = function(){
return new ns.StepExecutor();
};
}(window.stepViz));
(function(ns) {
'use strict';
function parseAndCalc(value, relativeValue) {
var retVal = parseFloat(value);
if (isNaN(retVal)) {
throw 'Invalid layout value ' + value;
} else {
if (typeof value == 'string') {
value = value.trim();
if (value.endsWith('%')) {
retVal = (retVal / 100) * relativeValue;
}
}
}
return retVal;
}
ns.Layout = function(parent, box, margin) {
this._parent = parent;
// defaults
this._box = {
top: 0,
left: 0,
width: 'auto',
height: 'auto'
};
this._margin = {
top: 0,
left: 0,
bottom: 0,
right: 0
};
this.setBox(box, margin);
};
ns.Layout.prototype.reCalculate = function() {
var parentSize = {
width: 0,
height: 0
};
if (this._parent instanceof HTMLElement) {
parentSize.width = this._parent.offsetWidth;
parentSize.height = this._parent.offsetHeight;
} else if (typeof this._parent.layout == 'function') {
var parentBounds = this._parent.layout().getBox();
parentSize.width = parentBounds.width;
parentSize.height = parentBounds.height;
} else {
throw 'Invalid parent';
}
// calculate bounds
this._top = parseAndCalc(this._box.top, parentSize.height);
this._left = parseAndCalc(this._box.left, parentSize.width);
if (this._box.width == 'auto') {
// use remaining width
this._width = parentSize.width - this._left;
} else {
this._width = parseAndCalc(this._box.width, parentSize.width);
}
if (this._box.height == 'auto') {
// use remaining height
this._height = parentSize.height - this._top;
} else {
this._height = parseAndCalc(this._box.height, parentSize.height);
}
};
ns.Layout.prototype.setBox = function(box, margin) {
this._box = ns.util.defaults(box, this._box);
this._margin = ns.util.defaults(margin, this._margin);
this.reCalculate();
};
ns.Layout.prototype.getBounds = function() {
return {
top: this._top,
left: this._left,
width: this._width,
height: this._height
};
};
ns.Layout.prototype.getBox = function() {
return {
top: this._top + this._margin.top,
left: this._left + this._margin.left,
width: this._width - this._margin.left - this._margin.right,
height: this._height - this._margin.top - this._margin.bottom
};
};
ns.Layout.prototype.moveTo = function(x, y) {
this.setBox({
top: y,
left: x
});
};
ns.Layout.prototype.translate = function(x, y) {
this.setBox({
top: this._top + y,
left: this._left + x
});
};
ns.Layout.prototype.clone = function() {
return new ns.Layout(this._parent, ns.util.objClone(this._box),
ns.util.objClone(this._margin));
};
}(window.stepViz));
(function(ns) {
'use strict';
ns.StepExecutor = function() {
this._currentStepIndex = -1;
this._steps = [];
};
ns.StepExecutor.prototype.add = function(stepFn, clearFn, noOfTimes){
noOfTimes = noOfTimes || 1;
stepFn = stepFn || function(){};
clearFn = clearFn || function(){};
if (typeof stepFn != 'function' || typeof clearFn != 'function'){
throw Error('Invalid argument');
}
for (var i = 0; i < noOfTimes; i++){
this._steps.push({forward: stepFn, backward: clearFn});
}
};
ns.StepExecutor.prototype.hasNext = function(){
return (this._currentStepIndex + 1 < this._steps.length);
};
ns.StepExecutor.prototype.hasBack = function(){
return (this._currentStepIndex >= 0);
};
ns.StepExecutor.prototype.next = function(context){
if (this._currentStepIndex + 1 >= this._steps.length ){
throw Error('No forward steps');
}
this._currentStepIndex++;
this._steps[this._currentStepIndex].forward.call(context);
};
ns.StepExecutor.prototype.back = function(context){
if (this._currentStepIndex < 0){
throw Error('No backward steps');
}
this._steps[this._currentStepIndex].backward.call(context);
this._currentStepIndex--;
};
}(window.stepViz));
(function(ns) {
'use strict';
ns.util.inherits = function(base, child) {
child.prototype = Object.create(base.prototype);
child.prototype.constructor = child;
};
ns.util.defaults = function(props, defaults) {
props = props || {};
var clonedProps = ns.util.objClone(props);
for (var prop in defaults) {
if (defaults.hasOwnProperty(prop) && !clonedProps.hasOwnProperty(prop)) {
clonedProps[prop] = defaults[prop];
}
}
return clonedProps;
};
ns.util.objClone = function(obj) {
var cloneObj = null;
if (Array.isArray(obj)) {
cloneObj = [];
for (var i = 0; i < obj.length; i++) {
cloneObj.push(ns.util.objClone(obj[i]));
}
} else if (typeof obj == 'object') {
cloneObj = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
cloneObj[prop] = ns.util.objClone(obj[prop]);
}
}
} else {
cloneObj = obj;
}
return cloneObj;
};
ns.util.createTaskForPromise = function(fn, context, args) {
return function() {
return fn.apply(context, args);
};
};
}(window.stepViz));
(function(ns, d3) {
'use strict';
/**
* Base class for all components
*
* @class
* @memberof stepViz.components
* @abstract
*/
ns.components.Component = function(parent, value, layout, props, defaults) {
// default values for props
defaults = defaults || {};
if (typeof value == 'undefined') {
throw 'Invalid value';
}
if (!layout) {
throw 'Invalid layout';
}
this._state = ns.util.defaults(props, defaults);
this._state.parent = parent;
this._state.value = value;
this._state.layout = layout;
this._state.children = [];
// will be defined in child class
this._state.svgElem = null;
};
/**
* Returns or set value of the component.
* If new value is not specified, existing value is returned.
*
* @param {Object} [value] - New value to be saved in state
* @return {Object} Value associated with the component.
*/
ns.components.Component.prototype.value = function(newValue) {
if (typeof newValue != 'undefined') {
// set new value
this._state.value = newValue;
}
return this._state.value;
};
/**
* Returns parent of the component or null for root component.
*
* @return {stepViz.components.Component} Parent component
*/
ns.components.Component.prototype.parent = function() {
return this._state.parent;
};
/**
* Returns or set value of the specified state property.
* If value is not specified, existing value is returned.
*
* @param {String} property - State property name
* @param {Object} [value] - Value to be saved
* @return {Object} State property value
*/
ns.components.Component.prototype.state = function(property, value) {
if (typeof property != 'string') {
throw 'Invalid property name';
}
if (typeof value != 'undefined') {
// set new value
this._state[property] = value;
}
// return existing value
return this._state[property];
};
/**
* Returns layout of the component.
*
* @return {stepViz.Layout} Layout
*/
ns.components.Component.prototype.layout = function() {
return this._state.layout;
};
/**
* Create a layout with current component as parent.
*
* @param {Object} box - Layout box object
* @param {Object} margin - Layout margin object
* @return {stepViz.Layout} New layout
*/
ns.components.Component.prototype.createLayout = function(box, margin) {
return new ns.Layout(this, box, margin);
};
/**
* Update layout associated with current component.
*
* @param {Object} box - New layout box object
* @param {Object} margin - New layout margin object
*/
ns.components.Component.prototype.updateLayout = function(box, margin) {
return this._state.layout.setBox(box, margin);
};
/**
* Returns SVG container of the component. Usually an SVG group.
*
* @return {Array} d3 selector corresponding to SVGElement of the component.
*/
ns.components.Component.prototype.svg = function() {
return this._state.svgElem;
};
/**
* Set SVGElement of the component.
*
* @param {Array} d3 selector corresponding to SVGElement.
*/
ns.components.Component.prototype.setSVG = function(svgElem) {
this._state.svgElem = svgElem;
};
/**
* Redraws component
* @abstract
*/
ns.components.Component.prototype.redraw = function() {
// Needs to be implemented in the child class
throw 'Not implemented on Component base class';
};
/**
* Redraws all children of current component.
*/
ns.components.Component.prototype.redrawAllChildren = function() {
for (var i = 0; i < this._state.children.length; i++) {
this._state.children[i].redraw();
}
};
/**
* Add a child component to current component.
*
* @param {stepViz.components.Component} child - Child component
*/
ns.components.Component.prototype.addChild = function(child) {
this._state.children.push(child);
};
/**
* Returns child component at specified index or null if not available.
*
* @param {Number} index - Child component index
* @return {stepViz.components.Component} Child component
*/
ns.components.Component.prototype.child = function(index) {
if (index >= 0 && index < this._state.children.length) {
return this._state.children[index];
}
return null;
};
/**
* Clone state properties from the component.
*
* @param {Array} excludeProps - Array of properties to exclude while cloning.
* @return {Object} Cloned properties object
*/
ns.components.Component.prototype.cloneProps = function(excludeProps) {
excludeProps = excludeProps || [];
var state = this._state;
var props = {};
var discardProps = ['value', 'layout', 'parent', 'svgElem', 'children'].concat(excludeProps);
for (var prop in state) {
if (state.hasOwnProperty(prop) && discardProps.indexOf(prop) == -1) {
props[prop] = ns.util.objClone(state[prop]);
}
}
return props;
};
}(window.stepViz, window.d3));
(function(ns, d3) {
'use strict';
ns.constants.ARRAY_CSS_CLASS = 'array';
ns.constants.ARRAY_HORZ_DIR = 'horizontal';
ns.constants.ARRAY_VERT_DIR = 'vertical';
ns.constants.ARRAY_ANIM_SWAP_PATH_AFTER = 'after';
ns.constants.ARRAY_ANIM_SWAP_PATH_BEFORE = 'before';
ns.constants.ARRAY_ANIM_SWAP_PATH_NONE = 'none';
ns.constants.ARRAY_PROP_LIST = ['dir', 'fontSize', 'renderer'];
function drawArray(component) {
var direction = component.state('dir');
var compBox = component.layout().getBox();
var array = component.value();
var props = {};
ns.constants.TEXTBOX_PROP_LIST.forEach(function(propKey) {
if (component.state(propKey)) {
props[propKey] = component.state(propKey);
}
});
var itemSize = 0;
if (direction == ns.constants.ARRAY_VERT_DIR) {
itemSize = compBox.height / array.length;
} else {
itemSize = compBox.width / array.length;
}
var x = 0;
var y = 0;
for (var i = 0; i < array.length; i++) {
// create array item component
var itemBox = {
top: y,
left: x,
width: 0,
height: 0
};
if (direction == ns.constants.ARRAY_VERT_DIR) {
itemBox.width = compBox.width;
itemBox.height = itemSize;
y += itemSize;
} else {
itemBox.width = itemSize;
itemBox.height = compBox.height;
x += itemSize;
}
if (component.child(i)) {
component.child(i).updateLayout(itemBox);
component.child(i).redraw();
} else {
var childProps = ns.util.objClone(props);
if (component.state('highlight')[i]) {
childProps.highlight = true;
childProps.highlightProps = component.state('highlight')[i];
}
var itemLayout = component.createLayout(itemBox);
component.drawTextBox(array[i], itemLayout, childProps);
}
}
}
ns.components.Array = function(parent, array, layout, props) {
if (!Array.isArray(array)) {
throw 'Invalid array';
}
if (array.length === 0) {
throw 'Empty array';
}
ns.components.Component.call(this, parent, array, layout, props, {
dir: ns.constants.ARRAY_HORZ_DIR
});
var compBox = layout.getBox();
var svgElem = parent.svg().append('g')
.attr('class', ns.constants.ARRAY_CSS_CLASS)
.attr('transform', 'translate(' + compBox.left + ',' + compBox.top + ')');
// save SVG element
this.setSVG(svgElem);
// to save highlight state
if (!this.state('highlight')) {
this.state('highlight', {});
}
// draw
drawArray(this);
};
// inherit from base class
ns.util.inherits(ns.components.Component, ns.components.Array);
ns.components.Array.prototype.drawTextBox = function(value, layout, props) {
var textBoxComp = new ns.components.TextBox(this, value, layout, props);
this.addChild(textBoxComp);
return textBoxComp;
};
ns.components.Array.prototype.redraw = function() {
// recalculate layout
var layout = this.layout();
layout.reCalculate();
var compBox = layout.getBox();
this.svg()
.attr('transform', 'translate(' + compBox.left + ',' + compBox.top + ')');
// draw
drawArray(this);
};
ns.components.Array.prototype.highlight = function(arrayIndices, props) {
if (typeof arrayIndices == 'number') {
arrayIndices = [arrayIndices];
}
if (!Array.isArray(arrayIndices)) {
throw 'Invalid argument to highlight.';
}
for (var i = 0; i < arrayIndices.length; i++) {
var index = arrayIndices[i];
if (this.child(index)) {
this.child(index).highlight(props);
// saving state
this.state('highlight')[index] = props;
}
}
};
ns.components.Array.prototype.unhighlight = function(arrayIndices) {
if (typeof arrayIndices == 'number') {
arrayIndices = [arrayIndices];
}
if (!Array.isArray(arrayIndices)) {
throw 'Invalid argument to unhighlight.';
}
for (var i = 0; i < arrayIndices.length; i++) {
var index = arrayIndices[i];
if (this.child(index)) {
this.child(index).unhighlight();
if (this.state('highlight')[index]) {
delete this.state('highlight')[index];
}
}
}
};
ns.components.Array.prototype.translate = function(x, y, animate) {
var that = this;
return new Promise(function(resolve, reject) {
// animate by default
if (animate !== false) animate = true;
// update layout
that.layout().translate(x, y);
var elem = that.svg();
var transform = d3.transform(elem.attr('transform'));
// add to existing translate
transform.translate = [transform.translate[0] + x, transform.translate[1] + y];
if (animate) {
elem.transition().attr('transform', transform.toString()).each('end', resolve);
} else {
elem.attr('transform', transform.toString());
resolve();
}
});
};
ns.components.Array.prototype.changeValue = function(index, newValue) {
if (this.child(index)){
this.child(index).changeValue(newValue);
this.value()[index] = newValue;
}else{
throw 'Invalid index';
}
};
ns.components.Array.prototype.clone = function() {
return this.parent().drawArray(ns.util.objClone(this.value()),
this.layout().clone(), this.cloneProps());
};
// TODO
ns.components.Array.prototype.swap = function(i, j, animate, animProps) {
// animate by default
if (animate !== false) animate = true;
animProps = ns.util.defaults(animProps, {
iDir: ns.constants.ARRAY_ANIM_SWAP_PATH_NONE,
jDir: ns.constants.ARRAY_ANIM_SWAP_PATH_AFTER
});
if (this.child(i) && this.child(j) && i != j) {
var tempItem = this.child(i);
this._state.children[i] = this._state.children[j];
this._state.children[j] = tempItem;
// swap animation
}
};
}(window.stepViz, window.d3));
(function(ns, d3) {
'use strict';
ns.constants.MAIN_CSS_CLASS = 'stepViz';
ns.constants.CANVAS_PROP_LIST = ['margin'];
ns.components.Canvas = function(container, props) {
if (typeof container === 'string') {
container = document.getElementById(container);
} else if (!(container instanceof HTMLElement)) {
throw 'Invalid container';
}
props = props || {};
props.margin = props.margin || {
top: 10,
left: 10,
bottom: 10,
right: 10
};
var layout = new ns.Layout(container, {}, props.margin);
ns.components.Component.call(this, null, null, layout, props, {});
var compBounds = layout.getBounds();
var compBox = layout.getBox();
var svgElem = d3.select(container)
.append('svg')
.attr('width', compBounds.width)
.attr('height', compBounds.height)
.append('g')
.attr('transform', 'translate(' + compBox.left + ',' + compBox.top + ')')
.attr('class', ns.constants.MAIN_CSS_CLASS + ' ' + ns.config.themeCSSClass);
// save SVG element
this.setSVG(svgElem);
};
// inherit from base class
ns.util.inherits(ns.components.Component, ns.components.Canvas);
ns.components.Canvas.prototype.redraw = function() {
// recalculate layout
this.layout().reCalculate();
// update
var compBounds = this.layout().getBounds();
var svgRoot = d3.select(this.svg().node().parentNode);
svgRoot.attr('width', compBounds.width)
.attr('height', compBounds.height);
this.redrawAllChildren();
};
ns.components.Canvas.prototype.drawTextBox = function(value, layout, props) {
var textBoxComp = new ns.components.TextBox(this, value, layout, props);
this.addChild(textBoxComp);
return textBoxComp;
};
ns.components.Canvas.prototype.drawArray = function(array, layout, props) {
var arrayComp = new ns.components.Array(this, array, layout, props);
this.addChild(arrayComp);
return arrayComp;
};
ns.components.Canvas.prototype.drawMatrix = function(matrix, layout, props) {
var matrixComp = new ns.components.Matrix(this, matrix, layout, props);
this.addChild(matrixComp);
return matrixComp;
};
}(window.stepViz, window.d3));
(function(ns, d3) {
'use strict';
ns.constants.MATRIX_CSS_CLASS = 'matrix';
ns.constants.ARRAY_PROP_LIST = ['fontSize', 'renderer'];
ns.components.Matrix = function(parent, matrix, layout, props) {
if (!Array.isArray(matrix)) {
throw 'Invalid matrix';
}
if (matrix.length === 0) {
throw 'Empty matrix';
}
ns.components.Component.call(this, parent, matrix, layout, props, {});
var compBox = layout.getBox();
var svgElem = parent.svg().append('g')
.attr('class', ns.constants.MATRIX_CSS_CLASS)
.attr('transform', 'translate(' + compBox.left + ',' + compBox.top + ')');
// save SVG element
this.setSVG(svgElem);
// to save highlight state
if (!this.state('highlight')) {
this.state('highlight', {});
}
// draw
drawMatrix(this);
};
// inherit from base class
ns.util.inherits(ns.components.Component, ns.components.Matrix);
function drawMatrix(component) {
var compBox = component.layout().getBox();
var matrix = component.value();
var props = {};
ns.constants.ARRAY_PROP_LIST.forEach(function(propKey) {
if (component.state(propKey)){
props[propKey] = component.state(propKey);
}
});
var rowWidth = compBox.width;
var rowHeight = compBox.height / matrix.length;
var x = 0;
var y = 0;
for (var i = 0; i < matrix.length; i++) {
var row = matrix[i];
var rowBox = {
top: y,
left: x,
width: rowWidth,
height: rowHeight
};
y += rowHeight;
if (component.child(i)) {
component.child(i).updateLayout(itemBox);
component.child(i).redraw();
} else {
var childProps = ns.util.objClone(props);
if (component.state('highlight')[i]) {
childProps.highlight = true;
childProps.highlightProps = component.state('highlight')[i];
}
var rowLayout = component.createLayout(rowBox);
component.drawArray(row, rowLayout, childProps);
}
}
}
ns.components.Matrix.prototype.drawArray = function(array, layout, props) {
var arrayComp = new ns.components.Array(this, array, layout, props);
this.addChild(arrayComp);
return arrayComp;
};
ns.components.Matrix.prototype.changeValue = function(row, column, newValue){
if (this.child(row)){
this.child(row).changeValue(column, newValue);
this.value()[row][column] = newValue;
}else{
throw 'Invalid row';
}
};
}(window.stepViz, window.d3));
(function(ns, d3) {
'use strict';
// constants
ns.constants.TEXTBOX_CSS_CLASS = 'textBox';
ns.constants.TEXTBOX_PROP_LIST = ['fontSize', 'renderer'];
function drawTextBox(component) {
var svgElem = component.svg();
var compBox = component.layout().getBox();
var value = component.value();
var renderer = component.state('renderer');
var fontSize = component.state('fontSize');
// draw item
var rectElem = svgElem.select('rect');
if (rectElem.empty()) {
rectElem = svgElem.append('rect')
.attr('x', 0)
.attr('y', 0);
}
rectElem.attr('width', compBox.width)
.attr('height', compBox.height);
var textElem = svgElem.select('text');
if (textElem.empty()) {
textElem = svgElem.append('text')
.attr('x', 0)
.attr('y', 0);
}
textElem.text(renderer(value)).style('font-size', fontSize);
// align text in center of rect
var rectBBox = rectElem.node().getBBox();
var textBBox = textElem.node().getBBox();
textElem.attr('dx', (rectBBox.width - textBBox.width) / 2)
.attr('dy', ((rectBBox.height - textBBox.height) / 2) + (0.75 * textBBox.height));
// highlight
toggleHighlight(component);
}
function toggleHighlight(component) {
var props = component.state('highlightProps') || {};
var svgElem = component.svg();
var elemClass = svgElem.attr('class');
var prop = null;
// highlight if needed
if (component.state('highlight')) {
if (elemClass.indexOf(ns.config.highlightCSSClass) == -1) {
elemClass += ' ' + ns.config.highlightCSSClass;
}
// custom style for highlighting
for (prop in props) {
if (props.hasOwnProperty(prop)) {
if (prop.startsWith('rect-')) {
svgElem.select('rect').style(prop.substring(5), props[prop]);
} else if (prop.startsWith('text-')) {
svgElem.select('text').style(prop.substring(5), props[prop]);
}
}
}
} else {
elemClass = elemClass.replace(ns.config.highlightCSSClass, '');
// remove custom highlighting
for (prop in props) {
if (props.hasOwnProperty(prop)) {
if (prop.startsWith('rect-')) {
svgElem.select('rect').style(prop.substring(5), null);
} else if (prop.startsWith('text-')) {
svgElem.select('text').style(prop.substring(5), null);
}
}
}
}
svgElem.attr('class', elemClass);
}
ns.components.TextBox = function(parent, value, layout, props) {
ns.components.Component.call(this, parent, value, layout, props, {
fontSize: ns.config.defaultFontSize,
renderer: function(d) {
if (d === null) {
return '';
} else if (typeof d == 'string' || typeof d == 'number'){
return d;
} else {
return JSON.stringify(d);
}
}
});
var compBox = layout.getBox();
var svgElem = parent.svg().append('g')
.attr('class', ns.constants.TEXTBOX_CSS_CLASS)
.attr('transform', 'translate(' + compBox.left + ',' + compBox.top + ')');
// save SVG element
this.setSVG(svgElem);
// draw
drawTextBox(this);
};
// inherit from base class
ns.util.inherits(ns.components.Component, ns.components.TextBox);
ns.components.TextBox.prototype.redraw = function() {
if (!this.svg()) {
throw 'TextBox redraw error - Invalid state or SVG';
}
// recalculate layout
var layout = this.layout();
layout.reCalculate();
var compBox = layout.getBox();
this.svg()
.attr('transform', 'translate(' + compBox.left + ',' + compBox.top + ')');
// draw
drawTextBox(this);
};
ns.components.TextBox.prototype.clone = function(){
};
ns.components.TextBox.prototype.changeValue = function(newValue) {
this.value(newValue);
drawTextBox(this);
};
ns.components.TextBox.prototype.highlight = function(props) {
this.state('highlight', true);
this.state('highlightProps', props);
toggleHighlight(this);
};
ns.components.TextBox.prototype.unhighlight = function() {
this.state('highlight', false);
toggleHighlight(this);
this.state('highlightProps', null);
};
ns.components.TextBox.prototype.translate = function(x, y, animate) {
var that = this;
return new Promise(function(resolve, reject) {
// animate by default
if (animate !== false) animate = true;
// update layout
that.layout().translate(x, y);
var elem = that.svg();
var transform = d3.transform(elem.attr('transform'));
// add to existing translate
transform.translate = [transform.translate[0] + x, transform.translate[1] + y];
if (animate) {
elem.transition().attr('transform', transform.toString()).each('end', resolve);
} else {
elem.attr('transform', transform.toString());
resolve();
}
});
};
ns.components.TextBox.prototype.moveTo = function(x, y, animate) {
var that = this;
return new Promise(function(resolve, reject) {
// animate by default
if (animate !== false) animate = true;
// update layout
that.layout().moveTo(x, y);
var elem = that.svg();
var transform = d3.transform(elem.attr('transform'));
// new translate
transform.translate = [x, y];
if (animate) {
elem.transition().attr('transform', transform.toString()).each('end', resolve);
} else {
elem.attr('transform', transform.toString());
resolve();
}
});
};
ns.components.TextBox.prototype.moveThroughPath = function(path) {
var animTasks = [];
if (typeof path != 'string') {
throw 'Invalid path';
}
var pathCoords = path.split(' ');
for (var i = 0; i < pathCoords.length; i++) {
var coordStr = pathCoords[i];
var coordStrFirstChar = coordStr.charAt(0);
var animate = true;
if (coordStrFirstChar == 'M' || coordStrFirstChar == 'L' ||
(coordStrFirstChar >= '0' && coordStrFirstChar <= '9')) {
animate = coordStrFirstChar == 'M' ? false : true;
if (coordStrFirstChar == 'M' || coordStrFirstChar == 'L') {
coordStr = coordStr.substring(1);
}
var coords = coordStr.split(',').map(parseFloat);
if (coords.length == 2) {
var task = ns.util.createTaskForPromise(
this.moveTo, this, [coords[0], coords[1], animate]);
animTasks.push(task);
}
}
}
return animTasks.reduce(function(prevTask, nextTask) {
return promise.then(nextTask);
}, Promise.resolve());
};
}(window.stepViz, window.d3));
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) ||
Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
if (typeof Object.create != 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if(prototype !== Object(prototype) && prototype !== null) {
throw TypeError('Argument must be an object or null');
}
if (prototype === null) {
throw Error('null [[Prototype]] not supported');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
| suhaibkhan/stepviz | dist/stepviz.js | JavaScript | mit | 30,623 |
'use strict';
module.exports = function (req, res) {
res.statusCode = 401;
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-Xss-Protection', '1; mode=block');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('X-Request-Id', '08aedf09-deab-4c9b-ba18-ea100f209958');
res.setHeader('X-Runtime', '0.049840');
res.setHeader('Vary', 'Origin');
res.setHeader('Date', 'Tue, 22 Mar 2016 19:36:08 GMT');
res.setHeader('Connection', 'close');
res.write(new Buffer(JSON.stringify({"message": "Unauthorized"})));
res.end();
return __filename;
};
| regalii/regaliator_node | test/tapes/account/failed_info.js | JavaScript | mit | 708 |
<?php
require_once('core/action/Action.php');
require_once('core/action/ActionResponse_Default.php');
require_once('model/entities/User.php');
require_once('model/containers/AccessLevelContainer.php');
class Action_user_displayAddForm implements Action
{
public function run(HttpRequest $httpRequest)
{
$actionResponse = new ActionResponse_Default();
$alias = $httpRequest->alias or "";
$login = $httpRequest->login or "";
$password = $httpRequest->password or "";
$accessLevel = $httpRequest->accessLevel or "";
$user = new User();
$user->setAlias($alias);
$user->setLogin($login);
$user->setPassword($password);
$user->setAccessLevel($accessLevel);
$actionResponse->setElement('user', $user);
$accessLevelContainer = AccessLevelContainer::getInstance();
$accessLevels = $accessLevelContainer->getAllButAdmin();
$actionResponse->setElement('accessLevels', $accessLevels);
return $actionResponse;
}
}
?>
| fabienInizan/WebKernel | modules/user/Action_user_displayAddForm.php | PHP | mit | 957 |
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl, defineMessages } from 'react-intl';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardHeader from '@material-ui/core/CardHeader';
import CardActions from '@material-ui/core/CardActions';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import ConfirmEmail from './ConfirmEmail';
import CheckContext from '../../CheckContext';
import { getErrorMessage } from '../../helpers';
import { stringHelper } from '../../customHelpers';
import globalStrings from '../../globalStrings';
import { updateUserNameEmail } from '../../relay/mutations/UpdateUserNameEmailMutation';
import { units } from '../../styles/js/shared';
const messages = defineMessages({
title: {
id: 'userEmail.title',
defaultMessage: 'Add your email',
},
emailHint: {
id: 'userEmail.emailInputHint',
defaultMessage: 'email@example.com',
},
});
class UserEmail extends React.Component {
constructor(props) {
super(props);
this.state = {
message: null,
};
}
handleClickSkip = () => {
window.storage.set('dismiss-user-email-nudge', '1');
this.forceUpdate();
};
handleSubmit = () => {
const email = document.getElementById('user-email__input').value;
const onSuccess = () => {
this.setState({ message: null });
document.getElementById('user-email__input').value = '';
};
const onFailure = (transaction) => {
const fallbackMessage = this.props.intl.formatMessage(globalStrings.unknownError, { supportEmail: stringHelper('SUPPORT_EMAIL') });
const message = getErrorMessage(transaction, fallbackMessage);
this.setState({ message });
};
if (email) {
updateUserNameEmail(
this.props.user.id,
this.props.user.name,
email,
true,
onSuccess, onFailure,
);
}
};
render() {
const { currentUser } = new CheckContext(this).getContextStore();
if ((currentUser && currentUser.dbid) !== this.props.user.dbid) {
return null;
}
if (this.props.user.unconfirmed_email) {
return <ConfirmEmail user={this.props.user} />;
} else if (!this.props.user.email && window.storage.getValue('dismiss-user-email-nudge') !== '1') {
return (
<Card style={{ marginBottom: units(2) }}>
<CardHeader title={this.props.intl.formatMessage(messages.title)} />
<CardContent>
<FormattedMessage
id="userEmail.text"
defaultMessage={
'To send you notifications, we need your email address. If you\'d like to receive notifications, please enter your email address. Otherwise, click "Skip"'
}
/>
<div>
<TextField
id="user-email__input"
label={
<FormattedMessage
id="userEmail.emailInputLabel"
defaultMessage="Email"
/>
}
placeholder={
this.props.intl.formatMessage(messages.emailHint)
}
helperText={this.state.message}
error={this.state.message}
margin="normal"
fullWidth
/>
</div>
</CardContent>
<CardActions>
<Button onClick={this.handleClickSkip}>
<FormattedMessage id="userEmail.skip" defaultMessage="Skip" />
</Button>
<Button onClick={this.handleSubmit} color="primary">
<FormattedMessage id="userEmail.submit" defaultMessage="Submit" />
</Button>
</CardActions>
</Card>
);
}
return null;
}
}
UserEmail.contextTypes = {
store: PropTypes.object,
};
export default injectIntl(UserEmail);
| meedan/check-web | src/app/components/user/UserEmail.js | JavaScript | mit | 3,974 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ro_RO" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About GeyserCoin</source>
<translation>Despre GeyserCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>GeyserCoin</b> version</source>
<translation>Versiune <b>GeyserCoin</b></translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers</source>
<translation>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Agendă</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Dublu-click pentru a edita adresa sau eticheta</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Creează o adresă nouă</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiază adresa selectată în clipboard</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>Adresă nouă</translation>
</message>
<message>
<location line="-43"/>
<source>These are your GeyserCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Acestea sunt adresele GeyserCoin pentru a primi plăți. Poate doriți sa dați o adresa noua fiecarui expeditor pentru a putea ține evidența la cine efectuează plăti.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>&Copiază adresa</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>Arată cod &QR</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a GeyserCoin address</source>
<translation>Semnează un mesaj pentru a dovedi că dețineti o adresă GeyserCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Semnează &Mesajul</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Sterge adresele curent selectate din lista</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified GeyserCoin address</source>
<translation>Verifică un mesaj pentru a vă asigura că a fost semnat cu o anumită adresă GeyserCoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifică mesajul</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>Ște&rge</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Copiază &eticheta</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Editează</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Exportă datele din Agendă</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Valori separate prin virgulă (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Eroare la exportare</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nu s-a putut scrie în fișier %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(fără etichetă)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialogul pentru fraza de acces</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introdu fraza de acces</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Frază de acces nouă</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repetă noua frază de acces</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Servește pentru a dezactiva sendmoneyl atunci când sistemul de operare este compromis. Nu oferă nicio garanție reală.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Doar pentru staking</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Criptează portofelul</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Această acțiune necesită fraza ta de acces pentru deblocarea portofelului.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Deblochează portofelul</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Această acțiune necesită fraza ta de acces pentru decriptarea portofelului.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decriptează portofelul.</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Schimbă fraza de acces</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introdu vechea și noua parolă pentru portofel.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Confirmă criptarea portofelului</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Atentie: Daca encriptezi portofelul si iti uiti parola, <b>VEI PIERDE TOATA MONEDELE</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Sunteţi sigur că doriţi să criptaţi portofelul electronic?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT: Orice copie de siguranta facuta in prealabil portofelului dumneavoastra ar trebui inlocuita cu cea generata cel mai recent fisier criptat al portofelului. Pentru siguranta, copiile de siguranta vechi ale portofelului ne-criptat vor deveni inutile de indata ce veti incepe folosirea noului fisier criptat al portofelului.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Atentie! Caps Lock este pornit</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Portofel criptat</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>GeyserCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>GeyserCoin se va inchide pentru a termina procesul de encriptie. Amintiți-vă, criptarea portofelul dumneavoastră nu poate proteja pe deplin monedele dvs. de a fi furate de infectarea cu malware a computerului.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Criptarea portofelului a eșuat</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Criptarea portofelului a eșuat din cauza unei erori interne. Portofelul tău nu a fost criptat.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Frazele de acces introduse nu se potrivesc.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Deblocarea portofelului a eșuat</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Fraza de acces introdusă pentru decriptarea portofelului a fost incorectă.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Decriptarea portofelului a eșuat</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Parola portofelului electronic a fost schimbată.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>Semnează &mesaj...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Arată o stare generală de ansamblu a portofelului</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Tranzacții</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Răsfoiește istoricul tranzacțiilor</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>Agendă</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Editează lista de adrese si etichete stocate</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Arată lista de adrese pentru primire plăți</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Ieșire</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Închide aplicația</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about GeyserCoin</source>
<translation>Arată informații despre GeyserCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Despre &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Arată informații despre Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Setări...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>Criptează portofelul electronic...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>&Fă o copie de siguranță a portofelului...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>S&chimbă parola...</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Exportă</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a GeyserCoin address</source>
<translation>Trimite monede către o adresă GeyserCoin</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for GeyserCoin</source>
<translation>Modifică opțiuni de configurare pentru GeyserCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportă datele din tab-ul curent într-un fișier</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Criptează sau decriptează portofelul</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Creează o copie de rezervă a portofelului într-o locație diferită</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Schimbă fraza de acces folosită pentru criptarea portofelului</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>Fereastră &debug</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Deschide consola de debug și diagnosticare</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verifică mesajul...</translation>
</message>
<message>
<location line="-214"/>
<location line="+551"/>
<source>GeyserCoin</source>
<translation>GeyserCoin</translation>
</message>
<message>
<location line="-551"/>
<source>Wallet</source>
<translation>Portofelul</translation>
</message>
<message>
<location line="+193"/>
<source>&About GeyserCoin</source>
<translation>Despre GeyserCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Arata/Ascunde</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Deblochează portofelul</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>Blochează portofelul</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Blochează portofelul</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fișier</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Setări</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>A&jutor</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Bara de file</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>GeyserCoin client</source>
<translation>Clientul GeyserCoin</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to GeyserCoin network</source>
<translation><numerusform>%n conexiune activă la reteaua GeyserCoin</numerusform><numerusform>%n conexiuni active la reteaua GeyserCoin</numerusform><numerusform>%n conexiuni active la reteaua GeyserCoin</numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Staking. <br>Greutatea este %1<br>Greutatea retelei este %2<br>Timp estimat pentru a castiga recompensa este %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Nu este in modul stake deoarece portofelul este blocat</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Nu este in modul stake deoarece portofelul este offline</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Nu este in modul stake deoarece portofelul se sincronizeaza</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Nu este in modul stake deoarece nu sunt destule monede maturate</translation>
</message>
<message>
<location line="-808"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>&Deblochează portofelul</translation>
</message>
<message>
<location line="+273"/>
<source>Up to date</source>
<translation>Actualizat</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Se actualizează...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirmă comisinoul tranzacției</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Tranzacție expediată</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Tranzacție recepționată</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Suma: %2
Tipul: %3
Adresa: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>Manipulare URI</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid GeyserCoin address or malformed URI parameters.</source>
<translation>URI nu poate fi parsatt! Cauza poate fi o adresa GeyserCoin invalidă sau parametrii URI malformați.</translation>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portofelul este <b>criptat</b> iar în momentul de față este <b>deblocat</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portofelul este <b>criptat</b> iar în momentul de față este <b>blocat</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>Fă o copie de siguranță a portofelului</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Date portofel(*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Copia de rezerva a esuat</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Eroare la încercarea de a salva datele portofelului în noua locaţie.</translation>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n secundă</numerusform><numerusform>%n secunde</numerusform><numerusform>%n secunde</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minut</numerusform><numerusform>%n minute</numerusform><numerusform>%n minute</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n oră</numerusform><numerusform>%n ore</numerusform><numerusform>%n ore</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n zi</numerusform><numerusform>%n zile</numerusform><numerusform>%n zile</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation>Not staking</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. GeyserCoin can no longer continue safely and will quit.</source>
<translation>A apărut o eroare fatală. GeyserCoin nu mai poate continua în condiții de siguranță și va iesi.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Alertă rețea</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Controlează moneda</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Cantitate:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Octeţi:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Sumă:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioritate:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Ieşire minimă: </translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+552"/>
<source>no</source>
<translation>nu</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>După taxe:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Schimb:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(de)selectaţi tot</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Modul arborescent</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Modul lista</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Sumă</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmări</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmat</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioritate</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Copiază adresa</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiază eticheta</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copiază suma</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copiază ID tranzacție</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copiaţi quantitea</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Copiaţi taxele</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiaţi după taxe</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiaţi octeţi</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiaţi prioritatea</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiaţi ieşire minimă:</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiaţi schimb</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>cel mai mare</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>mare</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>marime medie</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>mediu</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>mediu-scazut</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>scazut</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>cel mai scazut</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation>DUST</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>da</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Aceasta eticheta se inroseste daca marimea tranzactiei este mai mare de 10000 bytes.
Acest lucru inseamna ca este nevoie de o taxa de cel putin %1 pe kb
Poate varia +/- 1 Byte pe imput.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Tranzacțiile cu prioritate mai mare ajunge mult mai probabil într-un bloc
Aceasta eticheta se inroseste daca prioritatea este mai mica decat "medium"
Acest lucru inseamna ca este necesar un comision cel putin de %1 pe kB</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Aceasta eticheta se inroseste daca oricare din contacte primeste o suma mai mica decat %1.
Acest lucru inseamna ca un comision de cel putin %2 este necesar.
Sume mai mici decat 0.546 ori minimul comisionului de relay sunt afisate ca DUST</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Această eticheta se înroseste dacă schimbul este mai mic de %1.
Acest lucru înseamnă că o taxă de cel puțin %2 este necesară</translation>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(fără etichetă)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>schimbă la %1(%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(schimb)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editează adresa</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etichetă</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Eticheta asociată cu această intrare în agendă</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresă</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adresa asociată cu această intrare în agendă. Acest lucru poate fi modificat numai pentru adresele de trimitere.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Noua adresă de primire</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Noua adresă de trimitere</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editează adresa de primire</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editează adresa de trimitere</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Adresa introdusă "%1" se află deja în lista de adrese.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid GeyserCoin address.</source>
<translation>Adresa introdusă "%1" nu este o adresă GeyserCoin validă</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Portofelul nu a putut fi deblocat.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Generarea noii chei a eșuat.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>GeyserCoin-Qt</source>
<translation>GeyserCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versiune</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Utilizare:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Optiuni linie de comanda</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Setări UI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Setează limba, de exemplu: "de_DE" (inițial: setare locală)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Pornește miniaturizat</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Afișează ecran splash la pornire (implicit: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Setări</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Comision de tranzacție opțional pe kB, care vă ajută ca tranzacțiile sa fie procesate rapid. Majoritatea tranzactiilor sunt de 1 kB. Comision de 0.01 recomandat</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Plăteşte comision pentru tranzacţie &f</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Suma rezervată nu participă la maturare și, prin urmare, se poate cheltui în orice moment.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Rezervă</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start GeyserCoin after logging in to the system.</source>
<translation>Pornește GeyserCoin imdiat după logarea în sistem</translation>
</message>
<message>
<location line="+3"/>
<source>&Start GeyserCoin on system login</source>
<translation>$Pornește GeyserCoin la logarea în sistem</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Retea</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the GeyserCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Deschide automat portul pentru cientul GeyserCoin pe router. Aces lucru este posibil doara daca routerul suporta UPnP si este activat</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapeaza portul folosind &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the GeyserCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Conecteaza la reteaua GeyserCoin prinr-un proxy SOCKS(ex. cand te conectezi prin Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>Conectează-te printr-un proxy socks</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Adresa IP a proxy-ului(ex. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Portul pe care se concetează proxy serverul (de exemplu: 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Versiune:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versiunea SOCKS a proxiului (ex. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Fereastra</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Afişează doar un icon in tray la ascunderea ferestrei</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&M Ascunde în tray în loc de taskbar</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Ascunde fereastra în locul părăsirii programului în momentul închiderii ferestrei. Când acestă opţiune e activă, aplicaţia se va opri doar în momentul selectării comenzii Quit din menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>&i Ascunde fereastra în locul închiderii programului</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Afişare</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Interfata & limba userului</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting GeyserCoin.</source>
<translation>Limba interfeței utilizator poate fi setat aici. Această setare va avea efect după repornirea GeyserCoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unitatea de măsură pentru afişarea sumelor:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Alege subdiviziunea folosită la afişarea interfeţei şi la trimiterea de bitcoin.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Dacă să se afişeze controlul caracteristicilor monedei sau nu.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Afiseaza &caracteristiclei de control ale monedei(numai experti!)</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>& OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>& Renunta</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Aplica</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>Initial</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation>Avertizare</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting GeyserCoin.</source>
<translation>Aceasta setare va avea efect dupa repornirea GeyserCoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Adresa bitcoin pe care a-ti specificat-o este invalida</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the GeyserCoin network after a connection is established, but this process has not completed yet.</source>
<translation>Informatia afisata poate fi depasita. Portofel se sincronizează automat cu rețeaua GeyserCoin după ce se stabilește o conexiune, dar acest proces nu s-a finalizat încă.</translation>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation>Stake:</translation>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>Neconfirmat:</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Portofel</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Cheltuibil:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Balanța ta curentă de cheltuieli</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>Nematurizat:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Balanta minata care nu s-a maturizat inca</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Balanța totală curentă</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Tranzacții recente</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total al tranzacțiilor care nu au fost confirmate încă și nu contează față de balanța curentă</translation>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Totalul de monede care au fost in stake si nu sunt numarate in balanta curenta</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>Nu este sincronizat</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start geysercoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Dialog cod QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Cerere de plată</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Cantitate:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etichetă</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Salvează ca...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Eroare la codarea URl-ului în cod QR.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Suma introdusă nu este validă, vă rugăm să verificați.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI rezultat este prea lung, încearcă să reduci textul pentru etichetă / mesaj.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Salvează codul QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imagini PNG(*png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nume client</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>Versiune client</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informație</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Foloseste versiunea OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Durata pornirii</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Rețea</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Numărul de conexiuni</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Pe testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Lanț de blocuri</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Numărul curent de blocuri</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Data ultimului bloc</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Deschide</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Optiuni linii de comandă</translation>
</message>
<message>
<location line="+7"/>
<source>Show the GeyserCoin-Qt help message to get a list with possible GeyserCoin command-line options.</source>
<translation>Afișa mesajul de ajutor GeyserCoin-Qt pentru a obține o listă cu posibile opțiuni de linie de comandă GeyserCoin.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Arată</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consolă</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Construit la data</translation>
</message>
<message>
<location line="-104"/>
<source>GeyserCoin - Debug window</source>
<translation>GeyserCoin - fereastră depanare</translation>
</message>
<message>
<location line="+25"/>
<source>GeyserCoin Core</source>
<translation>GeyserCoin Core</translation>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Loguri debug</translation>
</message>
<message>
<location line="+7"/>
<source>Open the GeyserCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Deschideti fisierul de depanare GeyserCoin din folderul curent. Acest lucru poate dura cateva secunde pentru fisiere de log mari.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Curăță consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the GeyserCoin RPC console.</source>
<translation>Bine ati venit la consola GeyserCoin RPC.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Foloseste sagetile sus si jos pentru a naviga in istoric si <b>Ctrl-L</b> pentru a curata.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Scrie <b>help</b> pentru a vedea comenzile disponibile</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+181"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Trimite monede</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Caracteristici control ale monedei</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Intrări</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>Selectie automatică</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Fonduri insuficiente!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Cantitate:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Octeţi:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Sumă:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 GSR</source>
<translation>123.456 GSR {0.00 ?}</translation>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Prioritate:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>mediu</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Ieşire minimă: </translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>nu</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>După taxe:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Schimbă:</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>personalizează schimbarea adresei</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Trimite simultan către mai mulți destinatari</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Adaugă destinatar</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation>Scoateți toate câmpuirile de tranzacții</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Șterge &tot</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Balanță:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 GSR</source>
<translation>123.456 GSR</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirmă operațiunea de trimitere</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&S Trimite</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a GeyserCoin address (e.g. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</source>
<translation>Introduceți o adresă GeyserCoin(ex:JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Copiaţi quantitea</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiază suma</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Copiaţi taxele</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copiaţi după taxe</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiaţi octeţi</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copiaţi prioritatea</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiaţi ieşire minimă:</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiaţi schimb</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmă trimiterea de monede</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Sunteți sigur că doriți să trimiteți %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>și</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adresa destinatarului nu este validă, vă rugăm să o verificaţi.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Suma de plată trebuie să fie mai mare decât 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Suma depășește soldul contului.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalul depășește soldul contului dacă se include și plata comisionului de %1.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>S-a descoperit o adresă care figurează de două ori. Expedierea se poate realiza către fiecare adresă doar o singură dată pe operațiune.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Eroare: tranzacția a fost respinsă. Acest lucru s-ar putea întâmpla în cazul în care unele dintre monedele din portofel au fost deja cheltuite, cum si cum ați utilizat o copie a wallet.dat și monedele au fost cheltuite în copie dar nu au fost marcate ca și cheltuite aici.</translation>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid GeyserCoin address</source>
<translation>Atenție: Adresă GeyserCoin invalidă</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(fără etichetă)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>ATENTIE: adresa schimb necunoscuta</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Su&mă:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Plătește că&tre:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Introdu o etichetă pentru această adresă pentru a fi adăugată în lista ta de adrese</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etichetă:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Alegeti adresa din agenda</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Lipește adresa din clipboard</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Scoateti acest destinatar</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a GeyserCoin address (e.g. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</source>
<translation>Introduceți o adresă GeyserCoin(ex:JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Semnatura- Semneaza/verifica un mesaj</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>Semneaza Mesajul</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Puteti semna mesaje cu adresa dumneavoastra pentru a demostra ca sunteti proprietarul lor. Aveti grija sa nu semnati nimic vag, deoarece atacurile de tip phishing va pot pacali sa le transferati identitatea. Semnati numai declaratiile detaliate cu care sunteti deacord.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</source>
<translation>Adresa cu care semnati mesajul(ex. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Alegeti o adresa din agenda</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Lipiţi adresa copiată in clipboard.</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Introduce mesajul pe care vrei sa il semnezi, aici.</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiaza semnatura curenta in clipboard-ul sistemului</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this GeyserCoin address</source>
<translation>Semnează un mesaj pentru a dovedi că dețineti o adresă GeyserCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Reseteaza toate spatiile mesajelor semnate.</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Şterge &tot</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>Verifica mesajul</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Introduceti adresa de semnatura, mesajul (asigurati-va ca ati copiat spatiile, taburile etc. exact) si semnatura dedesubt pentru a verifica mesajul. Aveti grija sa nu cititi mai mult in semnatura decat mesajul in sine, pentru a evita sa fiti pacaliti de un atac de tip man-in-the-middle.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</source>
<translation>Adresa cu care a fost semnat mesajul(ex. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified GeyserCoin address</source>
<translation>Verifică un mesaj pentru a vă asigura că a fost semnat cu o anumită adresă GeyserCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Reseteaza toate spatiile mesajelor semnate.</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a GeyserCoin address (e.g. JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</source>
<translation>Introduceți o adresă GeyserCoin(ex:JgZaH1DdikpMTYc2x1Xb6eFBkKGibjmPb9)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click "Semneaza msajul" pentru a genera semnatura</translation>
</message>
<message>
<location line="+3"/>
<source>Enter GeyserCoin signature</source>
<translation>Introduceti semnatura GeyserCoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Adresa introdusa nu este valida</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Te rugam verifica adresa si introduce-o din nou</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Adresa introdusa nu se refera la o cheie.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Blocarea portofelului a fost intrerupta</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Cheia privata pentru adresa introdusa nu este valida.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Semnarea mesajului a esuat</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mesaj Semnat!</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Aceasta semnatura nu a putut fi decodata</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Verifica semnatura si incearca din nou</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Semnatura nu seamana!</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Verificarea mesajului a esuat</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mesaj verificat</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>Deschis până la %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation>conflictual</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/deconectat</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/neconfirmat</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmări</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Stare</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, distribuit prin %n nod</numerusform><numerusform>, distribuit prin %n noduri</numerusform><numerusform>, distribuit prin %n de noduri</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Sursa</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generat</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De la</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Către</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>Adresa posedata</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etichetă</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>se maturizează în încă %n bloc</numerusform><numerusform>se maturizează în încă %n blocuri</numerusform><numerusform>se maturizează în încă %n de blocuri</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>nu este acceptat</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisionul tranzacţiei</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Suma netă</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentarii</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID-ul tranzactiei</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Monedele generate trebuie să se maturizeze 510 blocuri înainte de a fi cheltuite. Când ați generat acest bloc, a fost trimis la rețea pentru a fi adăugat la lanțul de blocuri. În cazul în care nu reușește să intre în lanț, starea sa se va schimba in "nu a fost acceptat", și nu va putea fi cheltuit. Acest lucru se poate întâmpla din când în când, dacă un alt nod generează un bloc cu câteva secunde inaintea blocului tau.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informatii pentru debug</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Tranzacţie</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Intrari</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Sumă</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>Adevarat!</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>Fals!</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, nu s-a propagat încă</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+71"/>
<source>unknown</source>
<translation>necunoscut</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detaliile tranzacției</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Acest panou afișează o descriere detaliată a tranzacției</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipul</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresa</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantitate</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Deschis până la %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmat (%1 confirmări)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Deschis pentru încă %1 bloc</numerusform><numerusform>Deschis pentru încă %1 blocuri</numerusform><numerusform>Deschis pentru încă %1 de blocuri</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Deconectat</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Neconfirmat</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Confirmare (%1 dintre %2 confirmări recomandate)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Conflictual</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Nematurate(%1 confirmari, vor fi valabile dupa %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Acest bloc nu a fost recepționat de niciun alt nod și probabil nu va fi acceptat!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generat dar neacceptat</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Recepționat cu</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Primit de la</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Trimis către</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Plată către tine</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Produs</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Starea tranzacției. Treci cu mausul peste acest câmp pentru afișarea numărului de confirmări.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Data și ora la care a fost recepționată tranzacția.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipul tranzacției.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Adresa de destinație a tranzacției.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Suma extrasă sau adăugată la sold.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Toate</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>Astăzi</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Săptămâna aceasta</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Luna aceasta</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Luna trecută</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Anul acesta</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Între...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Recepționat cu</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Trimis către</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Către tine</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Produs</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Altele</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introdu adresa sau eticheta pentru căutare</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantitatea minimă</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiază adresa</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiază eticheta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiază suma</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiază ID tranzacție</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editează eticheta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Arată detaliile tranzacției</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation>Exporta datele trazactiei</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Fișier text cu valori separate prin virgulă (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmat</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipul</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Sumă</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eroare la exportare</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nu s-a putut scrie în fișier %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Interval:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>către</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+208"/>
<source>Sending...</source>
<translation>Se trimite...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+173"/>
<source>GeyserCoin version</source>
<translation>Versiune GeyserCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Uz:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or geysercoind</source>
<translation>Trimite comanda catre server sau geysercoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Listă de comenzi</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Ajutor pentru o comandă</translation>
</message>
<message>
<location line="-147"/>
<source>Options:</source>
<translation>Setări:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: geysercoin.conf)</source>
<translation>Specifica fisier de configurare(implicit: geysercoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: geysercoind.pid)</source>
<translation>Speficica fisier pid(implicit: geysercoin.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Specifică fișierul wallet (în dosarul de date)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Specifică dosarul de date</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=geysercoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "GeyserCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Setează mărimea cache a bazei de date în megabiți (implicit: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Setează mărimea cache a bazei de date în megabiți (implicit: 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 16814 or testnet: 26814)</source>
<translation>Ascultă pentru conectări pe <port> (implicit: 16814 sau testnet: 26814) </translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Menține cel mult <n> conexiuni cu partenerii (implicit: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Conectează-te la nod pentru a obține adresele partenerilor, și apoi deconectează-te</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Specifică adresa ta publică</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Leaga la o adresa data. Utilizeaza notatie [host]:port pt IPv6</translation>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Prag pentru deconectarea partenerilor care nu funcționează corect (implicit: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Numărul de secunde pentru a preveni reconectarea partenerilor care nu funcționează corect (implicit: 86400)</translation>
</message>
<message>
<location line="-37"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>A intervenit o eroare in timp ce se seta portul RPC %u pentru ascultare pe IPv4: %s</translation>
</message>
<message>
<location line="+65"/>
<source>Listen for JSON-RPC connections on <port> (default: 16815 or testnet: 26815)</source>
<translation>Ascultă pentru conexiuni JSON-RPC pe <port> (implicit:16815 sau testnet: 26815)</translation>
</message>
<message>
<location line="-17"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Se acceptă comenzi din linia de comandă și comenzi JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Rulează în fundal ca un demon și acceptă comenzi</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utilizează rețeaua de test</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Acceptă conexiuni din afară (implicit: 1 dacă nu se folosește -proxy sau -connect)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>A intervenit o eroare in timp ce se seta portul RPC %u pentru ascultare pe IPv6, reintoarcere la IPv4: %s</translation>
</message>
<message>
<location line="+96"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Setati valoarea maxima a prioritate mare/taxa scazuta in bytes(implicit: 27000)</translation>
</message>
<message>
<location line="+12"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Atentie: setarea -paytxfee este foarte ridicata! Aceasta este taxa tranzactiei pe care o vei plati daca trimiti o tranzactie.</translation>
</message>
<message>
<location line="-103"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong GeyserCoin will not work properly.</source>
<translation>Atentie: Va rugam verificati ca timpul si data calculatorului sunt corete. Daca timpul este gresit GeyserCoin nu va functiona corect.</translation>
</message>
<message>
<location line="+132"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Atentie: eroare la citirea fisierului wallet.dat! Toate cheile sunt citite corect, dar datele tranzactiei sau anumite intrari din agenda sunt incorecte sau lipsesc.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Atentie: fisierul wallet.dat este corupt, date salvate! Fisierul original wallet.dat a fost salvat ca wallet.{timestamp}.bak in %s; daca balansul sau tranzactiile sunt incorecte ar trebui sa restaurati dintr-o copie de siguranta. </translation>
</message>
<message>
<location line="-31"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Încearcă recuperarea cheilor private dintr-un wallet.dat corupt</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Optiuni creare block</translation>
</message>
<message>
<location line="-69"/>
<source>Connect only to the specified node(s)</source>
<translation>Conecteaza-te doar la nod(urile) specifice</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descopera propria ta adresa IP (intial: 1)</translation>
</message>
<message>
<location line="+101"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Am esuat ascultarea pe orice port. Folositi -listen=0 daca vreti asta.</translation>
</message>
<message>
<location line="-91"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Sincronizeaza politica checkpoint(implicit: strict)</translation>
</message>
<message>
<location line="+89"/>
<source>Invalid -tor address: '%s'</source>
<translation>Adresa -tor invalida: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Suma invalida pentru -reservebalance=<amount></translation>
</message>
<message>
<location line="-88"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Tampon maxim pentru recepție per conexiune, <n>*1000 baiți (implicit: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Tampon maxim pentru transmitere per conexiune, <n>*1000 baiți (implicit: 1000)</translation>
</message>
<message>
<location line="-17"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Efectuează conexiuni doar către nodurile din rețeaua <net> (IPv4, IPv6 sau Tor)</translation>
</message>
<message>
<location line="+31"/>
<source>Prepend debug output with timestamp</source>
<translation>Ataseaza output depanare cu log de timp</translation>
</message>
<message>
<location line="+41"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Optiuni SSl (vezi Bitcoin wiki pentru intructiunile de instalare)</translation>
</message>
<message>
<location line="-81"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Selectati versiunea de proxy socks(4-5, implicit: 5)</translation>
</message>
<message>
<location line="+42"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trimite informațiile trace/debug la consolă în locul fișierului debug.log</translation>
</message>
<message>
<location line="+5"/>
<source>Send trace/debug info to debugger</source>
<translation>Trimite informațiile trace/debug la consolă</translation>
</message>
<message>
<location line="+30"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Setează mărimea maxima a blocului în bytes (implicit: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Setează mărimea minimă a blocului în baiți (implicit: 0)</translation>
</message>
<message>
<location line="-35"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Micsorati fisierul debug.log la inceperea clientului (implicit: 1 cand nu -debug)</translation>
</message>
<message>
<location line="-43"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specifică intervalul maxim de conectare în milisecunde (implicit: 5000)</translation>
</message>
<message>
<location line="+116"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation>În imposibilitatea de a semna checkpoint-ul, checkpointkey greșit?
</translation>
</message>
<message>
<location line="-86"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Foloseste UPnP pentru a vedea porturile (initial: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Foloseste UPnP pentru a vedea porturile (initial: 1 cand listezi)</translation>
</message>
<message>
<location line="-26"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utilizati proxy pentru a ajunge la serviciile tor (implicit: la fel ca proxy)</translation>
</message>
<message>
<location line="+47"/>
<source>Username for JSON-RPC connections</source>
<translation>Utilizator pentru conexiunile JSON-RPC</translation>
</message>
<message>
<location line="+51"/>
<source>Verifying database integrity...</source>
<translation>Se verifica integritatea bazei de date...</translation>
</message>
<message>
<location line="+44"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation>ATENTIONARE: s-a detectat o violare a checkpoint-ului sincronizat, dar s-a ignorat!</translation>
</message>
<message>
<location line="-1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Atenție: această versiune este depășită, este necesară actualizarea!</translation>
</message>
<message>
<location line="-54"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corupt, recuperare eșuată</translation>
</message>
<message>
<location line="-56"/>
<source>Password for JSON-RPC connections</source>
<translation>Parola pentru conexiunile JSON-RPC</translation>
</message>
<message>
<location line="-32"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Sincronizează timp cu alte noduri. Dezactivează daca timpul de pe sistemul dumneavoastră este precis ex: sincronizare cu NTP (implicit: 1)</translation>
</message>
<message>
<location line="+13"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Când creați tranzacții, ignorați intrări cu valori mai mici decât aceasta (implicit: 0,01)</translation>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permite conexiuni JSON-RPC de la adresa IP specificată</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Trimite comenzi la nodul care rulează la <ip> (implicit: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Execută comanda când cel mai bun bloc se modifică (%s în cmd este înlocuit cu hash-ul blocului)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Executati comanda cand o tranzactie a portofelului se schimba (%s in cmd este inlocuit de TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Necesita confirmari pentru schimbare (implicit: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Execută o comandă când o alerta relevantâ este primitâ(%s in cmd este înlocuit de mesaj)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizează portofelul la ultimul format</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Setează mărimea bazinului de chei la <n> (implicit: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescanează lanțul de bloc pentru tranzacțiile portofel lipsă</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Cat de temeinica sa fie verificarea blocurilor( 0-6, implicit: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Importă blocuri dintr-un fișier extern blk000?.dat</translation>
</message>
<message>
<location line="+9"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Folosește OpenSSL (https) pentru conexiunile JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificatul serverului (implicit: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Cheia privată a serverului (implicit: server.pem)</translation>
</message>
<message>
<location line="+10"/>
<source>Initialization sanity check failed. GeyserCoin is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Eroare: portofel blocat doar pentru staking, tranzactia nu s-a creat.</translation>
</message>
<message>
<location line="+17"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>ATENTIONARE: checkpoint invalid! Trazatiile afisate pot fi incorecte! Posibil să aveți nevoie să faceți upgrade, sau să notificati dezvoltatorii.</translation>
</message>
<message>
<location line="-174"/>
<source>This help message</source>
<translation>Acest mesaj de ajutor</translation>
</message>
<message>
<location line="+104"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Portofelul %s este in afara directorului %s</translation>
</message>
<message>
<location line="+37"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Nu se poate folosi %s pe acest calculator (eroarea returnată este %d, %s)</translation>
</message>
<message>
<location line="-133"/>
<source>Connect through socks proxy</source>
<translation>Conectează-te printr-un proxy socks</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permite căutări DNS pentru -addnode, -seednode și -connect</translation>
</message>
<message>
<location line="+126"/>
<source>Loading addresses...</source>
<translation>Încarc adrese...</translation>
</message>
<message>
<location line="-12"/>
<source>Error loading blkindex.dat</source>
<translation>Eroare la încărcarea blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Eroare la încărcarea wallet.dat: Portofel corupt</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of GeyserCoin</source>
<translation>Eroare la încărcarea wallet.dat: Portofelul necesita o versiune mai noua de GeyserCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart GeyserCoin to complete</source>
<translation>A fost nevoie de rescrierea portofelului: restartați GeyserCoin pentru a finaliza</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Eroare la încărcarea wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Adresa -proxy nevalidă: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Rețeaua specificată în -onlynet este necunoscută: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>S-a cerut o versiune necunoscută de proxy -socks: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Nu se poate rezolva adresa -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Nu se poate rezolva adresa -externalip: '%s'</translation>
</message>
<message>
<location line="-23"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Suma nevalidă pentru -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+60"/>
<source>Sending...</source>
<translation>Se trimite...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Sumă nevalidă</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fonduri insuficiente</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Încarc indice bloc...</translation>
</message>
<message>
<location line="-110"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adaugă un nod la care te poți conecta pentru a menține conexiunea deschisă</translation>
</message>
<message>
<location line="+125"/>
<source>Unable to bind to %s on this computer. GeyserCoin is probably already running.</source>
<translation>Imposibil de conectat %s pe acest computer. Cel mai probabil GeyserCoin ruleaza</translation>
</message>
<message>
<location line="-101"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Comision pe kB de adaugat la tranzactiile pe care le trimiti</translation>
</message>
<message>
<location line="+34"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Keep at most <n> unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Suma invalida pentru -mininput=<amount>: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. GeyserCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Loading wallet...</source>
<translation>Încarc portofel...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Nu se poate retrograda portofelul</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Nu se poate scrie adresa implicită</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Rescanez...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Încărcare terminată</translation>
</message>
<message>
<location line="-161"/>
<source>To use the %s option</source>
<translation>Pentru a folosi opțiunea %s</translation>
</message>
<message>
<location line="+188"/>
<source>Error</source>
<translation>Eroare</translation>
</message>
<message>
<location line="-18"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Trebuie sa setezi rpcpassword=<password> în fișierul de configurare:⏎
%s⏎
Dacă fișierul nu există, creează-l cu permisiuni de citire doar de către proprietar.</translation>
</message>
</context>
</TS> | geysercoin/geysercoin | src/qt/locale/bitcoin_ro_RO.ts | TypeScript | mit | 130,407 |
/* eslint no-unused-vars: 0 */
import { mount, shallow } from 'avoriaz'
import should from 'should'
import sinon from 'sinon'
import { pSwitchbox } from 'prpllnt'
describe('switchbox.vue', () => {
it('renders a wrapper div with class p-input-group', () => {
const value = false
const component = shallow(pSwitchbox, { propsData: { value } })
component.is('div').should.be.true()
component.hasClass('p-input-group').should.be.true()
})
it('renders the label with the correct class and using a prop for text', () => {
const labels = ['this is a label']
const value = false
const component = shallow(pSwitchbox, { propsData: { labels, value } })
const labelEl = component.first('label')
labelEl.hasClass('p-switchbox').should.be.true()
const rendered = labelEl.text().trim()
rendered.should.be.exactly(labels[0])
})
it('renders the label correctly when only the second element is used', () => {
const labels = ['', 'this is a label']
const value = false
const component = shallow(pSwitchbox, { propsData: { labels, value } })
const labelEl = component.first('label')
const rendered = labelEl.text().trim()
rendered.should.be.exactly(labels[1])
})
it('renders the label correctly when both label elements are used', () => {
const labels = ['this-is-a-label', 'this-is-also-a-label']
const value = false
const component = shallow(pSwitchbox, { propsData: { labels, value } })
const labelEl = component.first('label')
const rendered = labelEl.text().replace(/\s/g, '')
rendered.should.be.exactly(labels.join(''))
})
it('renders nothing for the label prop when not provided', () => {
const label = ''
const value = false
const component = shallow(pSwitchbox, { propsData: { value } })
const rendered = component.first('label').text().trim()
rendered.should.be.exactly(label)
})
it('it re-uses the model internally as a computed property', () => {
const value = false
const component = shallow(pSwitchbox, { propsData: { value } })
component.vm.innerModel.should.be.exactly(value)
})
it('it reacts to the input field being changed', () => {
const value = false
const component = shallow(pSwitchbox, { propsData: { value } })
const input = component.first('input')
const spy = sinon.spy(component.vm, 'stateFromEvent')
input.element.checked = true
input.trigger('change')
spy.calledOnce.should.be.true()
})
})
| pearofducks/propellant | test/switchbox.spec.js | JavaScript | mit | 2,482 |
<?php
/*
* This file is part of the Sulu CMS.
*
* (c) MASSIVE ART WebServices GmbH
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Sulu\Bundle\Sales\OrderBundle\Cart;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Sulu\Component\Security\Authentication\UserInterface;
use Sulu\Component\Persistence\RelationTrait;
use Sulu\Bundle\Sales\CoreBundle\Entity\ItemInterface;
use Sulu\Bundle\Sales\CoreBundle\Pricing\GroupedItemsPriceCalculatorInterface;
use Sulu\Bundle\Sales\CoreBundle\Manager\BaseSalesManager;
use Sulu\Bundle\Sales\CoreBundle\Manager\OrderAddressManager;
use Sulu\Bundle\Sales\OrderBundle\Cart\Exception\CartSubmissionException;
use Sulu\Bundle\Sales\OrderBundle\Api\ApiOrderInterface;
use Sulu\Bundle\Sales\OrderBundle\Api\Order as ApiOrder;
use Sulu\Bundle\Sales\OrderBundle\Entity\Order;
use Sulu\Bundle\Sales\OrderBundle\Entity\OrderInterface;
use Sulu\Bundle\Sales\OrderBundle\Entity\OrderAddress;
use Sulu\Bundle\Sales\OrderBundle\Entity\OrderRepository;
use Sulu\Bundle\Sales\OrderBundle\Entity\OrderStatus;
use Sulu\Bundle\Sales\OrderBundle\Entity\OrderType;
use Sulu\Bundle\Sales\OrderBundle\Order\OrderEmailManager;
use Sulu\Bundle\Sales\OrderBundle\Order\Exception\OrderException;
use Sulu\Bundle\Sales\OrderBundle\Order\OrderFactoryInterface;
use Sulu\Bundle\Sales\OrderBundle\Order\OrderManager;
class CartManager extends BaseSalesManager
{
use RelationTrait;
const CART_STATUS_OK = 1;
const CART_STATUS_ERROR = 2;
const CART_STATUS_PRICE_CHANGED = 3;
const CART_STATUS_PRODUCT_REMOVED = 4;
const CART_STATUS_ORDER_LIMIT_EXCEEDED = 5;
/**
* TODO: replace by config
*
* defines when a cart expires
*/
const EXPIRY_MONTHS = 2;
/**
* @var ObjectManager
*/
protected $em;
/**
* @var SessionInterface
*/
protected $session;
/**
* @var OrderManager
*/
protected $orderManager;
/**
* @var OrderRepository
*/
protected $orderRepository;
/**
* @var GroupedItemsPriceCalculatorInterface
*/
protected $priceCalculation;
/**
* @var string
*/
protected $defaultCurrency;
/**
* @var AccountManager
*/
protected $accountManager;
/**
* @var OrderFactoryInterface
*/
protected $orderFactory;
/**
* @var OrderAddressManager
*/
protected $orderAddressManager;
/**
* @var OrderEmailManager
*/
protected $orderEmailManager;
/**
* @param ObjectManager $em
* @param SessionInterface $session
* @param OrderRepository $orderRepository
* @param OrderManager $orderManager
* @param GroupedItemsPriceCalculatorInterface $priceCalculation
* @param string $defaultCurrency
* @param AccountManager $accountManager
* @param OrderFactoryInterface $orderFactory
* @param OrderAddressManager $orderAddressManager
* @param OrderEmailManager $orderEmailManager
*/
public function __construct(
ObjectManager $em,
SessionInterface $session,
OrderRepository $orderRepository,
OrderManager $orderManager,
GroupedItemsPriceCalculatorInterface $priceCalculation,
$defaultCurrency,
$accountManager,
OrderFactoryInterface $orderFactory,
OrderAddressManager $orderAddressManager,
OrderEmailManager $orderEmailManager
) {
$this->em = $em;
$this->session = $session;
$this->orderRepository = $orderRepository;
$this->orderManager = $orderManager;
$this->priceCalculation = $priceCalculation;
$this->defaultCurrency = $defaultCurrency;
$this->accountManager = $accountManager;
$this->orderFactory = $orderFactory;
$this->orderAddressManager = $orderAddressManager;
$this->orderEmailManager = $orderEmailManager;
}
/**
* @param UserInterface $user
* @param null|string $locale
* @param null|string $currency
* @param bool $persistEmptyCart Define if an empty cart should be persisted
* @param bool $updatePrices Defines if prices should be updated
*
* @return null|ApiOrder
*/
public function getUserCart(
$user = null,
$locale = null,
$currency = null,
$persistEmptyCart = false,
$updatePrices = false
) {
// cart by session ID
if (!$user) {
// TODO: get correct locale
$locale = 'de';
$cartsArray = $this->findCartBySessionId();
} else {
// TODO: check if cart for this sessionId exists and assign it to user
// default locale from user
$locale = $locale ?: $user->getLocale();
// get carts
$cartsArray = $this->findCartsByUser($user, $locale);
}
// cleanup cart array: remove duplicates and expired carts
$this->cleanupCartsArray($cartArray);
// check if cart exists
if ($cartsArray && count($cartsArray) > 0) {
// multiple carts found, do a cleanup
$cart = $cartsArray[0];
} else {
// user has no cart - return empty one
$cart = $this->createEmptyCart($user, $persistEmptyCart);
}
// check if all products are still available
$cartNoRemovedProducts = $this->checkProductsAvailability($cart);
// create api entity
$apiOrder = $this->orderFactory->createApiEntity($cart, $locale);
if (!$cartNoRemovedProducts) {
$apiOrder->addCartErrorCode(self::CART_STATUS_PRODUCT_REMOVED);
}
$this->orderManager->updateApiEntity($apiOrder, $locale);
// check if prices have changed
if ($apiOrder->hasChangedPrices()) {
$apiOrder->addCartErrorCode(self::CART_STATUS_PRICE_CHANGED);
}
if ($updatePrices) {
$this->updateCartPrices($apiOrder->getItems());
}
return $apiOrder;
}
/**
* Updates changed prices
*
* @param array $items
*
* @return bool
*/
public function updateCartPrices($items)
{
// set prices to changed
$hasChanged = $this->priceCalculation->setPricesOfChanged($items);
if ($hasChanged) {
$this->em->flush();
}
return $hasChanged;
}
/**
* Updates the cart
*
* @param array $data
* @param UserInterface $user
* @param string $locale
*
* @throws \Sulu\Bundle\Sales\OrderBundle\Order\Exception\OrderException
* @throws \Sulu\Bundle\Sales\OrderBundle\Order\Exception\OrderNotFoundException
*
* @return null|Order
*/
public function updateCart($data, $user, $locale)
{
$cart = $this->getUserCart($user, $locale);
$userId = $user ? $user->getId() : null;
$this->orderManager->save($data, $locale, $userId, $cart->getId(), null, null, true);
$this->removeItemAddressesThatAreEqualToOrderAddress($cart);
return $cart;
}
/**
* Submits an order
*
* @param UserInterface $user
* @param string $locale
* @param bool $orderWasSubmitted
* @param OrderInterface $originalCart The original cart that was submitted
*
* @throws OrderException
* @throws \Sulu\Component\Rest\Exception\EntityNotFoundException
*
* @return null|ApiOrder
*/
public function submit($user, $locale, &$orderWasSubmitted = true, &$originalCart = null)
{
$orderWasSubmitted = true;
$cart = $this->getUserCart($user, $locale, null, false, true);
$originalCart = $cart;
if (count($cart->getCartErrorCodes()) > 0) {
$orderWasSubmitted = false;
return $cart;
} else {
$orderWasSubmitted = $this->submitCartDirectly($cart, $user, $locale);
}
return $this->getUserCart($user, $locale);
}
/**
* Submits a cart
*
* @param ApiOrderInterface $cart
* @param string $locale
* @param UserInterface $user
*
* @return bool
*/
public function submitCartDirectly(
ApiOrderInterface $cart,
UserInterface $user,
$locale
) {
$orderWasSubmitted = true;
try {
$this->checkIfCartIsValid($user, $cart, $locale);
// set order-date to current date
$cart->setOrderDate(new \DateTime());
// change status of order to confirmed
$this->orderManager->convertStatus($cart, OrderStatus::STATUS_CONFIRMED);
// order-addresses have to be set to the current contact-addresses
$this->reApplyOrderAddresses($cart, $user);
$customer = $user->getContact();
// send confirmation email to customer
$this->orderEmailManager->sendCustomerConfirmation(
$customer->getMainEmail(),
$cart,
$customer
);
$shopOwnerEmail = null;
// get responsible person of contacts account
if ($customer->getMainAccount() &&
$customer->getMainAccount()->getResponsiblePerson() &&
$customer->getMainAccount()->getResponsiblePerson()->getMainEmail()
) {
$shopOwnerEmail = $customer->getMainAccount()->getResponsiblePerson()->getMainEmail();
}
// send confirmation email to shop owner
$this->orderEmailManager->sendShopOwnerConfirmation(
$shopOwnerEmail,
$cart,
$customer
);
// flush on success
$this->em->flush();
} catch (CartSubmissionException $cse) {
$orderWasSubmitted = false;
}
return $orderWasSubmitted;
}
/**
* Checks if cart is valid
*
* @param UserInterface $user
* @param ApiOrderInterface $cart
* @param string $locale
*
* @throws OrderException
*/
protected function checkIfCartIsValid(UserInterface $user, ApiOrderInterface $cart, $locale)
{
if (count($cart->getItems()) < 1) {
throw new OrderException('Empty Cart');
}
}
/**
* Removes items from cart that have no valid shop products
* applied; and returns if all products are still available
*
* @param OrderInterface $cart
*
* @return bool If all products are available
*/
private function checkProductsAvailability(OrderInterface $cart)
{
// no check needed
if ($cart->getItems()->isEmpty()) {
return true;
}
$containsInvalidProducts = false;
/** @var \Sulu\Bundle\Sales\CoreBundle\Entity\ItemInterface $item */
foreach ($cart->getItems() as $item) {
if (!$item->getProduct() ||
!$item->getProduct()->isValidShopProduct()
) {
$containsInvalidProducts = true;
$cart->removeItem($item);
$this->em->remove($item);
}
}
// persist new cart
if ($containsInvalidProducts) {
$this->em->flush();
}
return !$containsInvalidProducts;
}
/**
* Reapplies order-addresses on submit
*
* @param ApiOrderInterface $cart
*/
private function reApplyOrderAddresses($cart, $user)
{
// validate addresses
$this->validateOrCreateAddresses($cart, $user);
// reapply invoice address of cart
if ($cart->getInvoiceAddress()->getContactAddress()) {
$this->orderAddressManager->getAndSetOrderAddressByContactAddress(
$cart->getInvoiceAddress()->getContactAddress(),
null,
null,
$cart->getInvoiceAddress()
);
}
// reapply delivery address of cart
if ($cart->getDeliveryAddress()->getContactAddress()) {
$this->orderAddressManager->getAndSetOrderAddressByContactAddress(
$cart->getDeliveryAddress()->getContactAddress(),
null,
null,
$cart->getDeliveryAddress()
);
}
// reapply delivery-addresses of every item
foreach ($cart->getItems() as $item) {
if ($item->getDeliveryAddress() &&
$item->getDeliveryAddress()->getContactAddress()
) {
$this->orderAddressManager->getAndSetOrderAddressByContactAddress(
$item->getDeliveryAddress()->getContactAddress(),
null,
null,
$item->getDeliveryAddress()
);
}
}
}
/**
* Checks if addresses have been set and sets new ones
*
* @param ApiOrderInterface $cart
*/
protected function validateOrCreateAddresses($cart)
{
if ($cart instanceof ApiOrderInterface) {
$cart = $cart->getEntity();
}
if (!$cart->getDeliveryAddress() || !$cart->getInvoiceAddress()) {
$addresses = $cart->getCustomerAccount()->getAccountAddresses();
if ($addresses->isEmpty()) {
throw new Exception('customer has no addresses');
}
$mainAddress = $cart->getCustomerAccount()->getMainAddress();
if (!$mainAddress) {
throw new Exception('customer has no main-address');
}
if (!$cart->getDeliveryAddress()) {
$newAddress = $this->orderAddressManager->getAndSetOrderAddressByContactAddress(
$mainAddress,
$cart->getCustomerContact(),
$cart->getCustomerAccount()
);
$cart->setDeliveryAddress($newAddress);
$this->em->persist($newAddress);
}
if (!$cart->getInvoiceAddress()) {
$newAddress = $this->orderAddressManager->getAndSetOrderAddressByContactAddress(
$mainAddress,
$cart->getCustomerContact(),
$cart->getCustomerAccount()
);
$cart->setInvoiceAddress($newAddress);
$this->em->persist($newAddress);
}
}
}
/**
* Finds cart by session-id
*
* @return array
*/
private function findCartBySessionId()
{
$sessionId = $this->session->getId();
$cartsArray = $this->orderRepository->findBy(
array(
'sessionId' => $sessionId,
'status' => OrderStatus::STATUS_IN_CART
),
array(
'created' => 'DESC'
)
);
return $cartsArray;
}
/**
* Finds cart by locale and user
*
* @param string $locale
* @param UserInterface $user
*
* @return array|null
*/
private function findCartsByUser($user, $locale)
{
$cartsArray = $this->orderRepository->findByStatusIdsAndUser(
$locale,
array(OrderStatus::STATUS_IN_CART, OrderStatus::STATUS_CART_PENDING),
$user
);
return $cartsArray;
}
/**
* removes all elements from database but the first
*
* @param $cartsArray
*/
private function cleanupCartsArray(&$cartsArray)
{
if ($cartsArray && count($cartsArray) > 0) {
// handle cartsArray count is > 1
foreach ($cartsArray as $index => $cart) {
// delete expired carts
if ($cart->getChanged()->getTimestamp() < strtotime(static::EXPIRY_MONTHS . ' months ago')) {
// $this->em->remove($cart);
continue;
}
// dont delete first element, since this is the current cart
if ($index === 0) {
continue;
}
// remove duplicated carts
// $this->em->remove($cart);
}
}
}
/**
* Adds a product to cart
*
* @param array $data
* @param UserInterface|null $user
* @param string|null $locale
*
* @return null|Order
*/
public function addProduct($data, $user = null, $locale = null)
{
//TODO: locale
// get cart
$cart = $this->getUserCart($user, $locale, null, true);
// define user-id
$userId = $user ? $user->getId() : null;
$this->orderManager->addItem($data, $locale, $userId, $cart);
$this->orderManager->updateApiEntity($cart, $locale);
return $cart;
}
/**
* Update item data
*
* @param int $itemId
* @param array $data
* @param null|UserInterface $user
* @param null|string $locale
*
* @throws ItemNotFoundException
*
* @return null|Order
*/
public function updateItem($itemId, $data, $user = null, $locale = null)
{
$cart = $this->getUserCart($user, $locale);
$userId = $user ? $user->getId() : null;
$item = $this->orderManager->getOrderItemById($itemId, $cart->getEntity());
$this->orderManager->updateItem($item, $data, $locale, $userId);
$this->removeOrderAddressIfContactAddressIdIsEqualTo(
$item,
$cart->getDeliveryAddress()->getContactAddress()->getId()
);
$this->orderManager->updateApiEntity($cart, $locale);
return $cart;
}
/**
* Removes an item from cart
*
* @param int $itemId
* @param null|UserInterface $user
* @param null|string $locale
*
* @return null|Order
*/
public function removeItem($itemId, $user = null, $locale = null)
{
$cart = $this->getUserCart($user, $locale);
$item = $this->orderManager->getOrderItemById($itemId, $cart->getEntity(), $hasMultiple);
$this->orderManager->removeItem($item, $cart->getEntity(), !$hasMultiple);
$this->orderManager->updateApiEntity($cart, $locale);
return $cart;
}
/**
* Function creates an empty cart
* this means an order with status 'in_cart' is created and all necessary data is set
*
* @param UserInterface $user
* @param bool $persist
* @param null|string $currencyCode
*
* @return Order
* @throws \Sulu\Component\Rest\Exception\EntityNotFoundException
*/
protected function createEmptyCart($user, $persist, $currencyCode = null)
{
$cart = new Order();
$cart->setCreator($user);
$cart->setChanger($user);
$cart->setCreated(new \DateTime());
$cart->setChanged(new \DateTime());
$cart->setOrderDate(new \DateTime());
// set currency - if not defined use default
$currencyCode = $currencyCode ?: $this->defaultCurrency;
$cart->setCurrencyCode($currencyCode);
// get address from contact and account
$contact = $user->getContact();
$account = $contact->getMainAccount();
$cart->setCustomerContact($contact);
$cart->setCustomerAccount($account);
/** Account $account */
if ($account && $account->getResponsiblePerson()) {
$cart->setResponsibleContact($account->getResponsiblePerson());
}
$addressSource = $contact;
if ($account) {
$addressSource = $account;
}
// get billing address
$invoiceOrderAddress = null;
$invoiceAddress = $this->accountManager->getBillingAddress($addressSource, true);
if ($invoiceAddress) {
// convert to order-address
$invoiceOrderAddress = $this->orderAddressManager->getAndSetOrderAddressByContactAddress(
$invoiceAddress,
$contact,
$account
);
$cart->setInvoiceAddress($invoiceOrderAddress);
}
$deliveryOrderAddress = null;
$deliveryAddress = $this->accountManager->getDeliveryAddress($addressSource, true);
if ($deliveryAddress) {
// convert to order-address
$deliveryOrderAddress = $this->orderAddressManager->getAndSetOrderAddressByContactAddress(
$deliveryAddress,
$contact,
$account
);
$cart->setDeliveryAddress($deliveryOrderAddress);
}
// TODO: anonymous order
// set order type
if ($user) {
$name = $user->getContact()->getFullName();
$cart->setType($this->orderManager->getOrderTypeEntityById(OrderType::SHOP));
} else {
$name = 'Anonymous';
$cart->setType($this->orderManager->getOrderTypeEntityById(OrderType::ANONYMOUS));
}
$cart->setCustomerName($name);
$this->orderManager->convertStatus($cart, OrderStatus::STATUS_IN_CART, false, $persist);
if ($persist) {
$this->em->persist($cart);
if ($invoiceOrderAddress) {
$this->em->persist($invoiceOrderAddress);
}
if ($deliveryOrderAddress) {
$this->em->persist($deliveryOrderAddress);
}
}
return $cart;
}
/**
* Returns array containing number of items and total-price
* array('totalItems', 'totalPrice')
*
* @param UserInterface $user
* @param string $locale
*
* @return array
*/
public function getNumberItemsAndTotalPrice($user, $locale)
{
$cart = $this->getUserCart($user, $locale);
return array(
'totalItems' => count($cart->getItems()),
'totalPrice' => $cart->getTotalNetPrice(),
'totalPriceFormatted' => $cart->getTotalNetPriceFormatted(),
'currency' => $cart->getCurrencyCode()
);
}
/**
* Remove all item delivery-addresses that are the same as the default
* delivery address of the order
*
* @param ApiOrderInterface $order
*/
protected function removeItemAddressesThatAreEqualToOrderAddress($order)
{
$deliveryAddressId = $order->getDeliveryAddress()->getContactAddress()->getId();
foreach ($order->getItems() as $item) {
$itemEntity = $item->getEntity();
$this->removeOrderAddressIfContactAddressIdIsEqualTo($itemEntity, $deliveryAddressId);
}
}
/**
* Remove deliveryAddress if it has a relation to a certain contact-address-id
*
* @param OrderAddress $deliveryAddress
* @param int $contactAddressId
*/
protected function removeOrderAddressIfContactAddressIdIsEqualTo($item, $contactAddressId)
{
$deliveryAddress = $item->getDeliveryAddress();
if ($deliveryAddress
&& $deliveryAddress->getContactAddress()
&& $deliveryAddress->getContactAddress()->getID() === $contactAddressId
) {
$item->setDeliveryAddress(null);
$this->em->remove($deliveryAddress);
}
}
}
| sulu-io/SuluSalesOrderBundle | Cart/CartManager.php | PHP | mit | 23,396 |
<?php
namespace YourApp\App\Newsletter;
use Welp\MailchimpBundle\Provider\ProviderInterface;
use Welp\MailchimpBundle\Subscriber\Subscriber;
use YourApp\Model\User\UserRepository;
use YourApp\Model\User\User;
class ExampleSubscriberProvider implements ProviderInterface
{
// these tags should match the one you added in MailChimp's backend
const TAG_NICKNAME = 'NICKNAME';
const TAG_GENDER = 'GENDER';
const TAG_BIRTHDATE = 'BIRTHDATE';
const TAG_LAST_ACTIVITY_DATE = 'LASTACTIVI';
const TAG_REGISTRATION_DATE = 'REGISTRATI';
const TAG_CITY = 'CITY';
protected $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* {@inheritdoc}
*/
public function getSubscribers()
{
$users = $this->userRepository->findSubscribers();
$subscribers = array_map(function (User $user) {
$subscriber = new Subscriber($user->getEmail(), [
self::TAG_NICKNAME => $user->getNickname(),
self::TAG_GENDER => $user->getGender(),
self::TAG_BIRTHDATE => $user->getBirthdate() ? $user->getBirthdate()->format('Y-m-d') : null,
self::TAG_CITY => $user->getCity(),
self::TAG_LAST_ACTIVITY_DATE => $user->getLastActivityDate() ? $user->getLastActivityDate()->format('Y-m-d') : null,
self::TAG_REGISTRATION_DATE => $user->getRegistrationDate() ? $user->getRegistrationDate()->format('Y-m-d') : null,
], [
'language' => 'fr',
'email_type' => 'html'
]);
return $subscriber;
}, $users);
return $subscribers;
}
}
| welpdev/mailchimp-bundle | src/Provider/ExampleSubscriberProvider.php | PHP | mit | 1,790 |
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HeartBeatI extends Remote {
public void sendHeartBeat() throws RemoteException;
}
| jpavelw/SWEN-755 | HeartBeatRedundancy/HeartBeatI.java | Java | mit | 161 |
<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::uses('CakeTime', 'Utility');
class CategoriesController extends AppController {
public $uses = array(
'SpeedyCake',
'Page',
'User',
'Article',
'Articlefield',
'File',
'Categorie',
'Articlescategorie'
);
public $components = array('Session','Cookie','RequestHandler','SpeedyCake');
public $helpers = array('Html', 'Form', 'Session');
var $per_page = 10;
var $q = "";
var $filter = "";
public function index() {
$this->set('breadcrumbs', true);
$this->set('title',__('Categories'));
if (isset($_GET["q"])) {
$conditions = array();
if (isset($_GET["q"]) && $_GET["q"]!="") {
$this->q = $_GET["q"];
$conditions[] = array('Categorie.name LIKE '=>'%' .$this->q .'%');
}
$this->paginate = array(
'conditions'=>array('AND'=>$conditions),
'limit' => $this->per_page,
'order'=>array('Categorie.id'=>'DESC')
);
$rows = $this->Categorie->find('all',array(
'conditions'=>array('AND'=>$conditions),
'order'=>array('Categorie.id'=>'DESC')
));
}
else if (!isset($_GET["q"])) {
$this->paginate = array(
'limit' => $this->per_page,
'order'=>array('Categorie.id'=>'DESC')
);
$rows = $this->Categorie->find('all',array('order'=>array('Categorie.id'=>'DESC')));
}
$rows = $this->paginate('Categorie');
$this->set('rows',$rows);
$this->set('numRows',count($rows));
$this->set('q',$this->q);
}
public function add() {
$this->set('breadcrumbs', true);
$this->set('title',__('Add new category'));
if (!empty($this->request->data) && $this->request->is('post')) {
$this->request->data["Categorie"]["slug"] = strtolower(Inflector::slug($this->request->data["Categorie"]["name"],'-'));
$this->request->data["Categorie"]["user_id"] = $this->Session->read('Administrator.id');
if ($this->Categorie->save($this->request->data)) {
$this->Session->setFlash(__('Data saved.'),'default',
array('class'=>'alert alert-success')
);
$this->redirect('/admin/categories');
}
else {
$this->Session->setFlash(__('Saving failed!'),'default',
array('class'=>'alert')
);
}
}
}
public function nameIsUnique() {
if (!empty($this->request->data) && $this->request->is('post') && $this->request->is('ajax')) {
$this->autoRender = false;
$name = $this->request->data["name"];
echo $this->Categorie->find('count', array(
'conditions' => array('Categorie.name' => $name)
));
}
}
public function edit($id=NULL) {
$this->set('breadcrumbs', true);
if (!empty($this->request->data) && $this->request->is('post','put')) {
$this->Categorie->id = $this->request->data["Categorie"]["id"];
if ($this->Categorie->save($this->request->data)) {
$this->Session->setFlash(__('Data saved.'),'default',
array('class'=>'alert alert-success')
);
$this->redirect('/admin/categories');
}
else {
$this->Session->setFlash(__('Saving failed!'),'default',
array('class'=>'alert')
);
}
}
else {
if (!$id) $this->redirect(array('controller'=>'categories','action'=>'index'));
$row = $this->Categorie->find('first',array(
'conditions'=>array('Categorie.id'=>$id)
));
$this->set('title',__('Edit Category'));
$this->set('id',$row["Categorie"]["id"]);
$this->set('name',$row["Categorie"]["name"]);
$this->set('slug',$row["Categorie"]["slug"]);
}
}
public function delete($id=NULL) {
if (!$id) $this->redirect(array('controller'=>'categories','action'=>'index'));
$this->Categorie->id = $id;
if ($this->Categorie->delete($id)) {
$this->Articlescategorie->deleteAll(array('Articlescategorie.categorie_id' => $id), false);
$this->Session->setFlash(__('Category deleted.'),'default',
array('class'=>'alert alert-success')
);
$this->redirect('/admin/categories');
}
}
public function beforeFilter() {
if (!$this->SpeedyCake->ifDatabaseInstalled($this->Page->tablePrefix)) $this->redirect('/speedycake');
if (!$this->SpeedyCake->checkPermission($this->params["controller"],$this->params["action"],$this->params["id"])) {
$this->Session->setFlash('Permission denied.','default',
array('class'=>'alert alert-success')
);
$this->redirect(array('controller'=>'pages','action'=>'dashboard'));
}
if ($this->SpeedyCake->checkStatus()==1 && $this->SpeedyCake->isPublicPage($this->params["controller"],$this->params["action"])) $this->redirect(array('controller'=>'pages','action'=>'maintenance'));
$this->SpeedyCake->setLang();
$this->SpeedyCake->setTimezone();
if (!$this->SpeedyCake->isAuth() && !$this->SpeedyCake->isPublicPage($this->params["controller"],$this->params["action"])) {
$this->redirect(array('controller'=>'pages','action'=>'login'));
}
}
}
?> | Mr-Robota/speedy-cake-cms | Controller/CategoriesController.php | PHP | mit | 5,139 |
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import React from 'react';
import {
MappingProvider,
MappingProviderProps,
} from '../mapping/mappingProvider.component';
import {
ThemeProvider,
ThemeProviderProps,
} from '../theme/themeProvider.component';
export type StyleProviderProps = MappingProviderProps & ThemeProviderProps;
export class StyleProvider extends React.PureComponent<StyleProviderProps> {
public render(): React.ReactNode {
const { styles, theme, children } = this.props;
return (
<MappingProvider styles={styles}>
<ThemeProvider theme={theme}>
{children}
</ThemeProvider>
</MappingProvider>
);
}
}
| akveo/react-native-ui-kitten | src/components/theme/style/styleProvider.component.tsx | TypeScript | mit | 796 |
using System;
using System.Linq;
using AdventOfCodeLibrary;
using AdventOfCodeLibrary.FileImport;
using AdventOfCodeLibrary.Frequencies;
namespace Day6
{
class Program
{
static void Main(string[] args)
{
Part1();
Console.WriteLine();
Part2();
Console.ReadKey();
}
//Test should be easter
//Input should be agmwzecr
public static void Part1()
{
int sectorCount = 0;
var fileIO = new FileImportAdapter();
string[] invertedStrings = fileIO.ReadFileToArray("../../input.txt");
var strings = Utilities.Transpose(invertedStrings.ToList());
foreach (var str in strings)
{
var freq = new Frequency(str);
freq.Build();
Console.Write(freq.TopItem());
}
}
//Test should be advent
//Input should be owlaxqvq
public static void Part2()
{
int sectorCount = 0;
var fileIO = new FileImportAdapter();
string[] invertedStrings = fileIO.ReadFileToArray("../../input.txt");
var strings = Utilities.Transpose(invertedStrings.ToList());
foreach (var str in strings)
{
var freq = new Frequency(str);
freq.Build();
Console.Write(freq.BottomItem());
}
}
}
}
| codemonkey047/AdventOfCode | Day6/Day6/Program.cs | C# | mit | 1,471 |
# frozen_string_literal: true
module Analytics
class SubjectController < AnalyticsController
# rubocop:disable Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/AbcSize
def index
@subject_series = if @selected_student_id.present? && @selected_student_id != 'All'
performance_per_skill_single_student
else
performance_per_skill
end
end
private
def performance_per_skill_single_student
conn = ActiveRecord::Base.connection.raw_connection
students = {}
query_result = conn.exec(Sql.performance_per_skill_in_lessons_per_student_query([@selected_student_id])).values
result = query_result.reduce({}) do |acc, e|
student_id = e[-1]
student_name = students[student_id] ||= Student.find(student_id).proper_name
skill_name = e[-2]
acc.tap do |a|
if a.key?(skill_name)
if a[skill_name].key?(student_name)
a[skill_name][student_name].push(x: e[0], y: e[1], lesson_url: lesson_path(e[2]), date: e[3])
else
a[skill_name][student_name] = [{ x: e[0], y: e[1], lesson_url: lesson_path(e[2]), date: e[3] }]
end
else
a[skill_name] = { student_name => [{ x: e[0], y: e[1], lesson_url: lesson_path(e[2]), date: e[3] }] }
end
end
end
render_performance_per_skill(result)
end
def performance_per_skill
groups = policy_scope(
if @selected_group_id.present? && @selected_group_id != 'All'
Group.where(id: @selected_group_id)
elsif @selected_chapter_id.present? && @selected_chapter_id != 'All'
Group.where(chapter_id: @selected_chapter_id)
elsif @selected_organization_id.present? && @selected_organization_id != 'All'
Group.includes(:chapter).where(chapters: { organization_id: @selected_organization_id })
else
Group
end
)
return [] if groups.empty?
result = PerformancePerGroupPerSkillPerLesson.where(group: groups).reduce({}) do |acc, e|
acc.tap do |a|
if a.key?(e.skill_name)
if a[e.skill_name].key?(e.group_chapter_name)
a[e.skill_name][e.group_chapter_name].push(x: a[e.skill_name][e.group_chapter_name].length, y: e.mark, lesson_url: lesson_path(e.lesson_id), date: e.date)
else
a[e.skill_name][e.group_chapter_name] = [{ x: 0, y: e.mark, lesson_url: lesson_path(e.lesson_id), date: e.date }]
end
else
a[e.skill_name] = { e.group_chapter_name => [{ x: 0, y: e.mark, lesson_url: lesson_path(e.lesson_id), date: e.date }] }
end
end
end
render_performance_per_skill(result, t(:group))
end
def render_performance_per_skill(result, prefix = '')
series = []
result.each do |skill_name, hash|
# regression = RegressionService.new.skill_regression skill_name, hash.values.map(&:length).max
skill_series = []
hash.each_with_index do |(group, array), index|
skill_series << { name: "#{prefix} #{group}", data: array, color: get_color(index), regression: array.length > 1, regressionSettings: {
type: 'polynomial',
order: 4,
color: get_color(index),
name: "#{prefix} #{group} - Regression",
lineWidth: 1
} }
end
# skill_series << {name: t(:regression_curve), data: regression, color: '#FF0000', lineWidth: 1, marker: {enabled: false}}
series << { skill: skill_name, series: skill_series }
end
series
end
# rubocop:enable Metrics/AbcSize
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/PerceivedComplexity
# rubocop:enable Metrics/CyclomaticComplexity
end
end
| MindLeaps/tracker | app/controllers/analytics/subject_controller.rb | Ruby | mit | 3,998 |
<?php
namespace FMI\ImportBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Prices
*
* @ORM\Table(name="prices")
* @ORM\Entity(repositoryClass="FMI\ImportBundle\Repository\PricesRepository")
*/
class Prices
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var int
*
* @ORM\Column(name="postal_code", type="integer")
*/
private $postalCode;
/**
* @var float
*
* @ORM\Column(name="amount", type="float")
*/
private $amount;
/**
* @var string
*
* @ORM\Column(name="date", type="string", length=255)
*/
private $date;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set postalCode
*
* @param integer $postalCode
* @return Prices
*/
public function setPostalCode($postalCode)
{
$this->postalCode = $postalCode;
return $this;
}
/**
* Get postalCode
*
* @return integer
*/
public function getPostalCode()
{
return $this->postalCode;
}
/**
* Set amount
*
* @param float $amount
* @return Prices
*/
public function setAmount($amount)
{
$this->amount = $amount;
return $this;
}
/**
* Get amount
*
* @return float
*/
public function getAmount()
{
return $this->amount;
}
/**
* Set date
*
* @param string $date
* @return Prices
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* @return string
*/
public function getDate()
{
return $this->date;
}
}
| LAYLSAYF/IMPORT | src/FMI/ImportBundle/Entity/Prices.php | PHP | mit | 1,900 |
// èÌof[^ð\¦·é
#include "pxcsensemanager.h"
#include "pxchandconfiguration.h"
#include <opencv2\opencv.hpp>
class RealSenseApp
{
public:
~RealSenseApp()
{
if ( senseManager != 0 ){
senseManager->Release();
}
}
void initilize()
{
// SenseManager𶬷é
senseManager = PXCSenseManager::CreateInstance();
if ( senseManager == 0 ) {
throw std::runtime_error( "SenseManager̶¬É¸sµÜµ½" );
}
// DepthXg[ðLøÉ·é
pxcStatus sts = senseManager->EnableStream( PXCCapture::StreamType::STREAM_TYPE_DEPTH,
DEPTH_WIDTH, DEPTH_HEIGHT, DEPTH_FPS );
if ( sts<PXC_STATUS_NO_ERROR ) {
throw std::runtime_error( "DepthXg[ÌLø»É¸sµÜµ½" );
}
// èÌoðLøÉ·é
sts = senseManager->EnableHand();
if ( sts < PXC_STATUS_NO_ERROR ) {
throw std::runtime_error( "èÌoÌLø»É¸sµÜµ½" );
}
// pCvCðú»·é
sts = senseManager->Init();
if ( sts<PXC_STATUS_NO_ERROR ) {
throw std::runtime_error( "pCvCÌú»É¸sµÜµ½" );
}
// ~[\¦É·é
senseManager->QueryCaptureManager()->QueryDevice()->SetMirrorMode(
PXCCapture::Device::MirrorMode::MIRROR_MODE_HORIZONTAL );
// èÌoÌú»
initializeHandTracking();
}
void run()
{
// C[v
while ( 1 ) {
// t[f[^ðXV·é
updateFrame();
// \¦·é
auto ret = showImage();
if ( !ret ){
break;
}
}
}
private:
void initializeHandTracking()
{
// èÌoíð쬷é
handAnalyzer = senseManager->QueryHand();
if ( handAnalyzer == 0 ) {
throw std::runtime_error( "èÌoíÌæ¾É¸sµÜµ½" );
}
// èÌf[^ðæ¾·é
handData = handAnalyzer->CreateOutput();
if ( handData == 0 ) {
throw std::runtime_error( "èÌoíÌì¬É¸sµÜµ½" );
}
// RealSense JÅ êÎAvpeBðÝè·é
PXCCapture::DeviceInfo dinfo;
senseManager->QueryCaptureManager()->QueryDevice()->QueryDeviceInfo( &dinfo );
if ( dinfo.model == PXCCapture::DEVICE_MODEL_IVCAM ) {
PXCCapture::Device *device = senseManager->QueryCaptureManager()->QueryDevice();
device->SetDepthConfidenceThreshold( 1 );
//device->SetMirrorMode( PXCCapture::Device::MIRROR_MODE_DISABLED );
device->SetIVCAMFilterOption( 6 );
}
// Hand Module Configuration
PXCHandConfiguration* config = handAnalyzer->CreateActiveConfiguration();
//config->EnableNormalizedJoints( showNormalizedSkeleton );
//config->SetTrackingMode( PXCHandData::TRACKING_MODE_EXTREMITIES );
//config->EnableAllAlerts();
config->EnableSegmentationImage( true );
config->ApplyChanges();
config->Update();
}
void updateFrame()
{
// t[ðæ¾·é
pxcStatus sts = senseManager->AcquireFrame( false );
if ( sts < PXC_STATUS_NO_ERROR ) {
return;
}
// èÌXV
updateHandFrame();
// t[ððú·é
senseManager->ReleaseFrame();
}
void updateHandFrame()
{
// èÌf[^ðXV·é
handData->Update();
// æðú»
handImage = cv::Mat::zeros( DEPTH_HEIGHT, DEPTH_WIDTH, CV_8UC3 );
auto numOfHands = handData->QueryNumberOfHands();
for ( int i = 0; i < numOfHands; i++ ) {
// èðæ¾·é
PXCHandData::IHand* hand;
auto sts = handData->QueryHandData(
PXCHandData::AccessOrderType::ACCESS_ORDER_BY_ID, i, hand );
if ( sts < PXC_STATUS_NO_ERROR ) {
continue;
}
// èÌ}XNæðæ¾·é
PXCImage* image = 0;
sts = hand->QuerySegmentationImage( image );
if ( sts != PXC_STATUS_NO_ERROR ) {
continue;
}
// èÌæf[^ðæ¾·é
PXCImage::ImageData data;
sts = image->AcquireAccess( PXCImage::ACCESS_READ,
PXCImage::PIXEL_FORMAT_Y8, &data );
if ( sts != PXC_STATUS_NO_ERROR ){
continue;
}
// è̶Eðæ¾·é
auto side = hand->QueryBodySide();
// èÌJÂx(0-100)ðæ¾·é
auto openness = hand->QueryOpenness();
// }XNæÌTCYÍDepthÉ˶
// èÍ2ÂÜÅo·é
PXCImage::ImageInfo info = image->QueryInfo();
for ( int j = 0; j < info.height * info.width; ++j ){
if ( data.planes[0][j] != 0 ){
auto index = j * 3;
// è̶E¨æÑèÌJÂxÅF¢ðßé
// ¶è=1F0-127ÌÍÍ
// Eè=2F0-254ÌÍÍ
auto value = (uchar)((side * 127) * (openness / 100.0f));
handImage.data[index + 0] = value;
handImage.data[index + 1] = value;
handImage.data[index + 2] = value;
}
}
// èÌæf[^ððú·é
image->ReleaseAccess( &data );
// èÌSð\¦·é
auto center = hand->QueryMassCenterImage();
cv::circle( handImage, cv::Point( center.x, center.y ), 5,
cv::Scalar( 255, 0, 0 ), -1 );
// èÌÍÍð\¦·é
auto boundingbox = hand->QueryBoundingBoxImage();
cv::rectangle( handImage,
cv::Rect( boundingbox.x, boundingbox.y, boundingbox.w, boundingbox.h ),
cv::Scalar( 0, 0, 255 ), 2 );
}
}
// æð\¦·é
bool showImage()
{
// \¦·é
cv::imshow( "Hand Image", handImage );
int c = cv::waitKey( 10 );
if ( (c == 27) || (c == 'q') || (c == 'Q') ){
// ESC|q|Q for Exit
return false;
}
return true;
}
private:
PXCSenseManager* senseManager = 0;
cv::Mat handImage;
PXCHandModule* handAnalyzer = 0;
PXCHandData* handData = 0;
const int DEPTH_WIDTH = 640;
const int DEPTH_HEIGHT = 480;
const int DEPTH_FPS = 30;
};
void main()
{
try{
RealSenseApp app;
app.initilize();
app.run();
}
catch ( std::exception& ex ){
std::cout << ex.what() << std::endl;
}
}
| RealSense-Book/RealSense-Book-CPP | CH5-1_3/RealSenseSample/main.cpp | C++ | mit | 6,752 |
package alec_wam.CrystalMod.entities.minions.worker;
import net.minecraft.entity.EntityLiving;
import net.minecraft.pathfinding.Path;
import net.minecraft.pathfinding.PathNavigate;
import net.minecraft.pathfinding.WalkNodeProcessor;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.ChunkCache;
public class PathFinderWorker {
public static PathFinderCustom customInstance;
public static PathFinderCustom getPathFinder()
{
if(customInstance == null){
WalkNodeProcessor nodeProcessor = new WalkNodeProcessor();
nodeProcessor.setCanEnterDoors(true);
customInstance = new PathFinderCustom(nodeProcessor);
}
return customInstance;
}
public static Path findDetailedPath(EntityLiving entity, PathNavigate nav, double x, double y, double z){
if (!(entity.onGround || entity.isRiding()))
{
return null;
}
else if (nav.getPath() != null && !nav.getPath().isFinished())
{
return nav.getPath();
}
else
{
float f = nav.getPathSearchRange();
BlockPos blockpos = new BlockPos(entity);
int i = (int)(f + 8.0F);
ChunkCache chunkcache = new ChunkCache(entity.getEntityWorld(), blockpos.add(-i, -i, -i), blockpos.add(i, i, i), 0);
Path path = getPathFinder().findPath(chunkcache, entity, x, y, z, f);
return path;
}
}
}
| Alec-WAM/CrystalMod | src/main/java/alec_wam/CrystalMod/entities/minions/worker/PathFinderWorker.java | Java | mit | 1,491 |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto
package google_devtools_clouderrorreporting_v1beta1
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "go.pedge.io/pb/go/google/api"
import google_protobuf1 "github.com/golang/protobuf/ptypes/timestamp"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// A request for reporting an individual error event.
type ReportErrorEventRequest struct {
// [Required] The resource name of the Google Cloud Platform project. Written
// as `projects/` plus the
// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
// Example: `projects/my-project-123`.
ProjectName string `protobuf:"bytes,1,opt,name=project_name,json=projectName" json:"project_name,omitempty"`
// [Required] The error event to be reported.
Event *ReportedErrorEvent `protobuf:"bytes,2,opt,name=event" json:"event,omitempty"`
}
func (m *ReportErrorEventRequest) Reset() { *m = ReportErrorEventRequest{} }
func (m *ReportErrorEventRequest) String() string { return proto.CompactTextString(m) }
func (*ReportErrorEventRequest) ProtoMessage() {}
func (*ReportErrorEventRequest) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{0} }
func (m *ReportErrorEventRequest) GetProjectName() string {
if m != nil {
return m.ProjectName
}
return ""
}
func (m *ReportErrorEventRequest) GetEvent() *ReportedErrorEvent {
if m != nil {
return m.Event
}
return nil
}
// Response for reporting an individual error event.
// Data may be added to this message in the future.
type ReportErrorEventResponse struct {
}
func (m *ReportErrorEventResponse) Reset() { *m = ReportErrorEventResponse{} }
func (m *ReportErrorEventResponse) String() string { return proto.CompactTextString(m) }
func (*ReportErrorEventResponse) ProtoMessage() {}
func (*ReportErrorEventResponse) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} }
// An error event which is reported to the Error Reporting system.
type ReportedErrorEvent struct {
// [Optional] Time when the event occurred.
// If not provided, the time when the event was received by the
// Error Reporting system will be used.
EventTime *google_protobuf1.Timestamp `protobuf:"bytes,1,opt,name=event_time,json=eventTime" json:"event_time,omitempty"`
// [Required] The service context in which this error has occurred.
ServiceContext *ServiceContext `protobuf:"bytes,2,opt,name=service_context,json=serviceContext" json:"service_context,omitempty"`
// [Required] A message describing the error. The message can contain an
// exception stack in one of the supported programming languages and formats.
// In that case, the message is parsed and detailed exception information
// is returned when retrieving the error event again.
Message string `protobuf:"bytes,3,opt,name=message" json:"message,omitempty"`
// [Optional] A description of the context in which the error occurred.
Context *ErrorContext `protobuf:"bytes,4,opt,name=context" json:"context,omitempty"`
}
func (m *ReportedErrorEvent) Reset() { *m = ReportedErrorEvent{} }
func (m *ReportedErrorEvent) String() string { return proto.CompactTextString(m) }
func (*ReportedErrorEvent) ProtoMessage() {}
func (*ReportedErrorEvent) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{2} }
func (m *ReportedErrorEvent) GetEventTime() *google_protobuf1.Timestamp {
if m != nil {
return m.EventTime
}
return nil
}
func (m *ReportedErrorEvent) GetServiceContext() *ServiceContext {
if m != nil {
return m.ServiceContext
}
return nil
}
func (m *ReportedErrorEvent) GetMessage() string {
if m != nil {
return m.Message
}
return ""
}
func (m *ReportedErrorEvent) GetContext() *ErrorContext {
if m != nil {
return m.Context
}
return nil
}
func init() {
proto.RegisterType((*ReportErrorEventRequest)(nil), "google.devtools.clouderrorreporting.v1beta1.ReportErrorEventRequest")
proto.RegisterType((*ReportErrorEventResponse)(nil), "google.devtools.clouderrorreporting.v1beta1.ReportErrorEventResponse")
proto.RegisterType((*ReportedErrorEvent)(nil), "google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent")
}
func init() {
proto.RegisterFile("google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto", fileDescriptor3)
}
var fileDescriptor3 = []byte{
// 462 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xcd, 0x8a, 0x13, 0x41,
0x10, 0xc7, 0xe9, 0xf8, 0xb1, 0x6c, 0x47, 0x54, 0xda, 0x83, 0xc3, 0x20, 0xb8, 0xc6, 0xcb, 0xa2,
0x30, 0x6d, 0xe2, 0xc5, 0xac, 0xc8, 0x42, 0xd6, 0xb0, 0x37, 0x59, 0x66, 0x75, 0x4f, 0x81, 0xa1,
0x33, 0x29, 0xc3, 0x48, 0xa6, 0x6b, 0xec, 0xee, 0x04, 0x41, 0xbc, 0xf8, 0x0a, 0x7b, 0xf2, 0xee,
0xc9, 0x47, 0xf1, 0xea, 0x0b, 0x78, 0xf0, 0x21, 0x3c, 0x4a, 0x7f, 0x2d, 0x59, 0x93, 0xcb, 0xe8,
0xb1, 0x7a, 0xaa, 0x7e, 0xff, 0xfa, 0xf8, 0x0f, 0x3d, 0x9e, 0x23, 0xce, 0x17, 0xc0, 0x67, 0xb0,
0x32, 0x88, 0x0b, 0xcd, 0xcb, 0x05, 0x2e, 0x67, 0xa0, 0x14, 0x2a, 0x05, 0x0d, 0x2a, 0x53, 0xc9,
0x39, 0x5f, 0xf5, 0xa7, 0x60, 0x44, 0x9f, 0xfb, 0x97, 0xc2, 0x7d, 0xd5, 0x85, 0x06, 0xb5, 0xaa,
0x4a, 0xc8, 0x1a, 0x85, 0x06, 0xd9, 0x63, 0x0f, 0xca, 0x22, 0x28, 0xdb, 0x02, 0xca, 0x02, 0x28,
0xbd, 0x17, 0x54, 0x45, 0x53, 0x71, 0x21, 0x25, 0x1a, 0x61, 0x2a, 0x94, 0xda, 0xa3, 0xd2, 0x67,
0x6d, 0x7a, 0x2a, 0xb1, 0xae, 0x51, 0x86, 0xca, 0xfb, 0xa1, 0xd2, 0x45, 0xd3, 0xe5, 0x5b, 0x6e,
0xaa, 0x1a, 0xb4, 0x11, 0x75, 0xe3, 0x13, 0x7a, 0xe7, 0x84, 0xde, 0xcd, 0x1d, 0x63, 0x6c, 0x71,
0xe3, 0x15, 0x48, 0x93, 0xc3, 0xfb, 0x25, 0x68, 0xc3, 0x1e, 0xd0, 0x1b, 0x8d, 0xc2, 0x77, 0x50,
0x9a, 0x42, 0x8a, 0x1a, 0x12, 0xb2, 0x47, 0xf6, 0x77, 0xf3, 0x6e, 0x78, 0x7b, 0x25, 0x6a, 0x60,
0x6f, 0xe8, 0x35, 0xb0, 0x25, 0x49, 0x67, 0x8f, 0xec, 0x77, 0x07, 0x87, 0x59, 0x8b, 0xa1, 0x33,
0xaf, 0x0b, 0xb3, 0x35, 0x65, 0x4f, 0xeb, 0xa5, 0x34, 0xd9, 0x6c, 0x4a, 0x37, 0x28, 0x35, 0xf4,
0xbe, 0x76, 0x28, 0xdb, 0xac, 0x64, 0x43, 0x4a, 0x5d, 0x6d, 0x61, 0x27, 0x74, 0xad, 0x76, 0x07,
0x69, 0x6c, 0x27, 0x8e, 0x9f, 0xbd, 0x8e, 0xe3, 0xe7, 0xbb, 0x2e, 0xdb, 0xc6, 0x6c, 0x46, 0x6f,
0x85, 0xd3, 0x15, 0x25, 0x4a, 0x03, 0x1f, 0xe2, 0x38, 0xcf, 0x5b, 0x8d, 0x73, 0xea, 0x19, 0x47,
0x1e, 0x91, 0xdf, 0xd4, 0x97, 0x62, 0x96, 0xd0, 0x9d, 0x1a, 0xb4, 0x16, 0x73, 0x48, 0xae, 0xb8,
0x45, 0xc6, 0x90, 0x9d, 0xd2, 0x9d, 0xa8, 0x7b, 0xd5, 0xe9, 0x0e, 0x5b, 0xe9, 0xba, 0x25, 0x44,
0xd5, 0x48, 0x1a, 0xfc, 0x26, 0xf4, 0xce, 0xda, 0x0e, 0x75, 0xe8, 0x8e, 0xfd, 0x24, 0xf4, 0xf6,
0xdf, 0xbb, 0x65, 0x2f, 0xff, 0xe1, 0x6e, 0x1b, 0x7e, 0x49, 0xc7, 0xff, 0x49, 0x09, 0x07, 0x3e,
0xfc, 0xfc, 0xe3, 0xd7, 0x79, 0x67, 0xd8, 0x7b, 0x72, 0x61, 0xe9, 0x8f, 0xeb, 0x36, 0x7c, 0x11,
0x02, 0xcd, 0x1f, 0x7d, 0xe2, 0xee, 0x88, 0xfa, 0xc0, 0xd3, 0x0f, 0xbc, 0x7b, 0x46, 0x5f, 0x08,
0xb5, 0x7f, 0x41, 0x9b, 0x6e, 0x46, 0xc9, 0x96, 0x5d, 0x9d, 0x58, 0xd7, 0x9c, 0x90, 0x6f, 0x9d,
0x87, 0xc7, 0x9e, 0x74, 0x64, 0x01, 0x7e, 0xdf, 0xf9, 0x05, 0xe1, 0xac, 0x3f, 0xb2, 0x84, 0xef,
0x31, 0x6b, 0xe2, 0xb2, 0x26, 0x97, 0xb3, 0x26, 0x67, 0x5e, 0x67, 0x7a, 0xdd, 0x59, 0xf1, 0xe9,
0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6e, 0x41, 0x88, 0xbe, 0x67, 0x04, 0x00, 0x00,
}
| peter-edge/pb | go/google/devtools/clouderrorreporting/v1beta1/report_errors_service.pb.go | GO | mit | 7,473 |
#
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
class Hhvm488 < Formula
desc "JIT compiler and runtime for the Hack language"
homepage "http://hhvm.com/"
head "https://github.com/facebook/hhvm.git"
url "https://dl.hhvm.com/source/hhvm-4.88.1.tar.gz"
sha256 "452d33db06a885a4e75ab3eb60ec349889a8d7ec6802ca3d6535df6a6f03d46a"
bottle do
rebuild 1
root_url "https://dl.hhvm.com/homebrew-bottles"
sha256 catalina: "f7ca1970535d06b7a7cd8d996663b2f7d0a52a44244738165a740727ed6e907e"
sha256 mojave: "2404994febe21238ec8f2db7473057fac845e18cc48e5b47533661d516a4d364"
end
option "with-debug", <<~EOS
Make an unoptimized build with assertions enabled. This will run PHP and
Hack code dramatically slower than a release build, and is suitable mostly
for debugging HHVM itself.
EOS
# Needs very recent xcode
depends_on :macos => :sierra
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "cmake" => :build
depends_on "dwarfutils"
depends_on "gawk" => :build
depends_on "libelf" => :build
depends_on "libtool" => :build
depends_on "md5sha1sum" => :build
depends_on "pkg-config" => :build
depends_on "wget" => :build
# We statically link against icu4c as every non-bugfix release is not
# backwards compatible; needing to rebuild for every release is too
# brittle
depends_on "icu4c" => :build
depends_on "boost"
depends_on "double-conversion"
depends_on "freetype"
depends_on "gd"
depends_on "gettext"
depends_on "glog"
depends_on "gmp"
depends_on "imagemagick@6"
depends_on "jemalloc"
depends_on "jpeg"
depends_on "libevent"
depends_on "libmemcached"
depends_on "libsodium"
depends_on "libpng"
depends_on "libxml2"
depends_on "libzip"
depends_on "lz4"
depends_on "mcrypt"
depends_on "oniguruma"
depends_on "openssl@1.1"
depends_on "pcre" # Used for Hack but not HHVM build - see #116
depends_on "postgresql"
depends_on "sqlite"
depends_on "tbb@2020"
depends_on "zstd"
def install
cmake_args = std_cmake_args + %W[
-DCMAKE_INSTALL_SYSCONFDIR=#{etc}
-DDEFAULT_CONFIG_DIR=#{etc}/hhvm
]
# Force use of bundled PCRE to workaround #116
cmake_args += %W[
-DSYSTEM_PCRE_HAS_JIT=0
]
# Features which don't work on OS X yet since they haven't been ported yet.
cmake_args += %W[
-DENABLE_MCROUTER=OFF
-DENABLE_EXTENSION_MCROUTER=OFF
-DENABLE_EXTENSION_IMAP=OFF
]
# Required to specify a socket path if you are using the bundled async SQL
# client (which is very strongly recommended).
cmake_args << "-DMYSQL_UNIX_SOCK_ADDR=/tmp/mysql.sock"
# LZ4 warning macros are currently incompatible with clang
cmake_args << "-DCMAKE_C_FLAGS=-DLZ4_DISABLE_DEPRECATE_WARNINGS=1"
cmake_args << "-DCMAKE_CXX_FLAGS=-DLZ4_DISABLE_DEPRECATE_WARNINGS=1 -DU_USING_ICU_NAMESPACE=1"
# Debug builds. This switch is all that's needed, it sets all the right
# cflags and other config changes.
if build.with? "debug"
cmake_args << "-DCMAKE_BUILD_TYPE=Debug"
else
cmake_args << "-DCMAKE_BUILD_TYPE=RelWithDebInfo"
end
# Statically link libICU
cmake_args += %W[
-DICU_INCLUDE_DIR=#{Formula["icu4c"].opt_include}
-DICU_I18N_LIBRARY=#{Formula["icu4c"].opt_lib}/libicui18n.a
-DICU_LIBRARY=#{Formula["icu4c"].opt_lib}/libicuuc.a
-DICU_DATA_LIBRARY=#{Formula["icu4c"].opt_lib}/libicudata.a
]
# TBB looks for itself in a different place than brew installs to.
ENV["TBB_ARCH_PLATFORM"] = "."
cmake_args += %W[
-DTBB_INCLUDE_DIR=#{Formula["tbb@2020"].opt_include}
-DTBB_INSTALL_DIR=#{Formula["tbb@2020"].opt_prefix}
-DTBB_LIBRARY=#{Formula["tbb@2020"].opt_lib}/libtbb.dylib
-DTBB_LIBRARY_DEBUG=#{Formula["tbb@2020"].opt_lib}/libtbb.dylib
-DTBB_LIBRARY_DIR=#{Formula["tbb@2020"].opt_lib}
-DTBB_MALLOC_LIBRARY=#{Formula["tbb@2020"].opt_lib}/libtbbmalloc.dylib
-DTBB_MALLOC_LIBRARY_DEBUG=#{Formula["tbb@2020"].opt_lib}/libtbbmalloc.dylib
]
system "cmake", *cmake_args, '.'
system "make"
system "make", "install"
tp_notices = (share/"doc/third_party_notices.txt")
(share/"doc").install "third-party/third_party_notices.txt"
(share/"doc/third_party_notices.txt").append_lines <<EOF
-----
The following software may be included in this product: icu4c. This Software contains the following license and notice below:
Unicode Data Files include all data files under the directories
http://www.unicode.org/Public/, http://www.unicode.org/reports/,
http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and
http://www.unicode.org/utility/trac/browser/.
Unicode Data Files do not include PDF online code charts under the
directory http://www.unicode.org/Public/.
Software includes any source code published in the Unicode Standard
or under the directories
http://www.unicode.org/Public/, http://www.unicode.org/reports/,
http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and
http://www.unicode.org/utility/trac/browser/.
NOTICE TO USER: Carefully read the following legal agreement.
BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
TERMS AND CONDITIONS OF THIS AGREEMENT.
IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
THE DATA FILES OR SOFTWARE.
COPYRIGHT AND PERMISSION NOTICE
Copyright © 1991-2017 Unicode, Inc. All rights reserved.
Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Unicode data files and any associated documentation
(the "Data Files") or Unicode software and any associated documentation
(the "Software") to deal in the Data Files or Software
without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, and/or sell copies of
the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that either
(a) this copyright and permission notice appear with all copies
of the Data Files or Software, or
(b) this copyright and permission notice appear in associated
Documentation.
THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL 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 THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in these Data Files or Software without prior
written authorization of the copyright holder.
EOF
ini = etc/"hhvm"
(ini/"php.ini").write php_ini unless File.exist? (ini/"php.ini")
(ini/"server.ini").write server_ini unless File.exist? (ini/"server.ini")
end
test do
(testpath/"test.php").write <<~EOS
<?php
exit(is_integer(HHVM_VERSION_ID) ? 0 : 1);
EOS
system "#{bin}/hhvm", testpath/"test.php"
end
plist_options :manual => "hhvm -m daemon -c #{HOMEBREW_PREFIX}/etc/hhvm/php.ini -c #{HOMEBREW_PREFIX}/etc/hhvm/server.ini"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/hhvm</string>
<string>-m</string>
<string>server</string>
<string>-c</string>
<string>#{etc}/hhvm/php.ini</string>
<string>-c</string>
<string>#{etc}/hhvm/server.ini</string>
</array>
<key>WorkingDirectory</key>
<string>#{HOMEBREW_PREFIX}</string>
</dict>
</plist>
EOS
end
# https://github.com/hhvm/packaging/blob/master/hhvm/deb/skeleton/etc/hhvm/php.ini
def php_ini
<<~EOS
; php options
session.save_handler = files
session.save_path = #{var}/lib/hhvm/sessions
session.gc_maxlifetime = 1440
; hhvm specific
hhvm.log.always_log_unhandled_exceptions = true
hhvm.log.runtime_error_reporting_level = 8191
hhvm.mysql.typed_results = false
EOS
end
# https://github.com/hhvm/packaging/blob/master/hhvm/deb/skeleton/etc/hhvm/server.ini
def server_ini
<<~EOS
; php options
pid = #{var}/run/hhvm/pid
; hhvm specific
hhvm.server.port = 9000
hhvm.server.default_document = index.php
hhvm.log.use_log_file = true
hhvm.log.file = #{var}/log/hhvm/error.log
hhvm.repo.central.path = #{var}/run/hhvm/hhvm.hhbc
EOS
end
end
| hhvm/homebrew-hhvm | Formula/hhvm-4.88.rb | Ruby | mit | 9,629 |
# frozen_string_literal: true
FactoryBot.define do
factory :access_procedure, class: "Renalware::Accesses::Procedure" do
type { create(:access_type) }
side { :right }
performed_on { Time.zone.today }
end
end
| airslie/renalware-core | spec/factories/accesses/procedures.rb | Ruby | mit | 225 |
module.exports = function (grunt) {
"use strict";
require('matchdep').filterDev("grunt-*").forEach(grunt.loadNpmTasks);
//grunt.option('verbose', true);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
compass: {
prod: {
options: {
sassDir: 'frontend/sass',
cssDir: 'backend/public/css',
fontsDir: '/fonts',
outputStyle: 'compressed',
noLineComments: true,
environment: 'production',
force: true,
specify: 'frontend/sass/main.sass'
}
},
dev: {
options: {
sassDir: 'frontend/sass',
cssDir: 'backend/public/css',
fontsDir: '/fonts',
outputStyle: 'expanded',
noLineComments: false,
environment: 'development',
force: true,
specify: 'frontend/sass/main.sass'
}
}
},
requirejs: {
compile: {
options: {
baseUrl: "frontend/js",
mainConfigFile: "frontend/js/require.config.js",
include: 'application',
name: 'almond',
out: "backend/public/js/main.js",
fileExclusionRegExp: /^\.|node_modules|Gruntfile|\.md|package.json/,
almond: true,
wrapShim: true,
wrap: true,
optimize: "none"
}
}
},
uglify: {
options: {
mangle: {
mangleProperties: true,
reserveDOMCache: true
},
compress: {
drop_console: true
}
},
target: {
files: {
'backend/public/js/main.js': ['backend/public/js/main.js']
}
}
},
jshint: {
files: [
'Gruntfile.js',
'frontend/js/**/*.js',
'!frontend/js/vendor/**/*.js'
],
options: {
curly: true,
eqeqeq: true,
latedef: true,
noarg: true,
undef: true,
boss: true,
eqnull: true,
browser: true,
globals: {
console: true,
require: true,
requirejs: true,
define: true,
module: true
},
'-W030': false, /* allow one line expressions */
'-W014': false /* allow breaking of '? :' */
}
},
watch: {
js: {
files: [
'frontend/js/**/*.js',
'frontend/js/**/*.html'
],
tasks: ['requirejs']
},
css: {
files: [
'frontend/sass/**/*.sass',
'frontend/sass/**/*.scss'
],
tasks: ['compass:dev']
}
},
mocha: {
index: ['frontend/tests/test-runner.html']
}
});
grunt.registerTask('default', [
'jshint',
'compass:dev',
'requirejs'
]);
grunt.registerTask('release', [
'compass:prod',
'requirejs',
'uglify'
]);
};
| dbondus/code-samples | js/2015-chat-application/Gruntfile.js | JavaScript | mit | 3,745 |
const fs = require('fs');
const de = require('./locale/de.json');
const en = require('./locale/en.json');
const esMX = require('./locale/esMX.json');
const es = require('./locale/es.json');
const fr = require('./locale/fr.json');
const it = require('./locale/it.json');
const ja = require('./locale/ja.json');
const ko = require('./locale/ko.json');
const pl = require('./locale/pl.json');
const ptBR = require('./locale/ptBR.json');
const ru = require('./locale/ru.json');
const zhCHS = require('./locale/zhCHS.json');
const zhCHT = require('./locale/zhCHT.json');
function getI18nKey(key) {
let key1 = key.split('.')[0];
let key2 = key.split('.')[1];
return ` en: "${en[key1][key2]}",
de: "${de[key1]?.[key2] ?? en[key1][key2]}",
es: "${es[key1]?.[key2] ?? en[key1][key2]}",
'es-mx': "${esMX[key1]?.[key2] ?? en[key1][key2]}",
fr: "${fr[key1]?.[key2] ?? en[key1][key2]}",
it: "${it[key1]?.[key2] ?? en[key1][key2]}",
ja: "${ja[key1]?.[key2] ?? en[key1][key2]}",
ko: "${ko[key1]?.[key2] ?? en[key1][key2]}",
pl: "${pl[key1]?.[key2] ?? en[key1][key2]}",
'pt-br': "${ptBR[key1]?.[key2] ?? en[key1][key2]}",
ru: "${ru[key1]?.[key2] ?? en[key1][key2]}",
'zh-chs': "${zhCHS[key1]?.[key2] ?? en[key1][key2]}",
'zh-cht': "${zhCHT[key1]?.[key2] ?? en[key1][key2]}",\n};\n`;
}
var browserCheckUtils = `export const supportedLanguages = [
'en',
'de',
'es',
'es-mx',
'fr',
'it',
'ja',
'ko',
'pl',
'pt-br',
'ru',
'zh-chs',
'zh-cht',
];
export const unsupported = {
${getI18nKey('Browsercheck.Unsupported')}
export const steamBrowser = {
${getI18nKey('Browsercheck.Steam')}`;
fs.writeFile('src/browsercheck-utils.js', browserCheckUtils, (err) => {
if (err) {
// console.log(err);
}
});
| DestinyItemManager/DIM | src/build-browsercheck-utils.js | JavaScript | mit | 1,744 |
module Omnitest
class Psychic
module Execution
class TokenStrategy < DefaultStrategy
def execute(*extra_args)
template = File.read(absolute_file)
# Default token pattern/replacement (used by php-opencloud) should be configurable
token_handler = Tokens::RegexpTokenHandler.new(template, /["']\{(\w+)\}(["'])/, '\2\1\2')
confirm_or_update_parameters(token_handler.tokens)
content = token_handler.render(script.params)
temporarily_overwrite(absolute_file, content) do
super(*extra_args)
end
end
private
def temporarily_overwrite(file, content)
backup_file = "#{file}.bak"
logger.info("Temporarily replacing tokens in #{file} with actual values")
FileUtils.cp(file, backup_file)
File.write(file, content)
yield
ensure
if File.exist? backup_file
logger.info("Restoring #{file}")
FileUtils.mv(backup_file, absolute_file)
end
end
def logger
psychic.logger
end
def file
script.source_file
end
def absolute_file
script.absolute_source_file
end
def backup_file
"#{absolute_file}.bak"
end
def should_restore?(file, orig, timing = :before)
return true if [timing, 'always']. include? opts[:restore_mode]
if interactive?
cli.yes? "Would you like to #{file} to #{orig} before running the script?"
end
end
def backup_and_overwrite(file)
backup_file = "#{file}.bak"
if File.exist? backup_file
if should_restore?(backup_file, file)
FileUtils.mv(backup_file, file)
else
fail 'Please clear out old backups before rerunning' if File.exist? backup_file
end
end
FileUtils.cp(file, backup_file)
end
end
end
end
end
| omnitest/psychic | lib/omnitest/psychic/execution/token_strategy.rb | Ruby | mit | 2,030 |
/*
html2canvas 0.5.0-alpha2 <http://html2canvas.hertzen.com>
Copyright (c) 2015 Niklas von Hertzen
Released under MIT License
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.html2canvas=e()}}(function(){var define,module,exports;return (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(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 2.0.1
*/
(function() {
"use strict";
function $$utils$$objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
function $$utils$$isFunction(x) {
return typeof x === 'function';
}
function $$utils$$isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var $$utils$$_isArray;
if (!Array.isArray) {
$$utils$$_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
$$utils$$_isArray = Array.isArray;
}
var $$utils$$isArray = $$utils$$_isArray;
var $$utils$$now = Date.now || function() { return new Date().getTime(); };
function $$utils$$F() { }
var $$utils$$o_create = (Object.create || function (o) {
if (arguments.length > 1) {
throw new Error('Second argument not supported');
}
if (typeof o !== 'object') {
throw new TypeError('Argument must be an object');
}
$$utils$$F.prototype = o;
return new $$utils$$F();
});
var $$asap$$len = 0;
var $$asap$$default = function asap(callback, arg) {
$$asap$$queue[$$asap$$len] = callback;
$$asap$$queue[$$asap$$len + 1] = arg;
$$asap$$len += 2;
if ($$asap$$len === 2) {
// If len is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
$$asap$$scheduleFlush();
}
};
var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {};
var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver;
// test for web worker but not in IE10
var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function $$asap$$useNextTick() {
return function() {
process.nextTick($$asap$$flush);
};
}
function $$asap$$useMutationObserver() {
var iterations = 0;
var observer = new $$asap$$BrowserMutationObserver($$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function $$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = $$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function $$asap$$useSetTimeout() {
return function() {
setTimeout($$asap$$flush, 1);
};
}
var $$asap$$queue = new Array(1000);
function $$asap$$flush() {
for (var i = 0; i < $$asap$$len; i+=2) {
var callback = $$asap$$queue[i];
var arg = $$asap$$queue[i+1];
callback(arg);
$$asap$$queue[i] = undefined;
$$asap$$queue[i+1] = undefined;
}
$$asap$$len = 0;
}
var $$asap$$scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
$$asap$$scheduleFlush = $$asap$$useNextTick();
} else if ($$asap$$BrowserMutationObserver) {
$$asap$$scheduleFlush = $$asap$$useMutationObserver();
} else if ($$asap$$isWorker) {
$$asap$$scheduleFlush = $$asap$$useMessageChannel();
} else {
$$asap$$scheduleFlush = $$asap$$useSetTimeout();
}
function $$$internal$$noop() {}
var $$$internal$$PENDING = void 0;
var $$$internal$$FULFILLED = 1;
var $$$internal$$REJECTED = 2;
var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$selfFullfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function $$$internal$$cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.')
}
function $$$internal$$getThen(promise) {
try {
return promise.then;
} catch(error) {
$$$internal$$GET_THEN_ERROR.error = error;
return $$$internal$$GET_THEN_ERROR;
}
}
function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function $$$internal$$handleForeignThenable(promise, thenable, then) {
$$asap$$default(function(promise) {
var sealed = false;
var error = $$$internal$$tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
$$$internal$$resolve(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
$$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
$$$internal$$reject(promise, error);
}
}, promise);
}
function $$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, thenable._result);
} else if (promise._state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, thenable._result);
} else {
$$$internal$$subscribe(thenable, undefined, function(value) {
$$$internal$$resolve(promise, value);
}, function(reason) {
$$$internal$$reject(promise, reason);
});
}
}
function $$$internal$$handleMaybeThenable(promise, maybeThenable) {
if (maybeThenable.constructor === promise.constructor) {
$$$internal$$handleOwnThenable(promise, maybeThenable);
} else {
var then = $$$internal$$getThen(maybeThenable);
if (then === $$$internal$$GET_THEN_ERROR) {
$$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error);
} else if (then === undefined) {
$$$internal$$fulfill(promise, maybeThenable);
} else if ($$utils$$isFunction(then)) {
$$$internal$$handleForeignThenable(promise, maybeThenable, then);
} else {
$$$internal$$fulfill(promise, maybeThenable);
}
}
}
function $$$internal$$resolve(promise, value) {
if (promise === value) {
$$$internal$$reject(promise, $$$internal$$selfFullfillment());
} else if ($$utils$$objectOrFunction(value)) {
$$$internal$$handleMaybeThenable(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}
function $$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
$$$internal$$publish(promise);
}
function $$$internal$$fulfill(promise, value) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._result = value;
promise._state = $$$internal$$FULFILLED;
if (promise._subscribers.length === 0) {
} else {
$$asap$$default($$$internal$$publish, promise);
}
}
function $$$internal$$reject(promise, reason) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._state = $$$internal$$REJECTED;
promise._result = reason;
$$asap$$default($$$internal$$publishRejection, promise);
}
function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + $$$internal$$FULFILLED] = onFulfillment;
subscribers[length + $$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
$$asap$$default($$$internal$$publish, parent);
}
}
function $$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
$$$internal$$invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function $$$internal$$ErrorObject() {
this.error = null;
}
var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
$$$internal$$TRY_CATCH_ERROR.error = e;
return $$$internal$$TRY_CATCH_ERROR;
}
}
function $$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = $$utils$$isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = $$$internal$$tryCatch(callback, detail);
if (value === $$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
$$$internal$$reject(promise, $$$internal$$cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== $$$internal$$PENDING) {
// noop
} else if (hasCallback && succeeded) {
$$$internal$$resolve(promise, value);
} else if (failed) {
$$$internal$$reject(promise, error);
} else if (settled === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, value);
} else if (settled === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
}
}
function $$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
$$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
$$$internal$$reject(promise, reason);
});
} catch(e) {
$$$internal$$reject(promise, e);
}
}
function $$$enumerator$$makeSettledResult(state, position, value) {
if (state === $$$internal$$FULFILLED) {
return {
state: 'fulfilled',
value: value
};
} else {
return {
state: 'rejected',
reason: value
};
}
}
function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) {
this._instanceConstructor = Constructor;
this.promise = new Constructor($$$internal$$noop, label);
this._abortOnReject = abortOnReject;
if (this._validateInput(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._init();
if (this.length === 0) {
$$$internal$$fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
$$$internal$$fulfill(this.promise, this._result);
}
}
} else {
$$$internal$$reject(this.promise, this._validationError());
}
}
$$$enumerator$$Enumerator.prototype._validateInput = function(input) {
return $$utils$$isArray(input);
};
$$$enumerator$$Enumerator.prototype._validationError = function() {
return new Error('Array Methods must be provided an Array');
};
$$$enumerator$$Enumerator.prototype._init = function() {
this._result = new Array(this.length);
};
var $$$enumerator$$default = $$$enumerator$$Enumerator;
$$$enumerator$$Enumerator.prototype._enumerate = function() {
var length = this.length;
var promise = this.promise;
var input = this._input;
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
this._eachEntry(input[i], i);
}
};
$$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
var c = this._instanceConstructor;
if ($$utils$$isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== $$$internal$$PENDING) {
entry._onerror = null;
this._settledAt(entry._state, i, entry._result);
} else {
this._willSettleAt(c.resolve(entry), i);
}
} else {
this._remaining--;
this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry);
}
};
$$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
var promise = this.promise;
if (promise._state === $$$internal$$PENDING) {
this._remaining--;
if (this._abortOnReject && state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
} else {
this._result[i] = this._makeResult(state, i, value);
}
}
if (this._remaining === 0) {
$$$internal$$fulfill(promise, this._result);
}
};
$$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) {
return value;
};
$$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
$$$internal$$subscribe(promise, undefined, function(value) {
enumerator._settledAt($$$internal$$FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt($$$internal$$REJECTED, i, reason);
});
};
var $$promise$all$$default = function all(entries, label) {
return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise;
};
var $$promise$race$$default = function race(entries, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
if (!$$utils$$isArray(entries)) {
$$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
$$$internal$$resolve(promise, value);
}
function onRejection(reason) {
$$$internal$$reject(promise, reason);
}
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
$$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
};
var $$promise$resolve$$default = function resolve(object, label) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$resolve(promise, object);
return promise;
};
var $$promise$reject$$default = function reject(reason, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$reject(promise, reason);
return promise;
};
var $$es6$promise$promise$$counter = 0;
function $$es6$promise$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function $$es6$promise$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise’s eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function $$es6$promise$promise$$Promise(resolver) {
this._id = $$es6$promise$promise$$counter++;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
if ($$$internal$$noop !== resolver) {
if (!$$utils$$isFunction(resolver)) {
$$es6$promise$promise$$needsResolver();
}
if (!(this instanceof $$es6$promise$promise$$Promise)) {
$$es6$promise$promise$$needsNew();
}
$$$internal$$initializePromise(this, resolver);
}
}
$$es6$promise$promise$$Promise.all = $$promise$all$$default;
$$es6$promise$promise$$Promise.race = $$promise$race$$default;
$$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default;
$$es6$promise$promise$$Promise.reject = $$promise$reject$$default;
$$es6$promise$promise$$Promise.prototype = {
constructor: $$es6$promise$promise$$Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: function(onFulfillment, onRejection) {
var parent = this;
var state = parent._state;
if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) {
return this;
}
var child = new this.constructor($$$internal$$noop);
var result = parent._result;
if (state) {
var callback = arguments[state - 1];
$$asap$$default(function(){
$$$internal$$invokeCallback(state, child, callback, result);
});
} else {
$$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
},
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
var $$es6$promise$polyfill$$default = function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return $$utils$$isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = $$es6$promise$promise$$default;
}
};
var es6$promise$umd$$ES6Promise = {
'Promise': $$es6$promise$promise$$default,
'polyfill': $$es6$promise$polyfill$$default
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return es6$promise$umd$$ES6Promise; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = es6$promise$umd$$ES6Promise;
} else if (typeof this !== 'undefined') {
this['ES6Promise'] = es6$promise$umd$$ES6Promise;
}
}).call(this);
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":2}],2:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],3:[function(require,module,exports){
(function (global){
/*! http://mths.be/punycode v1.2.4 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports;
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
while (length--) {
array[length] = fn(array[length]);
}
return array;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings.
* @private
* @param {String} domain The domain name.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
return map(string.split(regexSeparators), fn).join('.');
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* http://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols to a Punycode string of ASCII-only
* symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name to Unicode. Only the
* Punycoded parts of the domain name will be converted, i.e. it doesn't
* matter if you call it on a string that has already been converted to
* Unicode.
* @memberOf punycode
* @param {String} domain The Punycode domain name to convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name to Punycode. Only the
* non-ASCII parts of the domain name will be converted, i.e. it doesn't
* matter if you call it with a domain that's already in ASCII.
* @memberOf punycode
* @param {String} domain The domain name to convert, as a Unicode string.
* @returns {String} The Punycode representation of the given domain name.
*/
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.2.4',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = punycode;
} else { // in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else { // in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],4:[function(require,module,exports){
var log = require('./log');
var Promise = require('./promise');
function restoreOwnerScroll(ownerDocument, x, y) {
if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
ownerDocument.defaultView.scrollTo(x, y);
}
}
function cloneCanvasContents(canvas, clonedCanvas) {
try {
if (clonedCanvas) {
clonedCanvas.width = canvas.width;
clonedCanvas.height = canvas.height;
clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
}
} catch(e) {
log("Unable to copy canvas content from", canvas, e);
}
}
function cloneNode(node, javascriptEnabled) {
var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
var child = node.firstChild;
while(child) {
if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
clone.appendChild(cloneNode(child, javascriptEnabled));
}
child = child.nextSibling;
}
if (node.nodeType === 1) {
clone._scrollTop = node.scrollTop;
clone._scrollLeft = node.scrollLeft;
if (node.nodeName === "CANVAS") {
cloneCanvasContents(node, clone);
} else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
clone.value = node.value;
}
}
return clone;
}
function initNode(node) {
if (node.nodeType === 1) {
node.scrollTop = node._scrollTop;
node.scrollLeft = node._scrollLeft;
var child = node.firstChild;
while(child) {
initNode(child);
child = child.nextSibling;
}
}
}
module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
var container = containerDocument.createElement("iframe");
container.className = "html2canvas-container";
container.style.visibility = "hidden";
container.style.position = "fixed";
container.style.left = "-10000px";
container.style.top = "0px";
container.style.border = "0";
container.width = width;
container.height = height;
container.scrolling = "no"; // ios won't scroll without it
containerDocument.body.appendChild(container);
return new Promise(function(resolve) {
var documentClone = container.contentWindow.document;
/* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
if window url is about:blank, we can assign the url to current by writing onto the document
*/
container.contentWindow.onload = container.onload = function() {
var interval = setInterval(function() {
if (documentClone.body.childNodes.length > 0) {
initNode(documentClone.documentElement);
clearInterval(interval);
if (options.type === "view") {
container.contentWindow.scrollTo(x, y);
if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
documentClone.documentElement.style.top = (-y) + "px";
documentClone.documentElement.style.left = (-x) + "px";
documentClone.documentElement.style.position = 'absolute';
}
}
resolve(container);
}
}, 50);
};
documentClone.open();
documentClone.write("<!DOCTYPE html><html></html>");
// Chrome scrolls the parent document for some reason after the write to the cloned window???
restoreOwnerScroll(ownerDocument, x, y);
documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
documentClone.close();
});
};
},{"./log":15,"./promise":18}],5:[function(require,module,exports){
// http://dev.w3.org/csswg/css-color/
function Color(value) {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = null;
var result = this.fromArray(value) ||
this.namedColor(value) ||
this.rgb(value) ||
this.rgba(value) ||
this.hex6(value) ||
this.hex3(value);
}
Color.prototype.darken = function(amount) {
var a = 1 - amount;
return new Color([
Math.round(this.r * a),
Math.round(this.g * a),
Math.round(this.b * a),
this.a
]);
};
Color.prototype.isTransparent = function() {
return this.a === 0;
};
Color.prototype.isBlack = function() {
return this.r === 0 && this.g === 0 && this.b === 0;
};
Color.prototype.fromArray = function(array) {
if (Array.isArray(array)) {
this.r = Math.min(array[0], 255);
this.g = Math.min(array[1], 255);
this.b = Math.min(array[2], 255);
if (array.length > 3) {
this.a = array[3];
}
}
return (Array.isArray(array));
};
var _hex3 = /^#([a-f0-9]{3})$/i;
Color.prototype.hex3 = function(value) {
var match = null;
if ((match = value.match(_hex3)) !== null) {
this.r = parseInt(match[1][0] + match[1][0], 16);
this.g = parseInt(match[1][1] + match[1][1], 16);
this.b = parseInt(match[1][2] + match[1][2], 16);
}
return match !== null;
};
var _hex6 = /^#([a-f0-9]{6})$/i;
Color.prototype.hex6 = function(value) {
var match = null;
if ((match = value.match(_hex6)) !== null) {
this.r = parseInt(match[1].substring(0, 2), 16);
this.g = parseInt(match[1].substring(2, 4), 16);
this.b = parseInt(match[1].substring(4, 6), 16);
}
return match !== null;
};
var _rgb = /^rgb\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})\)$/;
Color.prototype.rgb = function(value) {
var match = null;
if ((match = value.match(_rgb)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
}
return match !== null;
};
var _rgba = /^rgba\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3}) *, *(\d+\.?\d*)\)$/;
Color.prototype.rgba = function(value) {
var match = null;
if ((match = value.match(_rgba)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
this.a = Number(match[4]);
}
return match !== null;
};
Color.prototype.toString = function() {
return this.a !== null && this.a !== 1 ?
"rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
"rgb(" + [this.r, this.g, this.b].join(",") + ")";
};
Color.prototype.namedColor = function(value) {
var color = colors[value.toLowerCase()];
if (color) {
this.r = color[0];
this.g = color[1];
this.b = color[2];
} else if (value.toLowerCase() === "transparent") {
this.r = this.g = this.b = this.a = 0;
return true;
}
return !!color;
};
Color.prototype.isColor = true;
// JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
var colors = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
module.exports = Color;
},{}],6:[function(require,module,exports){
var Promise = require('./promise');
var Support = require('./support');
var CanvasRenderer = require('./renderers/canvas');
var ImageLoader = require('./imageloader');
var NodeParser = require('./nodeparser');
var NodeContainer = require('./nodecontainer');
var log = require('./log');
var utils = require('./utils');
var createWindowClone = require('./clone');
var loadUrlDocument = require('./proxy').loadUrlDocument;
var getBounds = utils.getBounds;
var html2canvasNodeAttribute = "data-html2canvas-node";
var html2canvasCloneIndex = 0;
function html2canvas(nodeList, options) {
var index = html2canvasCloneIndex++;
options = options || {};
if (options.logging) {
window.html2canvas.logging = true;
window.html2canvas.start = Date.now();
window.html2canvas.logmessage = '';
}
options.async = typeof(options.async) === "undefined" ? true : options.async;
options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
options.strict = !!options.strict;
if (typeof(nodeList) === "string") {
if (typeof(options.proxy) !== "string") {
return Promise.reject("Proxy must be used when rendering url");
}
var width = options.width != null ? options.width : window.innerWidth;
var height = options.height != null ? options.height : window.innerHeight;
return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
});
}
var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
node.setAttribute(html2canvasNodeAttribute + index, index);
return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
if (typeof(options.onrendered) === "function") {
log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
options.onrendered(canvas);
}
return canvas;
});
}
html2canvas.Promise = Promise;
html2canvas.CanvasRenderer = CanvasRenderer;
html2canvas.NodeContainer = NodeContainer;
html2canvas.log = log;
html2canvas.utils = utils;
module.exports = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
return Promise.reject("No canvas support");
} : html2canvas;
function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
log("Document cloned");
var attributeName = html2canvasNodeAttribute + html2canvasIndex;
var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
document.querySelector(selector).removeAttribute(attributeName);
var clonedWindow = container.contentWindow;
var node = clonedWindow.document.querySelector(selector);
var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
return oncloneHandler.then(function() {
return renderWindow(node, container, options, windowWidth, windowHeight);
});
});
}
function renderWindow(node, container, options, windowWidth, windowHeight) {
var clonedWindow = container.contentWindow;
var support = new Support(clonedWindow.document);
var imageLoader = new ImageLoader(options, support);
var bounds = getBounds(node);
var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
var renderer = new options.renderer(width, height, imageLoader, options, document);
var parser = new NodeParser(node, renderer, support, imageLoader, options);
return parser.ready.then(function() {
log("Finished rendering");
var canvas;
if (options.type === "view") {
canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
} else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
canvas = renderer.canvas;
} else {
canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: clonedWindow.pageXOffset, y: clonedWindow.pageYOffset});
}
cleanupContainer(container, options);
return canvas;
});
}
function cleanupContainer(container, options) {
if (options.removeContainer) {
container.parentNode.removeChild(container);
log("Cleaned up container");
}
}
function crop(canvas, bounds) {
var croppedCanvas = document.createElement("canvas");
var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
croppedCanvas.width = bounds.width;
croppedCanvas.height = bounds.height;
log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", (x2-x1), "height:", (y2-y1));
log("Resulting crop with width", bounds.width, "and height", bounds.height, " with x", x1, "and y", y1);
croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, x2-x1, y2-y1, bounds.x, bounds.y, x2-x1, y2-y1);
return croppedCanvas;
}
function documentWidth (doc) {
return Math.max(
Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
);
}
function documentHeight (doc) {
return Math.max(
Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
);
}
function absoluteUrl(url) {
var link = document.createElement("a");
link.href = url;
link.href = link.href;
return link;
}
},{"./clone":4,"./imageloader":13,"./log":15,"./nodecontainer":16,"./nodeparser":17,"./promise":18,"./proxy":19,"./renderers/canvas":23,"./support":25,"./utils":29}],7:[function(require,module,exports){
var Promise = require('./promise');
var log = require('./log');
var smallImage = require('./utils').smallImage;
function DummyImageContainer(src) {
this.src = src;
log("DummyImageContainer for", src);
if (!this.promise || !this.image) {
log("Initiating DummyImageContainer");
DummyImageContainer.prototype.image = new Image();
var image = this.image;
DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
image.onload = resolve;
image.onerror = reject;
image.src = smallImage();
if (image.complete === true) {
resolve(image);
}
});
}
}
module.exports = DummyImageContainer;
},{"./log":15,"./promise":18,"./utils":29}],8:[function(require,module,exports){
var smallImage = require('./utils').smallImage;
function Font(family, size) {
var container = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span'),
sampleText = 'Hidden Text',
baseline,
middle;
container.style.visibility = "hidden";
container.style.fontFamily = family;
container.style.fontSize = size;
container.style.margin = 0;
container.style.padding = 0;
document.body.appendChild(container);
img.src = smallImage();
img.width = 1;
img.height = 1;
img.style.margin = 0;
img.style.padding = 0;
img.style.verticalAlign = "baseline";
span.style.fontFamily = family;
span.style.fontSize = size;
span.style.margin = 0;
span.style.padding = 0;
span.appendChild(document.createTextNode(sampleText));
container.appendChild(span);
container.appendChild(img);
baseline = (img.offsetTop - span.offsetTop) + 1;
container.removeChild(span);
container.appendChild(document.createTextNode(sampleText));
container.style.lineHeight = "normal";
img.style.verticalAlign = "super";
middle = (img.offsetTop-container.offsetTop) + 1;
document.body.removeChild(container);
this.baseline = baseline;
this.lineWidth = 1;
this.middle = middle;
}
module.exports = Font;
},{"./utils":29}],9:[function(require,module,exports){
var Font = require('./font');
function FontMetrics() {
this.data = {};
}
FontMetrics.prototype.getMetrics = function(family, size) {
if (this.data[family + "-" + size] === undefined) {
this.data[family + "-" + size] = new Font(family, size);
}
return this.data[family + "-" + size];
};
module.exports = FontMetrics;
},{"./font":8}],10:[function(require,module,exports){
var utils = require('./utils');
var Promise = require('./promise');
var getBounds = utils.getBounds;
var loadUrlDocument = require('./proxy').loadUrlDocument;
function FrameContainer(container, sameOrigin, options) {
this.image = null;
this.src = container;
var self = this;
var bounds = getBounds(container);
this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
container.contentWindow.onload = container.onload = function() {
resolve(container);
};
} else {
resolve(container);
}
})).then(function(container) {
var html2canvas = require('./core');
return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
}).then(function(canvas) {
return self.image = canvas;
});
}
FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
var container = this.src;
return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
};
module.exports = FrameContainer;
},{"./core":6,"./promise":18,"./proxy":19,"./utils":29}],11:[function(require,module,exports){
var Promise = require('./promise');
function GradientContainer(imageData) {
this.src = imageData.value;
this.colorStops = [];
this.type = null;
this.x0 = 0.5;
this.y0 = 0.5;
this.x1 = 0.5;
this.y1 = 0.5;
this.promise = Promise.resolve(true);
}
GradientContainer.prototype.TYPES = {
LINEAR: 1,
RADIAL: 2
};
module.exports = GradientContainer;
},{"./promise":18}],12:[function(require,module,exports){
var Promise = require('./promise');
function ImageContainer(src, cors) {
this.src = src;
this.image = new Image();
var self = this;
this.tainted = null;
this.promise = new Promise(function(resolve, reject) {
self.image.onload = resolve;
self.image.onerror = reject;
if (cors) {
self.image.crossOrigin = "anonymous";
}
self.image.src = src;
if (self.image.complete === true) {
resolve(self.image);
}
});
}
module.exports = ImageContainer;
},{"./promise":18}],13:[function(require,module,exports){
var Promise = require('./promise');
var log = require('./log');
var ImageContainer = require('./imagecontainer');
var DummyImageContainer = require('./dummyimagecontainer');
var ProxyImageContainer = require('./proxyimagecontainer');
var FrameContainer = require('./framecontainer');
var SVGContainer = require('./svgcontainer');
var SVGNodeContainer = require('./svgnodecontainer');
var LinearGradientContainer = require('./lineargradientcontainer');
var WebkitGradientContainer = require('./webkitgradientcontainer');
var bind = require('./utils').bind;
function ImageLoader(options, support) {
this.link = null;
this.options = options;
this.support = support;
this.origin = this.getOrigin(window.location.href);
}
ImageLoader.prototype.findImages = function(nodes) {
var images = [];
nodes.reduce(function(imageNodes, container) {
switch(container.node.nodeName) {
case "IMG":
return imageNodes.concat([{
args: [container.node.src],
method: "url"
}]);
case "svg":
case "IFRAME":
return imageNodes.concat([{
args: [container.node],
method: container.node.nodeName
}]);
}
return imageNodes;
}, []).forEach(this.addImage(images, this.loadImage), this);
return images;
};
ImageLoader.prototype.findBackgroundImage = function(images, container) {
container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
return images;
};
ImageLoader.prototype.addImage = function(images, callback) {
return function(newImage) {
newImage.args.forEach(function(image) {
if (!this.imageExists(images, image)) {
images.splice(0, 0, callback.call(this, newImage));
log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
}
}, this);
};
};
ImageLoader.prototype.hasImageBackground = function(imageData) {
return imageData.method !== "none";
};
ImageLoader.prototype.loadImage = function(imageData) {
if (imageData.method === "url") {
var src = imageData.args[0];
if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
return new SVGContainer(src);
} else if (src.match(/data:image\/.*;base64,/i)) {
return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
} else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
return new ImageContainer(src, false);
} else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
return new ImageContainer(src, true);
} else if (this.options.proxy) {
return new ProxyImageContainer(src, this.options.proxy);
} else {
return new DummyImageContainer(src);
}
} else if (imageData.method === "linear-gradient") {
return new LinearGradientContainer(imageData);
} else if (imageData.method === "gradient") {
return new WebkitGradientContainer(imageData);
} else if (imageData.method === "svg") {
return new SVGNodeContainer(imageData.args[0], this.support.svg);
} else if (imageData.method === "IFRAME") {
return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
} else {
return new DummyImageContainer(imageData);
}
};
ImageLoader.prototype.isSVG = function(src) {
return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
};
ImageLoader.prototype.imageExists = function(images, src) {
return images.some(function(image) {
return image.src === src;
});
};
ImageLoader.prototype.isSameOrigin = function(url) {
return (this.getOrigin(url) === this.origin);
};
ImageLoader.prototype.getOrigin = function(url) {
var link = this.link || (this.link = document.createElement("a"));
link.href = url;
link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
return link.protocol + link.hostname + link.port;
};
ImageLoader.prototype.getPromise = function(container) {
return this.timeout(container, this.options.imageTimeout)['catch'](function() {
var dummy = new DummyImageContainer(container.src);
return dummy.promise.then(function(image) {
container.image = image;
});
});
};
ImageLoader.prototype.get = function(src) {
var found = null;
return this.images.some(function(img) {
return (found = img).src === src;
}) ? found : null;
};
ImageLoader.prototype.fetch = function(nodes) {
this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
this.images.forEach(function(image, index) {
image.promise.then(function() {
log("Succesfully loaded image #"+ (index+1), image);
}, function(e) {
log("Failed loading image #"+ (index+1), image, e);
});
});
this.ready = Promise.all(this.images.map(this.getPromise, this));
log("Finished searching images");
return this;
};
ImageLoader.prototype.timeout = function(container, timeout) {
var timer;
var promise = Promise.race([container.promise, new Promise(function(res, reject) {
timer = setTimeout(function() {
log("Timed out loading image", container);
reject(container);
}, timeout);
})]).then(function(container) {
clearTimeout(timer);
return container;
});
promise['catch'](function() {
clearTimeout(timer);
});
return promise;
};
module.exports = ImageLoader;
},{"./dummyimagecontainer":7,"./framecontainer":10,"./imagecontainer":12,"./lineargradientcontainer":14,"./log":15,"./promise":18,"./proxyimagecontainer":20,"./svgcontainer":26,"./svgnodecontainer":27,"./utils":29,"./webkitgradientcontainer":30}],14:[function(require,module,exports){
var GradientContainer = require('./gradientcontainer');
var Color = require('./color');
function LinearGradientContainer(imageData) {
GradientContainer.apply(this, arguments);
this.type = this.TYPES.LINEAR;
var hasDirection = imageData.args[0].match(this.stepRegExp) === null;
if (hasDirection) {
imageData.args[0].split(" ").reverse().forEach(function(position) {
switch(position) {
case "left":
this.x0 = 0;
this.x1 = 1;
break;
case "top":
this.y0 = 0;
this.y1 = 1;
break;
case "right":
this.x0 = 1;
this.x1 = 0;
break;
case "bottom":
this.y0 = 1;
this.y1 = 0;
break;
case "to":
var y0 = this.y0;
var x0 = this.x0;
this.y0 = this.y1;
this.x0 = this.x1;
this.x1 = x0;
this.y1 = y0;
break;
}
}, this);
} else {
this.y0 = 0;
this.y1 = 1;
}
this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
var colorStopMatch = colorStop.match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)|\w+)\s*(\d{1,3})?(%|px)?/);
return {
color: new Color(colorStopMatch[1]),
stop: colorStopMatch[3] === "%" ? colorStopMatch[2] / 100 : null
};
}, this);
if (this.colorStops[0].stop === null) {
this.colorStops[0].stop = 0;
}
if (this.colorStops[this.colorStops.length - 1].stop === null) {
this.colorStops[this.colorStops.length - 1].stop = 1;
}
this.colorStops.forEach(function(colorStop, index) {
if (colorStop.stop === null) {
this.colorStops.slice(index).some(function(find, count) {
if (find.stop !== null) {
colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
return true;
} else {
return false;
}
}, this);
}
}, this);
}
LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
LinearGradientContainer.prototype.stepRegExp = /((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/;
module.exports = LinearGradientContainer;
},{"./color":5,"./gradientcontainer":11}],15:[function(require,module,exports){
module.exports = function() {
if (window.html2canvas.logging && window.console && window.console.log) {
window.html2canvas.logmessage = String.prototype.call(arguments, 0);
Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - window.html2canvas.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
}
};
},{}],16:[function(require,module,exports){
var Color = require('./color');
var utils = require('./utils');
var getBounds = utils.getBounds;
var parseBackgrounds = utils.parseBackgrounds;
var offsetBounds = utils.offsetBounds;
function NodeContainer(node, parent) {
this.node = node;
this.parent = parent;
this.stack = null;
this.bounds = null;
this.borders = null;
this.clip = [];
this.backgroundClip = [];
this.offsetBounds = null;
this.visible = null;
this.computedStyles = null;
this.colors = {};
this.styles = {};
this.backgroundImages = null;
this.transformData = null;
this.transformMatrix = null;
this.isPseudoElement = false;
this.opacity = null;
}
NodeContainer.prototype.cloneTo = function(stack) {
stack.visible = this.visible;
stack.borders = this.borders;
stack.bounds = this.bounds;
stack.clip = this.clip;
stack.backgroundClip = this.backgroundClip;
stack.computedStyles = this.computedStyles;
stack.styles = this.styles;
stack.backgroundImages = this.backgroundImages;
stack.opacity = this.opacity;
};
NodeContainer.prototype.getOpacity = function() {
return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
};
NodeContainer.prototype.assignStack = function(stack) {
this.stack = stack;
stack.children.push(this);
};
NodeContainer.prototype.isElementVisible = function() {
return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
this.css('display') !== "none" &&
this.css('visibility') !== "hidden" &&
!this.node.hasAttribute("data-html2canvas-ignore") &&
(this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
);
};
NodeContainer.prototype.css = function(attribute) {
if (!this.computedStyles) {
this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
}
return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
};
NodeContainer.prototype.prefixedCss = function(attribute) {
var prefixes = ["webkit", "moz", "ms", "o"];
var value = this.css(attribute);
if (value === undefined) {
prefixes.some(function(prefix) {
value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
return value !== undefined;
}, this);
}
return value === undefined ? null : value;
};
NodeContainer.prototype.computedStyle = function(type) {
return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
};
NodeContainer.prototype.cssInt = function(attribute) {
var value = parseInt(this.css(attribute), 10);
return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
};
NodeContainer.prototype.color = function(attribute) {
return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
};
NodeContainer.prototype.cssFloat = function(attribute) {
var value = parseFloat(this.css(attribute));
return (isNaN(value)) ? 0 : value;
};
NodeContainer.prototype.fontWeight = function() {
var weight = this.css("fontWeight");
switch(parseInt(weight, 10)){
case 401:
weight = "bold";
break;
case 400:
weight = "normal";
break;
}
return weight;
};
NodeContainer.prototype.parseClip = function() {
var matches = this.css('clip').match(this.CLIP);
if (matches) {
return {
top: parseInt(matches[1], 10),
right: parseInt(matches[2], 10),
bottom: parseInt(matches[3], 10),
left: parseInt(matches[4], 10)
};
}
return null;
};
NodeContainer.prototype.parseBackgroundImages = function() {
return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
};
NodeContainer.prototype.cssList = function(property, index) {
var value = (this.css(property) || '').split(',');
value = value[index || 0] || value[0] || 'auto';
value = value.trim().split(' ');
if (value.length === 1) {
value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
}
return value;
};
NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
var size = this.cssList("backgroundSize", index);
var width, height;
if (isPercentage(size[0])) {
width = bounds.width * parseFloat(size[0]) / 100;
} else if (/contain|cover/.test(size[0])) {
var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
} else {
width = parseInt(size[0], 10);
}
if (size[0] === 'auto' && size[1] === 'auto') {
height = image.height;
} else if (size[1] === 'auto') {
height = width / image.width * image.height;
} else if (isPercentage(size[1])) {
height = bounds.height * parseFloat(size[1]) / 100;
} else {
height = parseInt(size[1], 10);
}
if (size[0] === 'auto') {
width = height / image.height * image.width;
}
return {width: width, height: height};
};
NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
var position = this.cssList('backgroundPosition', index);
var left, top;
if (isPercentage(position[0])){
left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
} else {
left = parseInt(position[0], 10);
}
if (position[1] === 'auto') {
top = left / image.width * image.height;
} else if (isPercentage(position[1])){
top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
} else {
top = parseInt(position[1], 10);
}
if (position[0] === 'auto') {
left = top / image.height * image.width;
}
return {left: left, top: top};
};
NodeContainer.prototype.parseBackgroundRepeat = function(index) {
return this.cssList("backgroundRepeat", index)[0];
};
NodeContainer.prototype.parseTextShadows = function() {
var textShadow = this.css("textShadow");
var results = [];
if (textShadow && textShadow !== 'none') {
var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
for (var i = 0; shadows && (i < shadows.length); i++) {
var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
results.push({
color: new Color(s[0]),
offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
blur: s[3] ? s[3].replace('px', '') : 0
});
}
}
return results;
};
NodeContainer.prototype.parseTransform = function() {
if (!this.transformData) {
if (this.hasTransform()) {
var offset = this.parseBounds();
var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
origin[0] += offset.left;
origin[1] += offset.top;
this.transformData = {
origin: origin,
matrix: this.parseTransformMatrix()
};
} else {
this.transformData = {
origin: [0, 0],
matrix: [1, 0, 0, 1, 0, 0]
};
}
}
return this.transformData;
};
NodeContainer.prototype.parseTransformMatrix = function() {
if (!this.transformMatrix) {
var transform = this.prefixedCss("transform");
var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
}
return this.transformMatrix;
};
NodeContainer.prototype.parseBounds = function() {
return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
};
NodeContainer.prototype.hasTransform = function() {
return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
};
NodeContainer.prototype.getValue = function() {
var value = this.node.value || "";
if (this.node.tagName === "SELECT") {
value = selectionValue(this.node);
} else if (this.node.type === "password") {
value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
}
return value.length === 0 ? (this.node.placeholder || "") : value;
};
NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
function selectionValue(node) {
var option = node.options[node.selectedIndex || 0];
return option ? (option.text || "") : "";
}
function parseMatrix(match) {
if (match && match[1] === "matrix") {
return match[2].split(",").map(function(s) {
return parseFloat(s.trim());
});
} else if (match && match[1] === "matrix3d") {
var matrix3d = match[2].split(",").map(function(s) {
return parseFloat(s.trim());
});
return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
}
}
function isPercentage(value) {
return value.toString().indexOf("%") !== -1;
}
function removePx(str) {
return str.replace("px", "");
}
function asFloat(str) {
return parseFloat(str);
}
module.exports = NodeContainer;
},{"./color":5,"./utils":29}],17:[function(require,module,exports){
var log = require('./log');
var punycode = require('punycode');
var NodeContainer = require('./nodecontainer');
var TextContainer = require('./textcontainer');
var PseudoElementContainer = require('./pseudoelementcontainer');
var FontMetrics = require('./fontmetrics');
var Color = require('./color');
var Promise = require('./promise');
var StackingContext = require('./stackingcontext');
var utils = require('./utils');
var bind = utils.bind;
var getBounds = utils.getBounds;
var parseBackgrounds = utils.parseBackgrounds;
var offsetBounds = utils.offsetBounds;
function NodeParser(element, renderer, support, imageLoader, options) {
log("Starting NodeParser");
this.renderer = renderer;
this.options = options;
this.range = null;
this.support = support;
this.renderQueue = [];
this.stack = new StackingContext(true, 1, element.ownerDocument, null);
var parent = new NodeContainer(element, null);
if (options.background) {
renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
}
if (element === element.ownerDocument.documentElement) {
// http://www.w3.org/TR/css3-background/#special-backgrounds
var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
}
parent.visibile = parent.isElementVisible();
this.createPseudoHideStyles(element.ownerDocument);
this.disableAnimations(element.ownerDocument);
this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
return container.visible = container.isElementVisible();
}).map(this.getPseudoElements, this));
this.fontMetrics = new FontMetrics();
log("Fetched nodes, total:", this.nodes.length);
log("Calculate overflow clips");
this.calculateOverflowClips();
log("Start fetching images");
this.images = imageLoader.fetch(this.nodes.filter(isElement));
this.ready = this.images.ready.then(bind(function() {
log("Images loaded, starting parsing");
log("Creating stacking contexts");
this.createStackingContexts();
log("Sorting stacking contexts");
this.sortStackingContexts(this.stack);
this.parse(this.stack);
log("Render queue created with " + this.renderQueue.length + " items");
return new Promise(bind(function(resolve) {
if (!options.async) {
this.renderQueue.forEach(this.paint, this);
resolve();
} else if (typeof(options.async) === "function") {
options.async.call(this, this.renderQueue, resolve);
} else if (this.renderQueue.length > 0){
this.renderIndex = 0;
this.asyncRenderer(this.renderQueue, resolve);
} else {
resolve();
}
}, this));
}, this));
}
NodeParser.prototype.calculateOverflowClips = function() {
this.nodes.forEach(function(container) {
if (isElement(container)) {
if (isPseudoElement(container)) {
container.appendToDOM();
}
container.borders = this.parseBorders(container);
var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
var cssClip = container.parseClip();
if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
clip.push([["rect",
container.bounds.left + cssClip.left,
container.bounds.top + cssClip.top,
cssClip.right - cssClip.left,
cssClip.bottom - cssClip.top
]]);
}
container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
if (isPseudoElement(container)) {
container.cleanDOM();
}
} else if (isTextNode(container)) {
container.clip = hasParentClip(container) ? container.parent.clip : [];
}
if (!isPseudoElement(container)) {
container.bounds = null;
}
}, this);
};
function hasParentClip(container) {
return container.parent && container.parent.clip.length;
}
NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
asyncTimer = asyncTimer || Date.now();
this.paint(queue[this.renderIndex++]);
if (queue.length === this.renderIndex) {
resolve();
} else if (asyncTimer + 20 > Date.now()) {
this.asyncRenderer(queue, resolve, asyncTimer);
} else {
setTimeout(bind(function() {
this.asyncRenderer(queue, resolve);
}, this), 0);
}
};
NodeParser.prototype.createPseudoHideStyles = function(document) {
this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
'.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
};
NodeParser.prototype.disableAnimations = function(document) {
this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
'-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
};
NodeParser.prototype.createStyles = function(document, styles) {
var hidePseudoElements = document.createElement('style');
hidePseudoElements.innerHTML = styles;
document.body.appendChild(hidePseudoElements);
};
NodeParser.prototype.getPseudoElements = function(container) {
var nodes = [[container]];
if (container.node.nodeType === Node.ELEMENT_NODE) {
var before = this.getPseudoElement(container, ":before");
var after = this.getPseudoElement(container, ":after");
if (before) {
nodes.push(before);
}
if (after) {
nodes.push(after);
}
}
return flatten(nodes);
};
function toCamelCase(str) {
return str.replace(/(\-[a-z])/g, function(match){
return match.toUpperCase().replace('-','');
});
}
NodeParser.prototype.getPseudoElement = function(container, type) {
var style = container.computedStyle(type);
if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
return null;
}
var content = stripQuotes(style.content);
var isImage = content.substr(0, 3) === 'url';
var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
for (var i = style.length-1; i >= 0; i--) {
var property = toCamelCase(style.item(i));
pseudoNode.style[property] = style[property];
}
pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
if (isImage) {
pseudoNode.src = parseBackgrounds(content)[0].args[0];
return [pseudoContainer];
} else {
var text = document.createTextNode(content);
pseudoNode.appendChild(text);
return [pseudoContainer, new TextContainer(text, pseudoContainer)];
}
};
NodeParser.prototype.getChildren = function(parentContainer) {
return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
}, this));
};
NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
container.cloneTo(stack);
var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
parentStack.contexts.push(stack);
container.stack = stack;
};
NodeParser.prototype.createStackingContexts = function() {
this.nodes.forEach(function(container) {
if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
this.newStackingContext(container, true);
} else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
this.newStackingContext(container, false);
} else {
container.assignStack(container.parent.stack);
}
}, this);
};
NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
};
NodeParser.prototype.isRootElement = function(container) {
return container.parent === null;
};
NodeParser.prototype.sortStackingContexts = function(stack) {
stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
stack.contexts.forEach(this.sortStackingContexts, this);
};
NodeParser.prototype.parseTextBounds = function(container) {
return function(text, index, textList) {
if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
if (this.support.rangeBounds && !container.parent.hasTransform()) {
var offset = textList.slice(0, index).join("").length;
return this.getRangeBounds(container.node, offset, text.length);
} else if (container.node && typeof(container.node.data) === "string") {
var replacementNode = container.node.splitText(text.length);
var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
container.node = replacementNode;
return bounds;
}
} else if(!this.support.rangeBounds || container.parent.hasTransform()){
container.node = container.node.splitText(text.length);
}
return {};
};
};
NodeParser.prototype.getWrapperBounds = function(node, transform) {
var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
var parent = node.parentNode,
backupText = node.cloneNode(true);
wrapper.appendChild(node.cloneNode(true));
parent.replaceChild(wrapper, node);
var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
parent.replaceChild(backupText, wrapper);
return bounds;
};
NodeParser.prototype.getRangeBounds = function(node, offset, length) {
var range = this.range || (this.range = node.ownerDocument.createRange());
range.setStart(node, offset);
range.setEnd(node, offset + length);
return range.getBoundingClientRect();
};
function ClearTransform() {}
NodeParser.prototype.parse = function(stack) {
// http://www.w3.org/TR/CSS21/visuren.html#z-index
var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
var descendantElements = stack.children.filter(isElement);
var descendantNonFloats = descendantElements.filter(not(isFloating));
var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
var text = stack.children.filter(isTextNode).filter(hasText);
var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
.concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
this.renderQueue.push(container);
if (isStackingContext(container)) {
this.parse(container);
this.renderQueue.push(new ClearTransform());
}
}, this);
};
NodeParser.prototype.paint = function(container) {
try {
if (container instanceof ClearTransform) {
this.renderer.ctx.restore();
} else if (isTextNode(container)) {
if (isPseudoElement(container.parent)) {
container.parent.appendToDOM();
}
this.paintText(container);
if (isPseudoElement(container.parent)) {
container.parent.cleanDOM();
}
} else {
this.paintNode(container);
}
} catch(e) {
log(e);
if (this.options.strict) {
throw e;
}
}
};
NodeParser.prototype.paintNode = function(container) {
if (isStackingContext(container)) {
this.renderer.setOpacity(container.opacity);
this.renderer.ctx.save();
if (container.hasTransform()) {
this.renderer.setTransform(container.parseTransform());
}
}
if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
this.paintCheckbox(container);
} else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
this.paintRadio(container);
} else {
this.paintElement(container);
}
};
NodeParser.prototype.paintElement = function(container) {
var bounds = container.parseBounds();
this.renderer.clip(container.backgroundClip, function() {
this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
}, this);
this.renderer.clip(container.clip, function() {
this.renderer.renderBorders(container.borders.borders);
}, this);
this.renderer.clip(container.backgroundClip, function() {
switch (container.node.nodeName) {
case "svg":
case "IFRAME":
var imgContainer = this.images.get(container.node);
if (imgContainer) {
this.renderer.renderImage(container, bounds, container.borders, imgContainer);
} else {
log("Error loading <" + container.node.nodeName + ">", container.node);
}
break;
case "IMG":
var imageContainer = this.images.get(container.node.src);
if (imageContainer) {
this.renderer.renderImage(container, bounds, container.borders, imageContainer);
} else {
log("Error loading <img>", container.node.src);
}
break;
case "CANVAS":
this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
break;
case "SELECT":
case "INPUT":
case "TEXTAREA":
this.paintFormValue(container);
break;
}
}, this);
};
NodeParser.prototype.paintCheckbox = function(container) {
var b = container.parseBounds();
var size = Math.min(b.width, b.height);
var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
var r = [3, 3];
var radius = [r, r, r, r];
var borders = [1,1,1,1].map(function(w) {
return {color: new Color('#A5A5A5'), width: w};
});
var borderPoints = calculateCurvePoints(bounds, radius, borders);
this.renderer.clip(container.backgroundClip, function() {
this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
if (container.node.checked) {
this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
}
}, this);
};
NodeParser.prototype.paintRadio = function(container) {
var bounds = container.parseBounds();
var size = Math.min(bounds.width, bounds.height) - 2;
this.renderer.clip(container.backgroundClip, function() {
this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
if (container.node.checked) {
this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
}
}, this);
};
NodeParser.prototype.paintFormValue = function(container) {
var value = container.getValue();
if (value.length > 0) {
var document = container.node.ownerDocument;
var wrapper = document.createElement('html2canvaswrapper');
var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
'boxSizing', 'whiteSpace', 'wordWrap'];
properties.forEach(function(property) {
try {
wrapper.style[property] = container.css(property);
} catch(e) {
// Older IE has issues with "border"
log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
}
});
var bounds = container.parseBounds();
wrapper.style.position = "fixed";
wrapper.style.left = bounds.left + "px";
wrapper.style.top = bounds.top + "px";
wrapper.textContent = value;
document.body.appendChild(wrapper);
this.paintText(new TextContainer(wrapper.firstChild, container));
document.body.removeChild(wrapper);
}
};
NodeParser.prototype.paintText = function(container) {
container.applyTextTransform();
var characters = punycode.ucs2.decode(container.node.data);
var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
return punycode.ucs2.encode([character]);
});
var weight = container.parent.fontWeight();
var size = container.parent.css('fontSize');
var family = container.parent.css('fontFamily');
var shadows = container.parent.parseTextShadows();
this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
if (shadows.length) {
// TODO: support multiple text shadows
this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
} else {
this.renderer.clearShadow();
}
this.renderer.clip(container.parent.clip, function() {
textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
if (bounds) {
this.renderer.text(textList[index], bounds.left, bounds.bottom);
this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
}
}, this);
}, this);
};
NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
switch(container.css("textDecoration").split(" ")[0]) {
case "underline":
// Draws a line at the baseline of the font
// TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
break;
case "overline":
this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
break;
case "line-through":
// TODO try and find exact position for line-through
this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
break;
}
};
var borderColorTransforms = {
inset: [
["darken", 0.60],
["darken", 0.10],
["darken", 0.10],
["darken", 0.60]
]
};
NodeParser.prototype.parseBorders = function(container) {
var nodeBounds = container.parseBounds();
var radius = getBorderRadiusData(container);
var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
var style = container.css('border' + side + 'Style');
var color = container.color('border' + side + 'Color');
if (style === "inset" && color.isBlack()) {
color = new Color([255, 255, 255, color.a]); // this is wrong, but
}
var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
return {
width: container.cssInt('border' + side + 'Width'),
color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
args: null
};
});
var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
return {
clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
};
};
function calculateBorders(borders, nodeBounds, borderPoints, radius) {
return borders.map(function(border, borderSide) {
if (border.width > 0) {
var bx = nodeBounds.left;
var by = nodeBounds.top;
var bw = nodeBounds.width;
var bh = nodeBounds.height - (borders[2].width);
switch(borderSide) {
case 0:
// top border
bh = borders[0].width;
border.args = drawSide({
c1: [bx, by],
c2: [bx + bw, by],
c3: [bx + bw - borders[1].width, by + bh],
c4: [bx + borders[3].width, by + bh]
}, radius[0], radius[1],
borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
break;
case 1:
// right border
bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
bw = borders[1].width;
border.args = drawSide({
c1: [bx + bw, by],
c2: [bx + bw, by + bh + borders[2].width],
c3: [bx, by + bh],
c4: [bx, by + borders[0].width]
}, radius[1], radius[2],
borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
break;
case 2:
// bottom border
by = (by + nodeBounds.height) - (borders[2].width);
bh = borders[2].width;
border.args = drawSide({
c1: [bx + bw, by + bh],
c2: [bx, by + bh],
c3: [bx + borders[3].width, by],
c4: [bx + bw - borders[3].width, by]
}, radius[2], radius[3],
borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
break;
case 3:
// left border
bw = borders[3].width;
border.args = drawSide({
c1: [bx, by + bh + borders[2].width],
c2: [bx, by],
c3: [bx + bw, by + borders[0].width],
c4: [bx + bw, by + bh]
}, radius[3], radius[0],
borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
break;
}
}
return border;
});
}
NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
var backgroundClip = container.css('backgroundClip'),
borderArgs = [];
switch(backgroundClip) {
case "content-box":
case "padding-box":
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
break;
default:
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
break;
}
return borderArgs;
};
function getCurvePoints(x, y, r1, r2) {
var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
var ox = (r1) * kappa, // control point offset horizontal
oy = (r2) * kappa, // control point offset vertical
xm = x + r1, // x-middle
ym = y + r2; // y-middle
return {
topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
};
}
function calculateCurvePoints(bounds, borderRadius, borders) {
var x = bounds.left,
y = bounds.top,
width = bounds.width,
height = bounds.height,
tlh = borderRadius[0][0],
tlv = borderRadius[0][1],
trh = borderRadius[1][0],
trv = borderRadius[1][1],
brh = borderRadius[2][0],
brv = borderRadius[2][1],
blh = borderRadius[3][0],
blv = borderRadius[3][1];
var topWidth = width - trh,
rightHeight = height - brv,
bottomWidth = width - brh,
leftHeight = height - blv;
return {
topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
};
}
function bezierCurve(start, startControl, endControl, end) {
var lerp = function (a, b, t) {
return {
x: a.x + (b.x - a.x) * t,
y: a.y + (b.y - a.y) * t
};
};
return {
start: start,
startControl: startControl,
endControl: endControl,
end: end,
subdivide: function(t) {
var ab = lerp(start, startControl, t),
bc = lerp(startControl, endControl, t),
cd = lerp(endControl, end, t),
abbc = lerp(ab, bc, t),
bccd = lerp(bc, cd, t),
dest = lerp(abbc, bccd, t);
return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
},
curveTo: function(borderArgs) {
borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
},
curveToReversed: function(borderArgs) {
borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
}
};
}
function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
var borderArgs = [];
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
outer1[1].curveTo(borderArgs);
} else {
borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
}
if (radius2[0] > 0 || radius2[1] > 0) {
borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
outer2[0].curveTo(borderArgs);
borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
inner2[0].curveToReversed(borderArgs);
} else {
borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
}
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
inner1[1].curveToReversed(borderArgs);
} else {
borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
}
return borderArgs;
}
function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
corner1[0].curveTo(borderArgs);
corner1[1].curveTo(borderArgs);
} else {
borderArgs.push(["line", x, y]);
}
if (radius2[0] > 0 || radius2[1] > 0) {
borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
}
}
function negativeZIndex(container) {
return container.cssInt("zIndex") < 0;
}
function positiveZIndex(container) {
return container.cssInt("zIndex") > 0;
}
function zIndex0(container) {
return container.cssInt("zIndex") === 0;
}
function inlineLevel(container) {
return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
}
function isStackingContext(container) {
return (container instanceof StackingContext);
}
function hasText(container) {
return container.node.data.trim().length > 0;
}
function noLetterSpacing(container) {
return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
}
function getBorderRadiusData(container) {
return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
var value = container.css('border' + side + 'Radius');
var arr = value.split(" ");
if (arr.length <= 1) {
arr[1] = arr[0];
}
return arr.map(asInt);
});
}
function renderableNode(node) {
return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
}
function isPositionedForStacking(container) {
var position = container.css("position");
var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
return zIndex !== "auto";
}
function isPositioned(container) {
return container.css("position") !== "static";
}
function isFloating(container) {
return container.css("float") !== "none";
}
function isInlineBlock(container) {
return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
}
function not(callback) {
var context = this;
return function() {
return !callback.apply(context, arguments);
};
}
function isElement(container) {
return container.node.nodeType === Node.ELEMENT_NODE;
}
function isPseudoElement(container) {
return container.isPseudoElement === true;
}
function isTextNode(container) {
return container.node.nodeType === Node.TEXT_NODE;
}
function zIndexSort(contexts) {
return function(a, b) {
return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
};
}
function hasOpacity(container) {
return container.getOpacity() < 1;
}
function asInt(value) {
return parseInt(value, 10);
}
function getWidth(border) {
return border.width;
}
function nonIgnoredElement(nodeContainer) {
return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
}
function flatten(arrays) {
return [].concat.apply([], arrays);
}
function stripQuotes(content) {
var first = content.substr(0, 1);
return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
}
function getWords(characters) {
var words = [], i = 0, onWordBoundary = false, word;
while(characters.length) {
if (isWordBoundary(characters[i]) === onWordBoundary) {
word = characters.splice(0, i);
if (word.length) {
words.push(punycode.ucs2.encode(word));
}
onWordBoundary =! onWordBoundary;
i = 0;
} else {
i++;
}
if (i >= characters.length) {
word = characters.splice(0, i);
if (word.length) {
words.push(punycode.ucs2.encode(word));
}
}
}
return words;
}
function isWordBoundary(characterCode) {
return [
32, // <space>
13, // \r
10, // \n
9, // \t
45 // -
].indexOf(characterCode) !== -1;
}
function hasUnicode(string) {
return (/[^\u0000-\u00ff]/).test(string);
}
module.exports = NodeParser;
},{"./color":5,"./fontmetrics":9,"./log":15,"./nodecontainer":16,"./promise":18,"./pseudoelementcontainer":21,"./stackingcontext":24,"./textcontainer":28,"./utils":29,"punycode":3}],18:[function(require,module,exports){
module.exports = require('es6-promise').Promise;
},{"es6-promise":1}],19:[function(require,module,exports){
var Promise = require('./promise');
var XHR = require('./xhr');
var utils = require('./utils');
var log = require('./log');
var createWindowClone = require('./clone');
var decode64 = utils.decode64;
function Proxy(src, proxyUrl, document) {
var supportsCORS = ('withCredentials' in new XMLHttpRequest());
if (!proxyUrl) {
return Promise.reject("No proxy configured");
}
var callback = createCallback(supportsCORS);
var url = createProxyUrl(proxyUrl, src, callback);
return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
return decode64(response.content);
}));
}
var proxyCount = 0;
function ProxyURL(src, proxyUrl, document) {
var supportsCORSImage = ('crossOrigin' in new Image());
var callback = createCallback(supportsCORSImage);
var url = createProxyUrl(proxyUrl, src, callback);
return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
return "data:" + response.type + ";base64," + response.content;
}));
}
function jsonp(document, url, callback) {
return new Promise(function(resolve, reject) {
var s = document.createElement("script");
var cleanup = function() {
delete window.html2canvas.proxy[callback];
document.body.removeChild(s);
};
window.html2canvas.proxy[callback] = function(response) {
cleanup();
resolve(response);
};
s.src = url;
s.onerror = function(e) {
cleanup();
reject(e);
};
document.body.appendChild(s);
});
}
function createCallback(useCORS) {
return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
}
function createProxyUrl(proxyUrl, src, callback) {
return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
}
function documentFromHTML(src) {
return function(html) {
var parser = new DOMParser(), doc;
try {
doc = parser.parseFromString(html, "text/html");
} catch(e) {
log("DOMParser not supported, falling back to createHTMLDocument");
doc = document.implementation.createHTMLDocument("");
try {
doc.open();
doc.write(html);
doc.close();
} catch(ee) {
log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
}
}
var b = doc.querySelector("base");
if (!b || !b.href.host) {
var base = doc.createElement("base");
base.href = src;
doc.head.insertBefore(base, doc.head.firstChild);
}
return doc;
};
}
function loadUrlDocument(src, proxy, document, width, height, options) {
return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
return createWindowClone(doc, document, width, height, options, 0, 0);
});
}
exports.Proxy = Proxy;
exports.ProxyURL = ProxyURL;
exports.loadUrlDocument = loadUrlDocument;
},{"./clone":4,"./log":15,"./promise":18,"./utils":29,"./xhr":31}],20:[function(require,module,exports){
var ProxyURL = require('./proxy').ProxyURL;
var Promise = require('./promise');
function ProxyImageContainer(src, proxy) {
var link = document.createElement("a");
link.href = src;
src = link.href;
this.src = src;
this.image = new Image();
var self = this;
this.promise = new Promise(function(resolve, reject) {
self.image.crossOrigin = "Anonymous";
self.image.onload = resolve;
self.image.onerror = reject;
new ProxyURL(src, proxy, document).then(function(url) {
self.image.src = url;
})['catch'](reject);
});
}
module.exports = ProxyImageContainer;
},{"./promise":18,"./proxy":19}],21:[function(require,module,exports){
var NodeContainer = require('./nodecontainer');
function PseudoElementContainer(node, parent, type) {
NodeContainer.call(this, node, parent);
this.isPseudoElement = true;
this.before = type === ":before";
}
PseudoElementContainer.prototype.cloneTo = function(stack) {
PseudoElementContainer.prototype.cloneTo.call(this, stack);
stack.isPseudoElement = true;
stack.before = this.before;
};
PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
PseudoElementContainer.prototype.appendToDOM = function() {
if (this.before) {
this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
} else {
this.parent.node.appendChild(this.node);
}
this.parent.node.className += " " + this.getHideClass();
};
PseudoElementContainer.prototype.cleanDOM = function() {
this.node.parentNode.removeChild(this.node);
this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
};
PseudoElementContainer.prototype.getHideClass = function() {
return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
};
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
module.exports = PseudoElementContainer;
},{"./nodecontainer":16}],22:[function(require,module,exports){
var log = require('./log');
function Renderer(width, height, images, options, document) {
this.width = width;
this.height = height;
this.images = images;
this.options = options;
this.document = document;
}
Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
var paddingLeft = container.cssInt('paddingLeft'),
paddingTop = container.cssInt('paddingTop'),
paddingRight = container.cssInt('paddingRight'),
paddingBottom = container.cssInt('paddingBottom'),
borders = borderData.borders;
var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
this.drawImage(
imageContainer,
0,
0,
imageContainer.image.width || width,
imageContainer.image.height || height,
bounds.left + paddingLeft + borders[3].width,
bounds.top + paddingTop + borders[0].width,
width,
height
);
};
Renderer.prototype.renderBackground = function(container, bounds, borderData) {
if (bounds.height > 0 && bounds.width > 0) {
this.renderBackgroundColor(container, bounds);
this.renderBackgroundImage(container, bounds, borderData);
}
};
Renderer.prototype.renderBackgroundColor = function(container, bounds) {
var color = container.color("backgroundColor");
if (!color.isTransparent()) {
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
}
};
Renderer.prototype.renderBorders = function(borders) {
borders.forEach(this.renderBorder, this);
};
Renderer.prototype.renderBorder = function(data) {
if (!data.color.isTransparent() && data.args !== null) {
this.drawShape(data.args, data.color);
}
};
Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
var backgroundImages = container.parseBackgroundImages();
backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
switch(backgroundImage.method) {
case "url":
var image = this.images.get(backgroundImage.args[0]);
if (image) {
this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
} else {
log("Error loading background-image", backgroundImage.args[0]);
}
break;
case "linear-gradient":
case "gradient":
var gradientImage = this.images.get(backgroundImage.value);
if (gradientImage) {
this.renderBackgroundGradient(gradientImage, bounds, borderData);
} else {
log("Error loading background-image", backgroundImage.args[0]);
}
break;
case "none":
break;
default:
log("Unknown background-image type", backgroundImage.args[0]);
}
}, this);
};
Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
var repeat = container.parseBackgroundRepeat(index);
switch (repeat) {
case "repeat-x":
case "repeat no-repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
break;
case "repeat-y":
case "no-repeat repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
break;
case "no-repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
break;
default:
this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
break;
}
};
module.exports = Renderer;
},{"./log":15}],23:[function(require,module,exports){
var Renderer = require('../renderer');
var LinearGradientContainer = require('../lineargradientcontainer');
var log = require('../log');
function CanvasRenderer(width, height) {
Renderer.apply(this, arguments);
this.canvas = this.options.canvas || this.document.createElement("canvas");
if (!this.options.canvas) {
this.canvas.width = width;
this.canvas.height = height;
}
this.ctx = this.canvas.getContext("2d");
this.taintCtx = this.document.createElement("canvas").getContext("2d");
this.ctx.textBaseline = "bottom";
this.variables = {};
log("Initialized CanvasRenderer with size", width, "x", height);
}
CanvasRenderer.prototype = Object.create(Renderer.prototype);
CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
return this.ctx;
};
CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
this.setFillStyle(color).fillRect(left, top, width, height);
};
CanvasRenderer.prototype.circle = function(left, top, size, color) {
this.setFillStyle(color);
this.ctx.beginPath();
this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
this.ctx.closePath();
this.ctx.fill();
};
CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
this.circle(left, top, size, color);
this.ctx.strokeStyle = strokeColor.toString();
this.ctx.stroke();
};
CanvasRenderer.prototype.drawShape = function(shape, color) {
this.shape(shape);
this.setFillStyle(color).fill();
};
CanvasRenderer.prototype.taints = function(imageContainer) {
if (imageContainer.tainted === null) {
this.taintCtx.drawImage(imageContainer.image, 0, 0);
try {
this.taintCtx.getImageData(0, 0, 1, 1);
imageContainer.tainted = false;
} catch(e) {
this.taintCtx = document.createElement("canvas").getContext("2d");
imageContainer.tainted = true;
}
}
return imageContainer.tainted;
};
CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
if (!this.taints(imageContainer) || this.options.allowTaint) {
this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
}
};
CanvasRenderer.prototype.clip = function(shapes, callback, context) {
this.ctx.save();
shapes.filter(hasEntries).forEach(function(shape) {
this.shape(shape).clip();
}, this);
callback.call(context);
this.ctx.restore();
};
CanvasRenderer.prototype.shape = function(shape) {
this.ctx.beginPath();
shape.forEach(function(point, index) {
if (point[0] === "rect") {
this.ctx.rect.apply(this.ctx, point.slice(1));
} else {
this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
}
}, this);
this.ctx.closePath();
return this.ctx;
};
CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
};
CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
this.setVariable("shadowColor", color.toString())
.setVariable("shadowOffsetY", offsetX)
.setVariable("shadowOffsetX", offsetY)
.setVariable("shadowBlur", blur);
};
CanvasRenderer.prototype.clearShadow = function() {
this.setVariable("shadowColor", "rgba(0,0,0,0)");
};
CanvasRenderer.prototype.setOpacity = function(opacity) {
this.ctx.globalAlpha = opacity;
};
CanvasRenderer.prototype.setTransform = function(transform) {
this.ctx.translate(transform.origin[0], transform.origin[1]);
this.ctx.transform.apply(this.ctx, transform.matrix);
this.ctx.translate(-transform.origin[0], -transform.origin[1]);
};
CanvasRenderer.prototype.setVariable = function(property, value) {
if (this.variables[property] !== value) {
this.variables[property] = this.ctx[property] = value;
}
return this;
};
CanvasRenderer.prototype.text = function(text, left, bottom) {
this.ctx.fillText(text, left, bottom);
};
CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
var shape = [
["line", Math.round(left), Math.round(top)],
["line", Math.round(left + width), Math.round(top)],
["line", Math.round(left + width), Math.round(height + top)],
["line", Math.round(left), Math.round(height + top)]
];
this.clip([shape], function() {
this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
}, this);
};
CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
this.ctx.translate(offsetX, offsetY);
this.ctx.fill();
this.ctx.translate(-offsetX, -offsetY);
};
CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
if (gradientImage instanceof LinearGradientContainer) {
var gradient = this.ctx.createLinearGradient(
bounds.left + bounds.width * gradientImage.x0,
bounds.top + bounds.height * gradientImage.y0,
bounds.left + bounds.width * gradientImage.x1,
bounds.top + bounds.height * gradientImage.y1);
gradientImage.colorStops.forEach(function(colorStop) {
gradient.addColorStop(colorStop.stop, colorStop.color.toString());
});
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
}
};
CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
var image = imageContainer.image;
if(image.width === size.width && image.height === size.height) {
return image;
}
var ctx, canvas = document.createElement('canvas');
canvas.width = size.width;
canvas.height = size.height;
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
return canvas;
};
function hasEntries(array) {
return array.length > 0;
}
module.exports = CanvasRenderer;
},{"../lineargradientcontainer":14,"../log":15,"../renderer":22}],24:[function(require,module,exports){
var NodeContainer = require('./nodecontainer');
function StackingContext(hasOwnStacking, opacity, element, parent) {
NodeContainer.call(this, element, parent);
this.ownStacking = hasOwnStacking;
this.contexts = [];
this.children = [];
this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
}
StackingContext.prototype = Object.create(NodeContainer.prototype);
StackingContext.prototype.getParentStack = function(context) {
var parentStack = (this.parent) ? this.parent.stack : null;
return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
};
module.exports = StackingContext;
},{"./nodecontainer":16}],25:[function(require,module,exports){
function Support(document) {
this.rangeBounds = this.testRangeBounds(document);
this.cors = this.testCORS();
this.svg = this.testSVG();
}
Support.prototype.testRangeBounds = function(document) {
var range, testElement, rangeBounds, rangeHeight, support = false;
if (document.createRange) {
range = document.createRange();
if (range.getBoundingClientRect) {
testElement = document.createElement('boundtest');
testElement.style.height = "123px";
testElement.style.display = "block";
document.body.appendChild(testElement);
range.selectNode(testElement);
rangeBounds = range.getBoundingClientRect();
rangeHeight = rangeBounds.height;
if (rangeHeight === 123) {
support = true;
}
document.body.removeChild(testElement);
}
}
return support;
};
Support.prototype.testCORS = function() {
return typeof((new Image()).crossOrigin) !== "undefined";
};
Support.prototype.testSVG = function() {
var img = new Image();
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
try {
ctx.drawImage(img, 0, 0);
canvas.toDataURL();
} catch(e) {
return false;
}
return true;
};
module.exports = Support;
},{}],26:[function(require,module,exports){
var Promise = require('./promise');
var XHR = require('./xhr');
var decode64 = require('./utils').decode64;
function SVGContainer(src) {
this.src = src;
this.image = null;
var self = this;
this.promise = this.hasFabric().then(function() {
return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
}).then(function(svg) {
return new Promise(function(resolve) {
window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
});
});
}
SVGContainer.prototype.hasFabric = function() {
return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
};
SVGContainer.prototype.inlineFormatting = function(src) {
return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
};
SVGContainer.prototype.removeContentType = function(src) {
return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
};
SVGContainer.prototype.isInline = function(src) {
return (/^data:image\/svg\+xml/i.test(src));
};
SVGContainer.prototype.createCanvas = function(resolve) {
var self = this;
return function (objects, options) {
var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
self.image = canvas.lowerCanvasEl;
canvas
.setWidth(options.width)
.setHeight(options.height)
.add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
.renderAll();
resolve(canvas.lowerCanvasEl);
};
};
SVGContainer.prototype.decode64 = function(str) {
return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
};
module.exports = SVGContainer;
},{"./promise":18,"./utils":29,"./xhr":31}],27:[function(require,module,exports){
var SVGContainer = require('./svgcontainer');
var Promise = require('./promise');
function SVGNodeContainer(node, _native) {
this.src = node;
this.image = null;
var self = this;
this.promise = _native ? new Promise(function(resolve, reject) {
self.image = new Image();
self.image.onload = resolve;
self.image.onerror = reject;
self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
if (self.image.complete === true) {
resolve(self.image);
}
}) : this.hasFabric().then(function() {
return new Promise(function(resolve) {
window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
});
});
}
SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
module.exports = SVGNodeContainer;
},{"./promise":18,"./svgcontainer":26}],28:[function(require,module,exports){
var NodeContainer = require('./nodecontainer');
function TextContainer(node, parent) {
NodeContainer.call(this, node, parent);
}
TextContainer.prototype = Object.create(NodeContainer.prototype);
TextContainer.prototype.applyTextTransform = function() {
this.node.data = this.transform(this.parent.css("textTransform"));
};
TextContainer.prototype.transform = function(transform) {
var text = this.node.data;
switch(transform){
case "lowercase":
return text.toLowerCase();
case "capitalize":
return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
case "uppercase":
return text.toUpperCase();
default:
return text;
}
};
function capitalize(m, p1, p2) {
if (m.length > 0) {
return p1 + p2.toUpperCase();
}
}
module.exports = TextContainer;
},{"./nodecontainer":16}],29:[function(require,module,exports){
exports.smallImage = function smallImage() {
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
};
exports.bind = function(callback, context) {
return function() {
return callback.apply(context, arguments);
};
};
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
exports.decode64 = function(base64) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
var output = "";
for (i = 0; i < len; i+=4) {
encoded1 = chars.indexOf(base64[i]);
encoded2 = chars.indexOf(base64[i+1]);
encoded3 = chars.indexOf(base64[i+2]);
encoded4 = chars.indexOf(base64[i+3]);
byte1 = (encoded1 << 2) | (encoded2 >> 4);
byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
byte3 = ((encoded3 & 3) << 6) | encoded4;
if (encoded3 === 64) {
output += String.fromCharCode(byte1);
} else if (encoded4 === 64 || encoded4 === -1) {
output += String.fromCharCode(byte1, byte2);
} else{
output += String.fromCharCode(byte1, byte2, byte3);
}
}
return output;
};
exports.getBounds = function(node) {
if (node.getBoundingClientRect) {
var clientRect = node.getBoundingClientRect();
var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
return {
top: clientRect.top,
bottom: clientRect.bottom || (clientRect.top + clientRect.height),
right: clientRect.left + width,
left: clientRect.left,
width: width,
height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
};
}
return {};
};
exports.offsetBounds = function(node) {
var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
return {
top: node.offsetTop + parent.top,
bottom: node.offsetTop + node.offsetHeight + parent.top,
right: node.offsetLeft + parent.left + node.offsetWidth,
left: node.offsetLeft + parent.left,
width: node.offsetWidth,
height: node.offsetHeight
};
};
exports.parseBackgrounds = function(backgroundImage) {
var whitespace = ' \r\n\t',
method, definition, prefix, prefix_i, block, results = [],
mode = 0, numParen = 0, quote, args;
var appendResult = function() {
if(method) {
if (definition.substr(0, 1) === '"') {
definition = definition.substr(1, definition.length - 2);
}
if (definition) {
args.push(definition);
}
if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
prefix = method.substr(0, prefix_i);
method = method.substr(prefix_i);
}
results.push({
prefix: prefix,
method: method.toLowerCase(),
value: block,
args: args,
image: null
});
}
args = [];
method = prefix = definition = block = '';
};
args = [];
method = prefix = definition = block = '';
backgroundImage.split("").forEach(function(c) {
if (mode === 0 && whitespace.indexOf(c) > -1) {
return;
}
switch(c) {
case '"':
if(!quote) {
quote = c;
} else if(quote === c) {
quote = null;
}
break;
case '(':
if(quote) {
break;
} else if(mode === 0) {
mode = 1;
block += c;
return;
} else {
numParen++;
}
break;
case ')':
if (quote) {
break;
} else if(mode === 1) {
if(numParen === 0) {
mode = 0;
block += c;
appendResult();
return;
} else {
numParen--;
}
}
break;
case ',':
if (quote) {
break;
} else if(mode === 0) {
appendResult();
return;
} else if (mode === 1) {
if (numParen === 0 && !method.match(/^url$/i)) {
args.push(definition);
definition = '';
block += c;
return;
}
}
break;
}
block += c;
if (mode === 0) {
method += c;
} else {
definition += c;
}
});
appendResult();
return results;
};
},{}],30:[function(require,module,exports){
var GradientContainer = require('./gradientcontainer');
function WebkitGradientContainer(imageData) {
GradientContainer.apply(this, arguments);
this.type = (imageData.args[0] === "linear") ? this.TYPES.LINEAR : this.TYPES.RADIAL;
}
WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
module.exports = WebkitGradientContainer;
},{"./gradientcontainer":11}],31:[function(require,module,exports){
var Promise = require('./promise');
function XHR(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(new Error("Network Error"));
};
xhr.send();
});
}
module.exports = XHR;
},{"./promise":18}]},{},[6])(6)
});
| ao-dexter/html2canvas | dist/html2canvas.js | JavaScript | mit | 154,883 |
<?php
namespace Mtls\ProjectBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* MessageRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class MessageRepository extends EntityRepository
{
public function findOrderedByDate()
{
return $this->getEntityManager()
->createQuery('SELECT message FROM MtlsProjectBundle:Message message ORDER BY message.date DESC')
->getResult();
}
}
| tolgap/Project56 | src/Mtls/ProjectBundle/Entity/MessageRepository.php | PHP | mit | 462 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace VoteApp.Models.AccountViewModels
{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
| GOlssn/VoteApp | Models/AccountViewModels/RegisterViewModel.cs | C# | mit | 861 |
// stdafx.cpp : source file that includes just the standard includes
// AllyTester.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| AndrewAMD/AllyInvestZorroPlugin | AllyTester/stdafx.cpp | C++ | mit | 289 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using KojtoCAD.KojtoCAD3D.UtilityClasses;
#if !bcad
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;
#else
using Bricscad.ApplicationServices;
using Teigha.DatabaseServices;
using Teigha.Geometry;
using Teigha.Runtime;
using Bricscad.EditorInput;
using Teigha.Colors;
using Teigha.BoundaryRepresentation;
using Face = Teigha.DatabaseServices.Face;
using Application = Bricscad.ApplicationServices.Application;
using Window = Bricscad.Windows.Window;
#endif
[assembly: CommandClass(typeof(KojtoCAD.KojtoCAD3D.Placement))]
namespace KojtoCAD.KojtoCAD3D
{
public class Placement
{
public Containers container = ContextVariablesProvider.Container;
//--- placement of blocks in nodes ---------------------------------
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_NODE_3D_IN_POSITION", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/PLACEMENT_OF_NODE_3D_IN_POSITION.htm", "")]
public void KojtoCAD_3D_Placement_of_Node_3D_in_Position()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
string blockName = "";
string layer = "";
double L = 0.0; //Distance from Node Position to the real Point of the Figure (lying on the axis)
#region prompt blockname, layer and work
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.Node3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.Node3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
#region check block
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
#endregion
#region check layer
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
#endregion
}
#endregion
#region work
if ((container.Nodes.Count > 0) && (blockName != "") && (layer != ""))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
if (acBlkTbl.Has(blockName))
{
foreach (WorkClasses.Node Node in container.Nodes)
{
bool noFictive = false;
foreach (int N in Node.Bends_Numers_Array)
{
WorkClasses.Bend bend = container.Bends[N];
if (!bend.IsFictive())
{
noFictive = true;
break;
}
}
if (noFictive)
{
try
{
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
UCS ucs = Node.CreateNodeUCS(L, ref container);
double[] matrxarr = ucs.GetAutoCAD_Matrix3d();
Matrix3d trM = new Matrix3d(matrxarr);
br.Layer = layer;
br.TransformBy(trM);
acBlkTblRec.AppendEntity(br);
tr.AddNewlyCreatedDBObject(br, true);
Node.SolidHandle = new Pair<int, Handle>(1, br.Handle);
}
catch { }
}
//KojtoCAD_3D_Placement_of_Node_3D_in_Position_By_Numer(Node, blockName, layer, L);
}
}
else
{
MessageBox.Show("\nBlock " + blockName + " Missing !", "Block Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
#endregion
}
else
MessageBox.Show("\nData Base Empty !\n", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_NODE_3D_IN_POSITION_DELETE", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Node_3D_in_Position_Delete()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec;
acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Node Node in container.Nodes)
{
bool noFictive = false;
foreach (int N in Node.Bends_Numers_Array)
{
WorkClasses.Bend bend = container.Bends[N];
if (!bend.IsFictive())
{
noFictive = true;
break;
}
}
if (noFictive)
{
if (Node.SolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(Node.SolidHandle.Second), OpenMode.ForWrite) as Entity;
Node.SolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
ent.Erase();
}
catch
{
Node.SolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
}
}
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_NODE_3D_IN_POSITION_HIDE", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Node_3D_in_Position_Hide()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec;
acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Node Node in container.Nodes)
{
if (Node.SolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(Node.SolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = false;
}
catch { }
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_NODE_3D_IN_POSITION_SHOW", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Node_3D_in_Position_SHOW()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec;
acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Node Node in container.Nodes)
{
if (Node.SolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(Node.SolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = true;
}
catch { }
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_BENDS_NOZZLE_BLOCKS_IN_NODES", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/PLACEMENT_OF_BENDS_NOZZLE_BLOCKS_IN_NODES.htm", "")]
public void KojtoCAD_3D_Placement_of_Bends_Nozzle_Blocks_in_Nodes()
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
string blockName = "";
string layer = "";
double mR = -1.0;
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
#region prompt blockname, layer, R and work
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.EndsOfBends3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.EndsOfBends3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
#region check
layer = pStrRes_.StringResult;
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
pDoubleOpts.Message =
"\n\nEnter the distance from the node point to the origin point of the block,\nmeasured along a line " +
"(the origin Point of the Block must lie on the Line of the Bend):";
pDoubleOpts.AllowNegative = false;
pDoubleOpts.AllowZero = false;
pDoubleOpts.AllowNone = false;
pDoubleOpts.DefaultValue = ConstantsAndSettings.DistanceNodeToNozzle;
PromptDoubleResult pDoubleRes = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
if (pDoubleRes.Status == PromptStatus.OK)
{
mR = pDoubleRes.Value;
#region work
if ((container.Nodes.Count > 0) && (blockName != "") && (layer != "") && (mR > 0.0))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
foreach (WorkClasses.Node Node in container.Nodes)
{
foreach (int N in Node.Bends_Numers_Array)
{
WorkClasses.Bend bend = container.Bends[N];
if (!bend.IsFictive())
{
double bendLen = bend.Length;
double bendHalfLen = bend.Length / 2.0 - mR;
quaternion bQ = bend.MidPoint - Node.Position;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(Node.Position + bQ, bend.MidPoint, bend.Normal);
UCS ucs = new UCS(Node.Position + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(Node.Position).GetZ() > 0)
ucs = new UCS(Node.Position + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
br.Layer = layer;
br.TransformBy(trM);
acBlkTblRec.AppendEntity(br);
tr.AddNewlyCreatedDBObject(br, true);
if ((bend.Start - Node.Position).abs() < (bend.End - Node.Position).abs())
{
bend.startSolidHandle = new Pair<int, Handle>(1, br.Handle);
}
else
{
bend.endSolidHandle = new Pair<int, Handle>(1, br.Handle);
}
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
}
#endregion
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
else
MessageBox.Show("\nData Base Empty !\n", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_BENDS_NOZZLE_3D_IN_POSITION_HIDE", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Bends_Nozzle_in_Position_Hide()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec;
acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.startSolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.startSolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = false;
}
catch { }
}
if (bend.endSolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.endSolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = false;
}
catch { }
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_BENDS_NOZZLE_3D_IN_POSITION_SHOW", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Bends_Nozzle_in_Position_Show()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec;
acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.startSolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.startSolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = true;
}
catch { }
}
if (bend.endSolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.endSolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = true;
}
catch { }
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_BEND_NOZZLE_3D_DELETE", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Bend_Nozzle_3D_Delete()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl;
acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec;
acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.startSolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.startSolidHandle.Second), OpenMode.ForWrite) as Entity;
bend.startSolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
ent.Erase();
}
catch
{
bend.startSolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
}
}
if (bend.endSolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.endSolidHandle.Second), OpenMode.ForWrite) as Entity;
bend.endSolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
ent.Erase();
}
catch
{
bend.endSolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
}
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
//------
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_BENDS_3D", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/PLACEMENT_BENDS_3D.htm", "")]
public void KojtoCAD_3D_Placement_Bends_3D()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");
pKeyOpts.Message = "\nEnter an option ";
pKeyOpts.Keywords.Add("Pereferial");
pKeyOpts.Keywords.Add("NoPereferial");
pKeyOpts.Keywords.Add("All");
pKeyOpts.Keywords.Default = "All";
pKeyOpts.AllowNone = true;
PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts);
if (pKeyRes.Status == PromptStatus.OK)
{
switch (pKeyRes.StringResult)
{
case "NoPereferial": KojtoCAD_3D_Placement_Bends_3D_NoPereferial(); break;
case "Pereferial": KojtoCAD_3D_Placement_Bends_3D_Pereferial(); break;
case "All": KojtoCAD_3D_Placement_Bends_3D_All(); break;
}
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
public void KojtoCAD_3D_Placement_Bends_3D_NoPereferial()
{
string blockName = "";
string layer = "";
double mR = -1.0;
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
#region prompt blockname, layer, R
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.Bends3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.Bends3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
pDoubleOpts.Message =
"\n\nEnter the distance from the node point to the origin point of the block,\nmeasured along a line " +
"(the origin Point of the Block must lie on the Line of the Bend):";
PromptDoubleResult pDoubleRes = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
pDoubleOpts.AllowNegative = false;
pDoubleOpts.AllowZero = false;
pDoubleOpts.AllowNone = false;
if (pDoubleRes.Status == PromptStatus.OK)
{
mR = pDoubleRes.Value;
#region work
if ((container.Bends.Count > 0) && (blockName != "") && (layer != ""))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
foreach (WorkClasses.Bend bend in container.Bends)
{
if (!bend.IsFictive() && !bend.IsPeripheral())
{
double bendLen = bend.Length;
double bendHalfLen = bend.Length / 2.0 - mR;
quaternion bQ = bend.MidPoint - bend.Start;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(bend.Start + bQ, bend.MidPoint, bend.Normal);
UCS ucs = new UCS(bend.Start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(bend.Start).GetZ() > 0)
ucs = new UCS(bend.Start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
double minX = br.Bounds.Value.MinPoint.Z;
double maxX = br.Bounds.Value.MaxPoint.Z;
double lX = Math.Abs(minX) + Math.Abs(maxX);
double kFaktorX = bendHalfLen * 2.0 / lX;
DBObjectCollection temp = new DBObjectCollection();
br.Explode(temp);
if (temp.Count == 1)
{
string type = temp[0].GetType().ToString();
if (type.ToUpper().IndexOf("REGION") >= 0)
{
Region reg = (Region)temp[0];
acBlkTblRec.AppendEntity(reg);
tr.AddNewlyCreatedDBObject(reg, true);
try
{
Solid3d acSol3D = new Solid3d();
acSol3D.SetDatabaseDefaults();
acSol3D.CreateExtrudedSolid(reg, new Vector3d(0, 0, (mR / Math.Abs(mR)) * bendHalfLen * 2.0), new SweepOptions());
acSol3D.Layer = layer;
acSol3D.TransformBy(trM);
acBlkTblRec.AppendEntity(acSol3D);
tr.AddNewlyCreatedDBObject(acSol3D, true);
bend.SolidHandle = new Pair<int, Handle>(1, acSol3D.Handle);
reg.Erase();
}
catch
{
reg.Erase();
}
}
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
}
#endregion
}
public void KojtoCAD_3D_Placement_Bends_3D_Pereferial()
{
string blockName = "";
string layer = "";
double mR = -1.0;
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
#region prompt blockname, layer, R
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.Bends3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.Bends3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
pDoubleOpts.Message =
"\n\nEnter the distance from the node point to the origin point of the block,\nmeasured along a line " +
"(the origin Point of the Block must lie on the Line of the Bend):";
PromptDoubleResult pDoubleRes = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
pDoubleOpts.AllowNegative = false;
pDoubleOpts.AllowZero = false;
pDoubleOpts.AllowNone = false;
if (pDoubleRes.Status == PromptStatus.OK)
{
mR = pDoubleRes.Value;
#region work
if ((container.Bends.Count > 0) && (blockName != "") && (layer != ""))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
foreach (WorkClasses.Bend bend in container.Bends)
{
if (!bend.IsFictive() && bend.IsPeripheral())
{
double bendLen = bend.Length;
double bendHalfLen = bend.Length / 2.0 - mR;
quaternion bQ = bend.MidPoint - bend.Start;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(bend.Start + bQ, bend.MidPoint, bend.Normal);
UCS ucs = new UCS(bend.Start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(bend.Start).GetZ() > 0)
ucs = new UCS(bend.Start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
WorkClasses.Triangle TR = container.Triangles[bend.FirstTriangleNumer];//(
quaternion trCentoid = ucs.FromACS(TR.GetCentroid());//(
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
if (trCentoid.GetY() < 0)
br.TransformBy(Matrix3d.Mirroring(new Line3d(new Point3d(0, 0, 0), new Point3d(100, 0, 0))));
double minX = br.Bounds.Value.MinPoint.Z;
double maxX = br.Bounds.Value.MaxPoint.Z;
double lX = Math.Abs(minX) + Math.Abs(maxX);
double kFaktorX = bendHalfLen * 2.0 / lX;
DBObjectCollection temp = new DBObjectCollection();
br.Explode(temp);
if (temp.Count == 1)
{
string type = temp[0].GetType().ToString();
if (type.ToUpper().IndexOf("REGION") >= 0)
{
Region reg = (Region)temp[0];
acBlkTblRec.AppendEntity(reg);
tr.AddNewlyCreatedDBObject(reg, true);
try
{
Solid3d acSol3D = new Solid3d();
acSol3D.SetDatabaseDefaults();
acSol3D.CreateExtrudedSolid(reg, new Vector3d(0, 0, (mR / Math.Abs(mR)) * bendHalfLen * 2.0), new SweepOptions());
acSol3D.Layer = layer;
acSol3D.TransformBy(trM);
acBlkTblRec.AppendEntity(acSol3D);
tr.AddNewlyCreatedDBObject(acSol3D, true);
bend.SolidHandle = new Pair<int, Handle>(1, acSol3D.Handle);
reg.Erase();
}
catch
{
reg.Erase();
}
}
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
}
#endregion
}
public void KojtoCAD_3D_Placement_Bends_3D_All()
{
string blockName = "";
string layer = "";
double mR = -1.0;
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
#region prompt blockname, layer, R
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.Bends3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.Bends3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
pDoubleOpts.Message =
"\n\nEnter the distance from the node point to the origin point of the block,\nmeasured along a line " +
"(the origin Point of the Block must lie on the Line of the Bend):";
PromptDoubleResult pDoubleRes = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
pDoubleOpts.AllowNegative = true;
pDoubleOpts.AllowZero = true;
pDoubleOpts.AllowNone = false;
if (pDoubleRes.Status == PromptStatus.OK)
{
mR = pDoubleRes.Value;
#region work
if ((container.Bends.Count > 0) && (blockName != "") && (layer != ""))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
foreach (WorkClasses.Bend bend in container.Bends)
{
if (!bend.IsFictive())
{
double bendLen = bend.Length;
double bendHalfLen = bend.Length / 2.0 - mR;
quaternion bQ = bend.MidPoint - bend.Start;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(bend.Start + bQ, bend.MidPoint, bend.Normal);
UCS ucs = new UCS(bend.Start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(bend.Start).GetZ() > 0)
ucs = new UCS(bend.Start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
WorkClasses.Triangle TR = container.Triangles[bend.FirstTriangleNumer];//(
quaternion trCentoid = ucs.FromACS(TR.GetCentroid());//(
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
if (bend.IsPeripheral())
if (trCentoid.GetY() < 0)
br.TransformBy(Matrix3d.Mirroring(new Line3d(new Point3d(0, 0, 0), new Point3d(100, 0, 0))));
double minX = br.Bounds.Value.MinPoint.Z;
double maxX = br.Bounds.Value.MaxPoint.Z;
double lX = Math.Abs(minX) + Math.Abs(maxX);
double kFaktorX = bendHalfLen * 2.0 / lX;
DBObjectCollection temp = new DBObjectCollection();
br.Explode(temp);
if (temp.Count == 1)
{
string type = temp[0].GetType().ToString();
if (type.ToUpper().IndexOf("REGION") >= 0)
{
Region reg = (Region)temp[0];
acBlkTblRec.AppendEntity(reg);
tr.AddNewlyCreatedDBObject(reg, true);
try
{
Solid3d acSol3D = new Solid3d();
acSol3D.SetDatabaseDefaults();
acSol3D.CreateExtrudedSolid(reg, new Vector3d(0, 0, (mR / Math.Abs(mR)) * bendHalfLen * 2.0), new SweepOptions());
acSol3D.Layer = layer;
acSol3D.TransformBy(trM);
acBlkTblRec.AppendEntity(acSol3D);
tr.AddNewlyCreatedDBObject(acSol3D, true);
bend.SolidHandle = new Pair<int, Handle>(1, acSol3D.Handle);
reg.Erase();
}
catch
{
reg.Erase();
}
}
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
}
#endregion
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_BENDS_3D_BY_NORMALS", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/PLACEMENT_BENDS_3D_BY_NORMALS.htm", "")]
public void KojtoCAD_3D_Placement_Bends_3D_By_Normals()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");
pKeyOpts.Message = "\nEnter an option ";
pKeyOpts.Keywords.Add("Pereferial");
pKeyOpts.Keywords.Add("NoPereferial");
pKeyOpts.Keywords.Add("All");
pKeyOpts.Keywords.Default = "All";
pKeyOpts.AllowNone = true;
PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts);
if (pKeyRes.Status == PromptStatus.OK)
{
switch (pKeyRes.StringResult)
{
case "NoPereferial": KojtoCAD_3D_Placement_Bends_3D_NoPereferial_By_Normals(); break;
case "Pereferial": KojtoCAD_3D_Placement_Bends_3D_Pereferial_By_Normals(); break;
case "All": KojtoCAD_3D_Placement_Bends_3D_All_By_Normals(); break;
}
}
}
catch { }
finally
{
ed.CurrentUserCoordinateSystem = old;
}
}
public void KojtoCAD_3D_Placement_Bends_3D_All_By_Normals()
{
string blockName = "";
string layer = "";
double mR = -1.0;
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
#region prompt blockname, layer, R
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.Bends3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.Bends3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
pDoubleOpts.Message =
"\n\nEnter the distance from the node point to the origin point of the block,\nmeasured along a line " +
"(the origin Point of the Block must lie on the Line of the Bend):";
PromptDoubleResult pDoubleRes = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
pDoubleOpts.AllowNegative = true;
pDoubleOpts.AllowZero = true;
pDoubleOpts.AllowNone = false;
if (pDoubleRes.Status == PromptStatus.OK)
{
mR = pDoubleRes.Value;
if (Math.Abs(mR) == 0.0) { mR = 0.000001; }
#region work
if ((container.Bends.Count > 0) && (blockName != "") && (layer != ""))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
foreach (WorkClasses.Bend bend in container.Bends)
{
if (!bend.IsFictive())
{
quaternion start = container.Nodes[bend.StartNodeNumer].Normal - container.Nodes[bend.StartNodeNumer].Position;
quaternion end = container.Nodes[bend.EndNodeNumer].Normal - container.Nodes[bend.EndNodeNumer].Position;
start /= start.abs();
end /= end.abs();
if ((object)container.Nodes[bend.StartNodeNumer].ExplicitNormal == null)
start *= ConstantsAndSettings.NormlLengthToShow;
else
start *= container.Nodes[bend.StartNodeNumer].ExplicitNormalLength;
if ((object)container.Nodes[bend.EndNodeNumer].ExplicitNormal == null)
end *= ConstantsAndSettings.NormlLengthToShow;
else
end *= container.Nodes[bend.EndNodeNumer].ExplicitNormalLength;
start += container.Nodes[bend.StartNodeNumer].Position;
end += container.Nodes[bend.EndNodeNumer].Position;
quaternion mid = (end + start) / 2.0;
double bendLen = (end - start).abs();// bend.Length;
double bendHalfLen = bendLen / 2.0 - mR;
quaternion bQ = mid - start;//bend.MidPoint - bend.Start;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(start + bQ, mid, mid + (bend.Normal - bend.MidPoint));
UCS ucs = new UCS(start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(start).GetZ() > 0)
ucs = new UCS(start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
WorkClasses.Triangle TR = container.Triangles[bend.FirstTriangleNumer];//(
quaternion trCentoid = ucs.FromACS(TR.GetCentroid());//(
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
if (bend.IsPeripheral())
if (trCentoid.GetY() < 0)
br.TransformBy(Matrix3d.Mirroring(new Line3d(new Point3d(0, 0, 0), new Point3d(100, 0, 0))));
double minX = br.Bounds.Value.MinPoint.Z;
double maxX = br.Bounds.Value.MaxPoint.Z;
double lX = Math.Abs(minX) + Math.Abs(maxX);
double kFaktorX = bendHalfLen * 2.0 / lX;
DBObjectCollection temp = new DBObjectCollection();
br.Explode(temp);
if (temp.Count == 1)
{
string type = temp[0].GetType().ToString();
if (type.ToUpper().IndexOf("REGION") >= 0)
{
Region reg = (Region)temp[0];
acBlkTblRec.AppendEntity(reg);
tr.AddNewlyCreatedDBObject(reg, true);
try
{
Solid3d acSol3D = new Solid3d();
acSol3D.SetDatabaseDefaults();
acSol3D.CreateExtrudedSolid(reg, new Vector3d(0, 0, (mR / Math.Abs(mR)) * bendHalfLen * 2.0), new SweepOptions());
acSol3D.Layer = layer;
acSol3D.TransformBy(trM);
acBlkTblRec.AppendEntity(acSol3D);
tr.AddNewlyCreatedDBObject(acSol3D, true);
bend.SolidHandle = new Pair<int, Handle>(1, acSol3D.Handle);
reg.Erase();
}
catch
{
reg.Erase();
}
}
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
}
#endregion
}
public void KojtoCAD_3D_Placement_Bends_3D_Pereferial_By_Normals()
{
string blockName = "";
string layer = "";
double mR = -1.0;
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
#region prompt blockname, layer, R
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.Bends3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.Bends3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
pDoubleOpts.Message =
"\n\nEnter the distance from the node point to the origin point of the block,\nmeasured along a line " +
"(the origin Point of the Block must lie on the Line of the Bend):";
PromptDoubleResult pDoubleRes = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
pDoubleOpts.AllowNegative = true;
pDoubleOpts.AllowZero = true;
pDoubleOpts.AllowNone = false;
if (pDoubleRes.Status == PromptStatus.OK)
{
mR = pDoubleRes.Value;
if (Math.Abs(mR) == 0.0) { mR = 0.000001; }
#region work
if ((container.Bends.Count > 0) && (blockName != "") && (layer != ""))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
foreach (WorkClasses.Bend bend in container.Bends)
{
if (!bend.IsFictive() && bend.IsPeripheral())
{
quaternion start = container.Nodes[bend.StartNodeNumer].Normal - container.Nodes[bend.StartNodeNumer].Position;
quaternion end = container.Nodes[bend.EndNodeNumer].Normal - container.Nodes[bend.EndNodeNumer].Position;
start /= start.abs();
end /= end.abs();
if ((object)container.Nodes[bend.StartNodeNumer].ExplicitNormal == null)
start *= ConstantsAndSettings.NormlLengthToShow;
else
start *= container.Nodes[bend.StartNodeNumer].ExplicitNormalLength;
if ((object)container.Nodes[bend.EndNodeNumer].ExplicitNormal == null)
end *= ConstantsAndSettings.NormlLengthToShow;
else
end *= container.Nodes[bend.EndNodeNumer].ExplicitNormalLength;
start += container.Nodes[bend.StartNodeNumer].Position;
end += container.Nodes[bend.EndNodeNumer].Position;
quaternion mid = (end + start) / 2.0;
double bendLen = (end - start).abs();// bend.Length;
double bendHalfLen = bendLen / 2.0 - mR;
quaternion bQ = mid - start;//bend.MidPoint - bend.Start;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(start + bQ, mid, mid + (bend.Normal - bend.MidPoint));
UCS ucs = new UCS(start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(start).GetZ() > 0)
ucs = new UCS(start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
WorkClasses.Triangle TR = container.Triangles[bend.FirstTriangleNumer];//(
quaternion trCentoid = ucs.FromACS(TR.GetCentroid());//(
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
if (bend.IsPeripheral())
if (trCentoid.GetY() < 0)
br.TransformBy(Matrix3d.Mirroring(new Line3d(new Point3d(0, 0, 0), new Point3d(100, 0, 0))));
double minX = br.Bounds.Value.MinPoint.Z;
double maxX = br.Bounds.Value.MaxPoint.Z;
double lX = Math.Abs(minX) + Math.Abs(maxX);
double kFaktorX = bendHalfLen * 2.0 / lX;
DBObjectCollection temp = new DBObjectCollection();
br.Explode(temp);
if (temp.Count == 1)
{
string type = temp[0].GetType().ToString();
if (type.ToUpper().IndexOf("REGION") >= 0)
{
Region reg = (Region)temp[0];
acBlkTblRec.AppendEntity(reg);
tr.AddNewlyCreatedDBObject(reg, true);
try
{
Solid3d acSol3D = new Solid3d();
acSol3D.SetDatabaseDefaults();
acSol3D.CreateExtrudedSolid(reg, new Vector3d(0, 0, (mR / Math.Abs(mR)) * bendHalfLen * 2.0), new SweepOptions());
acSol3D.Layer = layer;
acSol3D.TransformBy(trM);
acBlkTblRec.AppendEntity(acSol3D);
tr.AddNewlyCreatedDBObject(acSol3D, true);
bend.SolidHandle = new Pair<int, Handle>(1, acSol3D.Handle);
reg.Erase();
}
catch
{
reg.Erase();
}
}
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
}
#endregion
}
public void KojtoCAD_3D_Placement_Bends_3D_NoPereferial_By_Normals()
{
string blockName = "";
string layer = "";
double mR = -1.0;
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
#region prompt blockname, layer, R
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.Bends3DBlock;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.Bends3DLayer;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
pDoubleOpts.Message =
"\n\nEnter the distance from the node point to the origin point of the block,\nmeasured along a line " +
"(the origin Point of the Block must lie on the Line of the Bend):";
PromptDoubleResult pDoubleRes = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
pDoubleOpts.AllowNegative = true;
pDoubleOpts.AllowZero = true;
pDoubleOpts.AllowNone = false;
if (pDoubleRes.Status == PromptStatus.OK)
{
mR = pDoubleRes.Value;
if (Math.Abs(mR) == 0.0) { mR = 0.000001; }
#region work
if ((container.Bends.Count > 0) && (blockName != "") && (layer != ""))
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
SymbolUtilityServices.ValidateSymbolName(blockName, false);
SymbolUtilityServices.ValidateSymbolName(layer, false);
foreach (WorkClasses.Bend bend in container.Bends)
{
if (!bend.IsFictive() && !bend.IsPeripheral())
{
quaternion start = container.Nodes[bend.StartNodeNumer].Normal - container.Nodes[bend.StartNodeNumer].Position;
quaternion end = container.Nodes[bend.EndNodeNumer].Normal - container.Nodes[bend.EndNodeNumer].Position;
start /= start.abs();
end /= end.abs();
if ((object)container.Nodes[bend.StartNodeNumer].ExplicitNormal == null)
start *= ConstantsAndSettings.NormlLengthToShow;
else
start *= container.Nodes[bend.StartNodeNumer].ExplicitNormalLength;
if ((object)container.Nodes[bend.EndNodeNumer].ExplicitNormal == null)
end *= ConstantsAndSettings.NormlLengthToShow;
else
end *= container.Nodes[bend.EndNodeNumer].ExplicitNormalLength;
start += container.Nodes[bend.StartNodeNumer].Position;
end += container.Nodes[bend.EndNodeNumer].Position;
quaternion mid = (end + start) / 2.0;
double bendLen = (end - start).abs();// bend.Length;
double bendHalfLen = bendLen / 2.0 - mR;
quaternion bQ = mid - start;//bend.MidPoint - bend.Start;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(start + bQ, mid, mid + (bend.Normal - bend.MidPoint));
UCS ucs = new UCS(start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(start).GetZ() > 0)
ucs = new UCS(start + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
WorkClasses.Triangle TR = container.Triangles[bend.FirstTriangleNumer];//(
quaternion trCentoid = ucs.FromACS(TR.GetCentroid());//(
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
if (bend.IsPeripheral())
if (trCentoid.GetY() < 0)
br.TransformBy(Matrix3d.Mirroring(new Line3d(new Point3d(0, 0, 0), new Point3d(100, 0, 0))));
double minX = br.Bounds.Value.MinPoint.Z;
double maxX = br.Bounds.Value.MaxPoint.Z;
double lX = Math.Abs(minX) + Math.Abs(maxX);
double kFaktorX = bendHalfLen * 2.0 / lX;
DBObjectCollection temp = new DBObjectCollection();
br.Explode(temp);
if (temp.Count == 1)
{
string type = temp[0].GetType().ToString();
if (type.ToUpper().IndexOf("REGION") >= 0)
{
Region reg = (Region)temp[0];
acBlkTblRec.AppendEntity(reg);
tr.AddNewlyCreatedDBObject(reg, true);
try
{
Solid3d acSol3D = new Solid3d();
acSol3D.SetDatabaseDefaults();
acSol3D.CreateExtrudedSolid(reg, new Vector3d(0, 0, (mR / Math.Abs(mR)) * bendHalfLen * 2.0), new SweepOptions());
acSol3D.Layer = layer;
acSol3D.TransformBy(trM);
acBlkTblRec.AppendEntity(acSol3D);
tr.AddNewlyCreatedDBObject(acSol3D, true);
bend.SolidHandle = new Pair<int, Handle>(1, acSol3D.Handle);
reg.Erase();
}
catch
{
reg.Erase();
}
}
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#endregion
}
}
}
#endregion
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_BEND_3D_DELETE", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_Bends_3D_Delete()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if (container.Bends.Count > 0)
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.SolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.SolidHandle.Second), OpenMode.ForWrite) as Entity;
bend.SolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
ent.Erase();
}
catch
{
bend.SolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
}
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_BENDS_3D_IN_POSITION_HIDE", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Bends_in_Position_Hide()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if (container.Bends.Count > 0)
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.SolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.SolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = false;
}
catch { }
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_PLACEMENT_OF_BENDS_3D_IN_POSITION_SHOW", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/SHOW_OR_HIDE_3D.htm", "")]
public void KojtoCAD_3D_Placement_of_Bends_in_Position_Show()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if (container.Bends.Count > 0)
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.SolidHandle.First >= 0)
{
try
{
Entity ent = tr.GetObject(GlobalFunctions.GetObjectId(bend.SolidHandle.Second), OpenMode.ForWrite) as Entity;
ent.Visible = true;
}
catch { }
}
}
tr.Commit();
Application.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
}
}
else
{
MessageBox.Show("\nData Base Empty !\n\nMissing Nodes !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
//---------
[CommandMethod("KojtoCAD_3D", "KCAD_CALC_MIN_CAM_RADIUS", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/CALC_MIN_CAM_RADIUS.htm", "")]
public void KojtoCAD_Calc_Miin_Cam_Radius()
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if (container.Nodes.Count > 0)
{
double minR = 0;
int nodeNumer = -1;
System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
dlg.Filter = "Text Files|*.txt|All Files|*.*";
dlg.Title = "Enter File Name ";
dlg.DefaultExt = "txt";
dlg.FileName = "*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName = dlg.FileName;
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter test Block Name: ");
pStrOpts.AllowSpaces = false;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
string blockName = pStrRes.StringResult;
//PromptDoubleOptions pDoubleOpts = new PromptDoubleOptions("");
//pDoubleOpts.Message = "\n\nEnter the start Radius: ";
//PromptDoubleResult pDoubleRes = MgdAcApplication.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts);
// pDoubleOpts.AllowNegative = false;
// pDoubleOpts.AllowZero = false;
//pDoubleOpts.AllowNone = false;
//if (pDoubleRes.Status == PromptStatus.OK)
{
PromptDoubleOptions pDoubleOpts_ = new PromptDoubleOptions("");
pDoubleOpts_.Message = "\n\nEnter minimal Thickness of the Material between the Ends of the Bends: ";
PromptDoubleResult pDoubleRes_ = Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(pDoubleOpts_);
pDoubleOpts_.AllowNegative = false;
pDoubleOpts_.AllowZero = false;
pDoubleOpts_.AllowNone = false;
if (pDoubleRes_.Status == PromptStatus.OK)
{
new Utilities.UtilityClass().MinimizeWindow();
try
{
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
using (StreamWriter sw = new StreamWriter(fileName))
{
foreach (WorkClasses.Node Node in container.Nodes)
{
bool isfictve = true;
#region check for fictive
foreach (int N in Node.Bends_Numers_Array)
{
if (!container.Bends[N].IsFictive())
{
isfictve = false;
break;
}
}
#endregion
if (!isfictve)
{
List<Pair<Entity, quaternion>> coll = NodeFillWithNozzles(tr, ref acBlkTbl, ref acBlkTblRec, Node, 0.0, blockName);
double dist = 0;
double mdist = 10.0;
double minANG = 0.0;
while (CheckInterference(ref coll, ref minANG))
{
MoveNozzleByBendLine(mdist, ref coll);
dist += mdist;
}
dist -= mdist;
MoveNozzleByBendLine(mdist, ref coll, -1);
mdist = 1.0;
while (CheckInterference(ref coll, ref minANG))
{
MoveNozzleByBendLine(mdist, ref coll);
dist += mdist;
}
double L = pDoubleRes_.Value / Math.Sqrt(2.0 * (1 - Math.Cos(minANG)));
dist += L;
sw.WriteLine(string.Format("Node: {0} Minimal Radius = {1:f4} minAngular = {2:f4}", Node.Numer + 1, dist + 1.0 /*pDoubleRes.Value*/ , minANG * 180.0 / Math.PI));
if ((dist + 0.0/*pDoubleRes.Value*/) > minR)
{
minR = dist + 0.0;// pDoubleRes.Value;
nodeNumer = Node.Numer;
}
}
else
{
sw.WriteLine(string.Format("Node: {0} - All Bends are Fictive", Node.Numer + 1));
}
}
sw.WriteLine("-----------------------------------");
sw.WriteLine(string.Format("Node: {0} Minimal Radius = {1:f4}", nodeNumer + 1, minR));
sw.Flush();
sw.Close();
}//
//tr.Commit();
//ed.UpdateScreen();
}
}
catch
{
new Utilities.UtilityClass().MaximizeWindow();
}
}
}//
new Utilities.UtilityClass().MaximizeWindow();
MessageBox.Show(string.Format("Node: {0} Minimal Radius = {1:f4}", nodeNumer + 1, minR), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
public List<Pair<Entity, quaternion>> NodeFillWithNozzles(Transaction tr, ref BlockTable acBlkTbl, ref BlockTableRecord acBlkTblRec, WorkClasses.Node node, double mR, string blockName)
{
List<Pair<Entity, quaternion>> coll = new List<Pair<Entity, quaternion>>();
foreach (int N in node.Bends_Numers_Array)
{
WorkClasses.Bend bend = container.Bends[N];
if (!bend.IsFictive())
{
double bendLen = bend.Length;
double bendHalfLen = bend.Length / 2.0 - mR;
quaternion bQ = bend.MidPoint - node.Position;
bQ /= bQ.abs(); bQ *= mR;
UCS UCS = new UCS(node.Position + bQ, bend.MidPoint, bend.Normal);
UCS ucs = new UCS(node.Position + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(node.Position).GetZ() > 0)
ucs = new UCS(node.Position + bQ, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
DBObjectCollection tColl = new DBObjectCollection();
br.Explode(tColl);
// ((Solid3d)tColl[0]).OffsetBody(offset);
((Entity)tColl[0]).TransformBy(trM);
coll.Add(new Pair<Entity, quaternion>((Entity)tColl[0], (bend.MidPoint - node.Position) / (bend.MidPoint - node.Position).abs()));
acBlkTblRec.AppendEntity(((Entity)tColl[0]));
tr.AddNewlyCreatedDBObject(((Entity)tColl[0]), true);
}
}
return coll;
}
public void MoveNozzleByBendLine(double dist, ref List<Pair<Entity, quaternion>> coll, int k = 1)
{
foreach (Pair<Entity, quaternion> pa in coll)
pa.First.TransformBy(Matrix3d.Displacement(new Vector3d(pa.Second.GetX() * dist * k, pa.Second.GetY() * dist * k, pa.Second.GetZ() * dist * k)));
}
public bool CheckInterference(ref List<Pair<Entity, quaternion>> coll, ref double ang)
{
bool rez = false;
for (int i = 0; i < coll.Count - 1; i++)
{
for (int j = i + 1; j < coll.Count; j++)
{
bool b = ((Solid3d)coll[i].First).CheckInterference((Solid3d)coll[j].First);
if (b)
{
rez = true;
ang = coll[i].Second.angTo(coll[j].Second);
break;
}
}
if (rez)
break;
}
return rez;
}
//----- Fixing elements
[CommandMethod("KojtoCAD_3D", "KCAD_ADD_FIXING_ELEMENTS", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/ADD_FIXING_ELEMENTS.htm", "")]
public void KojtoCAD_Add_Fixing_Elements()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");
pKeyOpts.Message = "\nEnter an option ";
pKeyOpts.Keywords.Add("Pereferial");
pKeyOpts.Keywords.Add("NoPereferial");
pKeyOpts.Keywords.Default = "NoPereferial";
pKeyOpts.AllowNone = true;
PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts);
if (pKeyRes.Status == PromptStatus.OK)
{
switch (pKeyRes.StringResult)
{
case "NoPereferial": KojtoCAD_Add_Fixing_Elements_NoPereferial(); break;
case "Pereferial": KojtoCAD_Add_Fixing_Elements_Pereferial(); break;
}
}
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
public void KojtoCAD_Add_Fixing_Elements_NoPereferial()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
if ((container != null) && (container.Bends.Count > 0))
{
Fixing_Elements_Setings form = new Fixing_Elements_Setings();
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)
{
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.NoPereferialFixngBlockName;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
string blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.NoPereferialFixngLayerName;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
string layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
ConstantsAndSettings.SetFixing_A(form.A);
ConstantsAndSettings.SetFixing_B(form.B);
List<Pair<Entity, quaternion>> coll = new List<Pair<Entity, quaternion>>();
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.IsFictive() || bend.IsPeripheral()) continue;
UCS UCS = new UCS(bend.Start, bend.MidPoint, bend.Normal);
UCS ucs = new UCS(bend.Start, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(bend.Start).GetZ() > 0)
ucs = new UCS(bend.Start, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
double bLength = bend.Length;
double mA = form.A;
double mB = form.B;
int dN = (int)((bLength - 2.0 * mA) / mB);
mA = (bLength - dN * mB) / 2.0;
quaternion ort = bend.End - bend.Start;
ort /= ort.abs();
for (int i = 0; i <= dN; i++)
{
double vLen = mB * i + mA;
quaternion Pos = ort * vLen;
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
br.TransformBy(trM);
br.TransformBy(Matrix3d.Displacement(new Vector3d(Pos.GetX(), Pos.GetY(), Pos.GetZ())));
DBObjectCollection tColl = new DBObjectCollection();
br.Explode(tColl);
foreach (DBObject obj in tColl)
{
((Entity)obj).Layer = layer;
acBlkTblRec.AppendEntity((Entity)obj);
tr.AddNewlyCreatedDBObject((Entity)obj, true);
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
}
}
}
else
MessageBox.Show("Data Base Missing !", "E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void KojtoCAD_Add_Fixing_Elements_Pereferial()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
if ((container != null) && (container.Bends.Count > 0))
{
Fixing_Elements_Setings form = new Fixing_Elements_Setings(true);
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)
{
PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter Block Name: ");
pStrOpts.AllowSpaces = false;
pStrOpts.DefaultValue = ConstantsAndSettings.PereferialFixngBlockName;
PromptResult pStrRes;
pStrRes = ed.GetString(pStrOpts);
if (pStrRes.Status == PromptStatus.OK)
{
string blockName = pStrRes.StringResult;
PromptStringOptions pStrOpts_ = new PromptStringOptions("\nEnter Solids Layer Name: ");
pStrOpts_.AllowSpaces = false;
pStrOpts_.DefaultValue = ConstantsAndSettings.PereferialFixngLayerName;
PromptResult pStrRes_;
pStrRes_ = ed.GetString(pStrOpts_);
if (pStrRes_.Status == PromptStatus.OK)
{
string layer = pStrRes_.StringResult;
#region check
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
if (!acBlkTbl.Has(blockName))
{
MessageBox.Show("\nMissing Block " + blockName + " !", "Block E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
blockName = "";
return;
}
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
if (!lt.Has(layer))
{
MessageBox.Show("\nMissing Layer " + layer + " !", "Layer E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
layer = "";
return;
}
}
#endregion
ConstantsAndSettings.SetFixing_pereferial_A(form.A);
ConstantsAndSettings.SetFixing_pereferial_B(form.B);
List<Pair<Entity, quaternion>> coll = new List<Pair<Entity, quaternion>>();
using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
{
BlockTable acBlkTbl = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (bend.IsFictive() || !bend.IsPeripheral()) continue;
UCS UCS = new UCS(bend.Start, bend.MidPoint, bend.Normal);
UCS ucs = new UCS(bend.Start, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, 100)));
if (ucs.FromACS(bend.Start).GetZ() > 0)
ucs = new UCS(bend.Start, UCS.ToACS(new quaternion(0, 0, 100, 0)), UCS.ToACS(new quaternion(0, 0, 0, -100)));
WorkClasses.Triangle TR = container.Triangles[bend.FirstTriangleNumer];
quaternion trCentoid = ucs.FromACS(TR.GetCentroid());
Matrix3d trM = new Matrix3d(ucs.GetAutoCAD_Matrix3d());
double bLength = bend.Length;
double mA = form.A;
double mB = form.B;
int dN = (int)((bLength - 2.0 * mA) / mB);
mA = (bLength - dN * mB) / 2.0;
quaternion ort = bend.End - bend.Start;
ort /= ort.abs();
for (int i = 0; i <= dN; i++)
{
double vLen = mB * i + mA;
quaternion Pos = ort * vLen;
BlockTableRecord btr = tr.GetObject(acBlkTbl[blockName], OpenMode.ForWrite) as BlockTableRecord;
BlockReference br = new BlockReference(Point3d.Origin, btr.ObjectId);
if (trCentoid.GetY() < 0)
br.TransformBy(Matrix3d.Mirroring(new Line3d(new Point3d(0, 0, 0), new Point3d(100, 0, 0))));
br.TransformBy(trM);
br.TransformBy(Matrix3d.Displacement(new Vector3d(Pos.GetX(), Pos.GetY(), Pos.GetZ())));
DBObjectCollection tColl = new DBObjectCollection();
br.Explode(tColl);
foreach (DBObject obj in tColl)
{
((Entity)obj).Layer = layer;
acBlkTblRec.AppendEntity((Entity)obj);
tr.AddNewlyCreatedDBObject((Entity)obj, true);
}
}
}
tr.Commit();
ed.UpdateScreen();
}
}
}
}
}
else
MessageBox.Show("Data Base Missing !", "E R R O R", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
[CommandMethod("KojtoCAD_3D", "KCAD_ATTACHING_A_SOLID3D_TO_BEND", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/ATTACHING_A_SOLID3D_TO_BEND.htm", "")]
public void KojtoCAD_3D_Attaching_Solid3d_to_Bend()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
if ((container != null) && (container.Bends.Count > 0))
{
ObjectIdCollection coll = new ObjectIdCollection();
TypedValue[] acTypValAr = new TypedValue[1];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "3DSOLID"), 0);
do
{
PromptPointResult pPtRes;
PromptPointOptions pPtOpts = new PromptPointOptions("");
pPtOpts.Message = "\nEnter the first Mid (or an internal) Point of the Bend: ";
pPtRes = Application.DocumentManager.MdiActiveDocument.Editor.GetPoint(pPtOpts);
if (pPtRes.Status == PromptStatus.OK)
{
Point3d ptFirst = pPtRes.Value;
foreach (WorkClasses.Bend bend in container.Bends)
{
if (!bend.IsFictive())
{
if (bend == ptFirst)
{
PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");
pKeyOpts.Message = "\nEnter an option ";
pKeyOpts.Keywords.Add("Null");
pKeyOpts.Keywords.Add("Set");
pKeyOpts.Keywords.Default = "Set";
pKeyOpts.AllowNone = false;
PromptResult pKeyRes = Application.DocumentManager.MdiActiveDocument.Editor.GetKeywords(pKeyOpts);
if (pKeyRes.Status == PromptStatus.OK)
{
switch (pKeyRes.StringResult)
{
case "Null":
//MessageBox.Show(string.Format("{0}", bend.SolidHandle.First));
container.Bends[bend.Numer].SolidHandle = new Pair<int, Handle>(-1, new Handle(-1));
//MessageBox.Show(string.Format("{0}", bend.SolidHandle.First));
break;
case "Set":
try
{
List<Entity> solids = GlobalFunctions.GetSelection(ref acTypValAr, "Select Solid3d: ");
if (solids.Count == 1)
{
bend.SolidHandle = new Pair<int, Handle>(1, solids[0].Handle);
coll.Add(solids[0].ObjectId);
}
else
{
if (solids.Count < 1)
{
MessageBox.Show("Solid3d not selected !", "Empty Selection ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (solids.Count > 1)
MessageBox.Show("You have selected more than one Solids !", "Selection ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch
{
MessageBox.Show("Selection Error", "Error !");
}
break;
}
}
break;
}
}
}
}//
} while (MessageBox.Show("Repeat Selection ? ", "Selection", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes);
if (coll.Count > 0)
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
foreach (ObjectId ID in coll)
{
Entity ent = tr.GetObject(ID, OpenMode.ForWrite) as Entity;
ent.Visible = true;
}
tr.Commit();
}
}
}
else
MessageBox.Show("\nData Base Empty !\n\nMissing Bends !", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch { }
finally { ed.CurrentUserCoordinateSystem = old; }
}
[CommandMethod("KojtoCAD_3D", "KCAD_CUTTING_BENDS_IN_NODES", null, CommandFlags.Modal, null, "http://3dsoft.blob.core.windows.net/kojtocad/html/CUTTING_BENDS_IN_NODES.htm", "")]
public void KCAD_CUTTING_BENDS_IN_NODES()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Matrix3d old = ed.CurrentUserCoordinateSystem;
ed.CurrentUserCoordinateSystem = Matrix3d.Identity;
try
{
PromptKeywordOptions pop = new PromptKeywordOptions("");
pop.AppendKeywordsToMessage = true;
pop.AllowNone = false;
pop.Keywords.Add("Run");
pop.Keywords.Add("Help");
pop.Keywords.Default = "Run";
PromptResult res = ed.GetKeywords(pop);
//_AcAp.Application.ShowAlertDialog(res.ToString());
if (res.Status == PromptStatus.OK)
{
switch (res.StringResult)
{
case "Run":
//----------------
PromptKeywordOptions pop_ = new PromptKeywordOptions("");
pop_.AppendKeywordsToMessage = true;
pop_.AllowNone = false;
pop_.Keywords.Add("Base");
pop_.Keywords.Add("Additional");
pop_.Keywords.Default = "Base";
PromptResult res_ = ed.GetKeywords(pop_);
if (res_.Status == PromptStatus.OK)
{
switch (res_.StringResult)
{
case "Base": KCAD_CUTTING_BENDS_IN_NODES_PRE(); break;
case "Additional": KCAD_CUTTING_BENDS_IN_NODES_PRE(false); break;
}
}
//----------------
break;
case "Help":
GlobalFunctions.OpenHelpHTML("http://3dsoft.blob.core.windows.net/kojtocad/html/CUTTING_BENDS_IN_NODES.htm");
break;
}
}
}
catch (System.Exception ex)
{
Application.ShowAlertDialog(
string.Format("\nError: {0}\nStackTrace: {1}", ex.Message, ex.StackTrace));
}
finally { ed.CurrentUserCoordinateSystem = old; }
}
public void KCAD_CUTTING_BENDS_IN_NODES_PRE(bool variant = true)
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
if ((container != null) && (container.Bends.Count > 0) && (container.Nodes.Count > 0) && (container.Triangles.Count > 0))
{
foreach (WorkClasses.Node node in container.Nodes)
{
foreach (int N in node.Bends_Numers_Array)
{
WorkClasses.Bend bend0 = container.Bends[N];
if (!bend0.IsFictive() && (bend0.SolidHandle.First >= 0))
{
quaternion MID = bend0.GetMid();
using (Transaction tr = db.TransactionManager.StartTransaction())
{
Solid3d bendSolid = tr.GetObject(GlobalFunctions.GetObjectId(bend0.SolidHandle.Second), OpenMode.ForWrite) as Solid3d;
foreach (int NN in node.Bends_Numers_Array)
{
if (NN == N) { continue; }
if (container.Bends[NN].IsFictive()) { continue; }
ObjectId ID = ObjectId.Null;
if (node.ExplicitCuttingMethodForEndsOf3D_Bends < 0)
{
if (variant)
ID = GlobalFunctions.GetCutterWall(N, NN, node.Position, node.GetNodesNormalsByNoFictiveBends(ref container), MID, ref container, 100000, 0, 10000);
else
ID = GlobalFunctions.GetCutterWall(N, NN, node.Position, MID, ref container, 100000, 0, 10000);
}
else
{
if (node.ExplicitCuttingMethodForEndsOf3D_Bends == 0)
ID = GlobalFunctions.GetCutterWall(N, NN, node.Position, node.GetNodesNormalsByNoFictiveBends(ref container), MID, ref container, 100000, 0, 10000);
else
if (node.ExplicitCuttingMethodForEndsOf3D_Bends == 1)
ID = GlobalFunctions.GetCutterWall(N, NN, node.Position, MID, ref container, 100000, 0, 10000);
}
if (ID != ObjectId.Null)
{
Solid3d cSolid = tr.GetObject(ID, OpenMode.ForWrite) as Solid3d;
bendSolid.BooleanOperation(BooleanOperationType.BoolSubtract, cSolid);
}
}
tr.Commit();
}
}
}
}
}//
else
MessageBox.Show("\nData Base Empty !\n", "Range Error !", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
| kojtoLtd/KojtoCAD | KojtoCAD.2012/KojtoCAD3D/Placement.cs | C# | mit | 138,960 |
print ("Hello python world! My first python script!!")
print ("feeling excited!!") | balajithangamani/LearnPy | hello.py | Python | mit | 82 |
<?php
/**
* キーと値の取得サンプル
*/
//キーの取得(連想配列)
//インデックスはいてるでも使用できますが
//あまり意味がないため割愛します。
$array_associat = array(
'blue' => '空',
'yellow' => 'バナナ',
'red' => '血液'
);
$keys = array_keys($array_associat);
var_dump($keys);
//値の取得(連想配列)
//インデックスはいてるでも使用できますが
//あまり意味がないため割愛します。
$values = array_values($array_associat);
var_dump($values);
?>
| Kaoru-1127/php | fuel/app/views/array/array_sample5.php | PHP | mit | 568 |
<?php
namespace Application\Modules\Rest;
use \Phalcon\Mvc\Router\Group;
/**
* Routes Rest V1. Api router component
*
* @package Application\Modules\Rest
* @subpackage Routes
* @since PHP >=5.6
* @version 1.0
* @author Stanislav WEB | Lugansk <stanisov@gmail.com>
* @copyright Stanislav WEB
* @filesource /Application/Modules/Rest/Routes.php
*/
class Routes extends Group {
/**
* Initialize routes Rest V1
*/
public function initialize()
{
$this->setPaths([
'module' => 'Rest',
]);
$this->setPrefix('/api');
$this->addGet('/v1/:controller/:params', [
'namespace' => 'Application\Modules\Rest\Controllers',
'controller' => 1,
'action' => 'get',
'params' => 2,
]);
$this->addPost('/v1/:controller/:params', [
'namespace' => 'Application\Modules\Rest\Controllers',
'controller' => 1,
'action' => 'post',
'params' => 2,
]);
$this->addPut('/v1/:controller/:params', [
'namespace' => 'Application\Modules\Rest\Controllers',
'controller' => 1,
'action' => 'put',
'params' => 2,
]);
$this->addDelete('/v1/:controller/:params', [
'namespace' => 'Application\Modules\Rest\Controllers',
'controller' => 1,
'action' => 'delete',
'params' => 2,
]);
}
} | stanislav-web/Phalcon-development | Application/Modules/Rest/Routes.php | PHP | mit | 1,560 |
package iso20022
// Choice between a standard code or proprietary code to specify a rate type.
type RateType49Choice struct {
// Standard code to specify the type of gross dividend rate.
Code *GrossDividendRateType2Code `xml:"Cd"`
// Proprietary identification of the type of gross dividend rate.
Proprietary *GenericIdentification47 `xml:"Prtry"`
}
func (r *RateType49Choice) SetCode(value string) {
r.Code = (*GrossDividendRateType2Code)(&value)
}
func (r *RateType49Choice) AddProprietary() *GenericIdentification47 {
r.Proprietary = new(GenericIdentification47)
return r.Proprietary
}
| fgrid/iso20022 | RateType49Choice.go | GO | mit | 601 |
# -*- coding: utf-8 -*-
require "spec_helper"
require "date"
describe Date do
describe "Meiji period to Heisei period" do
it "should parse gregorian calendar date correctly" do
Date.parse("2012-02-15").should == Date.new(2012, 2, 15)
Date.parse("2012/02/15").should == Date.new(2012, 2, 15)
end
it "should parse Meiji period but uses Gregorian calendar" do
# 明治元(1)年〜明治5年は太陰太陽暦
# 明治6年〜はグレゴリオ歴
# Ruby の Date class は明治元年〜明治6年にもグレゴリオ歴を使っているので正しくない
# From Meiji 1st to Meiji 5th uses Lunisolar calendar
# From Meiji 6th uses Gregorian calendar
# Meiji 1st to 5th uses Lunisolar calendar, but Ruby Date class uses Gregorian calendar
# 明治: 慶応4年9月8日(1868年10月23日)- 1912年7月30日
# Meiji: Keio 4, 9th month, 8th day (1868-10-23) - 1912-07-30
Date.parse("m01.01.01").should == Date.parse("1868-01-01") # This is *NOT* correct
Date.parse("m05.12.31").should == Date.parse("1872-12-31") # This is *NOT* correct
end
it "should parse Meiji period correctly" do
# 明治: 慶応4年9月8日(1868年10月23日)- 1912年7月30日
# Meiji: Keio 4, 9th month, 8th day (1868-10-23) - 1912-07-30
# Meiji started to use Gregorian calendar
Date.parse("m06.01.01").should == Date.parse("1873-01-01")
Date.parse("m44.12.31").should == Date.parse("1911-12-31")
Date.parse("m45.07.30").should == Date.parse("1912-07-30")
end
it "should parse Taisho period correctly" do
# 大正: 1912年7月30日 - 1926年12月25日
# Taisho: 1912-07-30 - 1926/12/25
Date.parse("t01.07.30").should == Date.parse("1912-07-30")
Date.parse("t02.01.01").should == Date.parse("1913-01-01")
Date.parse("t15.12.25").should == Date.parse("1926-12-25")
end
it "should parse Showa period correctly" do
# 昭和: 1926年12月25日 - 1989年1月7日
# Showa: 1926/12/25 - 1989/01/07
Date.parse("s01.12.25").should == Date.parse("1926-12-25")
Date.parse("s02.01.01").should == Date.parse("1927-01-01")
Date.parse("s64.01.07").should == Date.parse("1989-01-07")
end
it "should parse Heisei period correctly" do
# 平成: 1989年1月8日
# Heisei: 1989/01/08
Date.parse("h01.01.08").should == Date.parse("1989-01-08")
Date.parse("h24.01.01").should == Date.parse("2012-01-01")
end
end
end
| meltedice/wareki | spec/wareki/default_date_spec.rb | Ruby | mit | 2,538 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sjl.mlbapp.gui.util;
import java.awt.GridBagConstraints;
import java.awt.Insets;
/**
*
* @author samlevin
*/
public class GBConstrManager extends GridBagConstraints {
public GBConstrManager (){
super();
}
/**
* The methods containing the word 'new' will wipe an existing
* configuration by calling resetDefaults. To configure
* the constraints before retrieving, call 'get'
* @param xPos
* @param yPos
* @return
*/
public GridBagConstraints newConstr(int xPos, int yPos){
GridBagConstraints ret = new GridBagConstraints();
resetDefaults(ret);
ret.gridx = xPos;
ret.gridy = yPos;
return ret;
}
public GridBagConstraints newConstrByWeight(int xPos, int yPos, double xWgt, double yWgt){
GridBagConstraints ret = new GridBagConstraints();
resetDefaults(ret);
ret.gridx = xPos;
ret.gridy = yPos;
ret.weightx = xWgt;
ret.weighty = yWgt;
return ret;
}
public static void resetDefaults(GridBagConstraints gbc){
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.ipadx = 0;
gbc.ipady = 0;
gbc.insets = new Insets(0,0,0,0);
}
public GridBagConstraints getConstr(int xPos, int yPos){
this.gridx = xPos;
this.gridy = yPos;
return this;
}
public GridBagConstraints getConstrByWeight(int xPos, int yPos, double xWgt, double yWgt){
this.gridx = xPos;
this.gridy = yPos;
this.weightx = xWgt;
this.weighty = yWgt;
return this;
}
public void setInsets(Insets ins){
this.insets = ins;
}
public void setPadding(int xPad, int yPad){
this.ipadx = xPad;
this.ipady = yPad;
}
public void setWeights(double xW, double yW){
this.weightx = xW;
this.weighty = yW;
}
}
| levinsamuel/rand | java/MLB2012App/src/main/java/sjl/mlbapp/gui/util/GBConstrManager.java | Java | mit | 2,162 |
module Confluence
class BlogEntry < Record
extend Findable
record_attr_accessor :id => :entry_id
record_attr_accessor :space
record_attr_accessor :title, :content
record_attr_accessor :publishDate
record_attr_accessor :url
def store
# reinitialize blog entry after storing it
initialize(client.storeBlogEntry(self.to_hash))
end
def remove
client.removePage(self.entry_id)
end
private
def self.find_criteria(args)
if args.key? :id
self.new(client.getBlogEntry(args[:id]))
elsif args.key? :space
client.getBlogEntries(args[:space]).collect { |summary| BlogEntry.find(:id => summary["id"]) }
end
end
end
end | sspinc/confluencer | lib/confluence/blog_entry.rb | Ruby | mit | 737 |
<?php
/**
* Emy Itegbe
* CMPE 207
* 008740953
*
**/
?>
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script>
function showForm(){
document.getElementById("addUser").style.display="block";
}
</script>
</head>
<body>
<h1>Files Viewer</h1>
<h3>CMPE207 Project, Team:Budweiser</h3>
<button class="btn btn-success" style="margin-left: 10px" onclick="showForm()">Add a File</button>
<form action="" method="get" class="form-inline" style="display: inline-block;margin-left: 10px">
<input type="text" class="form-control" name="query" value="Emy Itegbe">
<button type="submit" class="btn btn-primary">Search</button>
</form>
<div id="addUser" style="margin: 10px; display: none">
<form action="upload.php" method="post" class="form-inline" role="form" enctype="multipart/form-data">
<input type="hidden" name="user" value="Emy Itegbe" />
<div class="form-group">
<label for="first_name">Upload File</label>
<input type="file" class="form-control" id="file" name="file">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<?php
include 'db.php';
//connect to database
$con = mysqli_connect($host, $username, $password, $database);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL DB: " . mysqli_connect_error();
}
if(isset($_GET["query"])){
$query = $_GET["query"];
$result = mysqli_query($con, "SELECT * FROM Files WHERE Files.user_name LIKE '%$query%'
or Files.file_name LIKE '%$query%' or file_type LIKE '%$query%'");
}
else{
$result = mysqli_query($con, "SELECT * FROM Files ORDER BY idFiles DESC;");
}
echo "<table class='table table-striped table-bordered' style='margin-top: 5px'><tr>
<th>ID</th>
<th>File Name</th>
<th>Original Server</th>
<th>File Size</th>
<th>File Type</th>
<th>Action</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['idFiles'] . "</td><td>"
."<a href='".$row['url']."'>". $row['file_name'] . "</a></td><td>"
. $row['user_name'] . "</td><td>"
. ceil($row['file_size']/1024) . "kb</td><td>"
. $row['file_type'] . "</td><td>"
. "<form action='delete.php' method='post' class='form-inline' role='form'>
<input type='hidden' name='id' value='".$row['idFiles']."' />
<button type='submit' class='btn btn-danger'>DELETE</button>
</form></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
| Budweiser-CMPE207/FileSharingSystem_CMPE207 | Emy Itegbe/Php/webclient.php | PHP | mit | 2,891 |
using Microsoft.Azure.Mobile.Server;
namespace Miles.People.MobileAppService.DataObjects
{
public class Item : EntityData
{
public string Text { get; set; }
public string Description { get; set; }
}
} | pjsamuel3/xPlatformDotNet | app/Miles.People/Miles.People/Miles.People.MobileAppService/DataObjects/Item.cs | C# | mit | 232 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <httpserver.h>
#include <index/blockfilterindex.h>
#include <index/coinstatsindex.h>
#include <index/txindex.h>
#include <interfaces/chain.h>
#include <interfaces/echo.h>
#include <interfaces/init.h>
#include <interfaces/ipc.h>
#include <key_io.h>
#include <node/context.h>
#include <outputtype.h>
#include <rpc/blockchain.h>
#include <rpc/server.h>
#include <rpc/server_util.h>
#include <rpc/util.h>
#include <scheduler.h>
#include <script/descriptor.h>
#include <util/check.h>
#include <util/message.h> // For MessageSign(), MessageVerify()
#include <util/strencodings.h>
#include <util/syscall_sandbox.h>
#include <util/system.h>
#include <optional>
#include <stdint.h>
#include <tuple>
#ifdef HAVE_MALLOC_INFO
#include <malloc.h>
#endif
#include <univalue.h>
using node::NodeContext;
static RPCHelpMan validateaddress()
{
return RPCHelpMan{
"validateaddress",
"\nReturn information about the given groestlcoin address.\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The groestlcoin address to validate"},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::BOOL, "isvalid", "If the address is valid or not"},
{RPCResult::Type::STR, "address", /*optional=*/true, "The groestlcoin address validated"},
{RPCResult::Type::STR_HEX, "scriptPubKey", /*optional=*/true, "The hex-encoded scriptPubKey generated by the address"},
{RPCResult::Type::BOOL, "isscript", /*optional=*/true, "If the key is a script"},
{RPCResult::Type::BOOL, "iswitness", /*optional=*/true, "If the address is a witness address"},
{RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program"},
{RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program"},
{RPCResult::Type::STR, "error", /*optional=*/true, "Error message, if any"},
{RPCResult::Type::ARR, "error_locations", /*optional=*/true, "Indices of likely error locations in address, if known (e.g. Bech32 errors)",
{
{RPCResult::Type::NUM, "index", "index of a potential error"},
}},
}
},
RPCExamples{
HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::string error_msg;
std::vector<int> error_locations;
CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg, &error_locations);
const bool isValid = IsValidDestination(dest);
CHECK_NONFATAL(isValid == error_msg.empty());
UniValue ret(UniValue::VOBJ);
ret.pushKV("isvalid", isValid);
if (isValid) {
std::string currentAddress = EncodeDestination(dest);
ret.pushKV("address", currentAddress);
CScript scriptPubKey = GetScriptForDestination(dest);
ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
UniValue detail = DescribeAddress(dest);
ret.pushKVs(detail);
} else {
UniValue error_indices(UniValue::VARR);
for (int i : error_locations) error_indices.push_back(i);
ret.pushKV("error_locations", error_indices);
ret.pushKV("error", error_msg);
}
return ret;
},
};
}
static RPCHelpMan createmultisig()
{
return RPCHelpMan{"createmultisig",
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n",
{
{"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys."},
{"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.",
{
{"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"},
}},
{"address_type", RPCArg::Type::STR, RPCArg::Default{"legacy"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "address", "The value of the new multisig address."},
{RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."},
{RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"},
{RPCResult::Type::ARR, "warnings", /* optional */ true, "Any warnings resulting from the creation of this multisig",
{
{RPCResult::Type::STR, "", ""},
}},
}
},
RPCExamples{
"\nCreate a multisig address from 2 public keys\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("createmultisig", "2, [\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\",\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\"]")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
int required = request.params[0].get_int();
// Get the public keys
const UniValue& keys = request.params[1].get_array();
std::vector<CPubKey> pubkeys;
for (unsigned int i = 0; i < keys.size(); ++i) {
if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) {
pubkeys.push_back(HexToPubKey(keys[i].get_str()));
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\n.", keys[i].get_str()));
}
}
// Get the output type
OutputType output_type = OutputType::LEGACY;
if (!request.params[2].isNull()) {
std::optional<OutputType> parsed = ParseOutputType(request.params[2].get_str());
if (!parsed) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str()));
} else if (parsed.value() == OutputType::BECH32M) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "createmultisig cannot create bech32m multisig addresses");
}
output_type = parsed.value();
}
// Construct using pay-to-script-hash:
FillableSigningProvider keystore;
CScript inner;
const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, keystore, inner);
// Make the descriptor
std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore);
UniValue result(UniValue::VOBJ);
result.pushKV("address", EncodeDestination(dest));
result.pushKV("redeemScript", HexStr(inner));
result.pushKV("descriptor", descriptor->ToString());
UniValue warnings(UniValue::VARR);
if (!request.params[2].isNull() && OutputTypeFromDestination(dest) != output_type) {
// Only warns if the user has explicitly chosen an address type we cannot generate
warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
}
if (warnings.size()) result.pushKV("warnings", warnings);
return result;
},
};
}
static RPCHelpMan getdescriptorinfo()
{
const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/17h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)";
return RPCHelpMan{"getdescriptorinfo",
{"\nAnalyses a descriptor.\n"},
{
{"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
},
RPCResult{
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys"},
{RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"},
{RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"},
{RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"},
{RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"},
}
},
RPCExamples{
"Analyse a descriptor\n" +
HelpExampleCli("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"") +
HelpExampleRpc("getdescriptorinfo", "\"" + EXAMPLE_DESCRIPTOR + "\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
RPCTypeCheck(request.params, {UniValue::VSTR});
FlatSigningProvider provider;
std::string error;
auto desc = Parse(request.params[0].get_str(), provider, error);
if (!desc) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
}
UniValue result(UniValue::VOBJ);
result.pushKV("descriptor", desc->ToString());
result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str()));
result.pushKV("isrange", desc->IsRange());
result.pushKV("issolvable", desc->IsSolvable());
result.pushKV("hasprivatekeys", provider.keys.size() > 0);
return result;
},
};
}
static RPCHelpMan deriveaddresses()
{
const std::string EXAMPLE_DESCRIPTOR = "wpkh([d34db33f/84h/17h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu";
return RPCHelpMan{"deriveaddresses",
{"\nDerives one or more addresses corresponding to an output descriptor.\n"
"Examples of output descriptors are:\n"
" pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
" wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n"
" sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
" raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
"\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
"or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
{
{"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
{"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED_NAMED_ARG, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."},
},
RPCResult{
RPCResult::Type::ARR, "", "",
{
{RPCResult::Type::STR, "address", "the derived addresses"},
}
},
RPCExamples{
"First three native segwit receive addresses\n" +
HelpExampleCli("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\" \"[0,2]\"") +
HelpExampleRpc("deriveaddresses", "\"" + EXAMPLE_DESCRIPTOR + "\", \"[0,2]\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later
const std::string desc_str = request.params[0].get_str();
int64_t range_begin = 0;
int64_t range_end = 0;
if (request.params.size() >= 2 && !request.params[1].isNull()) {
std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
}
FlatSigningProvider key_provider;
std::string error;
auto desc = Parse(desc_str, key_provider, error, /* require_checksum = */ true);
if (!desc) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
}
if (!desc->IsRange() && request.params.size() > 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
}
if (desc->IsRange() && request.params.size() == 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
}
UniValue addresses(UniValue::VARR);
for (int i = range_begin; i <= range_end; ++i) {
FlatSigningProvider provider;
std::vector<CScript> scripts;
if (!desc->Expand(i, key_provider, scripts, provider)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot derive script without private keys");
}
for (const CScript &script : scripts) {
CTxDestination dest;
if (!ExtractDestination(script, dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Descriptor does not have a corresponding address");
}
addresses.push_back(EncodeDestination(dest));
}
}
// This should not be possible, but an assert seems overkill:
if (addresses.empty()) {
throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
}
return addresses;
},
};
}
static RPCHelpMan verifymessage()
{
return RPCHelpMan{"verifymessage",
"Verify a signed message.",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The groestlcoin address to use for the signature."},
{"signature", RPCArg::Type::STR, RPCArg::Optional::NO, "The signature provided by the signer in base 64 encoding (see signmessage)."},
{"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message that was signed."},
},
RPCResult{
RPCResult::Type::BOOL, "", "If the signature is verified or not."
},
RPCExamples{
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"FdeDnzHyMSroQWo2uz7GzHQhHEvtZRojCY\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"FdeDnzHyMSroQWo2uz7GzHQhHEvtZRojCY\" \"signature\" \"my message\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("verifymessage", "\"FdeDnzHyMSroQWo2uz7GzHQhHEvtZRojCY\", \"signature\", \"my message\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
LOCK(cs_main);
std::string strAddress = request.params[0].get_str();
std::string strSign = request.params[1].get_str();
std::string strMessage = request.params[2].get_str();
switch (MessageVerify(strAddress, strSign, strMessage)) {
case MessageVerificationResult::ERR_INVALID_ADDRESS:
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
case MessageVerificationResult::ERR_ADDRESS_NO_KEY:
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
case MessageVerificationResult::ERR_MALFORMED_SIGNATURE:
throw JSONRPCError(RPC_TYPE_ERROR, "Malformed base64 encoding");
case MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED:
case MessageVerificationResult::ERR_NOT_SIGNED:
return false;
case MessageVerificationResult::OK:
return true;
}
return false;
},
};
}
static RPCHelpMan signmessagewithprivkey()
{
return RPCHelpMan{"signmessagewithprivkey",
"\nSign a message with the private key of an address\n",
{
{"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key to sign the message with."},
{"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."},
},
RPCResult{
RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64"
},
RPCExamples{
"\nCreate the signature\n"
+ HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"FdeDnzHyMSroQWo2uz7GzHQhHEvtZRojCY\" \"signature\" \"my message\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::string strPrivkey = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CKey key = DecodeSecret(strPrivkey);
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
}
std::string signature;
if (!MessageSign(key, strMessage, signature)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
}
return signature;
},
};
}
static RPCHelpMan setmocktime()
{
return RPCHelpMan{"setmocktime",
"\nSet the local time to given timestamp (-regtest only)\n",
{
{"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n"
"Pass 0 to go back to using the system time."},
},
RPCResult{RPCResult::Type::NONE, "", ""},
RPCExamples{""},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
if (!Params().IsMockableChain()) {
throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only");
}
// For now, don't change mocktime if we're in the middle of validation, as
// this could have an effect on mempool time-based eviction, as well as
// IsCurrentForFeeEstimation() and IsInitialBlockDownload().
// TODO: figure out the right way to synchronize around mocktime, and
// ensure all call sites of GetTime() are accessing this safely.
LOCK(cs_main);
RPCTypeCheck(request.params, {UniValue::VNUM});
const int64_t time{request.params[0].get_int64()};
if (time < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Mocktime can not be negative: %s.", time));
}
SetMockTime(time);
auto node_context = util::AnyPtr<NodeContext>(request.context);
if (node_context) {
for (const auto& chain_client : node_context->chain_clients) {
chain_client->setMockTime(time);
}
}
return NullUniValue;
},
};
}
#if defined(USE_SYSCALL_SANDBOX)
static RPCHelpMan invokedisallowedsyscall()
{
return RPCHelpMan{
"invokedisallowedsyscall",
"\nInvoke a disallowed syscall to trigger a syscall sandbox violation. Used for testing purposes.\n",
{},
RPCResult{RPCResult::Type::NONE, "", ""},
RPCExamples{
HelpExampleCli("invokedisallowedsyscall", "") + HelpExampleRpc("invokedisallowedsyscall", "")},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
if (!Params().IsTestChain()) {
throw std::runtime_error("invokedisallowedsyscall is used for testing only.");
}
TestDisallowedSandboxCall();
return NullUniValue;
},
};
}
#endif // USE_SYSCALL_SANDBOX
static RPCHelpMan mockscheduler()
{
return RPCHelpMan{"mockscheduler",
"\nBump the scheduler into the future (-regtest only)\n",
{
{"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." },
},
RPCResult{RPCResult::Type::NONE, "", ""},
RPCExamples{""},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
if (!Params().IsMockableChain()) {
throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only");
}
// check params are valid values
RPCTypeCheck(request.params, {UniValue::VNUM});
int64_t delta_seconds = request.params[0].get_int64();
if (delta_seconds <= 0 || delta_seconds > 3600) {
throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)");
}
auto node_context = util::AnyPtr<NodeContext>(request.context);
// protect against null pointer dereference
CHECK_NONFATAL(node_context);
CHECK_NONFATAL(node_context->scheduler);
node_context->scheduler->MockForward(std::chrono::seconds(delta_seconds));
return NullUniValue;
},
};
}
static UniValue RPCLockedMemoryInfo()
{
LockedPool::Stats stats = LockedPoolManager::Instance().stats();
UniValue obj(UniValue::VOBJ);
obj.pushKV("used", uint64_t(stats.used));
obj.pushKV("free", uint64_t(stats.free));
obj.pushKV("total", uint64_t(stats.total));
obj.pushKV("locked", uint64_t(stats.locked));
obj.pushKV("chunks_used", uint64_t(stats.chunks_used));
obj.pushKV("chunks_free", uint64_t(stats.chunks_free));
return obj;
}
#ifdef HAVE_MALLOC_INFO
static std::string RPCMallocInfo()
{
char *ptr = nullptr;
size_t size = 0;
FILE *f = open_memstream(&ptr, &size);
if (f) {
malloc_info(0, f);
fclose(f);
if (ptr) {
std::string rv(ptr, size);
free(ptr);
return rv;
}
}
return "";
}
#endif
static RPCHelpMan getmemoryinfo()
{
/* Please, avoid using the word "pool" here in the RPC interface or help,
* as users will undoubtedly confuse it with the other "memory pool"
*/
return RPCHelpMan{"getmemoryinfo",
"Returns an object containing information about memory usage.\n",
{
{"mode", RPCArg::Type::STR, RPCArg::Default{"stats"}, "determines what kind of information is returned.\n"
" - \"stats\" returns general statistics about memory usage in the daemon.\n"
" - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+)."},
},
{
RPCResult{"mode \"stats\"",
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::OBJ, "locked", "Information about locked memory manager",
{
{RPCResult::Type::NUM, "used", "Number of bytes used"},
{RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"},
{RPCResult::Type::NUM, "total", "Total number of bytes managed"},
{RPCResult::Type::NUM, "locked", "Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk."},
{RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"},
{RPCResult::Type::NUM, "chunks_free", "Number unused chunks"},
}},
}
},
RPCResult{"mode \"mallocinfo\"",
RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\""
},
},
RPCExamples{
HelpExampleCli("getmemoryinfo", "")
+ HelpExampleRpc("getmemoryinfo", "")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str();
if (mode == "stats") {
UniValue obj(UniValue::VOBJ);
obj.pushKV("locked", RPCLockedMemoryInfo());
return obj;
} else if (mode == "mallocinfo") {
#ifdef HAVE_MALLOC_INFO
return RPCMallocInfo();
#else
throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo mode not available");
#endif
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode);
}
},
};
}
static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
cats = cats.get_array();
for (unsigned int i = 0; i < cats.size(); ++i) {
std::string cat = cats[i].get_str();
bool success;
if (enable) {
success = LogInstance().EnableCategory(cat);
} else {
success = LogInstance().DisableCategory(cat);
}
if (!success) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat);
}
}
}
static RPCHelpMan logging()
{
return RPCHelpMan{"logging",
"Gets and sets the logging configuration.\n"
"When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n"
"When called with arguments, adds or removes categories from debug logging and return the lists above.\n"
"The arguments are evaluated in order \"include\", \"exclude\".\n"
"If an item is both included and excluded, it will thus end up being excluded.\n"
"The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n"
"In addition, the following are available as category names with special meanings:\n"
" - \"all\", \"1\" : represent all logging categories.\n"
" - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n"
,
{
{"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to add to debug logging",
{
{"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
}},
{"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to remove from debug logging",
{
{"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"},
}},
},
RPCResult{
RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status",
{
{RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"},
}
},
RPCExamples{
HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"")
+ HelpExampleRpc("logging", "[\"all\"], [\"libevent\"]")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
uint32_t original_log_categories = LogInstance().GetCategoryMask();
if (request.params[0].isArray()) {
EnableOrDisableLogCategories(request.params[0], true);
}
if (request.params[1].isArray()) {
EnableOrDisableLogCategories(request.params[1], false);
}
uint32_t updated_log_categories = LogInstance().GetCategoryMask();
uint32_t changed_log_categories = original_log_categories ^ updated_log_categories;
// Update libevent logging if BCLog::LIBEVENT has changed.
// If the library version doesn't allow it, UpdateHTTPServerLogging() returns false,
// in which case we should clear the BCLog::LIBEVENT flag.
// Throw an error if the user has explicitly asked to change only the libevent
// flag and it failed.
if (changed_log_categories & BCLog::LIBEVENT) {
if (!UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT))) {
LogInstance().DisableCategory(BCLog::LIBEVENT);
if (changed_log_categories == BCLog::LIBEVENT) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
}
}
}
UniValue result(UniValue::VOBJ);
for (const auto& logCatActive : LogInstance().LogCategoriesList()) {
result.pushKV(logCatActive.category, logCatActive.active);
}
return result;
},
};
}
static RPCHelpMan echo(const std::string& name)
{
return RPCHelpMan{name,
"\nSimply echo back the input arguments. This command is for testing.\n"
"\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n"
"\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in "
"groestlcoin-cli and the GUI. There is no server-side difference.",
{
{"arg0", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg4", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg5", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg6", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg7", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg8", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
{"arg9", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""},
},
RPCResult{RPCResult::Type::ANY, "", "Returns whatever was passed in"},
RPCExamples{""},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
if (request.params[9].isStr()) {
CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug");
}
return request.params;
},
};
}
static RPCHelpMan echo() { return echo("echo"); }
static RPCHelpMan echojson() { return echo("echojson"); }
static RPCHelpMan echoipc()
{
return RPCHelpMan{
"echoipc",
"\nEcho back the input argument, passing it through a spawned process in a multiprocess build.\n"
"This command is for testing.\n",
{{"arg", RPCArg::Type::STR, RPCArg::Optional::NO, "The string to echo",}},
RPCResult{RPCResult::Type::STR, "echo", "The echoed string."},
RPCExamples{HelpExampleCli("echo", "\"Hello world\"") +
HelpExampleRpc("echo", "\"Hello world\"")},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue {
interfaces::Init& local_init = *EnsureAnyNodeContext(request.context).init;
std::unique_ptr<interfaces::Echo> echo;
if (interfaces::Ipc* ipc = local_init.ipc()) {
// Spawn a new groestlcoin-node process and call makeEcho to get a
// client pointer to a interfaces::Echo instance running in
// that process. This is just for testing. A slightly more
// realistic test spawning a different executable instead of
// the same executable would add a new groestlcoin-echo executable,
// and spawn groestlcoin-echo below instead of groestlcoin-node. But
// using groestlcoin-node avoids the need to build and install a
// new executable just for this one test.
auto init = ipc->spawnProcess("groestlcoin-node");
echo = init->makeEcho();
ipc->addCleanup(*echo, [init = init.release()] { delete init; });
} else {
// IPC support is not available because this is a bitcoind
// process not a groestlcoind-node process, so just create a local
// interfaces::Echo object and return it so the `echoipc` RPC
// method will work, and the python test calling `echoipc`
// can expect the same result.
echo = local_init.makeEcho();
}
return echo->echo(request.params[0].get_str());
},
};
}
static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name)
{
UniValue ret_summary(UniValue::VOBJ);
if (!index_name.empty() && index_name != summary.name) return ret_summary;
UniValue entry(UniValue::VOBJ);
entry.pushKV("synced", summary.synced);
entry.pushKV("best_block_height", summary.best_block_height);
ret_summary.pushKV(summary.name, entry);
return ret_summary;
}
static RPCHelpMan getindexinfo()
{
return RPCHelpMan{"getindexinfo",
"\nReturns the status of one or all available indices currently running in the node.\n",
{
{"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Filter results for an index with a specific name."},
},
RPCResult{
RPCResult::Type::OBJ_DYN, "", "", {
{
RPCResult::Type::OBJ, "name", "The name of the index",
{
{RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"},
{RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"},
}
},
},
},
RPCExamples{
HelpExampleCli("getindexinfo", "")
+ HelpExampleRpc("getindexinfo", "")
+ HelpExampleCli("getindexinfo", "txindex")
+ HelpExampleRpc("getindexinfo", "txindex")
},
[&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
UniValue result(UniValue::VOBJ);
const std::string index_name = request.params[0].isNull() ? "" : request.params[0].get_str();
if (g_txindex) {
result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name));
}
if (g_coin_stats_index) {
result.pushKVs(SummaryToJSON(g_coin_stats_index->GetSummary(), index_name));
}
ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) {
result.pushKVs(SummaryToJSON(index.GetSummary(), index_name));
});
return result;
},
};
}
void RegisterMiscRPCCommands(CRPCTable &t)
{
// clang-format off
static const CRPCCommand commands[] =
{ // category actor (function)
// --------------------- ------------------------
{ "control", &getmemoryinfo, },
{ "control", &logging, },
{ "util", &validateaddress, },
{ "util", &createmultisig, },
{ "util", &deriveaddresses, },
{ "util", &getdescriptorinfo, },
{ "util", &verifymessage, },
{ "util", &signmessagewithprivkey, },
{ "util", &getindexinfo, },
/* Not shown in help */
{ "hidden", &setmocktime, },
{ "hidden", &mockscheduler, },
{ "hidden", &echo, },
{ "hidden", &echojson, },
{ "hidden", &echoipc, },
#if defined(USE_SYSCALL_SANDBOX)
{ "hidden", &invokedisallowedsyscall, },
#endif // USE_SYSCALL_SANDBOX
};
// clang-format on
for (const auto& c : commands) {
t.appendCommand(c.name, &c);
}
}
| GroestlCoin/bitcoin | src/rpc/misc.cpp | C++ | mit | 36,710 |
<?php
namespace Milax\Mconsole\Models;
use Illuminate\Database\Eloquent\Model;
class Upload extends Model
{
use \HasTags;
protected $fillable = ['type', 'path', 'preset_id', 'filename', 'copies', 'related_id', 'related_class', 'group', 'order', 'unique', 'language_id', 'title', 'description', 'link'];
protected $casts = [
'copies' => 'array',
];
/**
* Relationship to MconsoleUploadPreset
*
* @return BelongsTo
*/
public function preset()
{
return $this->belongsTo('Milax\Mconsole\Models\MconsoleUploadPreset', 'preset_id');
}
/**
* Relationship to Language
*
* @return BelongsTo
*/
public function language()
{
return $this->belongsTo('Milax\Mconsole\Models\Language');
}
/**
* Get image url for given copy
*
* @param string $size
* @return string
*/
public function getImagePath($size = 'original')
{
return sprintf('/storage/uploads/%s/%s/%s', $this->path, $size, $this->filename);
}
/**
* Get document url for given copy
*
* @return string
*/
public function getDocumentPath()
{
return sprintf('/storage/uploads/%s/%s', $this->path, $this->filename);
}
/**
* Get original file path
*
* @return string
*/
public function getOriginalPath($size = 'original')
{
switch ($this->type) {
case 'image':
return $this->getImagePath($size);
default:
return $this->getDocumentPath();
}
}
/**
* Undocumented function
*
* @param boolean $includeOriginal [Include original file path]
* @return void
*/
public function getCopies($includeOriginal = false)
{
$copies = [];
foreach ($this->copies as $copy) {
$copies[$copy['path']] = $this->getImagePath($copy['path']);
}
if ($includeOriginal) {
$copies['original'] = $this->getOriginalPath();
}
return $copies;
}
// @TODO: REMOVE THIS METHOD
public function getImageCopies()
{
throw new \Milax\Mconsole\Exceptions\DeprecatedException('Upload getImageCopies is deprecated, use getCopies() instead');
}
/**
* Automatically delete related data
*
* @return void
*/
public static function boot()
{
parent::boot();
static::deleting(function ($file) {
if (\File::exists(sprintf('%s/%s/%s', MX_UPLOADS_PATH, $file->path, $file->filename))) {
\File::delete(sprintf('%s/%s/%s', MX_UPLOADS_PATH, $file->path, $file->filename));
}
if (\File::exists(sprintf('%s/%s/original/%s', MX_UPLOADS_PATH, $file->path, $file->filename))) {
\File::delete(sprintf('%s/%s/original/%s', MX_UPLOADS_PATH, $file->path, $file->filename));
}
if (\File::exists(sprintf('%s/%s/mconsole/%s', MX_UPLOADS_PATH, $file->path, $file->filename))) {
\File::delete(sprintf('%s/%s/mconsole/%s', MX_UPLOADS_PATH, $file->path, $file->filename));
}
if ($file->copies && count($file->copies) > 0) {
foreach ($file->copies as $copy) {
if (\File::exists(sprintf('%s/%s/%s/%s', MX_UPLOADS_PATH, $file->path, $copy['path'], $file->filename))) {
\File::delete(sprintf('%s/%s/%s/%s', MX_UPLOADS_PATH, $file->path, $copy['path'], $file->filename));
}
}
}
});
}
}
| misterpaladin/mconsole | src/Milax/Mconsole/Models/Upload.php | PHP | mit | 3,675 |
class Station < ActiveRecord::Base
belongs_to :forecast
# validates :pws_id, uniqueness: true
end
| jackzampolin/my_weather_map | app/models/station.rb | Ruby | mit | 102 |
package com.ngll_prototype;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.ngll_prototype.object.IMGCoordinate;
import com.searchly.jestdroid.DroidClientConfig;
import com.searchly.jestdroid.JestClientFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
CustomDrawableView cd;
private ImageView image;
private ImageView imageView;
private int ImgInfo[];
private TextView tvMac;
private Button mbtnExe;
private Button mbtnStop;
ProgressDialog mProgressDialog;
DisaplyPoint disaplyPoint;
private Bitmap bitmapBG, bitmap;
private Canvas canvas;
private Paint paint;
private int StatusBarHeight, ActionBarHeight;
private JSONArray list;
private Matrix matrix;
private ArrayList<IMGCoordinate> IMGCoorlist = new ArrayList<>();
private boolean firstExe = true;
private static boolean goFlag;
String query = "{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"data.macAddr\" : {\n" +
" \"query\" : \"101a0a000024\",\n" +
" \"type\" : \"boolean\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }";
String query2 = "{\n"
+ " \"query\":{\n"
+ " \"match\":{\n"
+ " \"data\": {\n"
+ " \"macAddr\" : \"101a0a000024\" \n"
+ " }\n"
+ " }\n"
+ " }\n"
+ "}";
String query3 =
"{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"data.macAddr\" : {\n" +
" \"query\" : \"101a0a000024\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
tvMac = (TextView) findViewById(R.id.tvmac);
mbtnExe = (Button) findViewById(R.id.btnexe);
mbtnStop = (Button) findViewById(R.id.btnstop);
setTitle("NGLL Prototype");
Log.d(TAG, "---- Old Activity ----");
setup();
// Node node = nodeBuilder().node();
// Client client = node.client();
// try {
// Settings settings = Settings.settingsBuilder()
// .put("", "").build();
// TransportClient client = TransportClient.builder().settings(settings).build()
// .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("54.169.218.103"), 9200));
// Log.d(TAG, "client:\t" + client.toString());
// client.close();
//// GetRequestBuilder getRequestBuilder = client.prepareGet();
//// getRequestBuilder.setFields("");
//// GetResponse response = getRequestBuilder.execute().actionGet();
//// String name = response.getField("").getValue().toString();
//// Log.d(TAG, "name:\t" + name );
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
}
private void setup() {
// int count = 0;
mbtnExe.setOnClickListener(new View.OnClickListener() {
// int count = 0;
@Override
public void onClick(View view) {
// Log.d(TAG, "mbtnExe pressed");
// int indoorCo[] ={8, count};
// paint(indoorCo);
// count = count +1;
disaplyPoint = new DisaplyPoint();
disaplyPoint.execute("101a0a000024");
goFlag = true;
chgButtonST(mbtnExe, false);
}
});
mbtnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goFlag = false;
chgButtonST(mbtnExe, true);
}
});
tvMac.setText("101a0a000024");
}
private void init() {
// RelativeLayout layout = (RelativeLayout) findViewById(R.id.root);
// final DrawView view = new DrawView(this);
// view.setMinimumHeight(700);
// view.setMinimumWidth(1274);
//
// //通知view组件重绘
// view.invalidate();
// layout.addView(view);
}
private void chgButtonST(Button btn, boolean state) {
btn.setClickable(state);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d(TAG, "onWindowFocusChanged");
if (firstExe) {
firstExe = false;
ImgInfo = getImageStartCoordinate(image); //get Image top, left, Height, wight
Log.d(TAG, "ImgInfo Top:\t" + ImgInfo[0]);
Log.d(TAG, "ImgInfo Left:\t" + ImgInfo[1]);
Log.d(TAG, "ImgInfo Height:\t" + ImgInfo[2]);
Log.d(TAG, "ImgInfo Wight:\t" + ImgInfo[3]);
bitmapBG = BitmapFactory.decodeResource(getResources(), R.drawable.gemtek8b_block2);
Log.d(TAG, "bitmapBG.getHeight():\t" + bitmapBG.getHeight() + "\tbitmapBG.getWidth():\t" + bitmapBG.getWidth());
// View v = new MyCanvas(getApplicationContext());
bitmap = Bitmap.createBitmap(bitmapBG.getWidth()/*width*/, bitmapBG.getHeight()/*height*/, Bitmap.Config.ARGB_8888); //create a bitmap size same as bitmapBG
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
matrix = new Matrix();
canvas.drawBitmap(bitmapBG, matrix, paint);
// canvas.drawCircle(324, 330, 10, paint);
// canvas.drawCircle(324, 168, 10, paint);
// canvas.drawText("Sample Text", 10, 10, paint);
StatusBarHeight = getStatusBarHeight();
ActionBarHeight = getActionBarHeight();
Log.d(TAG, "StatusBarHeight:\t" + StatusBarHeight + "\tActionBarHeight:\t" + ActionBarHeight);
image.setImageBitmap(bitmap);
// canvas.save();
ImgCoordinateSet(ImgInfo);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG, "onTouchEvent....");
int x = (int) event.getX();//取x軸
int y = (int) event.getY();//取y軸
int action = event.getAction();//取整數
switch (action) {
case MotionEvent.ACTION_DOWN:
// setTitle("按下:" + x + "," + y);
break;
case MotionEvent.ACTION_MOVE:
// setTitle("平移:" + x + "," + y);
break;
case MotionEvent.ACTION_UP:
setTitle("彈起:" + x + "," + y);
break;
}
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Drawable drawable = imageView.getDrawable();
Rect imageBounds = drawable.getBounds();
int[] posXY = new int[2];
imageView.getLocationOnScreen(posXY);
//original height and width of the bitmap
int intrinsicHeight = drawable.getIntrinsicHeight();
int intrinsicWidth = drawable.getIntrinsicWidth();
//height and width of the visible (scaled) image
int scaledHeight = imageBounds.height();
int scaledWidth = imageBounds.width();
//Find the ratio of the original image to the scaled image
//Should normally be equal unless a disproportionate scaling
//(e.g. fitXY) is used.
float heightRatio = intrinsicHeight / scaledHeight;
float widthRatio = intrinsicWidth / scaledWidth;
//do whatever magic to get your touch point
//MotionEvent event;
//get the distance from the left and top of the image bounds
float scaledImageOffsetX = event.getX() - imageBounds.left;
float scaledImageOffsetY = event.getY() - imageBounds.top;
Log.d(TAG, "scaledImageOffsetX:\n" + scaledImageOffsetX);
Log.d(TAG, "scaledImageOffsetY:\n" + scaledImageOffsetY);
//scale these distances according to the ratio of your scaling
//For example, if the original image is 1.5x the size of the scaled
//image, and your offset is (10, 20), your original image offset
//values should be (15, 30).
float originalImageOffsetX = scaledImageOffsetX * widthRatio;
float originalImageOffsetY = scaledImageOffsetY * heightRatio;
return super.onTouchEvent(event);
}
public class CustomDrawableView extends View {
private ShapeDrawable mDrawable;
private Paint mPaint;
private int x = 200;
private int y = 600;
private int width = 100;
private int height = 50;
public CustomDrawableView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.setBounds(x, y, x + width, y + height);
mPaint = mDrawable.getPaint();
mPaint.setColor(Color.BLUE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
mDrawable.draw(canvas);
}
}
public static int[] getBitmapPositionInsideImageView(ImageView imageView) {
int[] ret = new int[4];
if (imageView == null || imageView.getDrawable() == null)
return ret;
// Get image dimensions
// Get image matrix values and place them in an array
float[] f = new float[9];
imageView.getImageMatrix().getValues(f);
// for(int i =0; i < f.length; i++){
// Log.d(TAG, "f:" + f[i]);
// }
// Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
// Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
final Drawable d = imageView.getDrawable();
final int origW = d.getIntrinsicWidth();
final int origH = d.getIntrinsicHeight();
// Calculate the actual dimensions
final int actW = Math.round(origW * scaleX);
final int actH = Math.round(origH * scaleY);
ret[2] = actW;
ret[3] = actH;
// Get image position
// We assume that the image is centered into ImageView
int imgViewW = imageView.getWidth();
int imgViewH = imageView.getHeight();
Log.d(TAG, "origW:\t" + origW + "\norigH:\t" + origH);
Log.d(TAG, "actW:\t" + actW + "\nactH:\t" + actH);
Log.d(TAG, "imgViewW:\t" + imgViewW + "\nimgViewH:\t" + imgViewH);
int top = (int) (imgViewH - actH) / 2;
int left = (int) (imgViewW - actW) / 2;
ret[0] = left;
ret[1] = top;
return ret;
}
public int[] getImageStartCoordinate(ImageView image) {
int[] intXY = new int[2];
// ImageView image = (ImageView)findViewById(R.id.imageView);
Drawable drawable = image.getDrawable();
Rect imageBounds = drawable.getBounds();
image.getLocationOnScreen(intXY);
// imageView.getLocationInWindow(intXY);
final int origW = drawable.getIntrinsicWidth();
final int origH = drawable.getIntrinsicHeight();
// drawable.get
final int[] ret = new int[4];
//intXY[0] = x, [1] = y, start top & left
ret[0] = intXY[0];
ret[1] = intXY[1];
ret[2] = origH;
ret[3] = origW;
return ret;
}
/*
* calculation pic's coordinate with number save by Json
*/
public void ImgCoordinateSet(int[] ImgInfo) {
IMGCoordinate icl;
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
list = new JSONArray();
int toScaleH = 5;
int toScaleW = 6;
int spacingH = ImgInfo[2] / toScaleH;
int spacingW = ImgInfo[3] / toScaleW;
Log.d(TAG, "spacingH:\t" + spacingH + "\tspacingW:\t" + spacingW);
// int x = ImgInfo[0];
// int y = ImgInfo[1];
int x = 0;
int y = 0;
int count = 0;
Log.d(TAG, "Start x:\t" + x + "\ty:\t" + y);
for (int i = 1; i < toScaleH; i++) {
// x = ImgInfo[0];
x = 0;
y = y + spacingH;
for (int j = 1; j < toScaleW; j++) {
try {
x = x + spacingW;
obj.put("x", x);
obj.put("y", y);
obj2.put(Integer.toString(count), obj);
// Log.d(TAG, "No." + count +"\tX:\t" + x + "\tY:\t" + y);
// Log.d(TAG, "obj2:\t" + obj2.toString());
// canvas.drawCircle(x, y -StatusBarHeight - ActionBarHeight, 5, paint);
canvas.drawCircle(x, y, 5, paint);
list.put(obj2);
obj = new JSONObject();
obj2 = new JSONObject();
icl = new IMGCoordinate(count, x, y);
IMGCoorlist.add(icl);
count = count + 1;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Log.d(TAG, "IMGCoorlist.length:\t" + IMGCoorlist.size());
for (int i = 0; i < IMGCoorlist.size(); i++) {
Log.d(TAG, "I:\t" + i + "\tcount:\t" + IMGCoorlist.get(i).getNumber() + "\tX:\t" + IMGCoorlist.get(i).getX()
+ "\tY:\t" + IMGCoorlist.get(i).getY());
}
}
class DisaplyPoint extends AsyncTask<String, Integer, int[]> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// blockUI(getString(R.string.loading));
}
@Override
protected int[] doInBackground(String... strings) {
int coordinate[];
while (goFlag) {
try {
JestClientFactory factory = new JestClientFactory();
factory.setDroidClientConfig(new DroidClientConfig.Builder(getString(R.string.elasticsvr))
.multiThreaded(true)
.build());
JestClient client = factory.getObject();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.sort("@timestamp", SortOrder.DESC);
searchSourceBuilder.size(50);
searchSourceBuilder.query(QueryBuilders.matchQuery("data.macAddr", strings[0])); // generate DSL format
// newer search rule, desc find latest data & GPS_N not 0
SearchSourceBuilder searchSourceBuilderTry = new SearchSourceBuilder();
searchSourceBuilderTry.sort("@timestamp", SortOrder.DESC);
searchSourceBuilderTry.size(1);
searchSourceBuilderTry.query(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("data.macAddr", strings[0])).mustNot(QueryBuilders.termQuery("data.GPS_N", "0")));
Search search = new Search.Builder(searchSourceBuilderTry.toString()).addIndex("client_report").addType("asset_tracker").build();
SearchResult searchResult = client.execute(search);
// Log.d(TAG, "searchSourceBuilder:\t" + searchSourceBuilder.toString());
// Log.d(TAG, "Total:\t" + searchResult.getTotal());
// Log.d(TAG, "searchResult:\t" + searchResult.getJsonString());
IndoorLocation indoorLocation = new IndoorLocation();
coordinate = indoorLocation.getPositionNum(searchResult.getJsonObject());
//get specific document
// Get get = new Get.Builder("client_report", "AVe2_o5uJozORed8MBm_").type("asset_tracker").build();
// JestResult result = client.execute(get);
// Log.d(TAG, "Getting Document:\t" + result.getJsonString());
if (coordinate != null) {
publishProgress(coordinate[1]);
}
client.shutdownClient();
Thread.sleep(5000);
} catch (UnknownError e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
paint(values[0]);
}
@Override
protected void onPostExecute(int result[]) {
super.onPostExecute(result);
// Log.d(TAG, "result[]:\t" + result[0] + "\t, " + result[1] );
// paint(result[1]);
// blockUI(null);
}
}
public void paint(int anchorNUM) {
if (anchorNUM + 1 > IMGCoorlist.size()) {
return;
}
canvas.drawBitmap(bitmapBG, matrix, paint); // clear screen
int x = IMGCoorlist.get(anchorNUM).getX();
// int y = IMGCoorlist.get(coordinate[1]).getY() - StatusBarHeight - ActionBarHeight;
int y = IMGCoorlist.get(anchorNUM).getY();
// Log.d(TAG,"paint, input para coordinate[] :\t" + "\t[0]:\t" + coordinate[0] + "\t[1]:\t" + coordinate[1]);
Log.d(TAG, "paint, x:\t" + x);
Log.d(TAG, "paint, y:\t" + y);
canvas.drawCircle(x, y, 7, paint);
image.invalidate();
}
/*
* get Status bar Height
*/
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/*
* get Action bar Height
*/
public int getActionBarHeight() {
int result = 0;
// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
result = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}
return result;
}
private void blockUI(final String message) {
if (message != null) {
mProgressDialog = ProgressDialog.show(this, "", message, true);
mProgressDialog.show();
} else {
mProgressDialog.dismiss();
}
}
} | GIOT-POC/NGLL-APP | app/src/main/java/com/ngll_prototype/MainActivity.java | Java | mit | 20,066 |
#region File Header
// The MIT License (MIT)
//
// Copyright (c) 2016 Stefan Stolz
//
// 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.
#endregion
#region using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EmbeddedData")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EmbeddedData")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0")]
[assembly: AssemblyFileVersion("1.3.0")]
| StefanStolz/EmbeddedDataVisualStudioExtension | EmbeddedData/EmbeddedData/Properties/AssemblyInfo.cs | C# | mit | 2,427 |
"""
Last: 5069
Script with simple UI for creating gaplines data
Run: python WordClassDM.py --index 0
Controls:
setting gaplines - click and drag
saving gaplines - 's' key
reseting gaplines - 'r' key
skip to next img - 'n' key
delete last line - 'd' key
"""
import cv2
import os
import numpy as np
import glob
import argparse
import simplejson
from ocr.normalization import imageNorm
from ocr.viz import printProgressBar
def loadImages(dataloc, idx=0, num=None):
""" Load images and labels """
print("Loading words...")
# Load images and short them from the oldest to the newest
imglist = glob.glob(os.path.join(dataloc, u'*.jpg'))
imglist.sort(key=lambda x: float(x.split("_")[-1][:-4]))
tmpLabels = [name[len(dataloc):] for name in imglist]
labels = np.array(tmpLabels)
images = np.empty(len(imglist), dtype=object)
if num is None:
upper = len(imglist)
else:
upper = min(idx + num, len(imglist))
num += idx
for i, img in enumerate(imglist):
# TODO Speed up loading - Normalization
if i >= idx and i < upper:
images[i] = imageNorm(
cv2.cvtColor(cv2.imread(img), cv2.COLOR_BGR2RGB),
height=60,
border=False,
tilt=True,
hystNorm=True)
printProgressBar(i-idx, upper-idx-1)
print()
return (images[idx:num], labels[idx:num])
def locCheck(loc):
return loc + '/' if loc[-1] != '/' else loc
class Cycler:
drawing = False
scaleF = 4
def __init__(self, idx, data_loc, save_loc):
""" Load images and starts from given index """
# self.images, self.labels = loadImages(loc, idx)
# Create save_loc directory if not exists
if not os.path.exists(save_loc):
os.makedirs(save_loc)
self.data_loc = locCheck(data_loc)
self.save_loc = locCheck(save_loc)
self.idx = 0
self.org_idx = idx
self.blockLoad()
self.image_act = self.images[self.idx]
cv2.namedWindow('image')
cv2.setMouseCallback('image', self.mouseHandler)
self.nextImage()
self.run()
def run(self):
while(1):
self.imageShow()
k = cv2.waitKey(1) & 0xFF
if k == ord('d'):
# Delete last line
self.deleteLastLine()
elif k == ord('r'):
# Clear current gaplines
self.nextImage()
elif k == ord('s'):
# Save gaplines with image
if self.saveData():
self.idx += 1
if self.idx >= len(self.images):
if not self.blockLoad():
break
self.nextImage()
elif k == ord('n'):
# Skip to next image
self.idx += 1
if self.idx >= len(self.images):
if not self.blockLoad():
break
self.nextImage()
elif k == 27:
cv2.destroyAllWindows()
break
print("End of labeling at INDEX: " + str(self.org_idx + self.idx))
def blockLoad(self):
self.images, self.labels = loadImages(
self.data_loc, self.org_idx + self.idx, 100)
self.org_idx += self.idx
self.idx = 0
return len(self.images) is not 0
def imageShow(self):
cv2.imshow(
'image',
cv2.resize(
self.image_act,
(0,0),
fx=self.scaleF,
fy=self.scaleF,
interpolation=cv2.INTERSECT_NONE))
def nextImage(self):
self.image_act = cv2.cvtColor(self.images[self.idx], cv2.COLOR_GRAY2RGB)
self.label_act = self.labels[self.idx][:-4]
self.gaplines = [0, self.image_act.shape[1]]
self.redrawLines()
print(self.org_idx + self.idx, ":", self.label_act.split("_")[0])
self.imageShow();
def saveData(self):
self.gaplines.sort()
print("Saving image with gaplines: ", self.gaplines)
try:
assert len(self.gaplines) - 1 == len(self.label_act.split("_")[0])
cv2.imwrite(
self.save_loc + '%s.jpg' % (self.label_act),
self.images[self.idx])
with open(self.save_loc + '%s.txt' % (self.label_act), 'w') as fp:
simplejson.dump(self.gaplines, fp)
return True
except:
print("Wront number of gaplines")
return False
print()
self.nextImage()
def deleteLastLine(self):
if len(self.gaplines) > 0:
del self.gaplines[-1]
self.redrawLines()
def redrawLines(self):
self.image_act = cv2.cvtColor(self.images[self.idx], cv2.COLOR_GRAY2RGB)
for x in self.gaplines:
self.drawLine(x)
def drawLine(self, x):
cv2.line(
self.image_act, (x, 0), (x, self.image_act.shape[0]), (0,255,0), 1)
def mouseHandler(self, event, x, y, flags, param):
# Clip x into image width range
x = max(min(self.image_act.shape[1], x // self.scaleF), 0)
if event == cv2.EVENT_LBUTTONDOWN:
self.drawing = True
self.tmp = self.image_act.copy()
self.drawLine(x)
elif event == cv2.EVENT_MOUSEMOVE:
if self.drawing == True:
self.image_act = self.tmp.copy()
self.drawLine(x)
elif event == cv2.EVENT_LBUTTONUP:
self.drawing = False
if x not in self.gaplines:
self.gaplines.append(x)
self.image_act = self.tmp.copy()
self.drawLine(x)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
"Script creating UI for gaplines classification")
parser.add_argument(
"--index",
type=int,
default=0,
help="Index of starting image")
parser.add_argument(
"--data",
type=str,
default='data/words_raw',
help="Path to folder with images")
parser.add_argument(
"--save",
type=str,
default='data/words2',
help="Path to folder for saving images with gaplines")
args = parser.parse_args()
Cycler(args.index, args.data, args.save)
| Breta01/handwriting-ocr | src/data/data_creation/WordClassDM.py | Python | mit | 6,492 |
class FixColumnVerificationTypeVerifications < ActiveRecord::Migration
def self.up
change_column :verifications, :verification_type, "enum('idchecker', 'directid', 'netverify', 'authenticid')"
end
def self.down
end
end
| malahinisolutions/verify | db/migrate/20151008092718_fix_column_verification_type_verifications.rb | Ruby | mit | 232 |
package tilat;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import hallinta.Grafiikka;
import hallinta.Hiiri;
import hallinta.Musiikki;
import hallinta.Nappaimisto;
import hallinta.PeliAlue;
import hallinta.PeliOhi;
import hallinta.PeliPaussi;
import main.IkkunaPaneeli;
/**Luokka, joka hoitaa itse pelin hallinnan
* Perustuu kolmen eri luokan ilmentymiin
* Nämä ovat {@link PeliAlue}, {@link PeliOhi} ja {@link PeliPaussi}
* @author Juho Kuusinen
*
*/
public class Peli extends Pelitila{
private PeliAlue peli;
private PeliOhi peliOhi;
private PeliPaussi peliPaussi;
private boolean peliOhiAlustettu;
private Pelintilanhallitsija gm;
private boolean paussi;
/**
* Luodaan uusi Peli-luokan ilmentymä parametrina annetun {@link Pelintilanhallitsija}-luokan ilmentymän mukaan
* @param gm {@link Pelintilanhallitsija}
*/
public Peli(Pelintilanhallitsija gm){
alusta();
this.gm = gm;
}
@Override
public void alusta() {
paussi = false;
peli = new PeliAlue(0, 0, IkkunaPaneeli.LEVEYS, IkkunaPaneeli.KORKEUS,Grafiikka.annaKuva(Grafiikka.TAUSTA));
peliOhi = new PeliOhi(0, 0, IkkunaPaneeli.LEVEYS, IkkunaPaneeli.KORKEUS, Grafiikka.annaKuva(Grafiikka.TAUSTA),Grafiikka.annaKuva(Grafiikka.PISTETAULULOGO));
peliPaussi = new PeliPaussi(0, 0, IkkunaPaneeli.LEVEYS, IkkunaPaneeli.KORKEUS, Grafiikka.annaKuva(Grafiikka.TAUSTA),Grafiikka.annaKuva(Grafiikka.PAUSSI), gm);
peliPaussi.alusta();
}
@Override
public void paivita() {
kasitteleSyote();
if(peli.onkoElossa()){
if(paussi){
peliPaussi.paivita();
}else{
peli.paivita();
}
}else if(!peli.onkoElossa()){
if(!peliOhiAlustettu){
peliOhi.alusta(peli.annaPisteet());
peliOhiAlustettu = true;
}
peliOhi.paivita();
}else{
System.out.println("KUINKAS NÄIN KÄVI...");
}
Musiikki.toistaAudiotListasta();
}
@Override
public void piirra(Graphics2D g) {
if(peli.onkoElossa()){
if(paussi){
peliPaussi.piirra(g);
}else{
peli.piirra(g);
}
}else if(!peli.onkoElossa()){
peliOhi.piirra(g);
}else{
System.out.println("KUINKAS NÄIN KÄVI...");
}
}
@Override
public void kasitteleSyote() {
if(Nappaimisto.annaPainettuNappi() == KeyEvent.VK_ESCAPE){
if(paussi){
paussi = false;
}else{
paussi = true;
peliPaussi.asetaHiiri(Hiiri.annaX(), Hiiri.annaY());
}
}
if(paussi && Hiiri.tapahtuma==1){
if(Hiiri.annaX() > IkkunaPaneeli.LEVEYS/2 - Grafiikka.annaKuva(Grafiikka.NAPPI).getWidth()/2 && Hiiri.annaX() < IkkunaPaneeli.LEVEYS/2 + Grafiikka.annaKuva(Grafiikka.NAPPI).getWidth()/2 ){
if(Hiiri.annaY() > 150+50 && Hiiri.annaY() < 150 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() + 50){
paussi = false;
}
if(Hiiri.annaY() > 150+50 +Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() && Hiiri.annaY() < 150 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() * 2 + 50){
gm.asetaTila(Pelintilanhallitsija.PAAMENU);
}
if(Hiiri.annaY() > 150+50 +Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight()*2 && Hiiri.annaY() < 150 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight() * 3 + 50){
System.exit(0);
}
}
}
if(!peli.onkoElossa() && Hiiri.tapahtuma ==1){
if(Hiiri.annaX() > 50 && Hiiri.annaX() < 50 + Grafiikka.annaKuva(Grafiikka.NAPPI).getWidth() &&
Hiiri.annaY() > 50 && Hiiri.annaY() < 50 + Grafiikka.annaKuva(Grafiikka.NAPPI).getHeight()){
gm.asetaTila(Pelintilanhallitsija.PAAMENU);
}
}
}
}
| Qurred/Bubble-Game | src/tilat/Peli.java | Java | mit | 3,583 |
<?php
/* SonataAdminBundle:CRUD:edit_sonata_type_immutable_array.html.twig */
class __TwigTemplate_4756e8c5a9c146a3fcb19b2bc6e739a2 extends Twig_Template
{
protected $parent;
public function getParent(array $context)
{
if (null === $this->parent) {
$this->parent = $this->getContext($context, 'base_template');
if (!$this->parent instanceof Twig_Template) {
$this->parent = $this->env->loadTemplate($this->parent);
}
}
return $this->parent;
}
protected function doDisplay(array $context, array $blocks = array())
{
$context = array_merge($this->env->getGlobals(), $context);
$this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
}
public function getTemplateName()
{
return "SonataAdminBundle:CRUD:edit_sonata_type_immutable_array.html.twig";
}
public function isTraitable()
{
return false;
}
}
| kohr/HRSymfony2 | app/cache/dev/twig/47/56/e8c5a9c146a3fcb19b2bc6e739a2.php | PHP | mit | 992 |
/**
* @author weism
* copyright 2015 Qcplay All Rights Reserved.
*/
qc.RoundedRectangle = Phaser.RoundedRectangle;
/**
* 类名
*/
Object.defineProperty(qc.RoundedRectangle.prototype, 'class', {
get : function() { return 'qc.RoundedRectangle'; }
});
/**
* 序列化
*/
qc.RoundedRectangle.prototype.toJson = function() {
return [this.x, this.y, this.width, this.height, this.radius];
}
/**
* 反序列化
*/
qc.RoundedRectangle.prototype.fromJson = function(v) {
this.x = v[0];
this.y = v[1];
this.width = v[2];
this.height = v[3];
this.radius = v[4];
}
| qiciengine/qiciengine-core | src/geom/RoundedRectangle.js | JavaScript | mit | 594 |
package zame.game.store.products;
public class ProductText extends Product {
public int purchasedTextResourceId;
public int purchasedImageResourceId;
public ProductText(
int id,
int dependsOnId,
int price,
int titleResourceId,
int descriptionResourceId,
int iconResourceId,
int imageResourceId,
int purchasedTextResourceId,
int purchasedImageResourceId
) {
super(id, dependsOnId, price, titleResourceId, descriptionResourceId, iconResourceId, imageResourceId);
this.purchasedTextResourceId = purchasedTextResourceId;
this.purchasedImageResourceId = purchasedImageResourceId;
}
}
| restorer/gloomy-dungeons-2 | src/main/java/zame/game/store/products/ProductText.java | Java | mit | 610 |
shared_examples_for type: :collection do |context|
let(:described_collection) { described_class.new(service: service) }
end
| cpb/opennorth-represent | spec/support/shared_examples/collection_spec.rb | Ruby | mit | 126 |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "treemap.hoverlabel"
_path_str = "treemap.hoverlabel.font"
_valid_props = {"color", "colorsrc", "family", "familysrc", "size", "sizesrc"}
# color
# -----
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
# colorsrc
# --------
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
# family
# ------
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
# familysrc
# ---------
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = val
# size
# ----
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
# sizesrc
# -------
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
size=None,
sizesrc=None,
**kwargs
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.treemap.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.treemap.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.treemap.hoverlabel.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("colorsrc", None)
_v = colorsrc if colorsrc is not None else _v
if _v is not None:
self["colorsrc"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("familysrc", None)
_v = familysrc if familysrc is not None else _v
if _v is not None:
self["familysrc"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("sizesrc", None)
_v = sizesrc if sizesrc is not None else _v
if _v is not None:
self["sizesrc"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| plotly/python-api | packages/python/plotly/plotly/graph_objs/treemap/hoverlabel/_font.py | Python | mit | 11,209 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings
{
public partial class PreviewTests
{
[WpfFact]
public async Task TestExceptionInComputePreview()
{
using var workspace = CreateWorkspaceFromFile("class D {}", new TestParameters());
await GetPreview(workspace, new ErrorCases.ExceptionInCodeAction());
}
[WpfFact]
public void TestExceptionInDisplayText()
{
using var workspace = CreateWorkspaceFromFile("class D {}", new TestParameters());
DisplayText(workspace, new ErrorCases.ExceptionInCodeAction());
}
[WpfFact]
public async Task TestExceptionInActionSets()
{
using var workspace = CreateWorkspaceFromFile("class D {}", new TestParameters());
await ActionSets(workspace, new ErrorCases.ExceptionInCodeAction());
}
private static async Task GetPreview(TestWorkspace workspace, CodeRefactoringProvider provider)
{
var codeActions = new List<CodeAction>();
RefactoringSetup(workspace, provider, codeActions, out var extensionManager, out var textBuffer);
var suggestedAction = new CodeRefactoringSuggestedAction(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
workspace.ExportProvider.GetExportedValue<SuggestedActionsSourceProvider>(),
workspace, textBuffer, provider, codeActions.First());
await suggestedAction.GetPreviewAsync(CancellationToken.None);
Assert.True(extensionManager.IsDisabled(provider));
Assert.False(extensionManager.IsIgnored(provider));
}
private static void DisplayText(TestWorkspace workspace, CodeRefactoringProvider provider)
{
var codeActions = new List<CodeAction>();
RefactoringSetup(workspace, provider, codeActions, out var extensionManager, out var textBuffer);
var suggestedAction = new CodeRefactoringSuggestedAction(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
workspace.ExportProvider.GetExportedValue<SuggestedActionsSourceProvider>(),
workspace, textBuffer, provider, codeActions.First());
_ = suggestedAction.DisplayText;
Assert.True(extensionManager.IsDisabled(provider));
Assert.False(extensionManager.IsIgnored(provider));
}
private static async Task ActionSets(TestWorkspace workspace, CodeRefactoringProvider provider)
{
var codeActions = new List<CodeAction>();
RefactoringSetup(workspace, provider, codeActions, out var extensionManager, out var textBuffer);
var suggestedAction = new CodeRefactoringSuggestedAction(
workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
workspace.ExportProvider.GetExportedValue<SuggestedActionsSourceProvider>(),
workspace, textBuffer, provider, codeActions.First());
_ = await suggestedAction.GetActionSetsAsync(CancellationToken.None);
Assert.True(extensionManager.IsDisabled(provider));
Assert.False(extensionManager.IsIgnored(provider));
}
private static void RefactoringSetup(
TestWorkspace workspace, CodeRefactoringProvider provider, List<CodeAction> codeActions,
out EditorLayerExtensionManager.ExtensionManager extensionManager,
out VisualStudio.Text.ITextBuffer textBuffer)
{
var document = GetDocument(workspace);
textBuffer = workspace.GetTestDocument(document.Id).GetTextBuffer();
var span = document.GetSyntaxRootAsync().Result.Span;
var context = new CodeRefactoringContext(document, span, (a) => codeActions.Add(a), CancellationToken.None);
provider.ComputeRefactoringsAsync(context).Wait();
var action = codeActions.Single();
extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager;
}
}
}
| diryboy/roslyn | src/EditorFeatures/CSharpTest/CodeActions/Preview/PreviewExceptionTests.cs | C# | mit | 4,931 |
export enum Collection {
NESTJS = '@nestjs/schematics',
}
| ThomRick/nest-cli | lib/schematics/collection.ts | TypeScript | mit | 60 |
namespace DataTradeExamples
{
class Program
{
static void Main()
{
string address = "localhost";
string username = "5";
string password = "123qwe!";
//var example = new TradeServerInfoExample(address, username, password);
var example = new AccountInfoExample(address, username, password);
//var example = new SendLimitOrderExample(address, username, password);
//var example = new SendMarketOrderExample(address, username, password);
//var example = new SendStopOrderExample(address, username, password);
//var example = new CloseAllPositionsExample(address, username, password);
//var example = new ClosePositionExample(address, username, password);
//var example = new ClosePartiallyPositionExample(address, username, password);
//var example = new DeletePendingOrderExample(address, username, password);
//var example = new GetOrdersExample(address, username, password);
//var example = new GetTradeTransactionReportsExample(address, username, password);
//var example = new ModifyTradeRecordExample(address, username, password);
//var example = new CloseByExample(address, username, password);
//var example = new GetDailyAccountSnapshotsExample(address, username, password);
using (example)
{
example.Run();
}
}
}
}
| SoftFx/FDK | Examples/CSharp/DataTradeExamples/Program.cs | C# | mit | 1,518 |
package com.skidsdev.fyrestone.item;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
public final class ItemRegister
{
public static Item itemShard;
public static Item itemFyrestoneIngot;
public static Item itemEarthstoneIngot;
public static Item itemMysticalOrb;
public static Item itemPlagueEssence;
public static Item itemPlagueCore;
public static Item itemBlazingCore;
public static Item itemFyrestoneCatalyst;
public static Item itemGuideBook;
public static Item itemSword;
public static ToolMaterial FYRESTONE = EnumHelper.addToolMaterial("FYRESTONE", 2, 500, 10.0F, 2.0F, 18);
public static List<Item> registeredItems;
public static final void createItems()
{
registeredItems = new ArrayList<Item>();
GameRegistry.register(itemShard = new ItemBaseShard());
itemFyrestoneIngot = registerItem(new BaseItem("itemFyrestoneIngot"), "ingotFyrestone");
itemEarthstoneIngot = registerItem(new BaseItem("itemEarthstoneIngot"), "ingotEarthstone");
itemMysticalOrb = registerItem(new BaseItem("itemMysticalOrb"));
itemPlagueEssence = registerItem(new BaseItem("itemPlagueEssence"));
itemPlagueCore = registerItem(new BaseItem("itemPlagueCore"));
itemBlazingCore = registerItem(new BaseItem("itemBlazingCore"));
itemFyrestoneCatalyst = registerItem(new BaseItem("itemFyrestoneCatalyst"));
itemGuideBook = registerItem(new ItemGuideBook());
itemSword = registerItem(new ItemBaseSword(FYRESTONE, "itemSword"));
}
private static Item registerItem(Item item, String oreDict)
{
OreDictionary.registerOre(oreDict, registerItem(item));
return item;
}
private static Item registerItem(Item item)
{
GameRegistry.register(item);
registeredItems.add(item);
return item;
}
} | gunnerwolf/Fyrestone | src/main/java/com/skidsdev/fyrestone/item/ItemRegister.java | Java | mit | 2,022 |
// Copyright (c) 2013 Richard Long & HexBeerium
//
// Released under the MIT license ( http://opensource.org/licenses/MIT )
//
package jsonbroker.library.common.broker;
import jsonbroker.library.common.exception.BaseException;
/**
*
* @deprecated use jsonbroker.library.broker.BrokerMessageType
*
*/
public class BrokerMessageType extends jsonbroker.library.broker.BrokerMessageType {
public static final BrokerMessageType FAULT = new BrokerMessageType("fault");
public static final BrokerMessageType NOTIFICATION = new BrokerMessageType("notification");
public static final BrokerMessageType ONEWAY = new BrokerMessageType("oneway");
public static final BrokerMessageType META_REQUEST = new BrokerMessageType("meta-request");
public static final BrokerMessageType META_RESPONSE = new BrokerMessageType("meta-response");
public static final BrokerMessageType REQUEST = new BrokerMessageType("request");
public static final BrokerMessageType RESPONSE = new BrokerMessageType("response");
private BrokerMessageType(String identifier) {
super( identifier );
}
public static BrokerMessageType lookup( String identifier) {
if( FAULT._identifier.equals(identifier) ) {
return FAULT;
}
if( NOTIFICATION._identifier.equals( identifier) ) {
return NOTIFICATION;
}
if( ONEWAY._identifier.equals(identifier) ) {
return ONEWAY;
}
if( META_REQUEST._identifier.equals(identifier) ) {
return META_REQUEST;
}
if( META_RESPONSE._identifier.equals(identifier) ) {
return META_RESPONSE;
}
if( REQUEST._identifier.equals(identifier) ) {
return REQUEST;
}
if( RESPONSE._identifier.equals(identifier) ) {
return RESPONSE;
}
String technicalError = String.format("unexpected identifier; identifier = '%s'", identifier);
throw new BaseException(BrokerMessageType.class, technicalError);
}
}
| rlong/java.jsonbroker.library | src/jsonbroker/library/common/broker/BrokerMessageType.java | Java | mit | 1,946 |
class DropTable < ActiveRecord::Migration
def up
end
def down
drop_table :Stat
end
end
| suhasdeshpande/DigFollowers | db/migrate/20120308180244_drop_table.rb | Ruby | mit | 97 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BusinessLogic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BusinessLogic")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("96558876-6abb-4f6f-a392-b1503c239f40")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| PhatTrien-MNM/ptnm_cuoiki | BusinessLogic/Properties/AssemblyInfo.cs | C# | mit | 1,402 |
require 'spec_helper'
module Recurly
describe BillingInfo do
# version accounts based on this current files modification dates
timestamp = File.mtime(__FILE__).to_i
def verify_billing_info(billing_info, billing_attributes)
# check the billing data fields
billing_info.first_name.should == billing_attributes[:first_name]
billing_info.last_name.should == billing_attributes[:last_name]
billing_info.address1.should == billing_attributes[:address1]
billing_info.city.should == billing_attributes[:city]
billing_info.state.should == billing_attributes[:state]
billing_info.zip.should == billing_attributes[:zip]
# check the credit card fields
billing_info.credit_card.last_four.should == billing_attributes[:credit_card][:number][-4, 4]
end
describe "create an account's billing information" do
use_vcr_cassette "billing/create/#{timestamp}"
let(:account){ Factory.create_account("billing-create-#{timestamp}") }
before(:each) do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name
})
@billing_info = BillingInfo.create(@billing_attributes)
end
it "should successfully create the billing info record" do
@billing_info.updated_at.should_not be_nil
end
it "should set the correct billing_info on the server " do
billing_info = BillingInfo.find(account.account_code)
verify_billing_info(billing_info, @billing_attributes)
end
end
describe "update an account's billing information" do
use_vcr_cassette "billing/update/#{timestamp}"
let(:account){ Factory.create_account_with_billing_info("billing-update-#{timestamp}") }
before(:each) do
@new_billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:address1 => "1st Ave South, Apt 5001"
})
@billing_info = BillingInfo.create(@new_billing_attributes)
end
it "should set the correct billing_info on the server " do
billing_info = BillingInfo.find(account.account_code)
verify_billing_info(billing_info, @new_billing_attributes)
end
end
describe "get account's billing information" do
use_vcr_cassette "billing/find/#{timestamp}"
let(:account){ Factory.create_account_with_billing_info("billing-find-#{timestamp}") }
before(:each) do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name
})
@billing_info = BillingInfo.find(account.account_code)
end
it "should return the correct billing_info from the server" do
billing_info = BillingInfo.find(account.account_code)
verify_billing_info(billing_info, @billing_attributes)
end
end
describe "clearing an account's billing information" do
use_vcr_cassette "billing/destroy/#{timestamp}"
let(:account){ Factory.create_account("billing-destroy-#{timestamp}") }
before(:each) do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:address1 => "500 South Central Blvd",
:city => "Los Angeles",
:state => "CA",
:zip => "90001"
})
BillingInfo.create(@billing_attributes)
@billing_info = BillingInfo.find(account.account_code)
end
it "should allow destroying the billing info for an account" do
@billing_info.destroy
expect {
fresh = BillingInfo.find(account.account_code)
}.to raise_error ActiveResource::ResourceNotFound
end
end
describe "set the appropriate error" do
use_vcr_cassette "billing/errors/#{timestamp}"
let(:account){ Factory.create_account("billing-errors-#{timestamp}") }
it "should set an error on base if the card number is blank" do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:credit_card => {
:number => '',
},
})
billing_info = BillingInfo.create(@billing_attributes)
billing_info.errors[:base].count.should == 1
end
it "should set an error if the card number is invalid" do
@billing_attributes = Factory.billing_attributes({
:account_code => account.account_code,
:first_name => account.first_name,
:last_name => account.last_name,
:credit_card => {
:number => '4000-0000-0000-0002',
},
})
billing_info = BillingInfo.create(@billing_attributes)
billing_info.errors.count.should == 1
end
end
end
end | compactcode/recurly-client-ruby | spec/integration/billing_info_spec.rb | Ruby | mit | 5,228 |
<?php
namespace Fer\UserBundle\Security\User\Provider;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use \BaseFacebook;
use \FacebookApiException;
class FacebookProvider implements UserProviderInterface
{
/**
* @var \Facebook
*/
protected $facebook;
protected $userManager;
protected $validator;
public function __construct(BaseFacebook $facebook, $userManager, $validator)
{
$this->facebook = $facebook;
$this->userManager = $userManager;
$this->validator = $validator;
}
public function supportsClass($class)
{
return $this->userManager->supportsClass($class);
}
public function findUserByFbId($fbId)
{
return $this->userManager->findUserBy(array('facebookId' => $fbId));
}
public function loadUserByUsername($username)
{
$user = $this->findUserByFbId($username);
try {
$fbdata = $this->facebook->api('/me');
} catch (FacebookApiException $e) {
$fbdata = null;
}
if (!empty($fbdata)) {
if (empty($user)) {
$user = $this->userManager->createUser();
$user->setEnabled(true);
$user->setPassword('');
}
// TODO use http://developers.facebook.com/docs/api/realtime
$user->setFBData($fbdata);
if (count($this->validator->validate($user, 'Facebook'))) {
// TODO: the user was found obviously, but doesnt match our expectations, do something smart
throw new UsernameNotFoundException('The facebook user could not be stored');
}
$this->userManager->updateUser($user);
}
if (empty($user)) {
throw new UsernameNotFoundException('The user is not authenticated on facebook');
}
return $user;
}
public function refreshUser(UserInterface $user)
{
if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
return $this->loadUserByUsername($user->getFacebookId());
}
} | farconada/sfapi | src/Fer/UserBundle/Security/User/Provider/FacebookProvider.php | PHP | mit | 2,117 |
<?php
/*
* The MIT License
*
* Copyright 2014 Ronny Hildebrandt <ronny.hildebrandt@avorium.de>.
*
* 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.
*/
/**
* This file is used for installation.
*/
require_once './code/App.php';
// Check file permissions
$candeleteinstallsript = Install::canDeleteInstallScript();
$canwritelocalconfig = Install::canWriteLocalConfig();
$canwritemediadir = Install::canWriteMediaDir();
$canwritelocaledir = Install::canWriteLocaleDir();
$isdatabaseavailable = Install::isPostgresAvailable();
$isgdavailable = Install::isGdAvailable();
// Handle postbacks for form
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
// Form was posted back
$databasehost = filter_input(INPUT_POST, 'databasehost');
$databaseusername = filter_input(INPUT_POST, 'databaseusername');
$databasepassword = filter_input(INPUT_POST, 'databasepassword');
$databasename = filter_input(INPUT_POST, 'databasename');
$tableprefix = filter_input(INPUT_POST, 'tableprefix');
$defaultlanguage = filter_input(INPUT_POST, 'defaultlanguage');
$GLOBALS['databasehost'] = $databasehost;
$GLOBALS['databaseusername'] = $databaseusername;
$GLOBALS['databasepassword'] = $databasepassword;
$GLOBALS['databasename'] = $databasename;
$GLOBALS['tableprefix'] = $tableprefix;
$GLOBALS['defaultlanguage'] = $defaultlanguage;
// Check database connection
$databaseerror = !Install::canAccessDatabase();
if ($candeleteinstallsript && $canwritelocalconfig && $canwritemediadir && $canwritelocaledir && $isdatabaseavailable && $isgdavailable && !$databaseerror) {
// Store localconfig file
$installationprogress = Install::createLocalConfig();
// Perform the database installation
$installationprogress .= Install::createAndUpdateTables($tableprefix);
rename('install.php', 'install.php.bak');
$installationprogress .= '<p class="success">'.sprintf(__('The installation is completed. The %s file was renamed to %s for security reasons.'), 'install.php', 'install.php.bak').'</p>';
} else {
$installationprogress = false;
}
} else {
// Single GET page call
if (file_exists('config/localconfig.inc.php')) {
require_once 'config/localconfig.inc.php';
} else {
$databasehost = 'localhost';
$databaseusername = '';
$databasepassword = '';
$databasename = '';
$tableprefix = 'mps_';
$defaultlanguage = 'en';
}
$databaseerror = null;
$installationprogress = false;
}
?><!DOCTYPE html>
<html>
<head>
<title><?php echo __('Install MyPhotoStorage') ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="static/css/install.css" />
</head>
<body>
<h1><?php echo __('Install MyPhotoStorage') ?></h1>
<form method="post" action="install.php#end" class="simple install">
<h2><?php echo __('File system check') ?></h2>
<div>
<?php if ($candeleteinstallsript) : ?>
<p class="success"><?php echo __('Install script can be deleted.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Install script cannot be deleted. Please make sure that the webserver process has write permissions to the file %s'), Install::$installFileName) ?></p>
<?php endif ?>
<?php if ($canwritelocalconfig) : ?>
<p class="success"><?php echo __('Config file is writeable.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Config file is not writeable. Please make sure that the webserver process has write permissions to the file %s'), Install::$localConfigFileName) ?></p>
<?php endif ?>
<?php if ($canwritemediadir) : ?>
<p class="success"><?php echo __('Media directory is writeable.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Media directory is not writeable. Please make sure that the webserver process has write permissions to the directory %s'), Install::$mediaDir) ?></p>
<?php endif ?>
<?php if ($canwritelocaledir) : ?>
<p class="success"><?php echo __('Locale directory is writeable.') ?></p>
<?php else : ?>
<p class="error"><?php echo sprintf(__('Locale directory is not writeable. Please make sure that the webserver process has write permissions to the directory %s'), Install::$localeDir) ?></p>
<?php endif ?>
</div>
<h2><?php echo __('PHP modules') ?></h2>
<div>
<?php if ($isdatabaseavailable) : ?>
<p class="success"><?php echo __('Database is available.') ?></p>
<?php else : ?>
<p class="error"><?php echo __('The Database PHP extension is not available. Please install it. On Debian you can use "sudo apt-get install php5-mysql"') ?></p>
<?php endif ?>
<?php if ($isgdavailable) : ?>
<p class="success"><?php echo __('GD is available.') ?></p>
<?php else : ?>
<p class="error"><?php echo __('The GD PHP extension is not available. Please install it. On Debian you can use "sudo apt-get install php5-gd"') ?></p>
<?php endif ?>
</div>
<h2><?php echo __('Database connection') ?></h2>
<div>
<?php if ($isdatabaseavailable) : ?>
<label><?php echo __('Database host') ?></label>
<input type="text" name="databasehost" value="<?php echo $databasehost ?>" />
<label><?php echo __('Database username') ?></label>
<input type="text" name="databaseusername" value="<?php echo $databaseusername ?>" />
<label><?php echo __('Database password') ?></label>
<input type="text" name="databasepassword" value="<?php echo $databasepassword ?>" />
<label><?php echo __('Database name') ?></label>
<input type="text" name="databasename" value="<?php echo $databasename ?>" />
<label><?php echo __('Table prefix') ?></label>
<input type="text" name="tableprefix" value="<?php echo $tableprefix ?>" />
<?php endif ?>
<?php if ($databaseerror === true) : ?>
<p class="error"><?php echo __('Cannot access database. Please check the settings above.') ?></p>
<?php elseif ($databaseerror === false) : ?>
<p class="success"><?php echo __('Database connection succeeded.') ?></p>
<?php endif ?>
</div>
<h2><?php echo __('Language') ?></h2>
<div>
<label><?php echo __('Default language') ?></label>
<input type="text" name="defaultlanguage" value="<?php echo $defaultlanguage ?>" />
</div>
<div>
<input type="submit" value="<?php echo __('Install') ?>" />
</div>
<?php if ($installationprogress) : ?>
<h2><?php echo __('Installation progress') ?></h2>
<div>
<?php echo $installationprogress ?>
</div>
<div><a href="account/register.php"><?php echo __('Register a new account') ?></a></div>
<?php endif ?>
</form>
<a name="end"></a>
</body>
</html> | avorium/myphotostorage | install.php | PHP | mit | 7,966 |
package com.mindera.skeletoid.rxbindings.extensions.views.searchview.support;
import android.view.View;
import androidx.appcompat.widget.SearchView;
import com.jakewharton.rxbinding3.InitialValueObservable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;
public class SearchViewFocusChangeObservable extends InitialValueObservable<Boolean> {
private final SearchView view;
public SearchViewFocusChangeObservable(SearchView view) {
this.view = view;
}
@Override
protected void subscribeListener(Observer<? super Boolean> observer) {
Listener listener = new Listener(view, observer);
observer.onSubscribe(listener);
view.setOnQueryTextFocusChangeListener(listener);
}
@Override
protected Boolean getInitialValue() {
return view.hasFocus();
}
static final class Listener extends MainThreadDisposable
implements SearchView.OnFocusChangeListener {
private final SearchView view;
private final Observer<? super Boolean> observer;
Listener(SearchView view, Observer<? super Boolean> observer) {
this.view = view;
this.observer = observer;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!isDisposed()) {
observer.onNext(hasFocus);
}
}
@Override
protected void onDispose() {
view.setOnFocusChangeListener(null);
}
}
}
| Mindera/skeletoid | rxbindings/src/main/java/com/mindera/skeletoid/rxbindings/extensions/views/searchview/support/SearchViewFocusChangeObservable.java | Java | mit | 1,529 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PlotRenderer.cs" company="OxyPlot">
// The MIT License (MIT)
//
// Copyright (c) 2012 Oystein Bjorke
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
namespace OxyPlot
{
public class PlotRenderer
{
protected readonly PlotModel plot;
protected readonly IRenderContext rc;
public PlotRenderer(IRenderContext rc, PlotModel p)
{
this.rc = rc;
plot = p;
}
public void RenderTitle(string title, string subtitle)
{
OxySize size1 = rc.MeasureText(title, plot.TitleFont, plot.TitleFontSize, plot.TitleFontWeight);
OxySize size2 = rc.MeasureText(subtitle, plot.TitleFont, plot.TitleFontSize, plot.TitleFontWeight);
double height = size1.Height + size2.Height;
double dy = (plot.AxisMargins.Top - height) * 0.5;
double dx = (plot.Bounds.Left + plot.Bounds.Right) * 0.5;
if (!String.IsNullOrEmpty(title))
rc.DrawText(
new ScreenPoint(dx, dy), title, plot.TextColor,
plot.TitleFont, plot.TitleFontSize, plot.TitleFontWeight,
0,
HorizontalTextAlign.Center, VerticalTextAlign.Top);
if (!String.IsNullOrEmpty(subtitle))
rc.DrawText(new ScreenPoint(dx, dy + size1.Height), subtitle, plot.TextColor,
plot.TitleFont, plot.SubtitleFontSize, plot.SubtitleFontWeight, 0,
HorizontalTextAlign.Center, VerticalTextAlign.Top);
}
public void RenderRect(OxyRect bounds, OxyColor fill, OxyColor borderColor, double borderThickness)
{
var border = new[]
{
new ScreenPoint(bounds.Left, bounds.Top), new ScreenPoint(bounds.Right, bounds.Top),
new ScreenPoint(bounds.Right, bounds.Bottom), new ScreenPoint(bounds.Left, bounds.Bottom),
new ScreenPoint(bounds.Left, bounds.Top)
};
rc.DrawPolygon(border, fill, borderColor, borderThickness, null, true);
}
private static readonly double LEGEND_PADDING = 8;
public void RenderLegends()
{
double maxWidth = 0;
double maxHeight = 0;
double totalHeight = 0;
// Measure
foreach (var s in plot.Series)
{
if (String.IsNullOrEmpty(s.Title))
continue;
var oxySize = rc.MeasureText(s.Title, plot.LegendFont, plot.LegendFontSize);
if (oxySize.Width > maxWidth) maxWidth = oxySize.Width;
if (oxySize.Height > maxHeight) maxHeight = oxySize.Height;
totalHeight += oxySize.Height;
}
double lineLength = plot.LegendSymbolLength;
// Arrange
double x0 = double.NaN, x1 = double.NaN, y0 = double.NaN;
// padding padding
// lineLength
// y0 -----o---- seriesName
// x0 x1
double sign = 1;
if (plot.IsLegendOutsidePlotArea)
sign = -1;
// Horizontal alignment
HorizontalTextAlign ha = HorizontalTextAlign.Left;
switch (plot.LegendPosition)
{
case LegendPosition.TopRight:
case LegendPosition.BottomRight:
x0 = plot.Bounds.Right - LEGEND_PADDING * sign;
x1 = x0 - lineLength * sign - LEGEND_PADDING * sign;
ha = sign == 1 ? HorizontalTextAlign.Right : HorizontalTextAlign.Left;
break;
case LegendPosition.TopLeft:
case LegendPosition.BottomLeft:
x0 = plot.Bounds.Left + LEGEND_PADDING * sign;
x1 = x0 + lineLength * sign + LEGEND_PADDING * sign;
ha = sign == 1 ? HorizontalTextAlign.Left : HorizontalTextAlign.Right;
break;
}
// Vertical alignment
VerticalTextAlign va = VerticalTextAlign.Middle;
switch (plot.LegendPosition)
{
case LegendPosition.TopRight:
case LegendPosition.TopLeft:
y0 = plot.Bounds.Top + LEGEND_PADDING + maxHeight / 2;
break;
case LegendPosition.BottomRight:
case LegendPosition.BottomLeft:
y0 = plot.Bounds.Bottom - maxHeight + LEGEND_PADDING;
break;
}
foreach (var s in plot.Series)
{
if (String.IsNullOrEmpty(s.Title))
continue;
rc.DrawText(new ScreenPoint(x1, y0),
s.Title, plot.TextColor,
plot.LegendFont, plot.LegendFontSize, 500, 0,
ha, va);
OxyRect rect = new OxyRect(x0 - lineLength, y0 - maxHeight / 2, lineLength, maxHeight);
if (ha == HorizontalTextAlign.Left)
rect = new OxyRect(x0, y0 - maxHeight / 2, lineLength, maxHeight);
s.RenderLegend(rc, rect);
if (plot.LegendPosition == LegendPosition.TopLeft || plot.LegendPosition == LegendPosition.TopRight)
y0 += maxHeight;
else
y0 -= maxHeight;
}
}
}
} | ylatuya/oxyplot | Source/OxyPlot/Render/PlotRenderer.cs | C# | mit | 7,113 |
version https://git-lfs.github.com/spec/v1
oid sha256:d99fc51072a5fe30289f7dc885457700f9b08ae17fe81d034245aba73c408033
size 34706
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/model/model.js | JavaScript | mit | 130 |
<?php
namespace App\AWS;
use Aws\S3\S3Client;
use Psr\Log\LoggerInterface;
class S3
{
private $s3;
private $bucketName;
private $baseUrl;
private $logger;
/**
* S3 constructor.
*
* @param S3Client $s3
* @param $baseUrl
* @param $bucketName
* @param LoggerInterface $loggerInterface
*/
public function __construct(S3Client $s3, $baseUrl, $bucketName, LoggerInterface $loggerInterface)
{
$this->bucketName = $bucketName;
$this->baseUrl = $baseUrl;
$this->s3 = $s3;
$this->logger = $loggerInterface;
}
/**
* @param string $path
* @param string $filename
* @param array $headers
*
* @return mixed
*
* @throws \Exception
*/
public function upload($path, $filename, $headers = [])
{
try {
$config = [
'Bucket' => $this->bucketName,
'Key' => trim($filename, '/'),
'Body' => fopen($path, 'r'),
'ACL' => 'public-read'
];
foreach ($headers as $key => $header) {
$config[$key] = $header;
}
$result = $this->s3->putObject($config);
return $result['ObjectURL'];
} catch (\Exception $e) {
$this->logger->error('Failed to upload file', ['e' => $e]);
throw $e;
}
}
/**
* @param string $filename
*/
public function delete($filename)
{
$this->s3->deleteObject([
'Bucket' => $this->bucketName,
'Key' => trim($filename, '/'),
]);
}
/**
* @param array $parameters
*
* @return \Aws\ResultPaginator
*/
public function getPaginator(array $parameters)
{
return $this->s3->getPaginator('ListObjectsV2', array_merge(['Bucket' => $this->bucketName], $parameters));
}
/**
* @param array $parameters
*
* @return \Iterator
*/
public function getIterator(array $parameters)
{
return $this->s3->getIterator('ListObjectsV2', array_merge(['Bucket' => $this->bucketName], $parameters));
}
/**
* @param array $parameters
*
* @return \Aws\Result
*/
public function getListObject(array $parameters)
{
return $this->s3->listObjectsV2(array_merge(['Bucket' => $this->bucketName], $parameters));
}
/**
* @param string $key
*
* @return string
*/
public function getObjectByKey($key)
{
$result = $this->s3->getObject([
'Bucket' => $this->bucketName,
'Key' => $key,
]);
return (string) $result['Body'];
}
}
| ekreative/apps-server | src/AWS/S3.php | PHP | mit | 2,714 |
namespace CameraBazar.Services.Models.Users
{
using System;
public class UserDetailsModel
{
public string Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Phone { get; set; }
public DateTime LasLogin { get; set; }
}
}
| VaskoViktorov/SoftUni-Homework | 11. C# ASP.NET Core - 30.10.2017/06. Razor & Filters - Part II - Exercise/CameraBazar/CameraBazar.Services/Models/Users/UserDetailsModel.cs | C# | mit | 335 |
module GURPS
class Template
@modifiers = []
def initialize name
@name = name
end
def << modifier
@modifiers << modifier
end
def applyTo char
# Apply this template to a GURPS character.
@modifiers.each do |modifier|
modifier.applyTo char
end
char.templates << self
end
end
class PropertyModifier
def initialize prop, modifier, op="add"
@property = prop
@modifier = modifier
@operator = op
end
def applyTo char
if prop = char.try(@property.to_sym)
case @operator
when "add" then prop += @modifier
when "mult" then prop *= @modifier
end
end
end
end
module TemplateShorthands
# @todo Fill this in.
def template templ_name
send templ_name
end
end
end
| AlexSafatli/gurps | lib/gurps/template.rb | Ruby | mit | 840 |
package org.karoglan.tollainmear.signeditor.commandexecutor;
import org.karoglan.tollainmear.signeditor.KSECommandManager;
import org.karoglan.tollainmear.signeditor.KSERecordsManager;
import org.karoglan.tollainmear.signeditor.KaroglanSignEditor;
import org.karoglan.tollainmear.signeditor.utils.Translator;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.serializer.TextSerializers;
import java.io.IOException;
public class ReloadExecutor implements CommandExecutor {
private KSERecordsManager rm;
private KaroglanSignEditor kse = KaroglanSignEditor.getInstance();
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
kse = KaroglanSignEditor.getInstance();
rm = KaroglanSignEditor.getInstance().getKSERecordsManager();
try {
kse.cfgInit();
rm.init();
kse.setTranslator(new Translator(kse));
kse.getTranslator().checkUpdate();
kse.setKseCmdManager(new KSECommandManager(kse));
} catch (IOException e) {
e.printStackTrace();
}
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(kse.getTranslator().getstring("message.KSEprefix")+kse.getTranslator().getstring("message.reload")));
return CommandResult.success();
}
}
| Tollainmear/KaroglanSignEditor | src/main/java/org/karoglan/tollainmear/signeditor/commandexecutor/ReloadExecutor.java | Java | mit | 1,591 |
package gl8080.lifegame.web.resource;
import java.net.URI;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import gl8080.lifegame.application.definition.RegisterGameDefinitionService;
import gl8080.lifegame.application.definition.RemoveGameDefinitionService;
import gl8080.lifegame.application.definition.SearchGameDefinitionService;
import gl8080.lifegame.application.definition.UpdateGameDefinitionService;
import gl8080.lifegame.logic.definition.GameDefinition;
import gl8080.lifegame.util.Maps;
@Path("/game/definition")
@ApplicationScoped
public class GameDefinitionResource {
@Inject
private RegisterGameDefinitionService registerService;
@Inject
private SearchGameDefinitionService searchService;
@Inject
private UpdateGameDefinitionService saveService;
@Inject
private RemoveGameDefinitionService removeService;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response register(@QueryParam("size") int size) {
GameDefinition gameDefinition = this.registerService.register(size);
long id = gameDefinition.getId();
URI uri = UriBuilder
.fromResource(GameDefinitionResource.class)
.path(GameDefinitionResource.class, "search")
.build(id);
return Response
.created(uri)
.entity(Maps.map("id", id))
.build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public LifeGameDto search(@PathParam("id") long id) {
GameDefinition gameDefinition = this.searchService.search(id);
return LifeGameDto.of(gameDefinition);
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(LifeGameDto dto) {
if (dto == null) {
return Response.status(Status.BAD_REQUEST).build();
}
GameDefinition gameDefinition = this.saveService.update(dto);
return Response.ok()
.entity(Maps.map("version", gameDefinition.getVersion()))
.build();
}
@DELETE
@Path("/{id}")
public Response remove(@PathParam("id") long id) {
this.removeService.remove(id);
return Response.noContent().build();
}
}
| opengl-8080/lifegame-javaee | src/main/java/gl8080/lifegame/web/resource/GameDefinitionResource.java | Java | mit | 2,858 |
package edacc.parameterspace.domain;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
@SuppressWarnings("serial")
public class RealDomain extends Domain {
protected Double low, high;
public static final String name = "Real";
@SuppressWarnings("unused")
private RealDomain() {
}
public RealDomain(Double low, Double high) {
this.low = low;
this.high = high;
}
public RealDomain(Integer low, Integer high) {
this.low = Double.valueOf(low);
this.high = Double.valueOf(high);
}
@Override
public boolean contains(Object value) {
if (!(value instanceof Number)) return false;
double d = ((Number)value).doubleValue();
return d >= this.low && d <= this.high;
}
@Override
public Object randomValue(Random rng) {
return rng.nextDouble() * (this.high - this.low) + this.low;
}
@Override
public String toString() {
return "[" + this.low + "," + this.high + "]";
}
public Double getLow() {
return low;
}
public void setLow(Double low) {
this.low = low;
}
public Double getHigh() {
return high;
}
public void setHigh(Double high) {
this.high = high;
}
@Override
public Object mutatedValue(Random rng, Object value) {
return mutatedValue(rng, value, 0.1f);
}
@Override
public Object mutatedValue(Random rng, Object value, float stdDevFactor) {
if (!contains(value)) return value;
double r = rng.nextGaussian() * ((high - low) * stdDevFactor);
return Math.min(Math.max(this.low, ((Number)value).doubleValue() + r), this.high);
}
@Override
public List<Object> getDiscreteValues() {
List<Object> values = new LinkedList<Object>();
for (double d = low; d <= high; d += (high - low) / 100.0f) {
values.add(d);
}
return values;
}
@Override
public String getName() {
return name;
}
@Override
public List<Object> getGaussianDiscreteValues(Random rng, Object value,
float stdDevFactor, int numberSamples) {
List<Object> vals = new LinkedList<Object>();
for (int i = 0; i < numberSamples; i++) {
vals.add(mutatedValue(rng, value, stdDevFactor));
}
return vals;
}
@Override
public List<Object> getUniformDistributedValues(int numberSamples) {
List<Object> vals = new LinkedList<Object>();
double dist = (high - low) / (double) (numberSamples-1);
double cur = low;
for (int i = 0; i < numberSamples; i++) {
if (i == numberSamples -1)
cur = high;
vals.add(cur);
cur += dist;
}
return vals;
}
@Override
public Object getMidValueOrNull(Object o1, Object o2) {
if (!(o1 instanceof Double) || !(o2 instanceof Double))
return null;
Double d1 = (Double) o1;
Double d2 = (Double) o2;
if (d1.equals(d2)) {
return null;
}
return (d1+d2) / 2;
}
}
| EDACC/edacc_api | src/edacc/parameterspace/domain/RealDomain.java | Java | mit | 2,816 |
//# sourceMappingURL=request-constructor.js.map | jlberrocal/ng2-dynatable | src/interfaces/request-constructor.js | JavaScript | mit | 47 |
/*
* jQuery File Upload Plugin 5.0.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*/
/*jslint nomen: false, unparam: true, regexp: false */
/*global document, XMLHttpRequestUpload, Blob, File, FormData, location, jQuery */
(function ($) {
'use strict';
// The fileupload widget listens for change events on file input fields
// defined via fileInput setting and drop events of the given dropZone.
// In addition to the default jQuery Widget methods, the fileupload widget
// exposes the "add" and "send" methods, to add or directly send files
// using the fileupload API.
// By default, files added via file input selection, drag & drop or
// "add" method are uploaded immediately, but it is possible to override
// the "add" callback option to queue file uploads.
$.widget('blueimp.fileupload', {
options: {
// The namespace used for event handler binding on the dropZone and
// fileInput collections.
// If not set, the name of the widget ("fileupload") is used.
namespace: undefined,
// The drop target collection, by the default the complete document.
// Set to null or an empty collection to disable drag & drop support:
dropZone: $(document),
// The file input field collection, that is listened for change events.
// If undefined, it is set to the file input fields inside
// of the widget element on plugin initialization.
// Set to null or an empty collection to disable the change listener.
fileInput: undefined,
// By default, the file input field is replaced with a clone after
// each input field change event. This is required for iframe transport
// queues and allows change events to be fired for the same file
// selection, but can be disabled by setting the following option to false:
replaceFileInput: true,
// The parameter name for the file form data (the request argument name).
// If undefined or empty, the name property of the file input field is
// used, or "files[]" if the file input name property is also empty:
paramName: undefined,
// By default, each file of a selection is uploaded using an individual
// request for XHR type uploads. Set to false to upload file
// selections in one request each:
singleFileUploads: true,
// Set the following option to true to issue all file upload requests
// in a sequential order:
sequentialUploads: false,
// Set the following option to true to force iframe transport uploads:
forceIframeTransport: false,
// By default, XHR file uploads are sent as multipart/form-data.
// The iframe transport is always using multipart/form-data.
// Set to false to enable non-multipart XHR uploads:
multipart: true,
// To upload large files in smaller chunks, set the following option
// to a preferred maximum chunk size. If set to 0, null or undefined,
// or the browser does not support the required Blob API, files will
// be uploaded as a whole.
maxChunkSize: undefined,
// When a non-multipart upload or a chunked multipart upload has been
// aborted, this option can be used to resume the upload by setting
// it to the size of the already uploaded bytes. This option is most
// useful when modifying the options object inside of the "add" or
// "send" callbacks, as the options are cloned for each file upload.
uploadedBytes: undefined,
// By default, failed (abort or error) file uploads are removed from the
// global progress calculation. Set the following option to false to
// prevent recalculating the global progress data:
recalculateProgress: true,
// Additional form data to be sent along with the file uploads can be set
// using this option, which accepts an array of objects with name and
// value properties, a function returning such an array, a FormData
// object (for XHR file uploads), or a simple object.
// The form of the first fileInput is given as parameter to the function:
formData: function (form) {
return form.serializeArray();
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// If the singleFileUploads option is enabled, this callback will be
// called once for each file in the selection for XHR file uplaods, else
// once for each file selection.
// The upload starts when the submit method is invoked on the data parameter.
// The data object contains a files property holding the added files
// and allows to override plugin options as well as define ajax settings.
// Listeners for this callback can also be bound the following way:
// .bind('fileuploadadd', func);
// data.submit() returns a Promise object and allows to attach additional
// handlers using jQuery's Deferred callbacks:
// data.submit().done(func).fail(func).always(func);
add: function (e, data) {
data.submit();
},
// Other callbacks:
// Callback for the start of each file upload request:
// send: function (e, data) {}, // .bind('fileuploadsend', func);
// Callback for successful uploads:
// done: function (e, data) {}, // .bind('fileuploaddone', func);
// Callback for failed (abort or error) uploads:
// fail: function (e, data) {}, // .bind('fileuploadfail', func);
// Callback for completed (success, abort or error) requests:
// always: function (e, data) {}, // .bind('fileuploadalways', func);
// Callback for upload progress events:
// progress: function (e, data) {}, // .bind('fileuploadprogress', func);
// Callback for global upload progress events:
// progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
// Callback for uploads start, equivalent to the global ajaxStart event:
// start: function (e) {}, // .bind('fileuploadstart', func);
// Callback for uploads stop, equivalent to the global ajaxStop event:
// stop: function (e) {}, // .bind('fileuploadstop', func);
// Callback for change events of the fileInput collection:
// change: function (e, data) {}, // .bind('fileuploadchange', func);
// Callback for drop events of the dropZone collection:
// drop: function (e, data) {}, // .bind('fileuploaddrop', func);
// Callback for dragover events of the dropZone collection:
// dragover: function (e) {}, // .bind('fileuploaddragover', func);
// The plugin options are used as settings object for the ajax calls.
// The following are jQuery ajax settings required for the file uploads:
processData: false,
contentType: false,
cache: false
},
// A list of options that require a refresh after assigning a new value:
_refreshOptionsList: ['namespace', 'dropZone', 'fileInput'],
_isXHRUpload: function (options) {
var undef = 'undefined';
return !options.forceIframeTransport &&
typeof XMLHttpRequestUpload !== undef && typeof File !== undef &&
(!options.multipart || typeof FormData !== undef);
},
_getFormData: function (options) {
var formData;
if (typeof options.formData === 'function') {
return options.formData(options.form);
} else if ($.isArray(options.formData)) {
return options.formData;
} else if (options.formData) {
formData = [];
$.each(options.formData, function (name, value) {
formData.push({name: name, value: value});
});
return formData;
}
return [];
},
_getTotal: function (files) {
var total = 0;
$.each(files, function (index, file) {
total += file.size || 1;
});
return total;
},
_onProgress: function (e, data) {
if (e.lengthComputable) {
var total = data.total || this._getTotal(data.files),
loaded = parseInt(
e.loaded / e.total * (data.chunkSize || total),
10
) + (data.uploadedBytes || 0);
this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
data.lengthComputable = true;
data.loaded = loaded;
data.total = total;
// Trigger a custom progress event with a total data property set
// to the file size(s) of the current upload and a loaded data
// property calculated accordingly:
this._trigger('progress', e, data);
// Trigger a global progress event for all current file uploads,
// including ajax calls queued for sequential file uploads:
this._trigger('progressall', e, {
lengthComputable: true,
loaded: this._loaded,
total: this._total
});
}
},
_initProgressListener: function (options) {
var that = this,
xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
// Accesss to the native XHR object is required to add event listeners
// for the upload progress event:
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener('progress', function (e) {
that._onProgress(e, options);
}, false);
options.xhr = function () {
return xhr;
};
}
},
_initXHRData: function (options) {
var formData,
file = options.files[0];
if (!options.multipart || options.blob) {
// For non-multipart uploads and chunked uploads,
// file meta data is not part of the request body,
// so we transmit this data as part of the HTTP headers.
// For cross domain requests, these headers must be allowed
// via Access-Control-Allow-Headers or removed using
// the beforeSend callback:
options.headers = $.extend(options.headers, {
'X-File-Name': file.name,
'X-File-Type': file.type,
'X-File-Size': file.size
});
if (!options.blob) {
// Non-chunked non-multipart upload:
options.contentType = file.type;
options.data = file;
} else if (!options.multipart) {
// Chunked non-multipart upload:
options.contentType = 'application/octet-stream';
options.data = options.blob;
}
}
if (options.multipart) {
if (options.formData instanceof FormData) {
formData = options.formData;
} else {
formData = new FormData();
$.each(this._getFormData(options), function (index, field) {
formData.append(field.name, field.value);
});
}
if (options.blob) {
formData.append(options.paramName, options.blob);
} else {
$.each(options.files, function (index, file) {
// File objects are also Blob instances.
// This check allows the tests to run with
// dummy objects:
if (file instanceof Blob) {
formData.append(options.paramName, file);
}
});
}
options.data = formData;
}
// Blob reference is not needed anymore, free memory:
options.blob = null;
},
_initIframeSettings: function (options) {
// Setting the dataType to iframe enables the iframe transport:
options.dataType = 'iframe ' + (options.dataType || '');
// The iframe transport accepts a serialized array as form data:
options.formData = this._getFormData(options);
},
_initDataSettings: function (options) {
if (this._isXHRUpload(options)) {
if (!this._chunkedUpload(options, true)) {
if (!options.data) {
this._initXHRData(options);
}
this._initProgressListener(options);
}
} else {
this._initIframeSettings(options);
}
},
_initFormSettings: function (options) {
// Retrieve missing options from the input field and the
// associated form, if available:
if (!options.form || !options.form.length) {
options.form = $(options.fileInput.prop('form'));
}
if (!options.paramName) {
options.paramName = options.fileInput.prop('name') ||
'files[]';
}
if (!options.url) {
options.url = options.form.prop('action') || location.href;
}
// The HTTP request method must be "POST" or "PUT":
options.type = (options.type || options.form.prop('method') || '')
.toUpperCase();
if (options.type !== 'POST' && options.type !== 'PUT') {
options.type = 'POST';
}
},
_getAJAXSettings: function (data) {
var options = $.extend({}, this.options, data);
this._initFormSettings(options);
this._initDataSettings(options);
return options;
},
// Maps jqXHR callbacks to the equivalent
// methods of the given Promise object:
_enhancePromise: function (promise) {
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.always;
return promise;
},
// Creates and returns a Promise object enhanced with
// the jqXHR methods abort, success, error and complete:
_getXHRPromise: function (resolveOrReject, context) {
var dfd = $.Deferred(),
promise = dfd.promise();
context = context || this.options.context || promise;
if (resolveOrReject === true) {
dfd.resolveWith(context);
} else if (resolveOrReject === false) {
dfd.rejectWith(context);
}
promise.abort = dfd.promise;
return this._enhancePromise(promise);
},
// Uploads a file in multiple, sequential requests
// by splitting the file up in multiple blob chunks.
// If the second parameter is true, only tests if the file
// should be uploaded in chunks, but does not invoke any
// upload requests:
_chunkedUpload: function (options, testOnly) {
var that = this,
file = options.files[0],
fs = file.size,
ub = options.uploadedBytes = options.uploadedBytes || 0,
mcs = options.maxChunkSize || fs,
// Use the Blob methods with the slice implementation
// according to the W3C Blob API specification:
slice = file.webkitSlice || file.mozSlice || file.slice,
upload,
n,
jqXHR,
pipe;
if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
options.data) {
return false;
}
if (testOnly) {
return true;
}
if (ub >= fs) {
file.error = 'uploadedBytes';
return this._getXHRPromise(false);
}
// n is the number of blobs to upload,
// calculated via filesize, uploaded bytes and max chunk size:
n = Math.ceil((fs - ub) / mcs);
// The chunk upload method accepting the chunk number as parameter:
upload = function (i) {
if (!i) {
return that._getXHRPromise(true);
}
// Upload the blobs in sequential order:
return upload(i -= 1).pipe(function () {
// Clone the options object for each chunk upload:
var o = $.extend({}, options);
o.blob = slice.call(
file,
ub + i * mcs,
ub + (i + 1) * mcs
);
// Store the current chunk size, as the blob itself
// will be dereferenced after data processing:
o.chunkSize = o.blob.size;
// Process the upload data (the blob and potential form data):
that._initXHRData(o);
// Add progress listeners for this chunk upload:
that._initProgressListener(o);
jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
.done(function () {
// Create a progress event if upload is done and
// no progress event has been invoked for this chunk:
if (!o.loaded) {
that._onProgress($.Event('progress', {
lengthComputable: true,
loaded: o.chunkSize,
total: o.chunkSize
}), o);
}
options.uploadedBytes = o.uploadedBytes
+= o.chunkSize;
});
return jqXHR;
});
};
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe = upload(n);
pipe.abort = function () {
return jqXHR.abort();
};
return this._enhancePromise(pipe);
},
_beforeSend: function (e, data) {
if (this._active === 0) {
// the start callback is triggered when an upload starts
// and no other uploads are currently running,
// equivalent to the global ajaxStart event:
this._trigger('start');
}
this._active += 1;
// Initialize the global progress values:
this._loaded += data.uploadedBytes || 0;
this._total += this._getTotal(data.files);
},
_onDone: function (result, textStatus, jqXHR, options) {
if (!this._isXHRUpload(options)) {
// Create a progress event for each iframe load:
this._onProgress($.Event('progress', {
lengthComputable: true,
loaded: 1,
total: 1
}), options);
}
options.result = result;
options.textStatus = textStatus;
options.jqXHR = jqXHR;
this._trigger('done', null, options);
},
_onFail: function (jqXHR, textStatus, errorThrown, options) {
options.jqXHR = jqXHR;
options.textStatus = textStatus;
options.errorThrown = errorThrown;
this._trigger('fail', null, options);
if (options.recalculateProgress) {
// Remove the failed (error or abort) file upload from
// the global progress calculation:
this._loaded -= options.loaded || options.uploadedBytes || 0;
this._total -= options.total || this._getTotal(options.files);
}
},
_onAlways: function (result, textStatus, jqXHR, options) {
this._active -= 1;
options.result = result;
options.textStatus = textStatus;
options.jqXHR = jqXHR;
this._trigger('always', null, options);
if (this._active === 0) {
// The stop callback is triggered when all uploads have
// been completed, equivalent to the global ajaxStop event:
this._trigger('stop');
// Reset the global progress values:
this._loaded = this._total = 0;
}
},
_onSend: function (e, data) {
var that = this,
jqXHR,
pipe,
options = that._getAJAXSettings(data),
send = function () {
jqXHR = ((that._trigger('send', e, options) !== false && (
that._chunkedUpload(options) ||
$.ajax(options)
)) || that._getXHRPromise(false, options.context)
).done(function (result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
}).always(function (result, textStatus, jqXHR) {
that._onAlways(result, textStatus, jqXHR, options);
});
return jqXHR;
};
this._beforeSend(e, options);
if (this.options.sequentialUploads) {
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe = (this._sequence = this._sequence.pipe(send, send));
pipe.abort = function () {
return jqXHR.abort();
};
return this._enhancePromise(pipe);
}
return send();
},
_onAdd: function (e, data) {
var that = this,
result = true,
options = $.extend({}, this.options, data);
if (options.singleFileUploads && this._isXHRUpload(options)) {
$.each(data.files, function (index, file) {
var newData = $.extend({}, data, {files: [file]});
newData.submit = function () {
return that._onSend(e, newData);
};
return (result = that._trigger('add', e, newData));
});
return result;
} else if (data.files.length) {
data = $.extend({}, data);
data.submit = function () {
return that._onSend(e, data);
};
return this._trigger('add', e, data);
}
},
// File Normalization for Gecko 1.9.1 (Firefox 3.5) support:
_normalizeFile: function (index, file) {
if (file.name === undefined && file.size === undefined) {
file.name = file.fileName;
file.size = file.fileSize;
}
},
_replaceFileInput: function (input) {
var inputClone = input.clone(true);
$('<form></form>').append(inputClone)[0].reset();
// Detaching allows to insert the fileInput on another form
// without loosing the file input value:
input.after(inputClone).detach();
// Replace the original file input element in the fileInput
// collection with the clone, which has been copied including
// event handlers:
this.options.fileInput = this.options.fileInput.map(function (i, el) {
if (el === input[0]) {
return inputClone[0];
}
return el;
});
},
_onChange: function (e) {
var that = e.data.fileupload,
data = {
files: $.each($.makeArray(e.target.files), that._normalizeFile),
fileInput: $(e.target),
form: $(e.target.form)
};
if (!data.files.length) {
// If the files property is not available, the browser does not
// support the File API and we add a pseudo File object with
// the input value as name with path information removed:
data.files = [{name: e.target.value.replace(/^.*\\/, '')}];
}
// Store the form reference as jQuery data for other event handlers,
// as the form property is not available after replacing the file input:
if (data.form.length) {
data.fileInput.data('blueimp.fileupload.form', data.form);
} else {
data.form = data.fileInput.data('blueimp.fileupload.form');
}
if (that.options.replaceFileInput) {
that._replaceFileInput(data.fileInput);
}
if (that._trigger('change', e, data) === false ||
that._onAdd(e, data) === false) {
return false;
}
},
_onDrop: function (e) {
var that = e.data.fileupload,
dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
data = {
files: $.each(
$.makeArray(dataTransfer && dataTransfer.files),
that._normalizeFile
)
};
if (that._trigger('drop', e, data) === false ||
that._onAdd(e, data) === false) {
return false;
}
e.preventDefault();
},
_onDragOver: function (e) {
var that = e.data.fileupload,
dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
if (that._trigger('dragover', e) === false) {
return false;
}
if (dataTransfer) {
dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy';
}
e.preventDefault();
},
_initEventHandlers: function () {
var ns = this.options.namespace || this.name;
this.options.dropZone
.bind('dragover.' + ns, {fileupload: this}, this._onDragOver)
.bind('drop.' + ns, {fileupload: this}, this._onDrop);
this.options.fileInput
.bind('change.' + ns, {fileupload: this}, this._onChange);
},
_destroyEventHandlers: function () {
var ns = this.options.namespace || this.name;
this.options.dropZone
.unbind('dragover.' + ns, this._onDragOver)
.unbind('drop.' + ns, this._onDrop);
this.options.fileInput
.unbind('change.' + ns, this._onChange);
},
_beforeSetOption: function (key, value) {
this._destroyEventHandlers();
},
_afterSetOption: function (key, value) {
var options = this.options;
if (!options.fileInput) {
options.fileInput = $();
}
if (!options.dropZone) {
options.dropZone = $();
}
this._initEventHandlers();
},
_setOption: function (key, value) {
var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
if (refresh) {
this._beforeSetOption(key, value);
}
$.Widget.prototype._setOption.call(this, key, value);
if (refresh) {
this._afterSetOption(key, value);
}
},
_create: function () {
var options = this.options;
if (options.fileInput === undefined) {
options.fileInput = this.element.is('input:file') ?
this.element : this.element.find('input:file');
} else if (!options.fileInput) {
options.fileInput = $();
}
if (!options.dropZone) {
options.dropZone = $();
}
this._sequence = this._getXHRPromise(true);
this._active = this._loaded = this._total = 0;
this._initEventHandlers();
},
destroy: function () {
this._destroyEventHandlers();
$.Widget.prototype.destroy.call(this);
},
enable: function () {
$.Widget.prototype.enable.call(this);
this._initEventHandlers();
},
disable: function () {
this._destroyEventHandlers();
$.Widget.prototype.disable.call(this);
},
// This method is exposed to the widget API and allows adding files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('add', {files: filesList});
add: function (data) {
if (!data || this.options.disabled) {
return;
}
data.files = $.each($.makeArray(data.files), this._normalizeFile);
this._onAdd(null, data);
},
// This method is exposed to the widget API and allows sending files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('send', {files: filesList});
// The method returns a Promise object for the file upload call.
send: function (data) {
if (data && !this.options.disabled) {
data.files = $.each($.makeArray(data.files), this._normalizeFile);
if (data.files.length) {
return this._onSend(null, data);
}
}
return this._getXHRPromise(false, data && data.context);
}
});
}(jQuery)); | ilyakatz/cucumber-cinema | public/javascripts/jquery.fileupload.js | JavaScript | mit | 31,875 |
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosPint extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M368,170.085c0-21.022-0.973-88.554-19.308-125.013C344.244,36.228,336.25,32,316.999,32H195.001
c-19.25,0-27.246,4.197-31.693,13.041C144.973,81.5,144,149.25,144,170.272c0,98,32,100.353,32,180.853c0,39.5-16,71.402-16,99.402
c0,27,9,29.473,32,29.473h128c23,0,32-2.535,32-29.535c0-28-16-59.715-16-99.215C336,270.75,368,268.085,368,170.085z
M177.602,51.983c0.778-1.546,1.339-1.763,2.53-2.295c1.977-0.884,6.161-1.688,14.869-1.688h121.998
c8.708,0,12.893,0.803,14.869,1.687c1.19,0.532,1.752,0.872,2.53,2.418c8.029,15.967,13.601,42.611,16.105,75.896H161.496
C164.001,94.653,169.572,67.951,177.602,51.983z"></path>
</g>;
} return <IconBase>
<path d="M368,170.085c0-21.022-0.973-88.554-19.308-125.013C344.244,36.228,336.25,32,316.999,32H195.001
c-19.25,0-27.246,4.197-31.693,13.041C144.973,81.5,144,149.25,144,170.272c0,98,32,100.353,32,180.853c0,39.5-16,71.402-16,99.402
c0,27,9,29.473,32,29.473h128c23,0,32-2.535,32-29.535c0-28-16-59.715-16-99.215C336,270.75,368,268.085,368,170.085z
M177.602,51.983c0.778-1.546,1.339-1.763,2.53-2.295c1.977-0.884,6.161-1.688,14.869-1.688h121.998
c8.708,0,12.893,0.803,14.869,1.687c1.19,0.532,1.752,0.872,2.53,2.418c8.029,15.967,13.601,42.611,16.105,75.896H161.496
C164.001,94.653,169.572,67.951,177.602,51.983z"></path>
</IconBase>;
}
};IosPint.defaultProps = {bare: false} | fbfeix/react-icons | src/icons/IosPint.js | JavaScript | mit | 1,517 |
#include "pch.h"
#include "Item.h"
#include "GameManager.h"
#include "ObjectLayer.h"
Item::Item(Vec2 createPos, float scale, BuffTarget buffType)
{
m_UnitType = UNIT_ITEM;
m_CenterSprite->setPosition(createPos);
m_CenterSprite->setScale(scale);
switch (buffType)
{
case BUFF_HP: m_RealSprite = Sprite::create("Images/Unit/item_hp.png"); break;
case BUFF_DAMAGE: m_RealSprite = Sprite::create("Images/Unit/item_damage.png"); break;
case BUFF_COOLTIME: m_RealSprite = Sprite::create("Images/Unit/item_cooltime.png"); break;
case BUFF_SHIELD: m_RealSprite = Sprite::create("Images/Unit/item_shield.png"); break;
case BUFF_SPEED: m_RealSprite = Sprite::create("Images/Unit/item_speed.png"); break;
}
m_RealSprite->setScale(scale);
m_CenterSprite->addChild(m_RealSprite);
}
Item::~Item()
{
}
| dlakwwkd/CommitAgain | Skima/Classes/Item.cpp | C++ | mit | 873 |
namespace TwitterBackup.Services
{
using TwitterBackup.Data;
using TwitterBackup.Models;
using TwitterBackup.Services.Contracts;
using System.Linq;
using System.Collections.Generic;
using System;
using TwitterBackup.Services.Exceptions;
public class UserService : IUserService
{
private readonly IRepository<User> userRepo;
public UserService(IRepository<User> userRepo)
{
this.userRepo = userRepo;
}
/// <summary>
/// Store user in the TwitterBackup database
/// </summary>
/// <param name="user"></param>
public User Save(User user)
{
if (user == null)
{
throw new ArgumentException("Tweet is not valid");
}
var hasAlreadyExist = userRepo
.All()
.Any(userDTO => userDTO.ScreenName == user.ScreenName);
if (hasAlreadyExist)
{
throw new UserException(UserExceptionType.IsAlreadySaved);
}
var userDataModel = userRepo.Add(user);
return userDataModel;
}
public int GetUsersCount()
{
var usersCount = this.userRepo
.All()
.Count();
return usersCount;
}
public IEnumerable<User> GetUsers()
{
var allUsers = this.userRepo
.All()
.ToArray();
return allUsers;
}
}
}
| luboganchev/TwitterBackup | TwitterBackup/TwitterBackup.Services/UserService.cs | C# | mit | 1,545 |
package ee.golive.personal.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "workout")
public class Workout implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", unique=true, nullable = false)
private Integer id;
private String source;
private String source_id;
private String sport_type;
private Date date_created;
private Long duration;
private Double calories;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSource_id() {
return source_id;
}
public void setSource_id(String source_id) {
this.source_id = source_id;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public String getSport_type() {
return sport_type;
}
public void setSport_type(String sport_type) {
this.sport_type = sport_type;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public Double getCalories() {
return calories;
}
public void setCalories(Double calories) {
this.calories = calories;
}
}
| ilves/finance | src/main/java/ee/golive/personal/model/Workout.java | Java | mit | 1,619 |
/**
* Wheel, copyright (c) 2020 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const $ = require('../../program/commands');
const errors = require('../errors');
const err = require('../errors').errors;
const t = require('../tokenizer/tokenizer');
const Objct = require('../types/Objct').Objct;
const Var = require('../types/Var');
const CompileRecord = require('./CompileRecord').CompileRecord;
exports.CompileObjct = class extends CompileRecord {
getDataType() {
let token = this._token;
let objct = new Objct(null, this.getNamespacedRecordName(token.lexeme), false, this._compiler.getNamespace()).setToken(token);
objct.setCompiler(this._compiler);
return objct;
}
addLinterItem(token) {
this._linter && this._linter.addObject(this._token);
}
compileExtends(iterator, dataType) {
let token = iterator.skipWhiteSpace().peek();
if (token.lexeme === t.LEXEME_EXTENDS) {
iterator.next();
iterator.skipWhiteSpace();
token = iterator.next();
if (token.cls !== t.TOKEN_IDENTIFIER) {
throw errors.createError(err.IDENTIFIER_EXPECTED, token, 'Identifier expected.');
}
let superObjct = this._scope.findIdentifier(token.lexeme);
if (!superObjct) {
throw errors.createError(err.UNDEFINED_IDENTIFIER, token, 'Undefined identifier.');
}
if (!(superObjct instanceof Objct)) {
throw errors.createError(err.OBJECT_TYPE_EXPECTED, token, 'Object type expected.');
}
dataType.extend(superObjct, this._compiler);
}
}
compileMethodTable(objct, methodTable) {
let compiler = this._compiler;
let program = this._program;
let methods = compiler.getUseInfo().getUseObjct(objct.getName());
// Move the self pointer to the pointer register...
program.addCommand($.CMD_SET, $.T_NUM_G, $.REG_PTR, $.T_NUM_L, 0);
// Get the methods from the super objects...
let superObjct = objct.getParentScope();
while (superObjct instanceof Objct) {
let superMethods = compiler.getUseInfo().getUseObjct(superObjct.getName());
for (let i = 0; i < superMethods; i++) {
methodTable.push(program.getLength());
program.addCommand($.CMD_SET, $.T_NUM_P, 0, $.T_NUM_C, 0);
}
superObjct = superObjct.getParentScope();
}
// Create the virtual method table...
for (let i = 0; i < methods; i++) {
methodTable.push(program.getLength());
// The offset relative to the self pointer and the method offset will be set when the main procedure is found!
program.addCommand($.CMD_SET, $.T_NUM_P, 0, $.T_NUM_C, 0);
}
program.addCommand($.CMD_RET, $.T_NUM_C, 0, 0, 0);
}
compile(iterator) {
let objct = super.compile(iterator);
let compiler = this._compiler;
compiler.getUseInfo().setUseObjct(objct.getName());
if (compiler.getPass() === 0) {
return;
}
let program = this._program;
let codeUsed = program.getCodeUsed();
let methodTable = [];
program.setCodeUsed(true);
objct
.setConstructorCodeOffset(program.getLength())
.setMethodTable(methodTable);
this.compileMethodTable(objct, methodTable);
program.addCommand($.CMD_RET, 0, 0, 0, 0);
program.setCodeUsed(codeUsed);
}
};
| ArnoVanDerVegt/wheel | js/frontend/compiler/keyword/CompileObjct.js | JavaScript | mit | 3,710 |
"""Transformation functions for expressions."""
from tt.expressions import BooleanExpression
from tt.transformations.utils import ensure_bexpr
def apply_de_morgans(expr):
"""Convert an expression to a form with De Morgan's Law applied.
:returns: A new expression object, transformed so that De Morgan's Law has
been applied to negated *ANDs* and *ORs*.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a couple of simple examples showing De Morgan's Law being applied
to a negated AND and a negated OR::
>>> from tt import apply_de_morgans
>>> apply_de_morgans('~(A /\\ B)')
<BooleanExpression "~A \\/ ~B">
>>> apply_de_morgans('~(A \\/ B)')
<BooleanExpression "~A /\\ ~B">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_de_morgans())
def apply_identity_law(expr):
"""Convert an expression to a form with the Identity Law applied.
It should be noted that this transformation will also annihilate terms
when possible. One such case where this would be applicable is the
expression ``A and 0``, which would be transformed to the constant value
``0``.
:returns: A new expression object, transformed so that the Identity Law
has been applied to applicable *ANDs* and *ORs*.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here are a few simple examples showing the behavior of this transformation
across all two-operand scenarios::
>>> from tt import apply_identity_law
>>> apply_identity_law('A and 1')
<BooleanExpression "A">
>>> apply_identity_law('A and 0')
<BooleanExpression "0">
>>> apply_identity_law('A or 0')
<BooleanExpression "A">
>>> apply_identity_law('A or 1')
<BooleanExpression "1">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_identity_law())
def apply_idempotent_law(expr):
"""Convert an expression to a form with the Idempotent Law applied.
:returns: A new expression object, transformed so that the Idempotent Law
has been applied to applicable clauses.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid data type.
This transformation will apply the Idempotent Law to clauses of *AND* and
*OR* operators containing redundant operands. Here are a couple of simple
examples::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('A and A')
<BooleanExpression "A">
>>> apply_idempotent_law('B or B')
<BooleanExpression "B">
This transformation will consider similarly-negated operands to be
redundant; for example::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('~A and ~~~A')
<BooleanExpression "~A">
>>> apply_idempotent_law('B or ~B or ~~B or ~~~B or ~~~~B or ~~~~~B')
<BooleanExpression "B or ~B">
Let's also take a quick look at this transformation's ability to prune
redundant operands from CNF and DNF clauses::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('(A and B and C and C and B) or (A and A)')
<BooleanExpression "(A and B and C) or A">
Of important note is that this transformation will not recursively apply
the Idempotent Law to operands that bubble up. Here's an example
illustrating this case::
>>> from tt import apply_idempotent_law
>>> apply_idempotent_law('(A or A) and (A or A)')
<BooleanExpression "A and A">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_idempotent_law())
def apply_inverse_law(expr):
"""Convert an expression to a form with the Inverse Law applied.
:returns: A new expression object, transformed so that the Inverse Law
has been applied to applicable *ANDs* and *ORs*.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
This transformation will apply the Identity Law to simple binary
expressions consisting of negated and non-negated forms of the same
operand. Let's take a look::
>>> from tt.transformations import apply_inverse_law
>>> apply_inverse_law('A and ~A')
<BooleanExpression "0">
>>> apply_inverse_law('A or B or ~B or C')
<BooleanExpression "1">
This transformation will also apply the behavior expected of the Inverse
Law when negated and non-negated forms of the same operand appear in the
same CNF or DNF clause in an expression::
>>> from tt.transformations import apply_inverse_law
>>> apply_inverse_law('(A or B or ~A) -> (C and ~C)')
<BooleanExpression "1 -> 0">
>>> apply_inverse_law('(A or !!!A) xor (not C or not not C)')
<BooleanExpression "1 xor 1">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.apply_inverse_law())
def coalesce_negations(expr):
"""Convert an expression to a form with all negations condensed.
:returns: A new expression object, transformed so that all "runs" of
logical *NOTs* are condensed into the minimal equivalent number.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a simple example showing the basic premise of this transformation::
>>> from tt import coalesce_negations
>>> coalesce_negations('~~A or ~B or ~~~C or ~~~~D')
<BooleanExpression "A or ~B or ~C or D">
This transformation works on more complex expressions, too::
>>> coalesce_negations('!!(A -> not not B) or ~(~(A xor B))')
<BooleanExpression "(A -> B) or (A xor B)">
It should be noted that this transformation will also apply negations
to constant operands, as well. The behavior for this functionality is as
follows::
>>> coalesce_negations('~0')
<BooleanExpression "1">
>>> coalesce_negations('~1')
<BooleanExpression "0">
>>> coalesce_negations('~~~0 -> ~1 -> not 1')
<BooleanExpression "1 -> 0 -> 0">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.coalesce_negations())
def distribute_ands(expr):
"""Convert an expression to distribute ANDs over ORed clauses.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to distribute ANDs over ORed
clauses.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a couple of simple examples::
>>> from tt import distribute_ands
>>> distribute_ands('A and (B or C or D)')
<BooleanExpression "(A and B) or (A and C) or (A and D)">
>>> distribute_ands('(A or B) and C')
<BooleanExpression "(A and C) or (B and C)">
And an example involving distributing a sub-expression::
>>> distribute_ands('(A and B) and (C or D or E)')
<BooleanExpression "(A and B and C) or (A and B and D) or \
(A and B and E)">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.distribute_ands())
def distribute_ors(expr):
"""Convert an expression to distribute ORs over ANDed clauses.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to distribute ORs over ANDed
clauses.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a couple of simple examples::
>>> from tt import distribute_ors
>>> distribute_ors('A or (B and C and D and E)')
<BooleanExpression "(A or B) and (A or C) and (A or D) and (A or E)">
>>> distribute_ors('(A and B) or C')
<BooleanExpression "(A or C) and (B or C)">
And an example involving distributing a sub-expression::
>>> distribute_ors('(A or B) or (C and D)')
<BooleanExpression "(A or B or C) and (A or B or D)">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.distribute_ors())
def to_cnf(expr):
"""Convert an expression to conjunctive normal form (CNF).
This transformation only guarantees to produce an equivalent form of the
passed expression in conjunctive normal form; the transformed expression
may be an inefficent representation of the passed expression.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to be in CNF.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here are a few examples::
>>> from tt import to_cnf
>>> b = to_cnf('(A nor B) impl C')
>>> b
<BooleanExpression "A or B or C">
>>> b.is_cnf
True
>>> b = to_cnf(r'~(~(A /\\ B) /\\ C /\\ D)')
>>> b
<BooleanExpression "(A \\/ ~C \\/ ~D) /\\ (B \\/ ~C \\/ ~D)">
>>> b.is_cnf
True
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.to_cnf())
def to_primitives(expr):
"""Convert an expression to a form with only primitive operators.
All operators will be transformed equivalent form composed only of the
logical AND, OR,and NOT operators. Symbolic operators in the passed
expression will remain symbolic in the transformed expression and the same
applies for plain English operators.
:param expr: The expression to transform.
:type expr: :class:`str <python:str>` or :class:`BooleanExpression \
<tt.expressions.bexpr.BooleanExpression>`
:returns: A new expression object, transformed to contain only primitive
operators.
:rtype: :class:`BooleanExpression <tt.expressions.bexpr.BooleanExpression>`
:raises InvalidArgumentTypeError: If ``expr`` is not a valid type.
Here's a simple transformation of exclusive-or::
>>> from tt import to_primitives
>>> to_primitives('A xor B')
<BooleanExpression "(A and not B) or (not A and B)">
And another example of if-and-only-if (using symbolic operators)::
>>> to_primitives('A <-> B')
<BooleanExpression "(A /\\ B) \\/ (~A /\\ ~B)">
"""
bexpr = ensure_bexpr(expr)
return BooleanExpression(bexpr.tree.to_primitives())
| welchbj/tt | tt/transformations/bexpr.py | Python | mit | 11,265 |
const assert = require('assert');
const MockServer = require('../../../../lib/mockserver.js');
const CommandGlobals = require('../../../../lib/globals/commands.js');
const Nightwatch = require('../../../../lib/nightwatch.js');
describe('browser.getFirstElementChild', function(){
before(function(done) {
CommandGlobals.beforeEach.call(this, done);
});
after(function(done) {
CommandGlobals.afterEach.call(this, done);
});
it('.getFirstElementChild', function(done){
MockServer.addMock({
url: '/wd/hub/session/1352110219202/execute',
method: 'POST',
response: {
value: {
'ELEMENT': '1'
}
}
}, true);
this.client.api.getFirstElementChild('#weblogin', function callback(result){
assert.strictEqual(result.value.getId(), '1');
});
this.client.start(done);
});
it('.getFirstElementChild - no such element', function(done) {
MockServer.addMock({
url: '/wd/hub/session/1352110219202/elements',
method: 'POST',
postdata: {
using: 'css selector',
value: '#badDriver'
},
response: {
status: 0,
sessionId: '1352110219202',
value: [{
ELEMENT: '2'
}]
}
});
MockServer.addMock({
url: '/wd/hub/session/1352110219202/execute',
method: 'POST',
response: {
status: 0,
value: null
}
});
this.client.api.getFirstElementChild('#badDriver', function callback(result){
assert.strictEqual(result.value, null);
});
this.client.start(done);
});
it('.getFirstElementChild - webdriver protcol', function(done){
Nightwatch.initW3CClient({
silent: true,
output: false
}).then(client => {
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: {
'element-6066-11e4-a52e-4f735466cecf': 'f54dc0ef-c84f-424a-bad0-16fef6595a70'
}
}
}, true);
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: {
'element-6066-11e4-a52e-4f735466cecf': 'f54dc0ef-c84f-424a-bad0-16fef6595a70'
}
}
}, true);
client.api.getFirstElementChild('#webdriver', function(result) {
assert.ok(result.value);
assert.strictEqual(result.value.getId(), 'f54dc0ef-c84f-424a-bad0-16fef6595a70');
}).getFirstElementChild('#webdriver', function callback(result){
assert.ok(result.value);
assert.strictEqual(result.value.getId(), 'f54dc0ef-c84f-424a-bad0-16fef6595a70');
});
client.start(done);
});
});
it('.getFirstElementChild - webdriver protcol no such element', function(done){
Nightwatch.initW3CClient({
silent: true,
output: false
}).then(client => {
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: null
}
});
client.api.getFirstElementChild('#webdriver', function(result) {
assert.strictEqual(result.value, null);
});
client.start(done);
});
});
}); | nightwatchjs/nightwatch | test/src/api/commands/element/testGetFirstElementChild.js | JavaScript | mit | 3,229 |
#!/usr/bin/python2.7
#-*- coding: utf-8 -*-
import numpy as np
import gl
def testkf(input1,Q,R):
print gl.X_i_1
print gl.P_i_1
#rang(1,N) do not contain N
K_i = gl.P_i_1 / (gl.P_i_1 + R)
X_i = gl.X_i_1 + K_i * (input1 - gl.X_i_1)
P_i = gl.P_i_1 - K_i * gl.P_i_1 + Q
#print (X[i])
#Update
gl.P_i_1 = P_i
gl.X_i_1 = X_i
return X_i
| zharuosi/2017 | pythonNRC/modules/testkf.py | Python | mit | 379 |
using System;
using System.Collections.Generic;
using System.Text;
namespace Nucleo.Web.EventsManagement
{
public class ProviderErrorEvent : WebMonitoringEventBase
{
private const string EVENT_MESSAGE = "An error occurred within the provider '{0}', with an exception of: {1}";
private const int EVENT_CODE = 100101;
#region " Constructors "
public ProviderErrorEvent(Type providerType, object source, Exception ex)
: base(string.Format(EVENT_MESSAGE, providerType.FullName, ex.ToString()), source, EVENT_CODE) { }
#endregion
}
}
| brianmains/Nucleo.NET | src/Nucleo.Web/Web/EventsManagement/ProviderErrorEvent.cs | C# | mit | 550 |
version https://git-lfs.github.com/spec/v1
oid sha256:e63ec89c8bce1f67a79c0a8042e7ad0f2197f9bf615c88fd1ce36266c4050e1b
size 5126
| yogeshsaroya/new-cdnjs | ajax/libs/backbone.layoutmanager/0.7.0/backbone.layoutmanager.min.js | JavaScript | mit | 129 |
<?php
use Illuminate\Database\Seeder;
use App\System\System;
/**
* @author Setiadi, 20 Agustus 2017
*/
class RoleUserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('t_role_user')->delete();
DB::table('t_role_user')->insert([
[
'user_id' => 1,
'role_id' => 1,
'flg_default' => 'Y',
'create_datetime' => System::dateTime(),
'update_datetime' => System::dateTime(),
'create_user_id' => -99,
'update_user_id' => -99
],
[
'user_id' => 2,
'role_id' => 2,
'flg_default' => 'Y',
'create_datetime' => System::dateTime(),
'update_datetime' => System::dateTime(),
'create_user_id' => -99,
'update_user_id' => -99
]
]);
}
}
| setiadi01/Office-Attendance-System-Rest | database/seeds/RoleUserTableSeeder.php | PHP | mit | 917 |
class AndroidController < ApplicationController
def index
end
def create
app = RailsPushNotifications::GCMApp.new
app.gcm_key = params[:gcm_api_key]
app.save
if app.save
notif = app.notifications.build(
destinations: [params[:destination]],
data: { text: params[:message] }
)
if notif.save
app.push_notifications
notif.reload
flash[:notice] = "Notification successfully pushed through!. Results #{notif.results.success} succeded, #{notif.results.failed} failed"
redirect_to :android_index
else
flash.now[:error] = notif.errors.full_messages
render :index
end
else
flash.now[:error] = app.errors.full_messages
render :index
end
end
end
| calonso/rails_push_notifications_test | app/controllers/android_controller.rb | Ruby | mit | 776 |
module tsp {
export interface IDOMBinder {
attributes?: { [name: string]: string; };
contentEditable?: bool;
dynamicAttributes?: { [name: string]: { (el: IElX): string; }; };
dynamicClasses?: { [name: string]: { (el: IElX): bool; }; };
dynamicStyles?: { [name: string]: { (el: IElX): string; }; };
classes?: string[];
id?: string;
kids?: IRenderable[];
kidsGet? (el: IElX): IElX[];
styles?: { [name: string]: string; };
tag?: string;
//Inner Content - used if textGet is null
text?: string;
//Dynamic Inner Content
textGet? (el: IElX): string;
//child elements - used if kidsGet is null
toggleKidsOnParentClick?: bool;
collapsed?: bool;
dataContext?: any;
selectSettings?: ISelectBinder;
container?: any;
onNotifyAddedToDom? (el: IElX): any;
}
export interface IRenderable {
parentElement: IRenderable;
doRender(context: IRenderContext);
ID: string;
}
export interface IElX extends IRenderable {
bindInfo: IDOMBinder;
//parentElement: IElX;
//doRender(context: IRenderContext);
//ID: string;
el: HTMLElement;
kidElements: IElX[];
selected: bool;
_rendered: bool;
innerRender(settings: IRenderContextProps);
removeClass(className: string);
ensureClass(className: string);
}
export interface IRenderContext {
output: string;
elements: IElX[];
settings: IRenderContextProps;
}
export interface ISelectBinder {
//static
selected?: bool;
//dynamic
selectGet? (elX: IElX): bool;
selectSet? (elX: IElX, newVal: bool): void;
group?: string;
selClassName?: string;
partialSelClassName?: string;
unselClassName?: string;
conformWithParent?: bool;
}
export interface IListenForTopic {
topicName: string;
conditionForNotification? (tEvent: ITopicEvent): bool;
callback(tEvent: ITopicEvent): void;
/**
element extension listening for the event
*/
elX?: IElX;
elXID?: string;
}
export interface ITopicEvent extends IListenForTopic {
topicEvent: Event;
}
export interface IRenderContextProps {
targetDomID?: string;
targetDom?: HTMLElement;
}
} | bahrus/teaspoon | TypeStrictTests/Interface_ElX.ts | TypeScript | mit | 2,489 |
package ee.tuleva.onboarding.user.exception;
public class UserAlreadyAMemberException extends RuntimeException {
public UserAlreadyAMemberException(String message) {
super(message);
}
}
| TulevaEE/onboarding-service | src/main/java/ee/tuleva/onboarding/user/exception/UserAlreadyAMemberException.java | Java | mit | 196 |
namespace ImageGallery.Data.Common.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public abstract class BaseModel<TKey> : IAuditInfo, IDeletableEntity
{
public DateTime CreatedOn { get; set; }
public DateTime? DeletedOn { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public TKey Id { get; set; }
[Index]
public bool IsDeleted { get; set; }
public DateTime? ModifiedOn { get; set; }
}
} | atanas-georgiev/ImageGallery | src/ImageGallery.Data.Common/Models/BaseModel{TKey}.cs | C# | mit | 581 |
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-laptop"></i> 한글제품 현재사용내역</h3>
</div>
</div>
<br/>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
목록
</header>
<table class="table table-striped table-advance table-hover">
<thead>
<tr>
<th scope="col">사용자</th>
<th scope="col">제품명</th>
<th scope="col">버전</th>
<th scope="col">제조사</th>
</tr>
</thead>
<tbody>
<?php
foreach ($use_hangul as $lt) {
?>
<tr>
<td>
<b><?php echo $lt->user_name; ?></b>
</td>
<td>
<?php echo $lt->product_number; ?>
</td>
<td>
<?php echo $lt->gian_num; ?>
</td>
<td>
<?php echo $lt->duration; ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</section>
| jangmac/CodeIgniter | application/views/list/computational/using_soft/use_hangul.php | PHP | mit | 1,961 |
//-----------------------------------------
// Grunt configuration
//-----------------------------------------
module.exports = function(grunt) {
// Init config
grunt.initConfig({
// environment constant
ngconstant: {
options: {
space: ' ',
name: 'envConstant',
dest: 'public/js/envConstant.js'
},
dev: {
constants: {
ENV: {
appURI: 'http://localhost:3000/',
instagramClientId: 'yourDevClientId'
}
}
},
prod:{
constants: {
ENV: {
appURI: 'http://instalurker-andreavitali.rhcloud.com/',
instagramClientId: 'yourProdClientId'
}
}
}
},
// concat
concat: {
options: {
separator: ';' // useful for following uglify
},
app: {
src: 'public/js/**/*.js',
dest: 'public/instalurker.js'
},
vendor: {
src: ['public/vendor/jquery.min.js','public/vendor/angular.min.js','public/vendor/*.min.js'], // order is important!
dest: 'public/vendor.min.js'
}
},
// uglify (only app JS because vendor's are already minified)
uglify: {
options: {
mangle: false
},
app: {
src: 'public/instalurker.js',
dest: 'public/instalurker.min.js',
ext: '.min.js'
}
},
// CSS minification
cssmin: {
prod: {
files: {
'public/stylesheets/app.min.css' : ['public/stylesheets/app.css']
}
}
},
// Change index.html to use minified files
targethtml: {
prod: {
files: {
'public/index.html': 'public/index.html'
}
}
}
// SASS compilation made by IDE
});
// Load plugins
grunt.loadNpmTasks('grunt-ng-constant');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-targethtml');
// Dev task
grunt.registerTask('dev', ['ngconstant:dev']); // no
// Default (prod) task
grunt.registerTask('default', ['ngconstant:prod','concat:vendor','concat:app','uglify:app','cssmin','targethtml']);
}
| andreavitali/instalurker | gruntfile.js | JavaScript | mit | 2,712 |
<?php
namespace Smath\VentasBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Smath\VentasBundle\Entity\Pedido;
use Smath\VentasBundle\Form\PedidoType;
/**
* Pedido controller.
*
* @Route("/pedido")
*/
class PedidoController extends Controller
{
/**
* Lists all Pedido entities.
*
* @Route("/", name="pedido")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SmathVentasBundle:Pedido')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Lists all Pedido entities.
*
* @Route("/list", name="pedido_list")
* @Method("GET")
*/
public function listAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository('SmathVentasBundle:Pedido')->createQueryBuilder('p')
->add('select','p.id, p.fechaCreacion, p.fechaEntrega, pv.nombre as puntoVenta, e.nombre as empleado, c.razonSocial')
->leftJoin('p.puntoVenta','pv')
->leftJoin('pv.cliente', 'c')
->leftJoin('p.usuario','u')
->leftJoin('u.empleado','e');
$fields = array (
'id' => 'p.id',
'fechaCreacion' => 'p.fechaCreacion',
'fechaEntrega' => 'p.fechaEntrega',
'empleado' => 'empleado',
'puntoVenta' => 'puntoVenta',
'empleado' => 'e.nombre',
'cliente' => 'c.razonSocial',
);
$paginator = $this->get('knp_paginator');
$r = $this->get('smath_helpers')->jqGridJson($request, $em, $qb, $fields, $paginator);
$response = new Response();
return $response->setContent($r);
}
/**
* Creates a new Pedido entity.
*
* @Route("/", name="pedido_create")
* @Method("POST")
* @Template("SmathVentasBundle:Pedido:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Pedido();
$entity->setFechaCreacion(new \DateTime());
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('pedido_edit', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Creates a form to create a Pedido entity.
*
* @param Pedido $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Pedido $entity)
{
$form = $this->createForm(new PedidoType(), $entity, array(
'action' => $this->generateUrl('pedido_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Pedido entity.
*
* @Route("/new", name="pedido_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new Pedido();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Pedido entity.
*
* @Route("/{id}", name="pedido_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Pedido entity.
*
* @Route("/{id}/edit", name="pedido_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
'pedidoId' => $entity->getId()
);
}
/**
* Creates a form to edit a Pedido entity.
*
* @param Pedido $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Pedido $entity)
{
$form = $this->createForm(new PedidoType(), $entity, array(
'action' => $this->generateUrl('pedido_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Pedido entity.
*
* @Route("/{id}", name="pedido_update")
* @Method("PUT")
* @Template("SmathVentasBundle:Pedido:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('pedido'));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Pedido entity.
*
* @Route("/{id}", name="pedido_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('SmathVentasBundle:Pedido')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Pedido entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('pedido'));
}
/**
* Creates a form to delete a Pedido entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('pedido_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
| rsuarezdeveloper/smath | src/Smath/VentasBundle/Controller/PedidoController.php | PHP | mit | 7,983 |
package com.backusnaurparser.helper;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* Runtime Exception thrown when something goes wrong with parsing the EBNF
* grammar. A reason is always given (automatically printed via every
* printStackTrace(...) permutation)
*
* @author Dominik Horn
*
*/
public class LanguageParseException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String reason;
public LanguageParseException() {
this("Unknown cause");
}
public LanguageParseException(String reason) {
this.reason = reason;
}
@Override
public void printStackTrace() {
super.printStackTrace();
System.err.println("\nReason: " + this.reason);
}
@Override
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
s.println("\nReason: " + this.reason);
}
@Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
s.print("\nReason: " + this.reason);
}
}
| DominikHorn/FormalLanguageParser | src/com/backusnaurparser/helper/LanguageParseException.java | Java | mit | 981 |
require 'spec_helper'
describe Skywriter::Resource::CloudFormation::Authentication do
it "is a Resource" do
expect(Skywriter::Resource::CloudFormation::Authentication.new('name')).to be_a(Skywriter::Resource)
end
describe "#as_json" do
it "allows the user to define the keyspace" do
resource = Skywriter::Resource::CloudFormation::Authentication.new(
'name',
Foo: {
access_key_id: 'some kind of key'
},
Bar: {
access_key_id: 'some other kind of key'
}
)
expect(resource.as_json).to eq(
{
'name' => {
'Type' => "AWS::CloudFormation::Authentication",
'Foo' => {
'accessKeyId' => 'some kind of key',
},
'Bar' => {
'accessKeyId' => 'some other kind of key',
},
'DependsOn' => [],
}
}
)
end
end
end
| otherinbox/skywriter | spec/skywriter/resource/cloud_formation/authentication_spec.rb | Ruby | mit | 937 |
/*!
* vue-i18n v9.0.0-beta.13
* (c) 2020 kazuya kawaguchi
* Released under the MIT License.
*/
import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue';
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const inBrowser = typeof window !== 'undefined';
let mark;
let measure;
{
const perf = inBrowser && window.performance;
if (perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures) {
mark = (tag) => perf.mark(tag);
measure = (name, startTag, endTag) => {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
};
}
}
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
/* eslint-disable */
function format(message, ...args) {
if (args.length === 1 && isObject(args[0])) {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return message.replace(RE_ARGS, (match, identifier) => {
return args.hasOwnProperty(identifier) ? args[identifier] : '';
});
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
/** @internal */
const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
/** @internal */
const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
/** @internal */
const friendlyJSONstringify = (json) => JSON.stringify(json)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/\u0027/g, '\\u0027');
const isNumber = (val) => typeof val === 'number' && isFinite(val);
const isDate = (val) => toTypeString(val) === '[object Date]';
const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
function warn(msg, err) {
if (typeof console !== 'undefined') {
const label = 'vue-i18n' ;
console.warn(`[${label}] ` + msg);
/* istanbul ignore if */
if (err) {
console.warn(err.stack);
}
}
}
let _globalThis;
const getGlobalThis = () => {
// prettier-ignore
return (_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}));
};
function escapeHtml(rawText) {
return rawText
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/* eslint-enable */
/**
* Useful Utilites By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isBoolean = (val) => typeof val === 'boolean';
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// for converting list and named values to displayed strings.
const toDisplayString = (val) => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val);
};
const RANGE = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start);
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
}
else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + '^'.repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join('\n');
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var env = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.hook = exports.target = exports.isBrowser = void 0;
exports.isBrowser = typeof navigator !== 'undefined';
exports.target = exports.isBrowser
? window
: typeof commonjsGlobal !== 'undefined'
? commonjsGlobal
: {};
exports.hook = exports.target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
});
var _const = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiHookEvents = void 0;
var ApiHookEvents;
(function (ApiHookEvents) {
ApiHookEvents["SETUP_DEVTOOLS_PLUGIN"] = "devtools-plugin:setup";
})(ApiHookEvents = exports.ApiHookEvents || (exports.ApiHookEvents = {}));
});
var api = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var app = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var component = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var context = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var hooks = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hooks = void 0;
var Hooks;
(function (Hooks) {
Hooks["TRANSFORM_CALL"] = "transformCall";
Hooks["GET_APP_RECORD_NAME"] = "getAppRecordName";
Hooks["GET_APP_ROOT_INSTANCE"] = "getAppRootInstance";
Hooks["REGISTER_APPLICATION"] = "registerApplication";
Hooks["WALK_COMPONENT_TREE"] = "walkComponentTree";
Hooks["WALK_COMPONENT_PARENTS"] = "walkComponentParents";
Hooks["INSPECT_COMPONENT"] = "inspectComponent";
Hooks["GET_COMPONENT_BOUNDS"] = "getComponentBounds";
Hooks["GET_COMPONENT_NAME"] = "getComponentName";
Hooks["GET_ELEMENT_COMPONENT"] = "getElementComponent";
Hooks["GET_INSPECTOR_TREE"] = "getInspectorTree";
Hooks["GET_INSPECTOR_STATE"] = "getInspectorState";
})(Hooks = exports.Hooks || (exports.Hooks = {}));
});
var api$1 = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(api, exports);
__exportStar(app, exports);
__exportStar(component, exports);
__exportStar(context, exports);
__exportStar(hooks, exports);
});
var lib = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupDevtoolsPlugin = void 0;
__exportStar(api$1, exports);
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
if (env.hook) {
env.hook.emit(_const.ApiHookEvents.SETUP_DEVTOOLS_PLUGIN, pluginDescriptor, setupFn);
}
else {
const list = env.target.__VUE_DEVTOOLS_PLUGINS__ = env.target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
exports.setupDevtoolsPlugin = setupDevtoolsPlugin;
});
const pathStateMachine = [];
pathStateMachine[0 /* BEFORE_PATH */] = {
["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[1 /* IN_PATH */] = {
["w" /* WORKSPACE */]: [1 /* IN_PATH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[2 /* BEFORE_IDENT */] = {
["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
};
pathStateMachine[3 /* IN_IDENT */] = {
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
};
pathStateMachine[4 /* IN_SUB_PATH */] = {
["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [
4 /* IN_SUB_PATH */,
2 /* INC_SUB_PATH_DEPTH */
],
["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
};
pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
};
pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
};
/**
* Check if an expression is a literal value.
*/
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Strip quotes from a string
*/
function stripQuotes(str) {
const a = str.charCodeAt(0);
const b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Determine the type of a character in a keypath.
*/
function getPathCharType(ch) {
if (ch === undefined || ch === null) {
return "o" /* END_OF_FAIL */;
}
const code = ch.charCodeAt(0);
switch (code) {
case 0x5b: // [
case 0x5d: // ]
case 0x2e: // .
case 0x22: // "
case 0x27: // '
return ch;
case 0x5f: // _
case 0x24: // $
case 0x2d: // -
return "i" /* IDENT */;
case 0x09: // Tab (HT)
case 0x0a: // Newline (LF)
case 0x0d: // Return (CR)
case 0xa0: // No-break space (NBSP)
case 0xfeff: // Byte Order Mark (BOM)
case 0x2028: // Line Separator (LS)
case 0x2029: // Paragraph Separator (PS)
return "w" /* WORKSPACE */;
}
return "i" /* IDENT */;
}
/**
* Format a subPath, return its plain form if it is
* a literal string or number. Otherwise prepend the
* dynamic indicator (*).
*/
function formatSubPath(path) {
const trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
return false;
}
return isLiteral(trimmed)
? stripQuotes(trimmed)
: "*" /* ASTARISK */ + trimmed;
}
/**
* Parse a string path into an array of segments
*/
function parse(path) {
const keys = [];
let index = -1;
let mode = 0 /* BEFORE_PATH */;
let subPathDepth = 0;
let c;
let key; // eslint-disable-line
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[0 /* APPEND */] = () => {
if (key === undefined) {
key = newChar;
}
else {
key += newChar;
}
};
actions[1 /* PUSH */] = () => {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
actions[0 /* APPEND */]();
subPathDepth++;
};
actions[3 /* PUSH_SUB_PATH */] = () => {
if (subPathDepth > 0) {
subPathDepth--;
mode = 4 /* IN_SUB_PATH */;
actions[0 /* APPEND */]();
}
else {
subPathDepth = 0;
if (key === undefined) {
return false;
}
key = formatSubPath(key);
if (key === false) {
return false;
}
else {
actions[1 /* PUSH */]();
}
}
};
function maybeUnescapeQuote() {
const nextChar = path[index + 1];
if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
nextChar === "'" /* SINGLE_QUOTE */) ||
(mode === 6 /* IN_DOUBLE_QUOTE */ &&
nextChar === "\"" /* DOUBLE_QUOTE */)) {
index++;
newChar = '\\' + nextChar;
actions[0 /* APPEND */]();
return true;
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue;
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
// check parse error
if (transition === 8 /* ERROR */) {
return;
}
mode = transition[0];
if (transition[1] !== undefined) {
action = actions[transition[1]];
if (action) {
newChar = c;
if (action() === false) {
return;
}
}
}
// check parse finish
if (mode === 7 /* AFTER_PATH */) {
return keys;
}
}
}
// path token cache
const cache = new Map();
function resolveValue(obj, path) {
// check object
if (!isObject(obj)) {
return null;
}
// parse path
let hit = cache.get(path);
if (!hit) {
hit = parse(path);
if (hit) {
cache.set(path, hit);
}
}
// check hit
if (!hit) {
return null;
}
// resolve path value
const len = hit.length;
let last = obj;
let i = 0;
while (i < len) {
const val = last[hit[i]];
if (val === undefined) {
return null;
}
last = val;
i++;
}
return last;
}
const DEFAULT_MODIFIER = (str) => str;
const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
const DEFAULT_MESSAGE_DATA_TYPE = 'text';
const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
const DEFAULT_INTERPOLATE = toDisplayString;
function pluralDefault(choice, choicesLength) {
choice = Math.abs(choice);
if (choicesLength === 2) {
// prettier-ignore
return choice
? choice > 1
? 1
: 0
: 1;
}
return choice ? Math.min(choice, 2) : 0;
}
function getPluralIndex(options) {
// prettier-ignore
const index = isNumber(options.pluralIndex)
? options.pluralIndex
: -1;
// prettier-ignore
return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
? isNumber(options.named.count)
? options.named.count
: isNumber(options.named.n)
? options.named.n
: index
: index;
}
function normalizeNamed(pluralIndex, props) {
if (!props.count) {
props.count = pluralIndex;
}
if (!props.n) {
props.n = pluralIndex;
}
}
function createMessageContext(options = {}) {
const locale = options.locale;
const pluralIndex = getPluralIndex(options);
const pluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? options.pluralRules[locale]
: pluralDefault;
const orgPluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? pluralDefault
: undefined;
const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
const _list = options.list || [];
const list = (index) => _list[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _named = options.named || {};
isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
const named = (key) => _named[key];
// TODO: need to design resolve message function?
function message(key) {
// prettier-ignore
const msg = isFunction(options.messages)
? options.messages(key)
: isObject(options.messages)
? options.messages[key]
: false;
return !msg
? options.parent
? options.parent.message(key) // resolve from parent messages
: DEFAULT_MESSAGE
: msg;
}
const _modifier = (name) => options.modifiers
? options.modifiers[name]
: DEFAULT_MODIFIER;
const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
? options.processor.normalize
: DEFAULT_NORMALIZE;
const interpolate = isPlainObject(options.processor) &&
isFunction(options.processor.interpolate)
? options.processor.interpolate
: DEFAULT_INTERPOLATE;
const type = isPlainObject(options.processor) && isString(options.processor.type)
? options.processor.type
: DEFAULT_MESSAGE_DATA_TYPE;
const ctx = {
["list" /* LIST */]: list,
["named" /* NAMED */]: named,
["plural" /* PLURAL */]: plural,
["linked" /* LINKED */]: (key, modifier) => {
// TODO: should check `key`
const msg = message(key)(ctx);
return isString(modifier) ? _modifier(modifier)(msg) : msg;
},
["message" /* MESSAGE */]: message,
["type" /* TYPE */]: type,
["interpolate" /* INTERPOLATE */]: interpolate,
["normalize" /* NORMALIZE */]: normalize
};
return ctx;
}
/** @internal */
const errorMessages = {
// tokenizer error messages
[0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`,
[1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`,
[2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`,
[3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`,
[4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`,
[5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`,
[6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`,
[7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`,
[8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`,
[9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`,
// parser error messages
[10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`,
[11 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'`
};
/** @internal */
function createCompileError(code, loc, optinos = {}) {
const { domain, messages, args } = optinos;
const msg = format((messages || errorMessages)[code] || '', ...(args || []))
;
const error = new SyntaxError(String(msg));
error.code = code;
if (loc) {
error.location = loc;
}
error.domain = domain;
return error;
}
/** @internal */
function defaultOnError(error) {
throw error;
}
function createPosition(line, column, offset) {
return { line, column, offset };
}
function createLocation(start, end, source) {
const loc = { start, end };
if (source != null) {
loc.source = source;
}
return loc;
}
const CHAR_SP = ' ';
const CHAR_CR = '\r';
const CHAR_LF = '\n';
const CHAR_LS = String.fromCharCode(0x2028);
const CHAR_PS = String.fromCharCode(0x2029);
function createScanner(str) {
const _buf = str;
let _index = 0;
let _line = 1;
let _column = 1;
let _peekOffset = 0;
const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
const isLF = (index) => _buf[index] === CHAR_LF;
const isPS = (index) => _buf[index] === CHAR_PS;
const isLS = (index) => _buf[index] === CHAR_LS;
const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
const index = () => _index;
const line = () => _line;
const column = () => _column;
const peekOffset = () => _peekOffset;
const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
const currentChar = () => charAt(_index);
const currentPeek = () => charAt(_index + _peekOffset);
function next() {
_peekOffset = 0;
if (isLineEnd(_index)) {
_line++;
_column = 0;
}
if (isCRLF(_index)) {
_index++;
}
_index++;
_column++;
return _buf[_index];
}
function peek() {
if (isCRLF(_index + _peekOffset)) {
_peekOffset++;
}
_peekOffset++;
return _buf[_index + _peekOffset];
}
function reset() {
_index = 0;
_line = 1;
_column = 1;
_peekOffset = 0;
}
function resetPeek(offset = 0) {
_peekOffset = offset;
}
function skipToPeek() {
const target = _index + _peekOffset;
// eslint-disable-next-line no-unmodified-loop-condition
while (target !== _index) {
next();
}
_peekOffset = 0;
}
return {
index,
line,
column,
peekOffset,
charAt,
currentChar,
currentPeek,
next,
peek,
reset,
resetPeek,
skipToPeek
};
}
const EOF = undefined;
const LITERAL_DELIMITER = "'";
const ERROR_DOMAIN = 'tokenizer';
function createTokenizer(source, options = {}) {
const location = !options.location;
const _scnr = createScanner(source);
const currentOffset = () => _scnr.index();
const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
const _initLoc = currentPosition();
const _initOffset = currentOffset();
const _context = {
currentType: 14 /* EOF */,
offset: _initOffset,
startLoc: _initLoc,
endLoc: _initLoc,
lastType: 14 /* EOF */,
lastOffset: _initOffset,
lastStartLoc: _initLoc,
lastEndLoc: _initLoc,
braceNest: 0,
inLinked: false,
text: ''
};
const context = () => _context;
const { onError } = options;
function emitError(code, pos, offset, ...args) {
const ctx = context();
pos.column += offset;
pos.offset += offset;
if (onError) {
const loc = createLocation(ctx.startLoc, pos);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN,
args
});
onError(err);
}
}
function getToken(context, type, value) {
context.endLoc = currentPosition();
context.currentType = type;
const token = { type };
if (location) {
token.loc = createLocation(context.startLoc, context.endLoc);
}
if (value != null) {
token.value = value;
}
return token;
}
const getEndToken = (context) => getToken(context, 14 /* EOF */);
function eat(scnr, ch) {
if (scnr.currentChar() === ch) {
scnr.next();
return ch;
}
else {
emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch);
return '';
}
}
function peekSpaces(scnr) {
let buf = '';
while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
buf += scnr.currentPeek();
scnr.peek();
}
return buf;
}
function skipSpaces(scnr) {
const buf = peekSpaces(scnr);
scnr.skipToPeek();
return buf;
}
function isIdentifierStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90)); // A-Z
}
function isNumberStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
}
function isNamedIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isListIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
const ret = isNumberStart(ch);
scnr.resetPeek();
return ret;
}
function isLiteralStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === LITERAL_DELIMITER;
scnr.resetPeek();
return ret;
}
function isLinkedDotStart(scnr, context) {
const { currentType } = context;
if (currentType !== 8 /* LinkedAlias */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === "." /* LinkedDot */;
scnr.resetPeek();
return ret;
}
function isLinkedModifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 9 /* LinkedDot */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isLinkedDelimiterStart(scnr, context) {
const { currentType } = context;
if (!(currentType === 8 /* LinkedAlias */ ||
currentType === 12 /* LinkedModifier */)) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
scnr.resetPeek();
return ret;
}
function isLinkedReferStart(scnr, context) {
const { currentType } = context;
if (currentType !== 10 /* LinkedDelimiter */) {
return false;
}
const fn = () => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return isIdentifierStart(scnr.peek());
}
else if (ch === "@" /* LinkedAlias */ ||
ch === "%" /* Modulo */ ||
ch === "|" /* Pipe */ ||
ch === ":" /* LinkedDelimiter */ ||
ch === "." /* LinkedDot */ ||
ch === CHAR_SP ||
!ch) {
return false;
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn();
}
else {
// other charactors
return isIdentifierStart(ch);
}
};
const ret = fn();
scnr.resetPeek();
return ret;
}
function isPluralStart(scnr) {
peekSpaces(scnr);
const ret = scnr.currentPeek() === "|" /* Pipe */;
scnr.resetPeek();
return ret;
}
function isTextStart(scnr, reset = true) {
const fn = (hasSpace = false, prev = '', detectModulo = false) => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return prev === "%" /* Modulo */ ? false : hasSpace;
}
else if (ch === "@" /* LinkedAlias */ || !ch) {
return prev === "%" /* Modulo */ ? true : hasSpace;
}
else if (ch === "%" /* Modulo */) {
scnr.peek();
return fn(hasSpace, "%" /* Modulo */, true);
}
else if (ch === "|" /* Pipe */) {
return prev === "%" /* Modulo */ || detectModulo
? true
: !(prev === CHAR_SP || prev === CHAR_LF);
}
else if (ch === CHAR_SP) {
scnr.peek();
return fn(true, CHAR_SP, detectModulo);
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn(true, CHAR_LF, detectModulo);
}
else {
return true;
}
};
const ret = fn();
reset && scnr.resetPeek();
return ret;
}
function takeChar(scnr, fn) {
const ch = scnr.currentChar();
if (ch === EOF) {
return EOF;
}
if (fn(ch)) {
scnr.next();
return ch;
}
return null;
}
function takeIdentifierChar(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90) || // A-Z
(cc >= 48 && cc <= 57) || // 0-9
cc === 95 ||
cc === 36); // _ $
};
return takeChar(scnr, closure);
}
function takeDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
};
return takeChar(scnr, closure);
}
function takeHexDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 48 && cc <= 57) || // 0-9
(cc >= 65 && cc <= 70) || // A-F
(cc >= 97 && cc <= 102)); // a-f
};
return takeChar(scnr, closure);
}
function getDigits(scnr) {
let ch = '';
let num = '';
while ((ch = takeDigit(scnr))) {
num += ch;
}
return num;
}
function readText(scnr) {
const fn = (buf) => {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "}" /* BraceRight */ ||
ch === "@" /* LinkedAlias */ ||
!ch) {
return buf;
}
else if (ch === "%" /* Modulo */) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
return fn(buf);
}
else {
return buf;
}
}
else if (ch === "|" /* Pipe */) {
return buf;
}
else if (ch === CHAR_SP || ch === CHAR_LF) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
return fn(buf);
}
else if (isPluralStart(scnr)) {
return buf;
}
else {
buf += ch;
scnr.next();
return fn(buf);
}
}
else {
buf += ch;
scnr.next();
return fn(buf);
}
};
return fn('');
}
function readNamedIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
if (scnr.currentChar() === EOF) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
return name;
}
function readListIdentifier(scnr) {
skipSpaces(scnr);
let value = '';
if (scnr.currentChar() === '-') {
scnr.next();
value += `-${getDigits(scnr)}`;
}
else {
value += getDigits(scnr);
}
if (scnr.currentChar() === EOF) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
return value;
}
function readLiteral(scnr) {
skipSpaces(scnr);
eat(scnr, `\'`);
let ch = '';
let literal = '';
const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
while ((ch = takeChar(scnr, fn))) {
if (ch === '\\') {
literal += readEscapeSequence(scnr);
}
else {
literal += ch;
}
}
const current = scnr.currentChar();
if (current === CHAR_LF || current === EOF) {
emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0);
// TODO: Is it correct really?
if (current === CHAR_LF) {
scnr.next();
eat(scnr, `\'`);
}
return literal;
}
eat(scnr, `\'`);
return literal;
}
function readEscapeSequence(scnr) {
const ch = scnr.currentChar();
switch (ch) {
case '\\':
case `\'`:
scnr.next();
return `\\${ch}`;
case 'u':
return readUnicodeEscapeSequence(scnr, ch, 4);
case 'U':
return readUnicodeEscapeSequence(scnr, ch, 6);
default:
emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch);
return '';
}
}
function readUnicodeEscapeSequence(scnr, unicode, digits) {
eat(scnr, unicode);
let sequence = '';
for (let i = 0; i < digits; i++) {
const ch = takeHexDigit(scnr);
if (!ch) {
emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
break;
}
sequence += ch;
}
return `\\${unicode}${sequence}`;
}
function readInvalidIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let identifiers = '';
const closure = (ch) => ch !== "{" /* BraceLeft */ &&
ch !== "}" /* BraceRight */ &&
ch !== CHAR_SP &&
ch !== CHAR_LF;
while ((ch = takeChar(scnr, closure))) {
identifiers += ch;
}
return identifiers;
}
function readLinkedModifier(scnr) {
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
return name;
}
function readLinkedRefer(scnr) {
const fn = (detect = false, buf) => {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "%" /* Modulo */ ||
ch === "@" /* LinkedAlias */ ||
ch === "|" /* Pipe */ ||
!ch) {
return buf;
}
else if (ch === CHAR_SP) {
return buf;
}
else if (ch === CHAR_LF) {
buf += ch;
scnr.next();
return fn(detect, buf);
}
else {
buf += ch;
scnr.next();
return fn(true, buf);
}
};
return fn(false, '');
}
function readPlural(scnr) {
skipSpaces(scnr);
const plural = eat(scnr, "|" /* Pipe */);
skipSpaces(scnr);
return plural;
}
// TODO: We need refactoring of token parsing ...
function readTokenInPlaceholder(scnr, context) {
let token = null;
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
if (context.braceNest >= 1) {
emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
skipSpaces(scnr);
context.braceNest++;
return token;
case "}" /* BraceRight */:
if (context.braceNest > 0 &&
context.currentType === 2 /* BraceLeft */) {
emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
context.braceNest--;
context.braceNest > 0 && skipSpaces(scnr);
if (context.inLinked && context.braceNest === 0) {
context.inLinked = false;
}
return token;
case "@" /* LinkedAlias */:
if (context.braceNest > 0) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
token = readTokenInLinked(scnr, context) || getEndToken(context);
context.braceNest = 0;
return token;
default:
let validNamedIdentifier = true;
let validListIdentifier = true;
let validLeteral = true;
if (isPluralStart(scnr)) {
if (context.braceNest > 0) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (context.braceNest > 0 &&
(context.currentType === 5 /* Named */ ||
context.currentType === 6 /* List */ ||
context.currentType === 7 /* Literal */)) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
context.braceNest = 0;
return readToken(scnr, context);
}
if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
token = getToken(context, 6 /* List */, readListIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validLeteral = isLiteralStart(scnr, context))) {
token = getToken(context, 7 /* Literal */, readLiteral(scnr));
skipSpaces(scnr);
return token;
}
if (!validNamedIdentifier && !validListIdentifier && !validLeteral) {
// TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value);
skipSpaces(scnr);
return token;
}
break;
}
return token;
}
// TODO: We need refactoring of token parsing ...
function readTokenInLinked(scnr, context) {
const { currentType } = context;
let token = null;
const ch = scnr.currentChar();
if ((currentType === 8 /* LinkedAlias */ ||
currentType === 9 /* LinkedDot */ ||
currentType === 12 /* LinkedModifier */ ||
currentType === 10 /* LinkedDelimiter */) &&
(ch === CHAR_LF || ch === CHAR_SP)) {
emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
}
switch (ch) {
case "@" /* LinkedAlias */:
scnr.next();
token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
context.inLinked = true;
return token;
case "." /* LinkedDot */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
case ":" /* LinkedDelimiter */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isLinkedDotStart(scnr, context) ||
isLinkedDelimiterStart(scnr, context)) {
skipSpaces(scnr);
return readTokenInLinked(scnr, context);
}
if (isLinkedModifierStart(scnr, context)) {
skipSpaces(scnr);
return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
}
if (isLinkedReferStart(scnr, context)) {
skipSpaces(scnr);
if (ch === "{" /* BraceLeft */) {
// scan the placeholder
return readTokenInPlaceholder(scnr, context) || token;
}
else {
return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
}
}
if (currentType === 8 /* LinkedAlias */) {
emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
}
context.braceNest = 0;
context.inLinked = false;
return readToken(scnr, context);
}
}
// TODO: We need refactoring of token parsing ...
function readToken(scnr, context) {
let token = { type: 14 /* EOF */ };
if (context.braceNest > 0) {
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
}
if (context.inLinked) {
return readTokenInLinked(scnr, context) || getEndToken(context);
}
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
case "}" /* BraceRight */:
emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0);
scnr.next();
return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
case "@" /* LinkedAlias */:
return readTokenInLinked(scnr, context) || getEndToken(context);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isTextStart(scnr)) {
return getToken(context, 0 /* Text */, readText(scnr));
}
if (ch === "%" /* Modulo */) {
scnr.next();
return getToken(context, 4 /* Modulo */, "%" /* Modulo */);
}
break;
}
return token;
}
function nextToken() {
const { currentType, offset, startLoc, endLoc } = _context;
_context.lastType = currentType;
_context.lastOffset = offset;
_context.lastStartLoc = startLoc;
_context.lastEndLoc = endLoc;
_context.offset = currentOffset();
_context.startLoc = currentPosition();
if (_scnr.currentChar() === EOF) {
return getToken(_context, 14 /* EOF */);
}
return readToken(_scnr, _context);
}
return {
nextToken,
currentOffset,
currentPosition,
context
};
}
const ERROR_DOMAIN$1 = 'parser';
// Backslash backslash, backslash quote, uHHHH, UHHHHHH.
const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
function fromEscapeSequence(match, codePoint4, codePoint6) {
switch (match) {
case `\\\\`:
return `\\`;
case `\\\'`:
return `\'`;
default: {
const codePoint = parseInt(codePoint4 || codePoint6, 16);
if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
return String.fromCodePoint(codePoint);
}
// invalid ...
// Replace them with U+FFFD REPLACEMENT CHARACTER.
return '�';
}
}
}
function createParser(options = {}) {
const location = !options.location;
const { onError } = options;
function emitError(tokenzer, code, start, offset, ...args) {
const end = tokenzer.currentPosition();
end.offset += offset;
end.column += offset;
if (onError) {
const loc = createLocation(start, end);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN$1,
args
});
onError(err);
}
}
function startNode(type, offset, loc) {
const node = {
type,
start: offset,
end: offset
};
if (location) {
node.loc = { start: loc, end: loc };
}
return node;
}
function endNode(node, offset, pos, type) {
node.end = offset;
if (type) {
node.type = type;
}
if (location && node.loc) {
node.loc.end = pos;
}
}
function parseText(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(3 /* Text */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseList(tokenizer, index) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(5 /* List */, offset, loc);
node.index = parseInt(index, 10);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseNamed(tokenizer, key) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(4 /* Named */, offset, loc);
node.key = key;
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLiteral(tokenizer, value) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(9 /* Literal */, offset, loc);
node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinkedModifier(tokenizer) {
const token = tokenizer.nextToken();
const context = tokenizer.context();
// check token
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
const node = startNode(8 /* LinkedModifier */, offset, loc);
node.value = token.value || '';
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinkedKey(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinked(tokenizer) {
const context = tokenizer.context();
const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
let token = tokenizer.nextToken();
if (token.type === 9 /* LinkedDot */) {
linkedNode.modifier = parseLinkedModifier(tokenizer);
token = tokenizer.nextToken();
}
// asset check token
if (token.type !== 10 /* LinkedDelimiter */) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
token = tokenizer.nextToken();
// skip brace left
if (token.type === 2 /* BraceLeft */) {
token = tokenizer.nextToken();
}
switch (token.type) {
case 11 /* LinkedKey */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseNamed(tokenizer, token.value || '');
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseList(tokenizer, token.value || '');
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseLiteral(tokenizer, token.value || '');
break;
}
endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
return linkedNode;
}
function parseMessage(tokenizer) {
const context = tokenizer.context();
const startOffset = context.currentType === 1 /* Pipe */
? tokenizer.currentOffset()
: context.offset;
const startLoc = context.currentType === 1 /* Pipe */
? context.endLoc
: context.startLoc;
const node = startNode(2 /* Message */, startOffset, startLoc);
node.items = [];
do {
const token = tokenizer.nextToken();
switch (token.type) {
case 0 /* Text */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseText(tokenizer, token.value || ''));
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseList(tokenizer, token.value || ''));
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseNamed(tokenizer, token.value || ''));
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseLiteral(tokenizer, token.value || ''));
break;
case 8 /* LinkedAlias */:
node.items.push(parseLinked(tokenizer));
break;
}
} while (context.currentType !== 14 /* EOF */ &&
context.currentType !== 1 /* Pipe */);
// adjust message node loc
const endOffset = context.currentType === 1 /* Pipe */
? context.lastOffset
: tokenizer.currentOffset();
const endLoc = context.currentType === 1 /* Pipe */
? context.lastEndLoc
: tokenizer.currentPosition();
endNode(node, endOffset, endLoc);
return node;
}
function parsePlural(tokenizer, offset, loc, msgNode) {
const context = tokenizer.context();
let hasEmptyMessage = msgNode.items.length === 0;
const node = startNode(1 /* Plural */, offset, loc);
node.cases = [];
node.cases.push(msgNode);
do {
const msg = parseMessage(tokenizer);
if (!hasEmptyMessage) {
hasEmptyMessage = msg.items.length === 0;
}
node.cases.push(msg);
} while (context.currentType !== 14 /* EOF */);
if (hasEmptyMessage) {
emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0);
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseResource(tokenizer) {
const context = tokenizer.context();
const { offset, startLoc } = context;
const msgNode = parseMessage(tokenizer);
if (context.currentType === 14 /* EOF */) {
return msgNode;
}
else {
return parsePlural(tokenizer, offset, startLoc, msgNode);
}
}
function parse(source) {
const tokenizer = createTokenizer(source, { ...options });
const context = tokenizer.context();
const node = startNode(0 /* Resource */, context.offset, context.startLoc);
if (location && node.loc) {
node.loc.source = source;
}
node.body = parseResource(tokenizer);
// assert wheather achieved to EOF
if (context.currentType !== 14 /* EOF */) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, context.currentType);
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
return { parse };
}
function createTransformer(ast, options = {} // eslint-disable-line
) {
const _context = {
ast,
helpers: new Set()
};
const context = () => _context;
const helper = (name) => {
_context.helpers.add(name);
return name;
};
return { context, helper };
}
function traverseNodes(nodes, transformer) {
for (let i = 0; i < nodes.length; i++) {
traverseNode(nodes[i], transformer);
}
}
function traverseNode(node, transformer) {
// TODO: if we need pre-hook of transform, should be implemeted to here
switch (node.type) {
case 1 /* Plural */:
traverseNodes(node.cases, transformer);
transformer.helper("plural" /* PLURAL */);
break;
case 2 /* Message */:
traverseNodes(node.items, transformer);
break;
case 6 /* Linked */:
const linked = node;
traverseNode(linked.key, transformer);
transformer.helper("linked" /* LINKED */);
break;
case 5 /* List */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("list" /* LIST */);
break;
case 4 /* Named */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("named" /* NAMED */);
break;
}
// TODO: if we need post-hook of transform, should be implemeted to here
}
// transform AST
function transform(ast, options = {} // eslint-disable-line
) {
const transformer = createTransformer(ast);
transformer.helper("normalize" /* NORMALIZE */);
// traverse
ast.body && traverseNode(ast.body, transformer);
// set meta information
const context = transformer.context();
ast.helpers = [...context.helpers];
}
function createCodeGenerator(ast, options) {
const { sourceMap, filename } = options;
const _context = {
source: ast.loc.source,
filename,
code: '',
column: 1,
line: 1,
offset: 0,
map: undefined,
indentLevel: 0
};
const context = () => _context;
function push(code, node) {
_context.code += code;
}
function _newline(n) {
push('\n' + ` `.repeat(n));
}
function indent() {
_newline(++_context.indentLevel);
}
function deindent(withoutNewLine) {
if (withoutNewLine) {
--_context.indentLevel;
}
else {
_newline(--_context.indentLevel);
}
}
function newline() {
_newline(_context.indentLevel);
}
const helper = (key) => `_${key}`;
return {
context,
push,
indent,
deindent,
newline,
helper
};
}
function generateLinkedNode(generator, node) {
const { helper } = generator;
generator.push(`${helper("linked" /* LINKED */)}(`);
generateNode(generator, node.key);
if (node.modifier) {
generator.push(`, `);
generateNode(generator, node.modifier);
}
generator.push(`)`);
}
function generateMessageNode(generator, node) {
const { helper } = generator;
generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
generator.indent();
const length = node.items.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.items[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent();
generator.push('])');
}
function generatePluralNode(generator, node) {
const { helper } = generator;
if (node.cases.length > 1) {
generator.push(`${helper("plural" /* PLURAL */)}([`);
generator.indent();
const length = node.cases.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.cases[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent();
generator.push(`])`);
}
}
function generateResource(generator, node) {
if (node.body) {
generateNode(generator, node.body);
}
else {
generator.push('null');
}
}
function generateNode(generator, node) {
const { helper } = generator;
switch (node.type) {
case 0 /* Resource */:
generateResource(generator, node);
break;
case 1 /* Plural */:
generatePluralNode(generator, node);
break;
case 2 /* Message */:
generateMessageNode(generator, node);
break;
case 6 /* Linked */:
generateLinkedNode(generator, node);
break;
case 8 /* LinkedModifier */:
generator.push(JSON.stringify(node.value), node);
break;
case 7 /* LinkedKey */:
generator.push(JSON.stringify(node.value), node);
break;
case 5 /* List */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
break;
case 4 /* Named */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
break;
case 9 /* Literal */:
generator.push(JSON.stringify(node.value), node);
break;
case 3 /* Text */:
generator.push(JSON.stringify(node.value), node);
break;
default:
{
throw new Error(`unhandled codegen node type: ${node.type}`);
}
}
}
// generate code from AST
const generate = (ast, options = {} // eslint-disable-line
) => {
const mode = isString(options.mode) ? options.mode : 'normal';
const filename = isString(options.filename)
? options.filename
: 'message.intl';
const sourceMap = isBoolean(options.sourceMap) ? options.sourceMap : false;
const helpers = ast.helpers || [];
const generator = createCodeGenerator(ast, { mode, filename, sourceMap });
generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
generator.indent();
if (helpers.length > 0) {
generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
generator.newline();
}
generator.push(`return `);
generateNode(generator, ast);
generator.deindent();
generator.push(`}`);
const { code, map } = generator.context();
return {
ast,
code,
map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
};
};
function baseCompile(source, options = {}) {
// parse source codes
const parser = createParser({ ...options });
const ast = parser.parse(source);
// transform ASTs
transform(ast, { ...options });
// generate javascript codes
return generate(ast, { ...options });
}
/** @internal */
const warnMessages = {
[0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
[1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
[2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
[3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
[4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
[5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
};
/** @internal */
function getWarnMessage(code, ...args) {
return format(warnMessages[code], ...args);
}
/** @internal */
const NOT_REOSLVED = -1;
/** @internal */
const MISSING_RESOLVE_VALUE = '';
function getDefaultLinkedModifiers() {
return {
upper: (val) => (isString(val) ? val.toUpperCase() : val),
lower: (val) => (isString(val) ? val.toLowerCase() : val),
// prettier-ignore
capitalize: (val) => (isString(val)
? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
: val)
};
}
let _compiler;
/** @internal */
function registerMessageCompiler(compiler) {
_compiler = compiler;
}
/** @internal */
function createCoreContext(options = {}) {
// setup options
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
isString(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const messages = isPlainObject(options.messages)
? options.messages
: { [locale]: {} };
const datetimeFormats = isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [locale]: {} };
const numberFormats = isPlainObject(options.numberFormats)
? options.numberFormats
: { [locale]: {} };
const modifiers = Object.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
const pluralRules = options.pluralRules || {};
const missing = isFunction(options.missing) ? options.missing : null;
const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
const fallbackFormat = !!options.fallbackFormat;
const unresolving = !!options.unresolving;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
const processor = isPlainObject(options.processor) ? options.processor : null;
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
const escapeParameter = !!options.escapeParameter;
const messageCompiler = isFunction(options.messageCompiler)
? options.messageCompiler
: _compiler;
const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
// setup internal options
const internalOptions = options;
const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
? internalOptions.__datetimeFormatters
: new Map();
const __numberFormatters = isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map();
const context = {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
modifiers,
pluralRules,
missing,
missingWarn,
fallbackWarn,
fallbackFormat,
unresolving,
postTranslation,
processor,
warnHtmlMessage,
escapeParameter,
messageCompiler,
onWarn,
__datetimeFormatters,
__numberFormatters
};
// for vue-devtools timeline event
{
context.__emitter =
internalOptions.__emitter != null ? internalOptions.__emitter : undefined;
}
return context;
}
/** @internal */
function isTranslateFallbackWarn(fallback, key) {
return fallback instanceof RegExp ? fallback.test(key) : fallback;
}
/** @internal */
function isTranslateMissingWarn(missing, key) {
return missing instanceof RegExp ? missing.test(key) : missing;
}
/** @internal */
function handleMissing(context, key, locale, missingWarn, type) {
const { missing, onWarn } = context;
// for vue-devtools timeline event
{
const emitter = context.__emitter;
if (emitter) {
emitter.emit("missing" /* MISSING */, {
locale,
key,
type
});
}
}
if (missing !== null) {
const ret = missing(context, locale, key, type);
return isString(ret) ? ret : key;
}
else {
if ( isTranslateMissingWarn(missingWarn, key)) {
onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale }));
}
return key;
}
}
/** @internal */
function getLocaleChain(ctx, fallback, start = '') {
const context = ctx;
if (start === '') {
return [];
}
if (!context.__localeChainCache) {
context.__localeChainCache = new Map();
}
let chain = context.__localeChainCache.get(start);
if (!chain) {
chain = [];
// first block defined by start
let block = [start];
// while any intervening block found
while (isArray(block)) {
block = appendBlockToChain(chain, block, fallback);
}
// prettier-ignore
// last block defined by default
const defaults = isArray(fallback)
? fallback
: isPlainObject(fallback)
? fallback['default']
? fallback['default']
: null
: fallback;
// convert defaults to array
block = isString(defaults) ? [defaults] : defaults;
if (isArray(block)) {
appendBlockToChain(chain, block, false);
}
context.__localeChainCache.set(start, chain);
}
return chain;
}
function appendBlockToChain(chain, block, blocks) {
let follow = true;
for (let i = 0; i < block.length && isBoolean(follow); i++) {
const locale = block[i];
if (isString(locale)) {
follow = appendLocaleToChain(chain, block[i], blocks);
}
}
return follow;
}
function appendLocaleToChain(chain, locale, blocks) {
let follow;
const tokens = locale.split('-');
do {
const target = tokens.join('-');
follow = appendItemToChain(chain, target, blocks);
tokens.splice(-1, 1);
} while (tokens.length && follow === true);
return follow;
}
function appendItemToChain(chain, target, blocks) {
let follow = false;
if (!chain.includes(target)) {
follow = true;
if (target) {
follow = target[target.length - 1] !== '!';
const locale = target.replace(/!/g, '');
chain.push(locale);
if ((isArray(blocks) || isPlainObject(blocks)) &&
blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
follow = blocks[locale];
}
}
}
return follow;
}
/** @internal */
function updateFallbackLocale(ctx, locale, fallback) {
const context = ctx;
context.__localeChainCache = new Map();
getLocaleChain(ctx, fallback, locale);
}
const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
function checkHtmlMessage(source, options) {
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
warn(format(WARN_MESSAGE, { source }));
}
}
const defaultOnCacheKey = (source) => source;
let compileCache = Object.create(null);
/** @internal */
function compileToFunction(source, options = {}) {
{
// check HTML message
checkHtmlMessage(source, options);
// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey;
const key = onCacheKey(source);
const cached = compileCache[key];
if (cached) {
return cached;
}
// compile error detecting
let occured = false;
const onError = options.onError || defaultOnError;
options.onError = (err) => {
occured = true;
onError(err);
};
// compile
const { code } = baseCompile(source, options);
// evaluate function
const msg = new Function(`return ${code}`)();
// if occured compile error, don't cache
return !occured ? (compileCache[key] = msg) : msg;
}
}
/** @internal */
function createCoreError(code) {
return createCompileError(code, null, { messages: errorMessages$1 } );
}
/** @internal */
const errorMessages$1 = {
[12 /* INVALID_ARGUMENT */]: 'Invalid arguments',
[13 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
'Make sure your Date represents a valid date.',
[14 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
};
const NOOP_MESSAGE_FUNCTION = () => '';
const isMessageFunction = (val) => isFunction(val);
// implementationo of `translate` function
/** @internal */
function translate(context, ...args) {
const { fallbackFormat, postTranslation, unresolving, fallbackLocale } = context;
const [key, options] = parseTranslateArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const escapeParameter = isBoolean(options.escapeParameter)
? options.escapeParameter
: context.escapeParameter;
// prettier-ignore
const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
? !isBoolean(options.default)
? options.default
: key
: fallbackFormat // default by `fallbackFormat` option
? key
: '';
const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
const locale = isString(options.locale) ? options.locale : context.locale;
// escape params
escapeParameter && escapeParams(options);
// resolve message format
// eslint-disable-next-line prefer-const
let [format, targetLocale, message] = resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn);
// if you use default message, set it as message format!
let cacheBaseKey = key;
if (!(isString(format) || isMessageFunction(format))) {
if (enableDefaultMsg) {
format = defaultMsgOrKey;
cacheBaseKey = format;
}
}
// checking message format and target locale
if (!(isString(format) || isMessageFunction(format)) ||
!isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
// setup compile error detecting
let occured = false;
const errorDetector = () => {
occured = true;
};
// compile message format
const msg = compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector);
// if occured compile error, return the message format
if (occured) {
return format;
}
// evaluate message with context
const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
const msgContext = createMessageContext(ctxOptions);
const messaged = evaluateMessage(context, msg, msgContext);
// if use post translation option, procee it with handler
return postTranslation ? postTranslation(messaged) : messaged;
}
function escapeParams(options) {
if (isArray(options.list)) {
options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
}
else if (isObject(options.named)) {
Object.keys(options.named).forEach(key => {
if (isString(options.named[key])) {
options.named[key] = escapeHtml(options.named[key]);
}
});
}
}
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
const { messages, onWarn } = context;
const locales = getLocaleChain(context, fallbackLocale, locale);
let message = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'translate';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
message =
messages[targetLocale] || {};
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-resolve-start';
endTag = 'intlify-message-resolve-end';
mark && mark(startTag);
}
if ((format = resolveValue(message, key)) === null) {
// if null, resolve with object key path
format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
}
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start && format) {
emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
type: "message-resolve" /* MESSAGE_RESOLVE */,
key,
message: format,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message resolve', startTag, endTag);
}
}
if (isString(format) || isFunction(format))
break;
const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
if (missingRet !== key) {
format = missingRet;
}
from = to;
}
return [format, targetLocale, message];
}
function compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
const { messageCompiler, warnHtmlMessage } = context;
if (isMessageFunction(format)) {
const msg = format;
msg.locale = msg.locale || targetLocale;
msg.key = msg.key || key;
return msg;
}
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-compilation-start';
endTag = 'intlify-message-compilation-end';
mark && mark(startTag);
}
const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start) {
emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
type: "message-compilation" /* MESSAGE_COMPILATION */,
message: format,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message compilation', startTag, endTag);
}
}
msg.locale = targetLocale;
msg.key = key;
msg.source = format;
return msg;
}
function evaluateMessage(context, msg, msgCtx) {
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-evaluation-start';
endTag = 'intlify-message-evaluation-end';
mark && mark(startTag);
}
const messaged = msg(msgCtx);
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start) {
emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
type: "message-evaluation" /* MESSAGE_EVALUATION */,
value: messaged,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message evaluation', startTag, endTag);
}
}
return messaged;
}
/** @internal */
function parseTranslateArgs(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
if (!isString(arg1)) {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isString(arg2)) {
options.default = arg2;
}
else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
options.named = arg2;
}
else if (isArray(arg2)) {
options.list = arg2;
}
if (isNumber(arg3)) {
options.plural = arg3;
}
else if (isString(arg3)) {
options.default = arg3;
}
else if (isPlainObject(arg3)) {
Object.assign(options, arg3);
}
return [key, options];
}
function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
return {
warnHtmlMessage,
onError: (err) => {
errorDetector && errorDetector(err);
{
const message = `Message compilation error: ${err.message}`;
const codeFrame = err.location &&
generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
const emitter = context.__emitter;
if (emitter) {
emitter.emit("compile-error" /* COMPILE_ERROR */, {
message: source,
error: err.message,
start: err.location && err.location.start.offset,
end: err.location && err.location.end.offset
});
}
console.error(codeFrame ? `${message}\n${codeFrame}` : message);
}
},
onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
};
}
function getMessageContextOptions(context, locale, message, options) {
const { modifiers, pluralRules } = context;
const resolveMessage = (key) => {
const val = resolveValue(message, key);
if (isString(val)) {
let occured = false;
const errorDetector = () => {
occured = true;
};
const msg = compileMessasgeFormat(context, key, locale, val, key, errorDetector);
return !occured
? msg
: NOOP_MESSAGE_FUNCTION;
}
else if (isMessageFunction(val)) {
return val;
}
else {
// TODO: should be implemented warning message
return NOOP_MESSAGE_FUNCTION;
}
};
const ctxOptions = {
locale,
modifiers,
pluralRules,
messages: resolveMessage
};
if (context.processor) {
ctxOptions.processor = context.processor;
}
if (options.list) {
ctxOptions.list = options.list;
}
if (options.named) {
ctxOptions.named = options.named;
}
if (isNumber(options.plural)) {
ctxOptions.pluralIndex = options.plural;
}
return ctxOptions;
}
const intlDefined = typeof Intl !== 'undefined';
const Availabilities = {
dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
};
// implementation of `datetime` function
/** @internal */
function datetime(context, ...args) {
const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
const { __datetimeFormatters } = context;
if ( !Availabilities.dateTimeFormat) {
onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, orverrides] = parseDateTimeArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value);
}
// resolve format
let datetimeFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'datetime format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
datetimeFormat =
datetimeFormats[targetLocale] || {};
format = datetimeFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(orverrides)) {
id = `${id}__${JSON.stringify(orverrides)}`;
}
let formatter = __datetimeFormatters.get(id);
if (!formatter) {
formatter = new Intl.DateTimeFormat(targetLocale, Object.assign({}, format, orverrides));
__datetimeFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseDateTimeArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let orverrides = {};
let value;
if (isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */);
}
value = new Date(arg1);
try {
// This will fail if the date is not valid
value.toISOString();
}
catch (e) {
throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */);
}
}
else if (isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(13 /* INVALID_DATE_ARGUMENT */);
}
value = arg1;
}
else if (isNumber(arg1)) {
value = arg1;
}
else {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
orverrides = arg3;
}
if (isPlainObject(arg4)) {
orverrides = arg4;
}
return [options.key || '', value, options, orverrides];
}
/** @internal */
function clearDateTimeFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__datetimeFormatters.has(id)) {
continue;
}
context.__datetimeFormatters.delete(id);
}
}
// implementation of `number` function
/** @internal */
function number(context, ...args) {
const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
const { __numberFormatters } = context;
if ( !Availabilities.numberFormat) {
onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, orverrides] = parseNumberArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.NumberFormat(locale).format(value);
}
// resolve format
let numberFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'number format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
numberFormat =
numberFormats[targetLocale] || {};
format = numberFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(orverrides)) {
id = `${id}__${JSON.stringify(orverrides)}`;
}
let formatter = __numberFormatters.get(id);
if (!formatter) {
formatter = new Intl.NumberFormat(targetLocale, Object.assign({}, format, orverrides));
__numberFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseNumberArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let orverrides = {};
if (!isNumber(arg1)) {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
const value = arg1;
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
orverrides = arg3;
}
if (isPlainObject(arg4)) {
orverrides = arg4;
}
return [options.key || '', value, options, orverrides];
}
/** @internal */
function clearNumberFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__numberFormatters.has(id)) {
continue;
}
context.__numberFormatters.delete(id);
}
}
const DevToolsLabels = {
["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 'Vue I18n: Compile Errors',
["vue-i18n-missing" /* TIMELINE_MISSING */]: 'Vue I18n: Missing',
["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 'Vue I18n: Fallback',
["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 'Vue I18n: Performance'
};
const DevToolsPlaceholders = {
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
};
const DevToolsTimelineColors = {
["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 0xff0000,
["vue-i18n-missing" /* TIMELINE_MISSING */]: 0xffcd19,
["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 0xffcd19,
["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 0xffcd19
};
const DevToolsTimelineLayerMaps = {
["compile-error" /* COMPILE_ERROR */]: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */,
["missing" /* MISSING */]: "vue-i18n-missing" /* TIMELINE_MISSING */,
["fallback" /* FALBACK */]: "vue-i18n-fallback" /* TIMELINE_FALLBACK */,
["message-resolve" /* MESSAGE_RESOLVE */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
["message-compilation" /* MESSAGE_COMPILATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
["message-evaluation" /* MESSAGE_EVALUATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */
};
/**
* Event emitter, forked from the below:
* - original repository url: https://github.com/developit/mitt
* - code url: https://github.com/developit/mitt/blob/master/src/index.ts
* - author: Jason Miller (https://github.com/developit)
* - license: MIT
*/
/**
* Create a event emitter
*
* @returns An event emitter
*/
function createEmitter() {
const events = new Map();
const emitter = {
events,
on(event, handler) {
const handlers = events.get(event);
const added = handlers && handlers.push(handler);
if (!added) {
events.set(event, [handler]);
}
},
off(event, handler) {
const handlers = events.get(event);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(event, payload) {
(events.get(event) || [])
.slice()
.map(handler => handler(payload));
(events.get('*') || [])
.slice()
.map(handler => handler(event, payload));
}
};
return emitter;
}
let devtools;
function setDevtoolsHook(hook) {
devtools = hook;
}
function devtoolsRegisterI18n(i18n, version) {
if (!devtools) {
return;
}
devtools.emit("intlify:register" /* REGISTER */, i18n, version);
}
let devtoolsApi;
async function enableDevTools(app, i18n) {
return new Promise((resolve, reject) => {
try {
lib.setupDevtoolsPlugin({
id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
app
}, api => {
devtoolsApi = api;
api.on.inspectComponent(payload => {
const componentInstance = payload.componentInstance;
if (componentInstance.vnode.el.__INTLIFY__ &&
payload.instanceData) {
inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__);
}
});
api.addInspector({
id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
icon: 'language',
treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
});
api.on.getInspectorTree(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
registerScope(payload, i18n);
}
});
api.on.getInspectorState(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
inspectScope(payload, i18n);
}
});
api.addTimelineLayer({
id: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */,
label: DevToolsLabels["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */],
color: DevToolsTimelineColors["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]
});
api.addTimelineLayer({
id: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
label: DevToolsLabels["vue-i18n-performance" /* TIMELINE_PERFORMANCE */],
color: DevToolsTimelineColors["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]
});
api.addTimelineLayer({
id: "vue-i18n-missing" /* TIMELINE_MISSING */,
label: DevToolsLabels["vue-i18n-missing" /* TIMELINE_MISSING */],
color: DevToolsTimelineColors["vue-i18n-missing" /* TIMELINE_MISSING */]
});
api.addTimelineLayer({
id: "vue-i18n-fallback" /* TIMELINE_FALLBACK */,
label: DevToolsLabels["vue-i18n-fallback" /* TIMELINE_FALLBACK */],
color: DevToolsTimelineColors["vue-i18n-fallback" /* TIMELINE_FALLBACK */]
});
resolve(true);
});
}
catch (e) {
console.error(e);
reject(false);
}
});
}
function inspectComposer(instanceData, composer) {
const type = 'vue-i18n: composer properties';
instanceData.state.push({
type,
key: 'locale',
editable: false,
value: composer.locale.value
});
instanceData.state.push({
type,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
});
instanceData.state.push({
type,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
});
instanceData.state.push({
type,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
});
instanceData.state.push({
type,
key: 'messages',
editable: false,
value: composer.messages.value
});
instanceData.state.push({
type,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
});
instanceData.state.push({
type,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
});
}
function registerScope(payload, i18n) {
const children = [];
for (const [keyInstance, instance] of i18n.__instances) {
// prettier-ignore
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
const label = keyInstance.type.name ||
keyInstance.type.displayName ||
keyInstance.type.__file;
children.push({
id: composer.id.toString(),
label: `${label} Scope`
});
}
payload.rootNodes.push({
id: 'global',
label: 'Global Scope',
children
});
}
function inspectScope(payload, i18n) {
if (payload.nodeId === 'global') {
payload.state = makeScopeInspectState(i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer);
}
else {
const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId);
if (instance) {
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
payload.state = makeScopeInspectState(composer);
}
}
}
function makeScopeInspectState(composer) {
const state = {};
const localeType = 'Locale related info';
const localeStates = [
{
type: localeType,
key: 'locale',
editable: false,
value: composer.locale.value
},
{
type: localeType,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
},
{
type: localeType,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
},
{
type: localeType,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
}
];
state[localeType] = localeStates;
const localeMessagesType = 'Locale messages info';
const localeMessagesStates = [
{
type: localeMessagesType,
key: 'messages',
editable: false,
value: composer.messages.value
}
];
state[localeMessagesType] = localeMessagesStates;
const datetimeFormatsType = 'Datetime formats info';
const datetimeFormatsStates = [
{
type: datetimeFormatsType,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
}
];
state[datetimeFormatsType] = datetimeFormatsStates;
const numberFormatsType = 'Datetime formats info';
const numberFormatsStates = [
{
type: numberFormatsType,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
}
];
state[numberFormatsType] = numberFormatsStates;
return state;
}
function addTimelineEvent(event, payload) {
if (devtoolsApi) {
devtoolsApi.addTimelineEvent({
layerId: DevToolsTimelineLayerMaps[event],
event: {
time: Date.now(),
meta: {},
data: payload || {}
}
});
}
}
/**
* Vue I18n Version
*
* @remarks
* Semver format. Same format as the package.json `version` field.
*
* @VueI18nGeneral
*/
const VERSION = '9.0.0-beta.13';
/**
* This is only called development env
* istanbul-ignore-next
*/
function initDev() {
const target = getGlobalThis();
target.__INTLIFY__ = true;
setDevtoolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
{
console.info(`You are running a development build of vue-i18n.\n` +
`Make sure to use the production build (*.prod.js) when deploying for production.`);
}
}
const warnMessages$1 = {
[6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
[7 /* NOT_SUPPORTED_PRESERVE */]: `Not supportted 'preserve'.`,
[8 /* NOT_SUPPORTED_FORMATTER */]: `Not supportted 'formatter'.`,
[9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supportted 'preserveDirectiveContent'.`,
[10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supportted 'getChoiceIndex'.`,
[11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
[12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
};
function getWarnMessage$1(code, ...args) {
return format(warnMessages$1[code], ...args);
}
function createI18nError(code, ...args) {
return createCompileError(code, null, { messages: errorMessages$2, args } );
}
const errorMessages$2 = {
[12 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
[13 /* INVALID_ARGUMENT */]: 'Invalid argument',
[14 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
[15 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
[20 /* UNEXPECTED_ERROR */]: 'Unexpected error',
[16 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
[17 /* REQUIRED_VALUE */]: `Required in value: {0}`,
[18 /* INVALID_VALUE */]: `Invalid value`,
[19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
};
/**
* Composer
*
* Composer is offered composable API for Vue 3
* This module is offered new style vue-i18n API
*/
const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
const DatetimePartsSymbol = makeSymbol('__datetimeParts');
const NumberPartsSymbol = makeSymbol('__numberParts');
const EnableEmitter = makeSymbol('__enableEmitter');
const DisableEmitter = makeSymbol('__disableEmitter');
let composerID = 0;
function defineCoreMissingHandler(missing) {
return ((ctx, locale, key, type) => {
return missing(locale, key, getCurrentInstance() || undefined, type);
});
}
function getLocaleMessages(locale, options) {
const { messages, __i18n } = options;
// prettier-ignore
const ret = isPlainObject(messages)
? messages
: isArray(__i18n)
? {}
: { [locale]: {} };
// merge locale messages of i18n custom block
if (isArray(__i18n)) {
__i18n.forEach(raw => {
deepCopy(isString(raw) ? JSON.parse(raw) : raw, ret);
});
return ret;
}
if (isFunction(__i18n)) {
const { functions } = __i18n();
addPreCompileMessages(ret, functions);
}
return ret;
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function deepCopy(source, destination) {
for (const key in source) {
if (hasOwn(source, key)) {
if (!isObject(source[key])) {
destination[key] = destination[key] != null ? destination[key] : {};
destination[key] = source[key];
}
else {
destination[key] = destination[key] != null ? destination[key] : {};
deepCopy(source[key], destination[key]);
}
}
}
}
function addPreCompileMessages(messages, functions) {
const keys = Object.keys(functions);
keys.forEach(key => {
const compiled = functions[key];
const { l, k } = JSON.parse(key);
if (!messages[l]) {
messages[l] = {};
}
const targetLocaleMessage = messages[l];
const paths = parse(k);
if (paths != null) {
const len = paths.length;
let last = targetLocaleMessage; // eslint-disable-line @typescript-eslint/no-explicit-any
let i = 0;
while (i < len) {
const path = paths[i];
if (i === len - 1) {
last[path] = compiled;
break;
}
else {
let val = last[path];
if (!val) {
last[path] = val = {};
}
last = val;
i++;
}
}
}
});
}
/**
* Create composer interface factory
*
* @internal
*/
function createComposer(options = {}) {
const { __root } = options;
const _isGlobal = __root === undefined;
let _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true;
const _locale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.locale.value
: isString(options.locale)
? options.locale
: 'en-US');
const _fallbackLocale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value);
const _messages = ref(getLocaleMessages(_locale.value, options));
const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} });
const _numberFormats = ref(isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} });
// warning suppress options
// prettier-ignore
let _missingWarn = __root
? __root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
// prettier-ignore
let _fallbackWarn = __root
? __root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
let _fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
// configure fall bakck to root
let _fallbackFormat = !!options.fallbackFormat;
// runtime missing
let _missing = isFunction(options.missing) ? options.missing : null;
let _runtimeMissing = isFunction(options.missing)
? defineCoreMissingHandler(options.missing)
: null;
// postTranslation handler
let _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
let _escapeParameter = !!options.escapeParameter;
// custom linked modifiers
// prettier-ignore
const _modifiers = __root
? __root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {};
// pluralRules
const _pluralRules = options.pluralRules;
// runtime context
// eslint-disable-next-line prefer-const
let _context;
function getCoreContext() {
return createCoreContext({
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
datetimeFormats: _datetimeFormats.value,
numberFormats: _numberFormats.value,
modifiers: _modifiers,
pluralRules: _pluralRules,
missing: _runtimeMissing === null ? undefined : _runtimeMissing,
missingWarn: _missingWarn,
fallbackWarn: _fallbackWarn,
fallbackFormat: _fallbackFormat,
unresolving: true,
postTranslation: _postTranslation === null ? undefined : _postTranslation,
warnHtmlMessage: _warnHtmlMessage,
escapeParameter: _escapeParameter,
__datetimeFormatters: isPlainObject(_context)
? _context.__datetimeFormatters
: undefined,
__numberFormatters: isPlainObject(_context)
? _context.__numberFormatters
: undefined,
__emitter: isPlainObject(_context)
? _context.__emitter
: undefined
});
}
_context = getCoreContext();
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
/*!
* define properties
*/
// locale
const locale = computed({
get: () => _locale.value,
set: val => {
_locale.value = val;
_context.locale = _locale.value;
}
});
// fallbackLocale
const fallbackLocale = computed({
get: () => _fallbackLocale.value,
set: val => {
_fallbackLocale.value = val;
_context.fallbackLocale = _fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, val);
}
});
// messages
const messages = computed(() => _messages.value);
// datetimeFormats
const datetimeFormats = computed(() => _datetimeFormats.value);
// numberFormats
const numberFormats = computed(() => _numberFormats.value);
/**
* define methods
*/
// getPostTranslationHandler
function getPostTranslationHandler() {
return isFunction(_postTranslation) ? _postTranslation : null;
}
// setPostTranslationHandler
function setPostTranslationHandler(handler) {
_postTranslation = handler;
_context.postTranslation = handler;
}
// getMissingHandler
function getMissingHandler() {
return _missing;
}
// setMissingHandler
function setMissingHandler(handler) {
if (handler !== null) {
_runtimeMissing = defineCoreMissingHandler(handler);
}
_missing = handler;
_context.missing = _runtimeMissing;
}
function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
const context = getCoreContext();
const ret = fn(context); // track reactive dependency, see the getRuntimeContext
if (isNumber(ret) && ret === NOT_REOSLVED) {
const key = argumentParser();
if ( _fallbackRoot && __root) {
warn(getWarnMessage$1(6 /* FALLBACK_TO_ROOT */, {
key,
type: warnType
}));
// for vue-devtools timeline event
{
const { __emitter: emitter } = context;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type: warnType,
key,
to: 'global'
});
}
}
}
return _fallbackRoot && __root
? fallbackSuccess(__root)
: fallbackFail(key);
}
else if (successCondition(ret)) {
return ret;
}
else {
/* istanbul ignore next */
throw createI18nError(12 /* UNEXPECTED_RETURN_TYPE */);
}
}
// t
function t(...args) {
return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val));
}
// d
function d(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// n
function n(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// for custom processor
function normalize(values) {
return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
}
const interpolate = (val) => val;
const processor = {
normalize,
interpolate,
type: 'vnode'
};
// __transrateVNode, using for `i18n-t` component
function __transrateVNode(...args) {
return wrapWithDeps(context => {
let ret;
const _context = context;
try {
_context.processor = processor;
ret = translate(_context, ...args);
}
finally {
_context.processor = null;
}
return ret;
}, () => parseTranslateArgs(...args)[0], 'translate',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
}
// __numberParts, using for `i18n-n` component
function __numberParts(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// __datetimeParts, using for `i18n-d` component
function __datetimeParts(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// te
function te(key, locale) {
const targetLocale = isString(locale) ? locale : _locale.value;
const message = getLocaleMessage(targetLocale);
return resolveValue(message, key) !== null;
}
// tm
function tm(key) {
const messages = _messages.value[_locale.value] || {};
const target = resolveValue(messages, key);
// prettier-ignore
return target != null
? target
: __root
? __root.tm(key) || {}
: {};
}
// getLocaleMessage
function getLocaleMessage(locale) {
return (_messages.value[locale] || {});
}
// setLocaleMessage
function setLocaleMessage(locale, message) {
_messages.value[locale] = message;
_context.messages = _messages.value;
}
// mergeLocaleMessage
function mergeLocaleMessage(locale, message) {
_messages.value[locale] = Object.assign(_messages.value[locale] || {}, message);
_context.messages = _messages.value;
}
// getDateTimeFormat
function getDateTimeFormat(locale) {
return _datetimeFormats.value[locale] || {};
}
// setDateTimeFormat
function setDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = format;
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// mergeDateTimeFormat
function mergeDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format);
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// getNumberFormat
function getNumberFormat(locale) {
return _numberFormats.value[locale] || {};
}
// setNumberFormat
function setNumberFormat(locale, format) {
_numberFormats.value[locale] = format;
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// mergeNumberFormat
function mergeNumberFormat(locale, format) {
_numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format);
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// for debug
composerID++;
// watch root locale & fallbackLocale
if (__root) {
watch(__root.locale, (val) => {
if (_inheritLocale) {
_locale.value = val;
_context.locale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
watch(__root.fallbackLocale, (val) => {
if (_inheritLocale) {
_fallbackLocale.value = val;
_context.fallbackLocale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
}
// export composition API!
const composer = {
// properties
id: composerID,
locale,
fallbackLocale,
get inheritLocale() {
return _inheritLocale;
},
set inheritLocale(val) {
_inheritLocale = val;
if (val && __root) {
_locale.value = __root.locale.value;
_fallbackLocale.value = __root.fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
},
get availableLocales() {
return Object.keys(_messages.value).sort();
},
messages,
datetimeFormats,
numberFormats,
get modifiers() {
return _modifiers;
},
get pluralRules() {
return _pluralRules || {};
},
get isGlobal() {
return _isGlobal;
},
get missingWarn() {
return _missingWarn;
},
set missingWarn(val) {
_missingWarn = val;
_context.missingWarn = _missingWarn;
},
get fallbackWarn() {
return _fallbackWarn;
},
set fallbackWarn(val) {
_fallbackWarn = val;
_context.fallbackWarn = _fallbackWarn;
},
get fallbackRoot() {
return _fallbackRoot;
},
set fallbackRoot(val) {
_fallbackRoot = val;
},
get fallbackFormat() {
return _fallbackFormat;
},
set fallbackFormat(val) {
_fallbackFormat = val;
_context.fallbackFormat = _fallbackFormat;
},
get warnHtmlMessage() {
return _warnHtmlMessage;
},
set warnHtmlMessage(val) {
_warnHtmlMessage = val;
_context.warnHtmlMessage = val;
},
get escapeParameter() {
return _escapeParameter;
},
set escapeParameter(val) {
_escapeParameter = val;
_context.escapeParameter = val;
},
// methods
t,
d,
n,
te,
tm,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getDateTimeFormat,
setDateTimeFormat,
mergeDateTimeFormat,
getNumberFormat,
setNumberFormat,
mergeNumberFormat,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
[TransrateVNodeSymbol]: __transrateVNode,
[NumberPartsSymbol]: __numberParts,
[DatetimePartsSymbol]: __datetimeParts
};
// for vue-devtools timeline event
{
composer[EnableEmitter] = (emitter) => {
_context.__emitter = emitter;
};
composer[DisableEmitter] = () => {
_context.__emitter = undefined;
};
}
return composer;
}
/**
* Legacy
*
* This module is offered legacy vue-i18n API compatibility
*/
/**
* Convert to I18n Composer Options from VueI18n Options
*
* @internal
*/
function convertComposerOptions(options) {
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const missing = isFunction(options.missing) ? options.missing : undefined;
const missingWarn = isBoolean(options.silentTranslationWarn) ||
isRegExp(options.silentTranslationWarn)
? !options.silentTranslationWarn
: true;
const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
isRegExp(options.silentFallbackWarn)
? !options.silentFallbackWarn
: true;
const fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
const fallbackFormat = !!options.formatFallbackMessages;
const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
const pluralizationRules = options.pluralizationRules;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: undefined;
const warnHtmlMessage = isString(options.warnHtmlInMessage)
? options.warnHtmlInMessage !== 'off'
: true;
const escapeParameter = !!options.escapeParameterHtml;
const inheritLocale = isBoolean(options.sync) ? options.sync : true;
if ( options.formatter) {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
}
if ( options.preserveDirectiveContent) {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
}
let messages = options.messages;
if (isPlainObject(options.sharedMessages)) {
const sharedMessages = options.sharedMessages;
const locales = Object.keys(sharedMessages);
messages = locales.reduce((messages, locale) => {
const message = messages[locale] || (messages[locale] = {});
Object.assign(message, sharedMessages[locale]);
return messages;
}, (messages || {}));
}
const { __i18n, __root } = options;
const datetimeFormats = options.datetimeFormats;
const numberFormats = options.numberFormats;
return {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
missing,
missingWarn,
fallbackWarn,
fallbackRoot,
fallbackFormat,
modifiers,
pluralRules: pluralizationRules,
postTranslation,
warnHtmlMessage,
escapeParameter,
inheritLocale,
__i18n,
__root
};
}
/**
* create VueI18n interface factory
*
* @internal
*/
function createVueI18n(options = {}) {
const composer = createComposer(convertComposerOptions(options));
// defines VueI18n
const vueI18n = {
/**
* properties
*/
// id
id: composer.id,
// locale
get locale() {
return composer.locale.value;
},
set locale(val) {
composer.locale.value = val;
},
// fallbackLocale
get fallbackLocale() {
return composer.fallbackLocale.value;
},
set fallbackLocale(val) {
composer.fallbackLocale.value = val;
},
// messages
get messages() {
return composer.messages.value;
},
// datetimeFormats
get datetimeFormats() {
return composer.datetimeFormats.value;
},
// numberFormats
get numberFormats() {
return composer.numberFormats.value;
},
// availableLocales
get availableLocales() {
return composer.availableLocales;
},
// formatter
get formatter() {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
// dummy
return {
interpolate() {
return [];
}
};
},
set formatter(val) {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
},
// missing
get missing() {
return composer.getMissingHandler();
},
set missing(handler) {
composer.setMissingHandler(handler);
},
// silentTranslationWarn
get silentTranslationWarn() {
return isBoolean(composer.missingWarn)
? !composer.missingWarn
: composer.missingWarn;
},
set silentTranslationWarn(val) {
composer.missingWarn = isBoolean(val) ? !val : val;
},
// silentFallbackWarn
get silentFallbackWarn() {
return isBoolean(composer.fallbackWarn)
? !composer.fallbackWarn
: composer.fallbackWarn;
},
set silentFallbackWarn(val) {
composer.fallbackWarn = isBoolean(val) ? !val : val;
},
// modifiers
get modifiers() {
return composer.modifiers;
},
// formatFallbackMessages
get formatFallbackMessages() {
return composer.fallbackFormat;
},
set formatFallbackMessages(val) {
composer.fallbackFormat = val;
},
// postTranslation
get postTranslation() {
return composer.getPostTranslationHandler();
},
set postTranslation(handler) {
composer.setPostTranslationHandler(handler);
},
// sync
get sync() {
return composer.inheritLocale;
},
set sync(val) {
composer.inheritLocale = val;
},
// warnInHtmlMessage
get warnHtmlInMessage() {
return composer.warnHtmlMessage ? 'warn' : 'off';
},
set warnHtmlInMessage(val) {
composer.warnHtmlMessage = val !== 'off';
},
// escapeParameterHtml
get escapeParameterHtml() {
return composer.escapeParameter;
},
set escapeParameterHtml(val) {
composer.escapeParameter = val;
},
// preserveDirectiveContent
get preserveDirectiveContent() {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
return true;
},
set preserveDirectiveContent(val) {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
},
// pluralizationRules
get pluralizationRules() {
return composer.pluralRules || {};
},
// for internal
__composer: composer,
/**
* methods
*/
// t
t(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// tc
tc(...args) {
const [arg1, arg2, arg3] = args;
const options = { plural: 1 };
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// te
te(key, locale) {
return composer.te(key, locale);
},
// tm
tm(key) {
return composer.tm(key);
},
// getLocaleMessage
getLocaleMessage(locale) {
return composer.getLocaleMessage(locale);
},
// setLocaleMessage
setLocaleMessage(locale, message) {
composer.setLocaleMessage(locale, message);
},
// mergeLocaleMessasge
mergeLocaleMessage(locale, message) {
composer.mergeLocaleMessage(locale, message);
},
// d
d(...args) {
return composer.d(...args);
},
// getDateTimeFormat
getDateTimeFormat(locale) {
return composer.getDateTimeFormat(locale);
},
// setDateTimeFormat
setDateTimeFormat(locale, format) {
composer.setDateTimeFormat(locale, format);
},
// mergeDateTimeFormat
mergeDateTimeFormat(locale, format) {
composer.mergeDateTimeFormat(locale, format);
},
// n
n(...args) {
return composer.n(...args);
},
// getNumberFormat
getNumberFormat(locale) {
return composer.getNumberFormat(locale);
},
// setNumberFormat
setNumberFormat(locale, format) {
composer.setNumberFormat(locale, format);
},
// mergeNumberFormat
mergeNumberFormat(locale, format) {
composer.mergeNumberFormat(locale, format);
},
// getChoiceIndex
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getChoiceIndex(choice, choicesLength) {
warn(getWarnMessage$1(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
return -1;
},
// for internal
__onComponentInstanceCreated(target) {
const { componentInstanceCreatedListener } = options;
if (componentInstanceCreatedListener) {
componentInstanceCreatedListener(target, vueI18n);
}
}
};
// for vue-devtools timeline event
{
vueI18n.__enableEmitter = (emitter) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[EnableEmitter] && __composer[EnableEmitter](emitter);
};
vueI18n.__disableEmitter = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[DisableEmitter] && __composer[DisableEmitter]();
};
}
return vueI18n;
}
const baseFormatProps = {
tag: {
type: [String, Object]
},
locale: {
type: String
},
scope: {
type: String,
validator: (val) => val === 'parent' || val === 'global',
default: 'parent'
}
};
/**
* Translation Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [TranslationProps](component#translationprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Component Interpolation](../advanced/component)
*
* @example
* ```html
* <div id="app">
* <!-- ... -->
* <i18n path="term" tag="label" for="tos">
* <a :href="url" target="_blank">{{ $t('tos') }}</a>
* </i18n>
* <!-- ... -->
* </div>
* ```
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* const messages = {
* en: {
* tos: 'Term of Service',
* term: 'I accept xxx {0}.'
* },
* ja: {
* tos: '利用規約',
* term: '私は xxx の{0}に同意します。'
* }
* }
*
* const i18n = createI18n({
* locale: 'en',
* messages
* })
*
* const app = createApp({
* data: {
* url: '/term'
* }
* }).use(i18n).mount('#app')
* ```
*
* @VueI18nComponent
*/
const Translation = {
/* eslint-disable */
name: 'i18n-t',
props: {
...baseFormatProps,
keypath: {
type: String,
required: true
},
plural: {
type: [Number, String],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validator: (val) => isNumber(val) || !isNaN(val)
}
},
/* eslint-enable */
setup(props, context) {
const { slots, attrs } = context;
const i18n = useI18n({ useScope: props.scope });
const keys = Object.keys(slots).filter(key => key !== '_');
return () => {
const options = {};
if (props.locale) {
options.locale = props.locale;
}
if (props.plural !== undefined) {
options.plural = isString(props.plural) ? +props.plural : props.plural;
}
const arg = getInterpolateArg(context, keys);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
};
function getInterpolateArg({ slots }, keys) {
if (keys.length === 1 && keys[0] === 'default') {
// default slot only
return slots.default ? slots.default() : [];
}
else {
// named slots
return keys.reduce((arg, key) => {
const slot = slots[key];
if (slot) {
arg[key] = slot();
}
return arg;
}, {});
}
}
function renderFormatter(props, context, slotKeys, partFormatter) {
const { slots, attrs } = context;
return () => {
const options = { part: true };
let orverrides = {};
if (props.locale) {
options.locale = props.locale;
}
if (isString(props.format)) {
options.key = props.format;
}
else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString(props.format.key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = props.format.key;
}
// Filter out number format options only
orverrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options;
}, {});
}
const parts = partFormatter(...[props.value, options, orverrides]);
let children = [options.key];
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type];
return slot
? slot({ [part.type]: part.value, index, parts })
: [part.value];
});
}
else if (isString(parts)) {
children = [parts];
}
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
const NUMBER_FORMAT_KEYS = [
'localeMatcher',
'style',
'unit',
'unitDisplay',
'currency',
'currencyDisplay',
'useGrouping',
'numberingSystem',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
'notation',
'formatMatcher'
];
/**
* Number Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/number#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.NumberForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
*
* @VueI18nComponent
*/
const NumberFormat = {
/* eslint-disable */
name: 'i18n-n',
props: {
...baseFormatProps,
value: {
type: Number,
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[NumberPartsSymbol](...args));
}
};
const DATETIME_FORMAT_KEYS = [
'dateStyle',
'timeStyle',
'fractionalSecondDigits',
'calendar',
'dayPeriod',
'numberingSystem',
'localeMatcher',
'timeZone',
'hour12',
'hourCycle',
'formatMatcher',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName'
];
/**
* Datetime Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/datetime#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.DateTimeForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
*
* @VueI18nComponent
*/
const DatetimeFormat = {
/* eslint-disable */
name: 'i18n-d',
props: {
...baseFormatProps,
value: {
type: [Number, Date],
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[DatetimePartsSymbol](...args));
}
};
function getComposer(i18n, instance) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
return (i18nInternal.__getInstance(instance) || i18n.global);
}
else {
const vueI18n = i18nInternal.__getInstance(instance);
return vueI18n != null
? vueI18n.__composer
: i18n.global.__composer;
}
}
function vTDirective(i18n) {
const bind = (el, { instance, value, modifiers }) => {
/* istanbul ignore if */
if (!instance || !instance.$) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const composer = getComposer(i18n, instance.$);
if ( modifiers.preserve) {
warn(getWarnMessage$1(7 /* NOT_SUPPORTED_PRESERVE */));
}
const parsedValue = parseValue(value);
el.textContent = composer.t(...makeParams(parsedValue));
};
return {
beforeMount: bind,
beforeUpdate: bind
};
}
function parseValue(value) {
if (isString(value)) {
return { path: value };
}
else if (isPlainObject(value)) {
if (!('path' in value)) {
throw createI18nError(17 /* REQUIRED_VALUE */, 'path');
}
return value;
}
else {
throw createI18nError(18 /* INVALID_VALUE */);
}
}
function makeParams(value) {
const { path, locale, args, choice, plural } = value;
const options = {};
const named = args || {};
if (isString(locale)) {
options.locale = locale;
}
if (isNumber(choice)) {
options.plural = choice;
}
if (isNumber(plural)) {
options.plural = plural;
}
return [path, named, options];
}
function apply(app, i18n, ...options) {
const pluginOptions = isPlainObject(options[0])
? options[0]
: {};
const useI18nComponentName = !!pluginOptions.useI18nComponentName;
const globalInstall = isBoolean(pluginOptions.globalInstall)
? pluginOptions.globalInstall
: true;
if ( globalInstall && useI18nComponentName) {
warn(getWarnMessage$1(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
name: Translation.name
}));
}
if (globalInstall) {
// install components
app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
app.component(NumberFormat.name, NumberFormat);
app.component(DatetimeFormat.name, DatetimeFormat);
}
// install directive
app.directive('t', vTDirective(i18n));
}
// supports compatibility for legacy vue-i18n APIs
function defineMixin(vuei18n, composer, i18n) {
return {
beforeCreate() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const options = this.$options;
if (options.i18n) {
const optionsI18n = options.i18n;
if (options.__i18n) {
optionsI18n.__i18n = options.__i18n;
}
optionsI18n.__root = composer;
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, optionsI18n);
}
else {
this.$i18n = createVueI18n(optionsI18n);
}
}
else if (options.__i18n) {
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, options);
}
else {
this.$i18n = createVueI18n({
__i18n: options.__i18n,
__root: composer
});
}
}
else {
// set global
this.$i18n = vuei18n;
}
vuei18n.__onComponentInstanceCreated(this.$i18n);
i18n.__setInstance(instance, this.$i18n);
// defines vue-i18n legacy APIs
this.$t = (...args) => this.$i18n.t(...args);
this.$tc = (...args) => this.$i18n.tc(...args);
this.$te = (key, locale) => this.$i18n.te(key, locale);
this.$d = (...args) => this.$i18n.d(...args);
this.$n = (...args) => this.$i18n.n(...args);
this.$tm = (key) => this.$i18n.tm(key);
},
mounted() {
/* istanbul ignore if */
{
this.$el.__INTLIFY__ = this.$i18n.__composer;
const emitter = (this.__emitter = createEmitter());
const _vueI18n = this.$i18n;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
emitter.on('*', addTimelineEvent);
}
},
beforeUnmount() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
/* istanbul ignore if */
{
if (this.__emitter) {
this.__emitter.off('*', addTimelineEvent);
delete this.__emitter;
}
const _vueI18n = this.$i18n;
_vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
delete this.$el.__INTLIFY__;
}
delete this.$t;
delete this.$tc;
delete this.$te;
delete this.$d;
delete this.$n;
delete this.$tm;
i18n.__deleteInstance(instance);
delete this.$i18n;
}
};
}
function mergeToRoot(root, optoins) {
root.locale = optoins.locale || root.locale;
root.fallbackLocale = optoins.fallbackLocale || root.fallbackLocale;
root.missing = optoins.missing || root.missing;
root.silentTranslationWarn =
optoins.silentTranslationWarn || root.silentFallbackWarn;
root.silentFallbackWarn =
optoins.silentFallbackWarn || root.silentFallbackWarn;
root.formatFallbackMessages =
optoins.formatFallbackMessages || root.formatFallbackMessages;
root.postTranslation = optoins.postTranslation || root.postTranslation;
root.warnHtmlInMessage = optoins.warnHtmlInMessage || root.warnHtmlInMessage;
root.escapeParameterHtml =
optoins.escapeParameterHtml || root.escapeParameterHtml;
root.sync = optoins.sync || root.sync;
const messages = getLocaleMessages(root.locale, {
messages: optoins.messages,
__i18n: optoins.__i18n
});
Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
if (optoins.datetimeFormats) {
Object.keys(optoins.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, optoins.datetimeFormats[locale]));
}
if (optoins.numberFormats) {
Object.keys(optoins.numberFormats).forEach(locale => root.mergeNumberFormat(locale, optoins.numberFormats[locale]));
}
return root;
}
/**
* Vue I18n factory
*
* @param options - An options, see the {@link I18nOptions}
*
* @returns {@link I18n} instance
*
* @remarks
* If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
*
* If you use composition API mode, you need to specify {@link ComposerOptions}.
*
* @VueI18nSee [Getting Started](../essentials/started)
* @VueI18nSee [Composition API](../advanced/composition)
*
* @example
* case: for Legacy API
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* // ...
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @example
* case: for composition API
* ```js
* import { createApp } from 'vue'
* import { createI18n, useI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* legacy: false, // you must specify 'lagacy: false' option
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* setup() {
* // ...
* const { t } = useI18n({ ... })
* return { ... , t }
* }
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @VueI18nGeneral
*/
function createI18n(options = {}) {
// prettier-ignore
const __legacyMode = isBoolean(options.legacy)
? options.legacy
: true;
const __globalInjection = !!options.globalInjection;
const __instances = new Map();
// prettier-ignore
const __global = __legacyMode
? createVueI18n(options)
: createComposer(options);
const symbol = makeSymbol( 'vue-i18n' );
const i18n = {
// mode
get mode() {
// prettier-ignore
return __legacyMode
? 'legacy'
: 'composition'
;
},
// install plugin
async install(app, ...options) {
{
app.__VUE_I18N__ = i18n;
}
// setup global provider
app.__VUE_I18N_SYMBOL__ = symbol;
app.provide(app.__VUE_I18N_SYMBOL__, i18n);
// global method and properties injection for Composition API
if (!__legacyMode && __globalInjection) {
injectGlobalFields(app, i18n.global);
}
// install built-in components and directive
{
apply(app, i18n, ...options);
}
// setup mixin for Legacy API
if ( __legacyMode) {
app.mixin(defineMixin(__global, __global.__composer, i18n));
}
// setup vue-devtools plugin
{
const ret = await enableDevTools(app, i18n);
if (!ret) {
throw createI18nError(19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
}
const emitter = createEmitter();
if (__legacyMode) {
const _vueI18n = __global;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
}
else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
}
emitter.on('*', addTimelineEvent);
}
},
// global accsessor
get global() {
return __global;
},
// @internal
__instances,
// @internal
__getInstance(component) {
return __instances.get(component) || null;
},
// @internal
__setInstance(component, instance) {
__instances.set(component, instance);
},
// @internal
__deleteInstance(component) {
__instances.delete(component);
}
};
{
devtoolsRegisterI18n(i18n, VERSION);
}
return i18n;
}
/**
* Use Composition API for Vue I18n
*
* @param options - An options, see {@link UseI18nOptions}
*
* @returns {@link Composer} instance
*
* @remarks
* This function is mainly used by `setup`.
*
* If options are specified, Composer instance is created for each component and you can be localized on the component.
*
* If options are not specified, you can be localized using the global Composer.
*
* @example
* case: Component resource base localization
* ```html
* <template>
* <form>
* <label>{{ t('language') }}</label>
* <select v-model="locale">
* <option value="en">en</option>
* <option value="ja">ja</option>
* </select>
* </form>
* <p>message: {{ t('hello') }}</p>
* </template>
*
* <script>
* import { useI18n } from 'vue-i18n'
*
* export default {
* setup() {
* const { t, locale } = useI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
* // Something to do ...
*
* return { ..., t, locale }
* }
* }
* </script>
* ```
*
* @VueI18nComposition
*/
function useI18n(options = {}) {
const instance = getCurrentInstance();
if (instance == null) {
throw createI18nError(14 /* MUST_BE_CALL_SETUP_TOP */);
}
if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
throw createI18nError(15 /* NOT_INSLALLED */);
}
const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
// prettier-ignore
const scope = isEmptyObject(options)
? ('__i18n' in instance.type)
? 'local'
: 'global'
: !options.useScope
? 'local'
: options.useScope;
if (scope === 'global') {
let messages = isObject(options.messages) ? options.messages : {};
if ('__i18nGlobal' in instance.type) {
messages = getLocaleMessages(global.locale.value, {
messages,
__i18n: instance.type.__i18nGlobal
});
}
// merge locale messages
const locales = Object.keys(messages);
if (locales.length) {
locales.forEach(locale => {
global.mergeLocaleMessage(locale, messages[locale]);
});
}
// merge datetime formats
if (isObject(options.datetimeFormats)) {
const locales = Object.keys(options.datetimeFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
});
}
}
// merge number formats
if (isObject(options.numberFormats)) {
const locales = Object.keys(options.numberFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeNumberFormat(locale, options.numberFormats[locale]);
});
}
}
return global;
}
if (scope === 'parent') {
let composer = getComposer$1(i18n, instance);
if (composer == null) {
{
warn(getWarnMessage$1(12 /* NOT_FOUND_PARENT_SCOPE */));
}
composer = global;
}
return composer;
}
// scope 'local' case
if (i18n.mode === 'legacy') {
throw createI18nError(16 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
}
const i18nInternal = i18n;
let composer = i18nInternal.__getInstance(instance);
if (composer == null) {
const type = instance.type;
const composerOptions = {
...options
};
if (type.__i18n) {
composerOptions.__i18n = type.__i18n;
}
if (global) {
composerOptions.__root = global;
}
composer = createComposer(composerOptions);
setupLifeCycle(i18nInternal, instance, composer);
i18nInternal.__setInstance(instance, composer);
}
return composer;
}
function getComposer$1(i18n, target) {
let composer = null;
const root = target.root;
let current = target.parent;
while (current != null) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
composer = i18nInternal.__getInstance(current);
}
else {
const vueI18n = i18nInternal.__getInstance(current);
if (vueI18n != null) {
composer = vueI18n
.__composer;
}
}
if (composer != null) {
break;
}
if (root === current) {
break;
}
current = current.parent;
}
return composer;
}
function setupLifeCycle(i18n, target, composer) {
let emitter = null;
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (
target.vnode.el) {
target.vnode.el.__INTLIFY__ = composer;
emitter = createEmitter();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
emitter.on('*', addTimelineEvent);
}
}, target);
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (
target.vnode.el &&
target.vnode.el.__INTLIFY__) {
emitter && emitter.off('*', addTimelineEvent);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[DisableEmitter] && _composer[DisableEmitter]();
delete target.vnode.el.__INTLIFY__;
}
i18n.__deleteInstance(target);
}, target);
}
const globalExportProps = [
'locale',
'fallbackLocale',
'availableLocales'
];
const globalExportMethods = ['t', 'd', 'n', 'tm'];
function injectGlobalFields(app, composer) {
const i18n = Object.create(null);
globalExportProps.forEach(prop => {
const desc = Object.getOwnPropertyDescriptor(composer, prop);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const wrap = isRef(desc.value) // check computed props
? {
get() {
return desc.value.value;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set(val) {
desc.value.value = val;
}
}
: {
get() {
return desc.get && desc.get();
}
};
Object.defineProperty(i18n, prop, wrap);
});
app.config.globalProperties.$i18n = i18n;
globalExportMethods.forEach(method => {
const desc = Object.getOwnPropertyDescriptor(composer, method);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
});
}
// register message compiler at vue-i18n
registerMessageCompiler(compileToFunction);
initDev();
export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };
| cdnjs/cdnjs | ajax/libs/vue-i18n/9.0.0-beta.13/vue-i18n.esm-browser.js | JavaScript | mit | 168,066 |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/msg/Motors.msg"
services_str = "/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/srv/AddTwoInts.srv"
pkg_name = "er1_motor_driver"
dependencies_str = "std_msgs"
langs = "gencpp;genlisp;genpy"
dep_include_paths_str = "er1_motor_driver;/home/arvind/clover_hack_day/er1_robot/src/er1_motor_driver/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg"
PYTHON_EXECUTABLE = "/usr/bin/python"
package_has_static_sources = '' == 'TRUE'
genmsg_check_deps_script = "/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
| arvindpereira/clover_hack_day | er1_robot/build/er1_motor_driver/cmake/er1_motor_driver-genmsg-context.py | Python | mit | 677 |
export default {
name: 'selfie-card',
type: 'text',
render() {
return '[ :) ]';
}
};
| atonse/mobiledoc-kit | demo/app/mobiledoc-cards/text/selfie.js | JavaScript | mit | 97 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ChallengeAccepted.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ChallengeAccepted.Models")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("186858b4-52b9-4a17-84aa-f4946a821fa2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| NativeScriptHybrids/ChallengeAccepted | ChallengeAccepted.Service/ChallengeAccepted.Models/Properties/AssemblyInfo.cs | C# | mit | 1,424 |
from mimetypes import guess_type
def get_git_info():
"""
Parses the git info and returns a tuple containg the owner and repo
:deprecated:
:rtype: tuple
:return: (owner name, repo name)
"""
repo = ''
with open('.git/config') as f:
for line in f.readlines():
if 'url' in line:
repo = line.replace('url = ', '').strip()
r = repo.split('/')
# Return a tuple containing the owner and the repo name
return r[-2], r[-1]
def detect_mimetype(file_):
"""
Detects the provided file's mimetype. Used to determine if we should read
the file line-by-line.
:param str file_: The name of the file to guess the mimetype of
:rtype: str
:return: The mimetype of the file provided
"""
return guess_type(file_)
| GrappigPanda/pygemony | pyg/utils.py | Python | mit | 811 |
#include "ticTacToeFunc.h"
#include <cstdio>
TicTacToeFunc::TicTacToeFunc()
{
size = 3;
winSize = 3;
field = new States *[size];
for (int i = 0; i < size; i++)
field[i] = new States[size];
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
field[i][j] = stateFree;
move = moveX;
state = inProcess;
}
TicTacToeFunc::~TicTacToeFunc()
{
for (int i = 0; i < size; i++)
delete[] field[i];
delete[] field;
}
TicTacToeFunc::States TicTacToeFunc::getCell(int x, int y)
{
return field[x][y];
}
void TicTacToeFunc::horizontalWin()
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size - winSize + 1; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[i][j + k] == TicTacToeFunc::stateFree || field[i][j + k] != field[i][j + k + 1])
{
win = false;
break;
}
if (!win)
continue;
state = (field[i][j] == stateX) ? winX : winO;
return;
}
}
void TicTacToeFunc::verticalWin()
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size - winSize + 1; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[j + k][i] == TicTacToeFunc::stateFree || field[j + k][i] != field[j + k + 1][i])
{
win = false;
break;
}
if (!win)
continue;
state = (field[j][i] == stateX) ? winX : winO;
return;
}
}
void TicTacToeFunc::mainDiagonalWin()
{
for (int i = 0; i < size - winSize + 1; i++)
for (int j = 0; j < size - winSize + 1; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[i + k][j + k] == TicTacToeFunc::stateFree || field[i + k][j + k] != field[i + k + 1][j + k + 1])
{
win = false;
break;
}
if (!win)
continue;
state = (field[i][j] == stateX) ? winX : winO;
return;
}
}
void TicTacToeFunc::secondaryDiagonalWin()
{
for (int i = 0; i < size - winSize + 1; i++)
for (int j = winSize - 1; j < size; j++)
{
bool win = true;
for (int k = 0; k < winSize - 1; k++)
if (field[i + k][j - k] == TicTacToeFunc::stateFree || field[i + k][j - k] != field[i + k + 1][j - k - 1])
{
win = false;
break;
}
if (!win)
continue;
state = (field[j][i] == stateX) ? winX : winO;
}
}
void TicTacToeFunc::updateState()
{
if (state != inProcess)
return;
horizontalWin();
if (state != inProcess)
return;
verticalWin();
if (state != inProcess)
return;
mainDiagonalWin();
if (state != inProcess)
return;
secondaryDiagonalWin();
}
TicTacToeFunc::Moves TicTacToeFunc::nextMove()
{
if (move == moveX)
return moveO;
return moveX;
}
TicTacToeFunc::States TicTacToeFunc::changeState(Moves m)
{
if (m == moveX)
return stateX;
return stateO;
}
void TicTacToeFunc::makeMove(int x, int y)
{
if (isFinished())
return;
field[x][y] = changeState(move);
updateState();
move = nextMove();
}
TicTacToeFunc::CurrentState TicTacToeFunc::getState()
{
return state;
}
bool TicTacToeFunc::isFinished()
{
if (state == winX || state == winO)
return true;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (field[i][j] == stateFree)
return false;
return true;
}
void TicTacToeFunc::changeSize(int newSize)
{
for (int i = 0; i < size; i++)
delete[] field[i];
delete[] field;
field = new States*[newSize];
for (int i = 0; i < newSize; i++)
field[i] = new TicTacToeFunc::States[newSize];
for (int i = 0; i < newSize; i++)
for (int j = 0; j < newSize; j++)
field[i][j] = TicTacToeFunc::stateFree;
size = newSize;
winSize = 5;
move = TicTacToeFunc::moveX;
}
int TicTacToeFunc::getSize()
{
return size;
}
| Sergey-Pravdyukov/Homeworks | term2/hw7/3/tictactoefunc.cpp | C++ | mit | 4,600 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace QrF.Core.Admin.Dto
{
public class BasePageInput
{
public BasePageInput()
{
this.Page = 1;
this.PageSize = 20;
}
/// <summary>
/// 当前分页
/// </summary>
public int Page { set; get; }
/// <summary>
/// 每页数量
/// </summary>
public int PageSize { set; get; }
}
}
| ren8179/QrF.Core | src/apis/QrF.Core.Admin/Dto/BasePageInput.cs | C# | mit | 507 |