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
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import assets from './assets'; import { port } from './config'; import Config from './config.json'; import fetch from './core/fetch'; const server = global.server = express(); // // Register Node.js middleware // ----------------------------------------------------------------------------- server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); server.all('*', (req, res, next) => { res.header('Access-Control-Allow-Origin', Config[process.env.NODE_ENV].clientUri); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); server.get('/api/steam', async (req, res, next) => { var url = req.query.path; var isXml = false; for (var key in req.query) { if (key !== 'path') { var joiner = url.indexOf('?') > -1 ? '&' : '?'; url = url + joiner + key + '=' + encodeURIComponent(req.query[key]); } if (key === 'xml') { isXml = true; } } if (isXml) { url = 'http://steamcommunity.com' + url; } else { url = 'http://api.steampowered.com' + url + (url.indexOf('?') > -1 ? '&' : '?') + 'key=' + process.env.STEAM_API_KEY; } const response = await fetch(url); const data = isXml ? await response.text() : await response.json(); if (isXml) { res.set('Content-Type', 'text/xml'); } res.send(data); }); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '', entry: assets.main.js }; const css = []; const context = { insertCss: styles => css.push(styles._getCss()), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
cheshire137/cheevo-plotter
src/server.js
JavaScript
mit
3,191
package com.github.robocup_atan.atan.parser.objects; /* * #%L * Atan * %% * Copyright (C) 2003 - 2014 Atan * %% * 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. * #L% */ //~--- non-JDK imports -------------------------------------------------------- import com.github.robocup_atan.atan.model.ControllerCoach; import com.github.robocup_atan.atan.model.ControllerPlayer; import com.github.robocup_atan.atan.model.ControllerTrainer; import com.github.robocup_atan.atan.model.enums.Flag; /** * The parser object for goal west. * * @author Atan */ public class ObjNameFlagGoalWest implements ObjName { char qualifier; /** * A constructor for goal west. * * @param qualifier Either 't' or 'b'. */ public ObjNameFlagGoalWest(char qualifier) { this.qualifier = qualifier; } /** {@inheritDoc} */ @Override public void infoSeeFromEast(ControllerPlayer c, double distance, double direction, double distChange, double dirChange, double bodyFacingDirection, double headFacingDirection) { switch (qualifier) { case 't' : c.infoSeeFlagGoalOther(Flag.RIGHT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; case 'b' : c.infoSeeFlagGoalOther(Flag.LEFT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; default : c.infoSeeFlagGoalOther(Flag.CENTER, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; } } /** {@inheritDoc} */ @Override public void infoSeeFromWest(ControllerPlayer c, double distance, double direction, double distChange, double dirChange, double bodyFacingDirection, double headFacingDirection) { switch (qualifier) { case 't' : c.infoSeeFlagGoalOwn(Flag.LEFT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; case 'b' : c.infoSeeFlagGoalOwn(Flag.RIGHT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; default : c.infoSeeFlagGoalOwn(Flag.CENTER, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; } } /** {@inheritDoc} */ @Override public void infoSeeFromEast(ControllerCoach c, double x, double y, double deltaX, double deltaY, double bodyAngle, double neckAngle) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public void infoSeeFromWest(ControllerCoach c, double x, double y, double deltaX, double deltaY, double bodyAngle, double neckAngle) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public void infoSee(ControllerTrainer c) { throw new UnsupportedOperationException(); } }
robocup-atan/atan
src/main/java/com/github/robocup_atan/atan/parser/objects/ObjNameFlagGoalWest.java
Java
mit
4,455
#pragma once #include <app/common.hpp> #include <app/LedDisplay.hpp> #include <audio.hpp> namespace rack { namespace app { struct AudioWidget : LedDisplay { LedDisplayChoice* driverChoice; LedDisplaySeparator* driverSeparator; LedDisplayChoice* deviceChoice; LedDisplaySeparator* deviceSeparator; LedDisplayChoice* sampleRateChoice; LedDisplaySeparator* sampleRateSeparator; LedDisplayChoice* bufferSizeChoice; void setAudioPort(audio::Port* port); }; } // namespace app } // namespace rack
AndrewBelt/Rack
include/app/AudioWidget.hpp
C++
mit
505
// @flow /* eslint-disable no-console */ import chalk from "chalk"; import createWatcher from "./watch"; import loadWatches from "./load-watches"; import hasWatchman from "./utils/has-watchman"; import type { WatchDefinition } from "./load-watches"; import getConfig from "./config"; type Targets = { [target: string]: Array<{ wd: string, data: Array<WatchDefinition> }> }; const getTargets = (definitions): Targets => { const targets = {}; definitions.forEach(def => { Object.keys(def.data).forEach(target => { targets[target] = targets[target] || []; targets[target].push({ wd: def.wd, data: def.data[target] }); }); }); return targets; }; const setupPhaseWatch = (definitions, watcher, config) => phase => { definitions.forEach(({ wd, data: phaseData }) => { if (!phaseData[phase]) { return; } const phaseWatches = phaseData[phase]; phaseWatches.forEach(watcher.add(wd, config[phase])); }); }; const setupWatches = async (phase: string | Array<string>) => { let phases; if (typeof phase === "string") { phases = [phase]; } else { phases = phase; } const [definitions, watchman, config] = await Promise.all([ loadWatches(), hasWatchman(), getConfig() ]); const watcher = createWatcher(watchman); const setup = setupPhaseWatch(definitions, watcher, config); phases.forEach(setup); const targets = getTargets(definitions); phases.forEach(p => { if (!Object.keys(targets).includes(p)) { console.error( `\n${chalk.yellow("WARNING")}: target ${chalk.yellow( p )} not found in any .watch files\n` ); } }); watcher.start(); }; export const listTargets = async (): Promise<Targets> => { const definitions = await loadWatches(); return getTargets(definitions); }; export default setupWatches;
laat/nurture
src/index.js
JavaScript
mit
1,846
$(document).ready(function(){ initUploadExcerptPhoto(); initUploadMedia(); $('#edcomment_save').removeAttr('disabled'); $(document).on('click', '.js-single-click', function(){ $(this).attr('disabled', 'disabled'); }); $(document).on('submit', '.js-single-submit', function(){ var submitBtn=$(this).find(':submit'); submitBtn.attr('disabled', 'disabled'); }); $(document).on('click', '.js-add-media', function(e){ e.preventDefault(); $('.js-modal-add-media').modal(); $('.js-modal-add-media').on('shown.bs.modal', function (e) { refreshIsotope(); }) }); $(document).on('click', '.js-pick-or-upload', function(e){ e.preventDefault(); $('.js-modal-add-excerpt-media').modal(); $('.js-modal-add-excerpt-media').on('shown.bs.modal', function (e) { refreshIsotope(); }) }); $(document).on('click', '.js-trigger-upload', function(){ $('.js-upload-input').click(); }); $(document).on('click', '.js-trigger-upload-medias', function(){ $('#article_media_media').click(); }); $(document).on('click', '.js-trigger-upload-excerpt', function(){ $('#article_excerpt_media').click(); }); $(document).on('click', '.js-media-object-remove', function(e){ e.preventDefault(); $.post($(this).attr('data-href'), function(){ $('.js-media-object-remove').addClass('hidden'); $('.js-media-object').attr('src', '/bundles/blog/img/svg/image-placeholder.svg'); $('#article_excerpt_photo').val(''); }); }); $(document).on('click', '.js-media-object-reset', function(e) { $('.js-media-object-remove').addClass('hidden'); $('.js-media-object').attr('src', '/bundles/blog/img/svg/image-placeholder.svg'); $('#article_excerpt_photo').val(''); }); $(document).on('click', '.js-delete-object', function(e){ e.preventDefault(); $('.js-delete-object-text').text($(this).attr('data-text')); $('.js-delete-object-title').text($(this).attr('data-title')); $('.js-delete-object-href').attr('href',$(this).attr('data-href')); }); $(document).on('click', '.js-insert-media', function(e){ e.preventDefault(); $('.phototiles__iteminner.selected').each(function(){ var caption = $(this).parents('li').find('.ajax_media_form textarea').val(); if(caption) { tinymce.editors[0].insertContent('<div>'+ $(this).find('.js-add-media-editor').attr('data-content') +'<span class="d--b margin--halft app-grey text--mini text--italic">'+ caption +'</span></div>'); } else tinymce.editors[0].insertContent($(this).find('.js-add-media-editor').attr('data-content')); }); $('.js-close-insert-modal').click(); }); $(document).on('click', '.js-pagination-pager', function(e){ e.preventDefault(); $.post($(this).attr('href'), function(data){ $('.js-load-more').remove(); $('.js-media-content').after(data.pagination); if ($('.js-media-content').hasClass("js-noisotope")){ $('.js-media-content').append(data.html); } else{ // Isotope after Load more // Second approach $container = $('.isotope:visible'); // We need jQuery object, so instead of response.photoContent we use $(response.photoContent) var $new_items = $(data.html); // imagesLoaded is independent plugin, which we use as timeout until all images in $container are fetched, so their real size can be calculated; When they all are on the page, than code within will be executed $container.append( $new_items ); $container.imagesLoaded( function() { $container.isotope( 'appended', $new_items ); //$container.isotope( 'prepended', $new_items ); $container.isotope('layout'); $('.phototiles__item').removeClass('muted--total'); if ( $('.modal:visible').length ) { $('.modal:visible').each(centerModal); } else { if ( $(window).width() >= 992 ) { $('html, body').animate({ scrollTop: $(document).height() }, 1200); $('.dashboard-menu.alltheway').css('min-height', $('.dashboard-content').height()); } } }); } }); }); $(document).on('click', '.js-content-replace', function(e){ e.preventDefault(); element=$(this); $.post($(this).attr('data-href'), function(data){ element.parent().html(data.html); }); }); // Correct display after slow page load $('.gl.muted--total').each(function() { $(this).removeClass('muted--total'); }); // Make modal as wide as possible $('.modal--full').on('shown.bs.modal', function (e) { recalculateModal($(this)); }); // Select image for insert into article $(document).on('click', '.js-modal-add-media .phototiles__iteminner', function(e){ $(this).toggleClass('selected'); }); $(document).on('click', '.js-modal-add-excerpt-media .phototiles__iteminner', function(e){ var item = $(this).find('.js-add-media-editor'); $('.js-excerpt-holder').html( item.attr('data-content') ); $('#article_excerptPhoto').val(item.attr('data-val')); $('.js-modal-add-excerpt-media .js-close-insert-modal').trigger('click'); }); $(document).on('submit', '.js-comment-form', function(e){ e.preventDefault(); var form=$(this); var submit=form.find(':submit'); submit.attr('disabled', 'disabled'); $.post($(this).attr('action'),$(this).serialize() , function(data){ $('.js-comments-content').replaceWith(data.html); if (data.currentComment) { $('html, body').animate({ scrollTop: $("#"+data.currentComment).offset().top }, 2000); } }); }); $(document).on('submit', '.ajax_media_form', function(e){ e.preventDefault(); $.post($(this).attr('action'), $(this).serialize(), function(data){}); }); getFancyCategories(); }); // End of $(document).ready() // Resize or orientationchange of document $(window).bind('resize orientationchange', function(){ if ( $('.modal--full:visible').length ) { recalculateModal($('.modal--full')); } }); // Calculate position for full-width modal function recalculateModal($this) { mod_width = Math.floor($(window).width()*0.96); mod_height = Math.floor($(window).height()*0.96); $this.find('.modal-dialog').css('width', mod_width); head_foot_offset = 150; $this.find('.modal-body').css('max-height', mod_height - head_foot_offset); $this.removeClass('muted--total'); refreshIsotope(); } // Refresh Isotope function refreshIsotope() { $container = $('.isotope'); $container.imagesLoaded(function () { $container.isotope().isotope('layout'); $('.phototiles__item').removeClass('muted--total'); $('.modal:visible').each(centerModal); }); } function initUploadExcerptPhoto() { $('#form_excerptImage').fileupload({ url: $('#form_excerptImage').attr('data-href'), dataType: 'json', maxFileSize: 20000000, done: function (e, response) { var data = response.result; if (data.success == 'true') { $('.js-media-object').replaceWith(data.media); $('.js-excerpt-photo').val(data.id); $('.js-media-object-remove').removeClass('hidden'); $('.js-media-object-remove').attr('data-href', data.href); } }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css('width', progress + '%'); } }); } function initUploadMedia() { $('#article_media_media').fileupload({ url: $('#article_media_media').attr('data-href'), dataType: 'json', maxFileSize: 20000000, done: function (e, response) { var data = response.result; $('.js-load-more').remove(); $('.pagination').remove(); $('.js-media-content').replaceWith(data.html); // $('.js-trigger-upload-medias').parent().removeClass('muted--total'); // $('.js-trigger-upload-medias').removeClass('muted--total'); // $('.js-trigger-upload-medias').parent().css('position', 'relative'); refreshIsotope(); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css('width', progress + '%'); } }); $('#article_excerpt_media').fileupload({ url: $('#article_excerpt_media').attr('data-href'), dataType: 'json', maxFileSize: 20000000, done: function (e, response) { var data = response.result; $('.js-load-more').remove(); $('.pagination').remove(); $('.js-media-content').replaceWith(data.html); // $('.js-trigger-upload-medias').parent().removeClass('muted--total'); // $('.js-trigger-upload-medias').removeClass('muted--total'); // $('.js-trigger-upload-medias').parent().css('position', 'relative'); refreshIsotope(); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css('width', progress + '%'); } }); } function getFancyCategories() { $('.js-get-pretty-categories').each(function(){ var input = $(this); var url = input.attr('data-category-url'); var selected = []; input.find('[checked]').each(function(){ selected.push($(this).val()); }); input.find('[selected]').each(function(){ selected.push($(this).val()); }); $.post(url, { 'select': selected }, function(data){ if(data.success === true) { if(input.attr('data-empty-option') != undefined) { input.html('<option value="">' + input.attr('data-empty-option') + '</option>'); } else input.html(''); input.append(data.html).removeClass('hide'); } }); }); } function initNprogress() { $(document).ajaxStart(function(e) { if( (e.target.activeElement == undefined) || !$(e.target.activeElement).hasClass('js-skip-nprogress') ) NProgress.start(); }).ajaxStop(function(e){ NProgress.done(); }); }
NegMozzie/tapha
src/BlogBundle/Resources/public/js/fe-general.js
JavaScript
mit
10,917
<?php namespace Arthem\GoogleApi\Infrastructure\Client; use Arthem\GoogleApi\Infrastructure\Client\Decoder\DecoderInterface; use Arthem\GoogleApi\Infrastructure\Client\Exception\ClientErrorException; use GuzzleHttp\ClientInterface; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerInterface; abstract class Client implements LoggerAwareInterface { /** * @var string */ protected $apiUrl; /** * The client API key. * * @var string */ private $apiKey; /** * @var ClientInterface */ private $httpClient; /** * @var DecoderInterface */ private $decoder; /** * @var LoggerInterface */ private $logger; /** * @param ClientInterface $httpClient * @param DecoderInterface $decoder * @param string $apiKey */ public function __construct(ClientInterface $httpClient, DecoderInterface $decoder, $apiKey) { $this->apiKey = $apiKey; $this->decoder = $decoder; $this->httpClient = $httpClient; } /** * @param string $method * @param string $uri * @param array $parameters * @param array $options * * @return array * * @throws ClientErrorException */ public function request($method, $uri, array $parameters = [], array $options = []) { $parameters['key'] = $this->apiKey; $options['query'] = $parameters; $uri = $this->apiUrl.$uri.'/json'; $this->log($method, $uri, $options); $response = $this->httpClient->request($method, $uri, $options); $result = $this->decoder->decode($response); if (!isset($result['status'])) { throw new ClientErrorException('Missing return status'); } if (!in_array($result['status'], [ 'OK', 'ZERO_RESULTS', ], true)) { throw new ClientErrorException(sprintf('Invalid return status "%s"', $result['status'])); } return $result; } /** * @param string $method * @param string $uri * @param array $options */ private function log($method, $uri, array $options = []) { if (null === $this->logger) { return; } $this->logger->info( sprintf( 'google-api request: %s %s', $method, $uri ), [ 'params' => http_build_query( $options['query'] ), ] ); } /** * {@inheritdoc} */ public function setLogger(LoggerInterface $logger) { $this->logger = $logger; return $this; } }
4rthem/google-api
src/Infrastructure/Client/Client.php
PHP
mit
2,757
require 'brahma/web/fall' class CmsController < ApplicationController def index @title = t('web.title.cms') @fall_card = Brahma::Web::FallCard.new nil lang = I18n.locale Cms::Article.select(:id, :title, :summary, :logo).where(lang: lang).order(created: :desc).limit(20).each { |a| @fall_card.add cms_article_path(a.id), a.title, a.summary, a.logo } @tags = Cms::Tag.select(:id, :name).where(lang: lang).order(visits: :desc).limit(10) end end
chonglou/portal
app/controllers/cms_controller.rb
Ruby
mit
468
var statusItems = initStatusItems(); module.exports = { // check for an item completion checkItems: function(content, callback) { // iterate each status item to check for matches for (var i = 0; i < statusItems.length; i++) { var item = statusItems[i]; // skip item if it is already complete if (item.complete === true) { continue; } // item is incomplete, check the document if (content.indexOf(item.text) >= 0) { item.complete = true; callback(item.output); } } }, // cleanup phantom variables once installation finishes cleanup: function() { //statusItems = null; statusItems = initStatusItems(); }, // check if the script completed checkComplete: function() { var lastItem = statusItems[statusItems.length - 1]; // only check the last item in the array if it's complete if (lastItem.complete === true) { return true; } return false; } }; // initialize the status items to check the DOM against function initStatusItems() { return [ newStatusItem( 'Creating Sugar configuration file (config.php)', 'Creating Sugar Configuration File...' ), newStatusItem( 'Creating Sugar application tables, audit tables and relationship metadata', 'Creating application/audit tables and relationship data...' ), newStatusItem( 'Creating the database', 'Creating the database...' ), newStatusItem( 'Creating default Sugar data', 'Creating default Sugar data...' ), newStatusItem( 'Updating license information...', 'Updating license information...' ), newStatusItem( 'Creating default users...', 'Creating default users...' ), newStatusItem( 'Creating default reports...', 'Creating default reports...' ), newStatusItem( 'Populating the database tables with demo data', 'Inserting demo data...' ), newStatusItem( 'Creating default scheduler jobs...', 'Creating default scheduler jobs...' ) /*newStatusItem( 'is now complete!', 'Installation is complete!' )*/ ]; } // create a new status item to check against function newStatusItem(searchText, outputText, isComplete) { if (typeof(isComplete) === 'undefined') { isComplete = false; } return { text: searchText, output: outputText, complete: isComplete }; }
ScopeXL/sugarbuild
lib/phantom-install-helper.js
JavaScript
mit
2,815
import numpy as np def random_flips(X): """ Take random x-y flips of images. Input: - X: (N, C, H, W) array of image data. Output: - An array of the same shape as X, containing a copy of the data in X, but with half the examples flipped along the horizontal direction. """ N, C, H, W = X.shape mask = np.random.randint(2, size=N) # what this means is the ith image should be flipped with probability 1/2 out = np.zeros_like(X) out[mask==1] = X[mask==1,:,:,::-1] out[mask==0] = X[mask==0] return out def random_crops(X, crop_shape): """ Take random crops of images. For each input image we will generate a random crop of that image of the specified size. Input: - X: (N, C, H, W) array of image data - crop_shape: Tuple (HH, WW) to which each image will be cropped. Output: - Array of shape (N, C, HH, WW) """ N, C, H, W = X.shape HH, WW = crop_shape assert HH < H and WW < W out = np.zeros((N, C, HH, WW), dtype=X.dtype) np.random.randint((H-HH), size=N) y_start = np.random.randint((H-HH), size=N) #(H-HH)*np.random.random_sample(N) x_start = np.random.randint((W-WW), size=N) #(W-WW)*np.random.random_sample(N) for i in xrange(N): out[i] = X[i, :, y_start[i]:y_start[i]+HH, x_start[i]:x_start[i]+WW] return out def random_contrast(X, scale=(0.8, 1.2)): """ Randomly adjust the contrast of images. For each input image, choose a number uniformly at random from the range given by the scale parameter, and multiply each pixel of the image by that number. Inputs: - X: (N, C, H, W) array of image data - scale: Tuple (low, high). For each image we sample a scalar in the range (low, high) and multiply the image by that scaler. Output: - Rescaled array out of shape (N, C, H, W) where out[i] is a contrast adjusted version of X[i]. """ low, high = scale N = X.shape[0] out = np.zeros_like(X) l = (scale[1]-scale[0])*np.random.random_sample(N)+scale[0] # for i in xrange(N): # out[i] = X[i] * l[i] out = X * l[:,None,None,None] # TODO: vectorize this somehow... #out = #np.diag(l).dot(X)#X*l[:,np.newaxis, np.newaxis, np.newaxis] return out def random_tint(X, scale=(-10, 10)): """ Randomly tint images. For each input image, choose a random color whose red, green, and blue components are each drawn uniformly at random from the range given by scale. Add that color to each pixel of the image. Inputs: - X: (N, C, W, H) array of image data - scale: A tuple (low, high) giving the bounds for the random color that will be generated for each image. Output: - Tinted array out of shape (N, C, H, W) where out[i] is a tinted version of X[i]. """ low, high = scale N, C = X.shape[:2] out = np.zeros_like(X) # for i in xrange(N): # l = (scale[1]-scale[0])*np.random.random_sample(C)+scale[0] # out[i] = X[i]+l[:,None,None] l = (scale[1]-scale[0])*np.random.random_sample((N,C))+scale[0] out = X+l[:,:,None,None] return out def fixed_crops(X, crop_shape, crop_type): """ Take center or corner crops of images. Inputs: - X: Input data, of shape (N, C, H, W) - crop_shape: Tuple of integers (HH, WW) giving the size to which each image will be cropped. - crop_type: One of the following strings, giving the type of crop to compute: 'center': Center crop 'ul': Upper left corner 'ur': Upper right corner 'bl': Bottom left corner 'br': Bottom right corner Returns: Array of cropped data of shape (N, C, HH, WW) """ N, C, H, W = X.shape HH, WW = crop_shape x0 = (W - WW) / 2 y0 = (H - HH) / 2 x1 = x0 + WW y1 = y0 + HH if crop_type == 'center': return X[:, :, y0:y1, x0:x1] elif crop_type == 'ul': return X[:, :, :HH, :WW] elif crop_type == 'ur': return X[:, :, :HH, -WW:] elif crop_type == 'bl': return X[:, :, -HH:, :WW] elif crop_type == 'br': return X[:, :, -HH:, -WW:] else: raise ValueError('Unrecognized crop type %s' % crop_type)
UltronAI/Deep-Learning
CS231n/reference/cnn_assignments-master/assignment3/cs231n/data_augmentation.py
Python
mit
4,178
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.1.1 (2019-10-28) */ (function (domGlobals) { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); function Plugin () { global.add('textcolor', function () { domGlobals.console.warn('Text color plugin is now built in to the core editor, please remove it from your editor configuration'); }); } Plugin(); }(window));
cdnjs/cdnjs
ajax/libs/tinymce/5.1.1/plugins/textcolor/plugin.js
JavaScript
mit
650
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using ZSUIFramework; public class CreatRoomGUI : ZSUI { public Button mBtnClose = null; public override void Init() { ZSUIListener.AddClickEvent( mBtnClose.gameObject, Close ); } }
zhanshu233/ZSUIFramework
Assets/Example/Scripts/UI/CreatRoomGUI.cs
C#
mit
293
export {NavbarItemComponent} from './navbar-item/navbar-item.component'; export {NavbarComponent} from './navbar.component';
Hertox82/Lortom
angular-backend/src/app/backend-module/navbar/index.ts
TypeScript
mit
125
# frozen_string_literal: true module DropletKit class AccountMapping include Kartograph::DSL kartograph do root_key singular: 'account', scopes: [:read] mapping Account scoped :read do property :droplet_limit property :floating_ip_limit property :email property :uuid property :email_verified end end end end
digitalocean/droplet_kit
lib/droplet_kit/mappings/account_mapping.rb
Ruby
mit
392
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-07 00:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payments', '0004_auto_20160904_0048'), ] operations = [ migrations.AlterField( model_name='subscription', name='status', field=models.CharField(choices=[('new', 'Created'), ('unconfirmed', 'Waiting for payment'), ('active', 'Active'), ('cancelled', 'Cancelled'), ('error', 'Error')], default='new', max_length=16), ), ]
CCrypto/ccvpn3
payments/migrations/0005_auto_20160907_0018.py
Python
mit
612
#!/usr/bin/python import requests import json # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields user_title = form.getvalue('search_title') print "Content-type: text/html\n\n"; # Setting attributes to send to Wikipedia API baseurl = 'http://en.wikipedia.org/w/api.php' search_atts = {} search_atts['action'] = 'query' search_atts['list'] = 'search' search_atts['srwhat'] = 'text' search_atts['format'] = 'json' search_atts['srsearch'] = user_title search_resp = requests.get(baseurl, params = search_atts) search_data = search_resp.json() title = search_data["query"]["search"][0]["title"] # Make the title with no space which will be needed for making a url link to send for summary title_w_no_space = "" for i in title: if i==" ": title_w_no_space = title_w_no_space + "_" else: title_w_no_space = title_w_no_space + i # Getting related topics using the result given by Wikipedia API topics = [] for key in search_data["query"]["search"]: topics.append (key["title"]) topics = topics [1:len(topics)] # Summarizing the content: # setting attributes for to send to Smmry API link_for_smmry = 'https://en.wikipedia.org/wiki/' + title_w_no_space smmry_base_url = 'http://api.smmry.com/' #smmry_atts = {} #smmry_atts ['SM_URL'] = 'https://en.wikipedia.org/wiki/Guyana' #smmry_atts ['SM_API_KEY'] = '6F297A53E3' # represents your registered API key. # Optional, X represents the webpage to summarize. #smmry_atts ['SM_LENGTH'] = N # Optional, N represents the number of sentences returned, default is 7 #smmry_atts ['SM_KEYWORD_COUNT'] = N # Optional, N represents how many of the top keywords to return #smmry_atts ['SM_QUOTE_AVOID'] # Optional, summary will not include quotations #smmry_atts ['SM_WITH_BREAK'] # Optional, summary will contain string [BREAK] between each sentence api_key_link = '&SM_API_KEY=9B07893CAD&SM_URL=' api_lenght = 'SM_LENGTH=7&SM_WITH_BREAK' #print api_key_link api_link = smmry_base_url + api_lenght + api_key_link + link_for_smmry #smmry_resp = requests.get('http://api.smmry.com/&SM_API_KEY=6F297A53E3&SM_URL=https://en.wikipedia.org/wiki/Guyana') smmry_resp = requests.get(api_link) smmry_data = smmry_resp.json() content= '<p>Try adding another key word.</p><a style="color:white;" id="backbtn" href="#" onclick="myFunction()" >Go back.</a>' try: content = smmry_data['sm_api_content'] except: pass content_with_non_ascii = "" for word in content: if ord(word) < 128: content_with_non_ascii+=word else: content_with_non_ascii+= "?" if len(content_with_non_ascii) >0: content = content_with_non_ascii # replacing "[BREAK]"s with a new line while "[BREAK]" in content: length = len (content) break_position = content.find("[BREAK]") content = content [0:break_position] + "<br><br>" + content [break_position+7: length] print '<div id="all-cont-alt"><div class="select-nav"><div id="nav-top-main"><a id="backbtn" href="#" onclick="myFunction()" ><i style="float:left; position: relative;margin-left: 10px;top: 26px; color: #d8d8d8;" class= "fa fa-chevron-left fa-2x"></i></a><h1>Geddit</h1></div></div>' print '<div id="loaddddd"></div><div id="contentss">' print '<h1 id="user-title">' print user_title print "</h1>" print content print "</div></div>"
azimos/geddit
old/geddit-backend.py
Python
mit
3,469
/* Copyright (c) 2013 Chris Wraith 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. */ package com.minorityhobbies.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; public class URLUtils { private URLUtils() { } /** * Useful for other classes which require a {@link URL} as a parameter. This * method allows a URL to be generated from a String. * * @param urlFilename * The filename to use for this URL. Can be anything. * @param content * The payload for this URL. This will be returned when you call * url.openStream() and read the data. * @return The URL backed by the specified content with the specified name. */ public static URL getStringBackedUrl(String urlFilename, String content) { return getStreamBackedUrl(urlFilename, new ByteArrayInputStream(content.getBytes())); } public static URL getStreamBackedUrl(String urlFilename, final InputStream content) { try { return new URL("bytes", "", 0, urlFilename, new URLStreamHandler() { @Override protected URLConnection openConnection(final URL url) throws IOException { return new URLConnection(url) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { return content; } }; } }); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public static String readUrlData(URL url) throws IOException { URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); if (in == null) { return null; } byte[] b = new byte[1024 * 64]; StringBuilder data = new StringBuilder(); for (int read = 0; (read = in.read(b)) > -1;) { data.append(new String(b, 0, read)); } return data.toString(); } }
jacksonps4/jutils
src/main/java/com/minorityhobbies/util/URLUtils.java
Java
mit
2,996
#region Usings using System; using Xunit; #endregion namespace Extend.Testing { public partial class StringExTest { [Fact] public void SubstringLeftSafeTest() { var actual = "testabc".SubstringLeftSafe( 4 ); Assert.Equal( "test", actual ); actual = "testabc".SubstringLeftSafe( 400 ); Assert.Equal( "testabc", actual ); actual = "".SubstringLeftSafe( 4 ); Assert.Equal( "", actual ); } [Fact] public void SubstringLeftSafeTest1() { var actual = "123test123".SubstringLeftSafe( 3, 4 ); Assert.Equal( "test", actual ); actual = "testabc".SubstringLeftSafe( 0, 400 ); Assert.Equal( "testabc", actual ); actual = "123tes".SubstringLeftSafe( 3, 4 ); Assert.Equal( "tes", actual ); actual = "".SubstringLeftSafe( 0, 4 ); Assert.Equal( "", actual ); actual = "".SubstringLeftSafe( 2, 4 ); Assert.Equal( "", actual ); } [Fact] public void SubstringLeftSafeTest1NullCheck() { // ReSharper disable once AssignNullToNotNullAttribute // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Action test = () => StringEx.SubstringLeftSafe( null, 1, 5 ); Assert.Throws<ArgumentNullException>( test ); } [Fact] public void SubstringLeftSafeTestNullCheck() { // ReSharper disable once AssignNullToNotNullAttribute // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Action test = () => StringEx.SubstringLeftSafe( null, 5 ); Assert.Throws<ArgumentNullException>( test ); } } }
DaveSenn/Extend
.Src/Extend.Testing/System.String/String.SubstringLeftSafe.Test.cs
C#
mit
1,814
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("PrintFirstAndLastName")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PrintFirstAndLastName")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("944423f7-a369-48ac-9b54-3b94dba73ae6")] // 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")]
BiserSirakov/TelerikAcademyHomeworks
C# - Part 1/Intro-Programming-Homework/04.PrintFirstAndLastName/Properties/AssemblyInfo.cs
C#
mit
1,418
// # Demo Particles 011 // Tracer entity: generation and functionality // [Run code](../../demo/particles-011.html) import * as scrawl from '../source/scrawl.js' import { reportSpeed } from './utilities.js'; // Get Scrawl-canvas to recognise and act on device pixel ratios greater than 1 scrawl.setIgnorePixelRatio(false); // #### Scene setup let canvas = scrawl.library.artefact.mycanvas; canvas.setBase({ backgroundColor: 'aliceblue', }); // Define some filters scrawl.makeFilter({ name: 'grayscale', method: 'grayscale', }).clone({ name: 'invert', method: 'invert', }); scrawl.makeFilter({ name: 'tint', method: 'tint', redInRed: 0.5, redInGreen: 1, redInBlue: 0.9, greenInRed: 0, greenInGreen: 0.3, greenInBlue: 0.8, blueInRed: 0.8, blueInGreen: 0.8, blueInBlue: 0.4, }); scrawl.makeFilter({ name: 'matrix', method: 'matrix', weights: [-1, -1, 0, -1, 1, 1, 0, 1, 1], }); // Create a Shape entity to act as a path for our Tracer entitys scrawl.makeShape({ name: 'my-arrow', pathDefinition: 'M266.2,703.1 h-178 L375.1,990 l287-286.9 H481.9 C507.4,365,683.4,91.9,911.8,25.5 877,15.4,840.9,10,803.9,10 525.1,10,295.5,313.4,266.2,703.1 z', start: ['center', 'center'], handle: ['center', 'center'], scale: 0.4, roll: -70, flipUpend: true, useAsPath: true, strokeStyle: 'gray', fillStyle: 'lavender', lineWidth: 8, method: 'fillThenDraw', bringToFrontOnDrag: false, }); // #### Particle physics animation scene // Tracer entitys don't have any color control built in; we need to create our own color factory let colorFactory = scrawl.makeColor({ name: 'tracer-3-color-factory', minimumColor: 'red', maximumColor: 'blue', }); // Create a Tracer entity // + Note that Tracers do not require a World object, cannot process Force objects, and cannot be connected together using Spring objects. scrawl.makeTracer({ name: 'trace-1', historyLength: 50, // We will delta-animate this Tracer alonbg the path of our Shape entity path: 'my-arrow', pathPosition: 0, lockTo: 'path', delta: { pathPosition: 0.002, }, artefact: scrawl.makeWheel({ name: 'burn-1', radius: 6, handle: ['center', 'center'], fillStyle: 'red', method: 'fill', visibility: false, noUserInteraction: true, noPositionDependencies: true, noFilters: true, noDeltaUpdates: true, }), // This Tracer will produce a 'dashed' effect, by displaying discrete ranges of its history stampAction: function (artefact, particle, host) { let history = particle.history, remaining, z, start; history.forEach((p, index) => { if (index < 10 || (index > 20 && index < 30) || index > 40) { [remaining, z, ...start] = p; artefact.simpleStamp(host, { start }); } }); }, // Clone the Tracer entity }).clone({ name: 'trace-2', pathPosition: 0.33, artefact: scrawl.library.artefact['burn-1'].clone({ name: 'burn-2', fillStyle: 'green', globalAlpha: 0.2, }), // Our second Tracer shows a 'tail-fade' effect stampAction: function (artefact, particle, host) { let history = particle.history, len = history.length, remaining, z, start; history.forEach((p, index) => { if (index % 3 === 0) { [remaining, z, ...start] = p; artefact.simpleStamp(host, { start, globalAlpha: (len - index) / len, }); } }); }, // Clone the second Tracer entity }).clone({ name: 'trace-3', pathPosition: 0.67, artefact: scrawl.library.artefact['burn-1'].clone({ name: 'burn-3', fillStyle: 'blue', }), // This Tracer varies its scale to create a 'teardrop' effect stampAction: function (artefact, particle, host) { let history = particle.history, len = history.length, remaining, z, start; history.forEach((p, index) => { [remaining, z, ...start] = p; let magicNumber = (len - index) / len; artefact.simpleStamp(host, { start, scale: magicNumber * 3, fillStyle: colorFactory.getRangeColor(magicNumber), }); }); }, }); // #### Scene animation // Function to display frames-per-second data, and other information relevant to the demo const report = reportSpeed('#reportmessage'); // Create the Display cycle animation scrawl.makeRender({ name: 'demo-animation', target: canvas, afterShow: report, }); // #### User interaction // Make the arrow draggable // + KNOWN BUG - the arrow is not draggable on first user mousedown, but is draggable afterwards scrawl.makeGroup({ name: 'my-draggable-group', }).addArtefacts('my-arrow'); scrawl.makeDragZone({ zone: canvas, collisionGroup: 'my-draggable-group', endOn: ['up', 'leave'], preventTouchDefaultWhenDragging: true, }); // Action user choice to apply a filter to a Tracer entity const filterChoice = function (e) { e.preventDefault(); e.returnValue = false; let val = e.target.value, entity = scrawl.library.entity['trace-2']; entity.clearFilters(); if (val) entity.addFilters(val); }; scrawl.addNativeListener(['input', 'change'], filterChoice, '#filter'); // @ts-expect-error document.querySelector('#filter').value = ''; // #### Development and testing console.log(scrawl.library);
KaliedaRik/Scrawl-canvas
demo/particles-011.js
JavaScript
mit
5,771
'use strict'; /** * Module dependencies. */ const express = require('express'); const session = require('express-session'); const compression = require('compression'); const morgan = require('morgan'); const cookieParser = require('cookie-parser'); const cookieSession = require('cookie-session'); const bodyParser = require('body-parser'); const methodOverride = require('method-override'); const upload = require('multer')(); const mongoStore = require('connect-mongo')(session); const flash = require('connect-flash'); const winston = require('winston'); const helpers = require('view-helpers'); const config = require('./'); const pkg = require('../package.json'); const env = process.env.NODE_ENV || 'development'; /** * Expose */ module.exports = function (app) { // Compression middleware (should be placed before express.static) app.use(compression({ threshold: 512 })); // Static files middleware app.use(express.static(config.root + '/public')); // Use winston on production let log = 'dev'; if (env !== 'development') { log = { stream: { write: message => winston.info(message) } }; } // Don't log during tests // Logging middleware if (env !== 'test') app.use(morgan(log)); // set views path, template engine and default layout app.set('views', config.root + '/app/views'); app.set('view engine', 'jade'); // expose package.json to views app.use(function (req, res, next) { res.locals.pkg = pkg; res.locals.env = env; next(); }); // bodyParser should be above methodOverride app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.single('image')); app.use(methodOverride(function (req) { if (req.body && typeof req.body === 'object' && '_method' in req.body) { // look in urlencoded POST bodies and delete it var method = req.body._method; delete req.body._method; return method; } })); // CookieParser should be above session app.use(session({ resave: false, saveUninitialized: true, secret: pkg.name, cookie: { maxAge: 3600 * 24 * 365 * 1000 }, store: new mongoStore({ url: config.db, collection : 'sessions' }) })); app.use(cookieParser()); // app.use(cookieSession({ secret: 'accedotv' })); // connect flash for flash messages - should be declared after sessions app.use(flash()); // should be declared after session and flash app.use(helpers(pkg.name)); if (env === 'development') { app.locals.pretty = true; } };
kyue1005/accedotv-demo
config/express.js
JavaScript
mit
2,588
namespace Nancy.Serialization.ServiceStack { using System.Collections.Generic; using System.IO; using global::ServiceStack.Text; using Responses.Negotiation; public class ServiceStackJsonSerializer : ISerializer { /// <summary> /// Whether the serializer can serialize the content type /// </summary> /// <param name="mediaRange">Content type to serialise</param> /// <returns>True if supported, false otherwise</returns> public bool CanSerialize(MediaRange mediaRange) { return Helpers.IsJsonType(mediaRange); } /// <summary> /// Gets the list of extensions that the serializer can handle. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value> public IEnumerable<string> Extensions { get { yield return "json"; } } /// <summary> /// Serialize the given model with the given contentType /// </summary> /// <param name="mediaRange">Content type to serialize into</param> /// <param name="model">Model to serialize</param> /// <param name="outputStream">Output stream to serialize to</param> /// <returns>Serialised object</returns> public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream) { JsonSerializer.SerializeToStream(model, outputStream); } } }
NancyFx/Nancy.Serialization.ServiceStack
src/Nancy.Serialization.ServiceStack/ServiceStackJsonSerializer.cs
C#
mit
1,570
/* * Copyright (c) 2017-2019 by Botorabi. All rights reserved. * https://github.com/botorabi/Meet4Eat * * License: MIT License (MIT), read the LICENSE text in * main directory for more details. */ package net.m4e.update.rest.comm; import org.junit.jupiter.api.*; import javax.json.bind.*; import java.time.Instant; import static org.assertj.core.api.Assertions.assertThat; /** * @author boto * Date of creation March 12, 2018 */ public class UpdateCheckResultTest { private final String UPDATE_VERSION = "1.0.0"; private final String OS = "Win"; private final String URL = "https://update.org"; private final Long RELEASE_DATE = Instant.now().toEpochMilli(); private Jsonb json; @BeforeEach void setup() { json = JsonbBuilder.create(); } @Test void serialize() { UpdateCheckResult result = new UpdateCheckResult(); result.setUpdateVersion(UPDATE_VERSION); result.setOs(OS); result.setUrl(URL); result.setReleaseDate(RELEASE_DATE); String jsonString = json.toJson(result); assertThat(jsonString).contains("updateVersion"); assertThat(jsonString).contains("os"); assertThat(jsonString).contains("url"); assertThat(jsonString).contains("releaseDate"); } @Test void deserialize() { String jsonString = json.toJson(new UpdateCheckResult(UPDATE_VERSION, OS, URL, RELEASE_DATE)); UpdateCheckResult result = json.fromJson(jsonString, UpdateCheckResult.class); assertThat(result.getUpdateVersion()).isEqualTo(UPDATE_VERSION); assertThat(result.getOs()).isEqualTo(OS); assertThat(result.getUrl()).isEqualTo(URL); assertThat(result.getReleaseDate()).isEqualTo(RELEASE_DATE); } }
botorabi/Meet4Eat
src/test/java/net/m4e/update/rest/comm/UpdateCheckResultTest.java
Java
mit
1,790
#!/usr/bin/env python import os import sys from setuptools import setup os.system('make rst') try: readme = open('README.rst').read() except FileNotFoundError: readme = "" setup( name='leicaautomator', version='0.0.2', description='Automate scans on Leica SPX microscopes', long_description=readme, author='Arve Seljebu', author_email='arve.seljebu@gmail.com', url='https://github.com/arve0/leicaautomator', packages=[ 'leicaautomator', ], package_dir={'leicaautomator': 'leicaautomator'}, include_package_data=True, install_requires=[ 'scipy', 'numpy', 'matplotlib', 'scikit-image', 'leicascanningtemplate', 'leicacam', 'leicaexperiment', 'microscopestitching', 'dask[bag]', 'numba', ], license='MIT', zip_safe=False, keywords='leicaautomator', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
arve0/leicaautomator
setup.py
Python
mit
1,212
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Class Jwt * jwt加密类 */ class Jwt { /** * @var int */ public static $leeway = 0; /** * @var null */ public static $timestamp = null; /** * @var array */ public static $supported_algs = array( 'HS256' => array('hash_hmac', 'SHA256'), 'HS512' => array('hash_hmac', 'SHA512'), 'HS384' => array('hash_hmac', 'SHA384'), 'RS256' => array('openssl', 'SHA256'), ); /** * @param $jwt * @param $key * @param array $allowed_algs * @return mixed */ public function decode($jwt, $key, $allowed_algs = array('HS256')) { $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp; if (empty($key)) { throw new InvalidArgumentException('密钥不能为空');//Key may not be empty } if (!is_array($allowed_algs)) { throw new InvalidArgumentException('算法不允许');//Algorithm not allowed } $tks = explode('.', $jwt); if (count($tks) != 3) { throw new UnexpectedValueException('错误的段数');//Wrong number of segments } list($headb64, $bodyb64, $cryptob64) = $tks; if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) { throw new UnexpectedValueException('无效的header编码');//Invalid encoding } if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) { throw new UnexpectedValueException('无效的claims编码');//Invalid claims encoding } $sig = static::urlsafeB64Decode($cryptob64); if (empty($header->alg)) { throw new UnexpectedValueException('alg是空的');//Empty algorithm } if (empty(static::$supported_algs[$header->alg])) { throw new UnexpectedValueException('算法不支持');//Algorithm not supported } if (!in_array($header->alg, $allowed_algs)) { throw new UnexpectedValueException('算法不允许');//Algorithm not allowed } if (is_array($key) || $key instanceof \ArrayAccess) { if (isset($header->kid)) { $key = $key[$header->kid]; } else { throw new UnexpectedValueException('"kid"空,无法查找正确的密钥');//"kid" empty, unable to lookup correct key } } // Check the signature 签名验证失败 if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { throw new UnexpectedValueException('签名验证失败');//Signature verification failed } // if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) { // throw new UnexpectedValueException( // 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf) // ); // } // // if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) { // throw new UnexpectedValueException( // 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat) // ); // } // Check if this token has expired.过期令牌 if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { throw new UnexpectedValueException('过期令牌');//Expired token } return $payload; } /** * @param $msg * @param $signature * @param $key * @param $alg * @return bool */ private static function verify($msg, $signature, $key, $alg) { if (empty(static::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = static::$supported_algs[$alg]; switch($function) { case 'openssl': $success = openssl_verify($msg, $signature, $key, $algorithm); if (!$success) { throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string()); } else { return $signature; } case 'hash_hmac': default: $hash = hash_hmac($algorithm, $msg, $key, true); if (function_exists('hash_equals')) { return hash_equals($signature, $hash); } $len = min(static::safeStrlen($signature), static::safeStrlen($hash)); $status = 0; for ($i = 0; $i < $len; $i++) { $status |= (ord($signature[$i]) ^ ord($hash[$i])); } $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash)); return ($status === 0); } } /** * @param $input * @return mixed */ public static function jsonDecode($input) { if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you * to specify that large ints (like Steam Transaction IDs) should be treated as * strings, rather than the PHP default behaviour of converting them to floats. */ $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING); } else { /** Not all servers will support that, however, so for older versions we must * manually detect large ints in the JSON string and quote them (thus converting *them to strings) before decoding, hence the preg_replace() call. */ $max_int_length = strlen((string) PHP_INT_MAX) - 1; $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input); $obj = json_decode($json_without_bigints); } if (function_exists('json_last_error') && $errno = json_last_error()) { static::handleJsonError($errno); } elseif ($obj === null && $input !== 'null') { throw new DomainException('Null result with non-null input'); } return $obj; } /** * @param $input * @return bool|string */ public static function urlsafeB64Decode($input) { $remainder = strlen($input) % 4; if ($remainder) { $padlen = 4 - $remainder; $input .= str_repeat('=', $padlen); } return base64_decode(strtr($input, '-_', '+/')); } /** * @param $str * @return int */ private static function safeStrlen($str) { if (function_exists('mb_strlen')) { return mb_strlen($str, '8bit'); } return strlen($str); } /** * @param $payload * @param $key * @param string $alg * @param null $keyId * @param null $head * @return string */ public function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) { $header = array('typ' => 'JWT', 'alg' => $alg); if ($keyId !== null) { $header['kid'] = $keyId; } if ( isset($head) && is_array($head) ) { $header = array_merge($head, $header); } $segments = array(); $segments[] = static::urlsafeB64Encode(static::jsonEncode($header)); $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload)); $signing_input = implode('.', $segments); $signature = static::sign($signing_input, $key, $alg); $segments[] = static::urlsafeB64Encode($signature); return implode('.', $segments); } /** * @param $msg * @param $key * @param string $alg * @return string */ public static function sign($msg, $key, $alg = 'HS256') { if (empty(static::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = static::$supported_algs[$alg]; switch($function) { case 'hash_hmac': return hash_hmac($algorithm, $msg, $key, true); case 'openssl': $signature = ''; $success = openssl_sign($msg, $signature, $key, $algorithm); if (!$success) { throw new DomainException("OpenSSL unable to sign data"); } else { return $signature; } } } /** * @param $input * @return string */ public static function jsonEncode($input) { $json = json_encode($input); if (function_exists('json_last_error') && $errno = json_last_error()) { static::handleJsonError($errno); } elseif ($json === 'null' && $input !== null) { throw new DomainException('Null result with non-null input'); } return $json; } /** * @param $input * @return mixed */ public static function urlsafeB64Encode($input) { return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); } /** * Helper method to create a JSON error. * @param int $errno An error number from json_last_error() * @return void */ private static function handleJsonError($errno) { $messages = array( JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON' ); throw new DomainException( isset($messages[$errno]) ? $messages[$errno] : 'Unknown JSON error: ' . $errno ); } }
wuanlife/wuanlife_api
application/libraries/Jwt.php
PHP
mit
9,916
/* * The MIT License * * Copyright (c) 2019, CloudBees, Inc. * * 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. */ package hudson.plugins.groovy; import hudson.util.FormValidation; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; public class StringScriptSourceTest { @Rule public JenkinsRule j = new JenkinsRule(); @Issue("SECURITY-1293") @Test public void blockASTTest() throws Exception { StringScriptSource.DescriptorImpl d = j.jenkins.getDescriptorByType(StringScriptSource.DescriptorImpl.class); assertThat(d.doCheckScript("import groovy.transform.*\n" + "import jenkins.model.Jenkins\n" + "import hudson.model.FreeStyleProject\n" + "@ASTTest(value={ assert Jenkins.getInstance().createProject(FreeStyleProject.class, \"should-not-exist\") })\n" + "@Field int x\n" + "echo 'hello'\n").toString(), containsString("Annotation ASTTest cannot be used in the sandbox")); assertNull(j.jenkins.getItem("should-not-exist")); } @Issue("SECURITY-1293") @Test public void blockGrab() throws Exception { StringScriptSource.DescriptorImpl d = j.jenkins.getDescriptorByType(StringScriptSource.DescriptorImpl.class); assertThat(d.doCheckScript("@Grab(group='foo', module='bar', version='1.0')\ndef foo\n").toString(), containsString("Annotation Grab cannot be used in the sandbox")); } @Issue("SECURITY-1338") @Test public void doNotExecuteConstructors() throws Exception { StringScriptSource.DescriptorImpl d = j.jenkins.getDescriptorByType(StringScriptSource.DescriptorImpl.class); assertThat(d.doCheckScript("class DoNotRunConstructor {\n" + " static void main(String[] args) {}\n" + " DoNotRunConstructor() {\n" + " assert jenkins.model.Jenkins.instance.createProject(hudson.model.FreeStyleProject, 'should-not-exist')\n" + " }\n" + "}\n").kind, equalTo(FormValidation.Kind.OK)); // Compilation ends before the constructor is invoked. assertNull(j.jenkins.getItem("should-not-exist")); } }
jenkinsci/groovy-plugin
src/test/java/hudson/plugins/groovy/StringScriptSourceTest.java
Java
mit
3,461
<aside id="featured" class="body"> <article> <figure> <img src="img/logo/<?= $prj->slug ?>.png" alt="<?= sprintf(_('Project’s logo for %s'), $prj->name) ?>" /> </figure> <hgroup> <h2><?= $prj->name ?></h2> <h3><?= $prj->short ?></h3> </hgroup> <p><?= Malenki\Ruche\Util\RichText::getFormated($prj->description) ?></p> </article> </aside> <section id="content" class="body"> <?php if(count($mls)): ?> <ol id="posts-list" class="hfeed"> <?php foreach($mls as $m): ?> <li> <article class="hentry"> <header> <h2 class="entry-title"><a href="/project/<?= $prj->slug ?>/roadmap/<?= $m->id ?>" rel="bookmark" title="Permalink to this <?= $m->name ?>"><?= $m->name ?></a></h2> </header> <footer class="post-info"> <abbr class="published" title="<?= $m->ttd ?>"> <?= $m->ttd ?> </abbr> <!-- à faire --> <address class="vcard author"> Par <a class="url fn" href="#">Michel Petit</a> </address> </footer> <div class="entry-content"> <p><?= $m->description ?></p> </div> </article> </li> <?php endforeach; ?> </ol> <?php else: ?> <p><a href="#"><?= _('No milestone defined. You can create one now') ?></a></p> <?php endif; ?> </section> <section id="extras" class="body"> <!-- Cette liste correspondra aux événements, sera mise à jour via Ajax, une ligne par événement --> <div class="activityroll"> <h2>Activité</h2> <ul> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Aujourd’hui à 20h10</abbr> Révision <strong class="revision">[3045]</strong> par <strong class="author">Malenki</strong> <em>Corrige un test foireux</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Aujourd’hui à 18h20</abbr> Le ticket <strong class="ticket">#745</strong> a été créé par <strong class="author">Elvis</strong> <em>La génération de page échoue sur Windows Vista avec PHP 5.3</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Aujourd’hui à 14h30</abbr> Le ticket <strong class="ticket">#744</strong> a été créé par <strong class="author">Malenki</strong> <em>Créer de nouvelles entrées dans le fichier de configuration</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-19T22:54:45+01:00">Hier à 22h54</abbr> Révision <strong class="revision">[3044]</strong> par <strong class="author">Elvis</strong> <em>Windows sucks, alors j’ai mis en place un hack…</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Hier à 20h02</abbr> Nouveau commentaire sur <strong class="ticket">#653</strong> par <strong class="author">Malenki</strong> <em>Serait-il possible d’utiliser la bibliothèque Yaml de Symfony pour…</em></a></li> </ul> </div> </section>
malenkiki/reine
templates/WebProjectsShow.php
PHP
mit
3,223
class Solution { public: vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) { vector<int> result; int i = arr1.size() - 1, j = arr2.size() - 1, carry = 0; while (i >= 0 || j >= 0 || carry) { int s = carry; if (i >= 0) { s += arr1[i--]; } if (j >= 0) { s += arr2[j--]; } result.push_back(s & 1); carry = -(s >> 1); } while (result.size() > 1 && result.back() == 0) { result.pop_back(); } reverse(result.begin(), result.end()); return result; } };
jiadaizhao/LeetCode
1001-1100/1073-Adding Two Negabinary Numbers/1073-Adding Two Negabinary Numbers.cpp
C++
mit
660
"""Forms of the aps_bom app.""" from csv import DictReader from django import forms from django.core.urlresolvers import reverse from django.utils.translation import ugettext as __ from .models import BOM, BOMItem, CBOM, CBOMItem, EPN, IPN, Unit class BaseUploadForm(forms.ModelForm): csv_file = forms.FileField() def append_error(self, error_message, field="__all__"): if field in self.errors: self.errors[field].append(error_message) else: self.errors[field] = [error_message] def clean(self): cleaned_data = super(BaseUploadForm, self).clean() # don't do anything with the file if there are errors already if any(self.errors): return cleaned_data if self.Meta.model == CBOM: self.company = self.cleaned_data['customer'] # initiate the csv dictreader with the uploaded file temp_csv_file = self.files.get('csv_file') with open(temp_csv_file.temporary_file_path(), 'rU') as csv_file: self.reader = DictReader(csv_file) self.clean_lines() return cleaned_data def clean_lines(self): # update the fieldnames to match the ones on the model new_names = [] for fieldname in self.reader.fieldnames: new_names.append(fieldname.lower()) self.reader.fieldnames = new_names # iterate over the lines and clean the values self.clean_lines = [] for line_dict in self.reader: for key, value in line_dict.iteritems(): # strip blank spaces value = value.strip() line_dict[key] = value if key == 'consign': if value == '0': value = False else: value = True line_dict[key] = value if key == 'ipn': try: ipn = IPN.objects.get(code=value) except IPN.DoesNotExist: this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_ipn_add'))) self.append_error(__( 'The ipn "{0}" does not exist.' ' Please create it first. {1}'.format( value, this_link))) except IPN.MultipleObjectsReturned: # TODO temporary workaround self.append_error(__( 'There are multiple entries for the IPN "{0}".' ' Please resolve this error before' ' uploading.'.format(value)), field='ipn') else: line_dict[key] = ipn if key == 'unit': try: unit = Unit.objects.get(code=value) except Unit.DoesNotExist: this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_unit_add'))) self.append_error(__( 'The unit "{0}" does not exist.' ' Please create it first. {1}'.format( value, this_link))) else: line_dict[key] = unit if key == 'epn': try: epn = EPN.objects.get(epn=value, company=self.company) except EPN.DoesNotExist: epn = EPN.objects.create( description=line_dict.get('description'), epn=value, company=self.company) this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_epn_change', args=(epn.id, )))) self.append_error(__( 'The EPN "{0}" does not exist.' ' Please visit {1} to update it and then' ' re-upload the file.'.format( value, this_link))) else: if epn.ipn is None or epn.cpn is None: this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_epn_change', args=(epn.id, )))) self.append_error(__( 'The EPN "{0}" does not have all the' ' required data.' ' Please visit {1} to update it and then' ' re-upload the file.'.format( value, this_link))) else: line_dict[key] = epn if key == 'shape': pass line_dict.pop('description') if 'shape' in line_dict: line_dict.pop('shape') self.clean_lines.append(line_dict) return self.clean_lines class BOMUploadForm(BaseUploadForm): """Custom ModelForm, that handles the upload for BOM.csv files.""" def __init__(self, *args, **kwargs): super(BOMUploadForm, self).__init__(*args, **kwargs) self.fields['ipn'].required = True def save(self): instance = super(BOMUploadForm, self).save() for bomitemdict in self.clean_lines: bomitemdict.update({'bom': instance}) BOMItem.objects.create(**bomitemdict) return instance class Meta: model = BOM fields = ['description', 'ipn'] class CBOMUploadForm(BaseUploadForm): """Custom ModelForm, that handles the upload for cBOM.csv files.""" def save(self): instance = super(CBOMUploadForm, self).save() for cbomitemdict in self.clean_lines: cbomitemdict.update({'bom': instance}) CBOMItem.objects.create(**cbomitemdict) return instance class Meta: model = CBOM fields = [ 'customer', 'description', 'html_link', 'product', 'version_date']
bitmazk/django-aps-bom
aps_bom/forms.py
Python
mit
6,549
class RenameBillingPeriodReferences < ActiveRecord::Migration def up rename_column :billing_schedules, :billing_period_id, :billing_period_range_id rename_column :bills, :billing_period_id, :billing_period_range_id end def down rename_column :billing_schedules, :billing_period_range_id, :billing_period_id rename_column :bills, :billing_period_range_id, :billing_period_id end end
jbrowning/billy
db/migrate/20130305040107_rename_billing_period_references.rb
Ruby
mit
407
require "test_helper" class CrossCrusadeOverallTest < ActiveSupport::TestCase def test_recalc_with_no_series competition_count = Competition.count CrossCrusadeOverall.calculate! CrossCrusadeOverall.calculate!(2007) assert_equal(competition_count, Competition.count, "Should add no new Competition if there are no Cross Crusade events") end def test_recalc_with_one_event series = Series.create!(:name => "Cross Crusade") event = series.children.create!(:date => Date.new(2007, 10, 7), :name => "Cross Crusade #4") series.children.create!(:date => Date.new(2007, 10, 14)) series.children.create!(:date => Date.new(2007, 10, 21)) series.children.create!(:date => Date.new(2007, 10, 28)) series.children.create!(:date => Date.new(2007, 11, 5)) series.reload assert_equal(Date.new(2007, 10, 7), series.date, "Series date") cat_a = Category.find_or_create_by_name("Category A") cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 1, :person => people(:weaver)) cat_a_race.results.create!(:place => 9, :person => people(:tonkin)) masters_35_plus_women = Category.find_or_create_by_name("Masters Women 35+") masters_race = event.races.create!(:category => masters_35_plus_women) masters_race.results.create!(:place => 15, :person => people(:alice)) masters_race.results.create!(:place => 19, :person => people(:molly)) # Previous year should be ignored previous_event = Series.create!(:name => "Cross Crusade").children.create!(:date => Date.new(2006), :name => "Cross Crusade #3") previous_event.races.create!(:category => cat_a).results.create!(:place => 6, :person => people(:weaver)) # Following year should be ignored following_event = Series.create!(:name => "Cross Crusade").children.create!(:date => Date.new(2008)) following_event.races.create!(:category => cat_a).results.create!(:place => 10, :person => people(:weaver)) CrossCrusadeOverall.calculate!(2007) assert_not_nil(series.overall(true), "Should add new Overall Competition child to parent Series") overall = series.overall assert_equal(18, overall.races.size, "Overall races") CrossCrusadeOverall.calculate!(2007) assert_not_nil(series.overall(true), "Should add new Overall Competition child to parent Series") overall = series.overall assert_equal(18, overall.races.size, "Overall races") assert(!overall.notes.blank?, "Should have notes about rules") cx_a_overall_race = overall.races.detect { |race| race.category == cat_a } assert_not_nil(cx_a_overall_race, "Should have Men A overall race") assert_equal(2, cx_a_overall_race.results.size, "Men A race results") cx_a_overall_race.results(true).sort! result = cx_a_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "Men A first result place") assert_equal(26, result.points, "Men A first result points") assert_equal(people(:weaver), result.person, "Men A first result person") result = cx_a_overall_race.results.last assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("2", result.place, "Men A second result place") assert_equal(10, result.points, "Men A second result points (double points for last result)") assert_equal(people(:tonkin), result.person, "Men A second result person") masters_35_plus_women_overall_race = overall.races.detect { |race| race.category == masters_35_plus_women } assert_not_nil(masters_35_plus_women_overall_race, "Should have Masters Women overall race") assert_equal(1, masters_35_plus_women_overall_race.results.size, "Masters Women race results") result = masters_35_plus_women_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "Masters Women first result place") assert_equal(4, result.points, "Masters Women first result points (double points for last result)") assert_equal(people(:alice), result.person, "Masters Women first result person") end def test_many_results series = Series.create!(:name => "Cross Crusade") masters = Category.find_or_create_by_name("Masters 35+ A") category_a = Category.find_or_create_by_name("Category A") singlespeed = Category.find_or_create_by_name("Singlespeed") person = Person.create!(:name => "John Browning") event = series.children.create!(:date => Date.new(2008, 10, 5)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 10, 12)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 10, 19)) event.races.create!(:category => masters).results.create!(:place => 2, :person => person) event.races.create!(:category => category_a).results.create!(:place => 4, :person => person) event.races.create!(:category => singlespeed).results.create!(:place => 5, :person => person) event = series.children.create!(:date => Date.new(2008, 10, 26)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 2)) event.races.create!(:category => masters).results.create!(:place => 2, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 9)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event.races.create!(:category => category_a).results.create!(:place => 20, :person => person) event.races.create!(:category => singlespeed).results.create!(:place => 12, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 10)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 17)) event.races.create!(:category => masters).results.create!(:place => 3, :person => person) event.races.create!(:category => category_a).results.create!(:place => 20, :person => person) CrossCrusadeOverall.calculate!(2008) masters_overall_race = series.overall.races.detect { |race| race.category == masters } assert_not_nil(masters_overall_race, "Should have Masters overall race") masters_overall_race.results(true).sort! result = masters_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "place") assert_equal(6, result.scores.size, "Scores") assert_equal(26 + 26 + 0 + 26 + 0 + 26 + 26 + (16 * 2), result.points, "points") assert_equal(person, result.person, "person") category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "place") assert_equal(1, result.scores.size, "Scores") assert_equal(15, result.points, "points") assert_equal(person, result.person, "person") singlespeed_overall_race = series.overall.races.detect { |race| race.category == singlespeed } assert_not_nil(singlespeed_overall_race, "Should have Singlespeed overall race") assert(singlespeed_overall_race.results.empty?, "Should not have any singlespeed results") end def test_preliminary_results_after_event_minimum series = Series.create!(:name => "Cross Crusade") series.children.create!(:date => Date.new(2007, 10, 7)) series.children.create!(:date => Date.new(2007, 10, 14)) series.children.create!(:date => Date.new(2007, 10, 21)) series.children.create!(:date => Date.new(2007, 10, 28)) series.children.create!(:date => Date.new(2007, 11, 5)) cat_a = Category.find_or_create_by_name("Category A") cat_a_race = series.children[0].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 1, :person => people(:weaver)) cat_a_race.results.create!(:place => 2, :person => people(:tonkin)) cat_a_race = series.children[1].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 43, :person => people(:weaver)) cat_a_race = series.children[2].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 1, :person => people(:weaver)) cat_a_race = series.children[3].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 8, :person => people(:tonkin)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(false, result.preliminary?, "Weaver did three races. His result should not be preliminary") result = category_a_overall_race.results.last assert_equal(true, result.preliminary?, "Tonkin did only two races. His result should be preliminary") end def test_raced_minimum_events_boundaries series = Series.create!(:name => "Cross Crusade") cat_a = Category.find_or_create_by_name("Category A") molly = people(:molly) event = series.children.create!(:date => Date.new(2007, 10, 7)) # Molly does three races in different categories cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 6, :person => molly) single_speed_race = event.races.create!(:category => categories(:single_speed)) single_speed_race.results.create!(:place => 8, :person => molly) masters_women_race = event.races.create!(:category => categories(:masters_women)) masters_women_race.results.create!(:place => 10, :person => molly) cat_a_race.results.create!(:place => 17, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(!series.overall.raced_minimum_events?(molly, category_a_overall_race), "One event. No people have raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "One event. No people have raced minimum") event = series.children.create!(:date => Date.new(2007, 10, 14)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 14, :person => molly) cat_a_race.results.create!(:place => 6, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(!series.overall.raced_minimum_events?(molly, category_a_overall_race), "Two events. No people have raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "Two events. No people have raced minimum") event = series.children.create!(:date => Date.new(2007, 10, 21)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => "DNF", :person => molly) single_speed_race = event.races.create!(:category => categories(:single_speed)) single_speed_race.results.create!(:place => 8, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall(true).races.detect { |race| race.category == cat_a } assert(series.overall.raced_minimum_events?(molly, category_a_overall_race), "Three events. Molly has raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "Three events. Alice has not raced minimum") event = series.children.create!(:date => Date.new(2007, 10, 28)) cat_a_race = event.races.create!(:category => cat_a) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(series.overall.raced_minimum_events?(molly, category_a_overall_race), "Four events. Molly has raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "Four events. Alice has not raced minimum") end def test_minimum_events_should_handle_results_without_person series = Series.create!(:name => "Cross Crusade") cat_a = Category.find_or_create_by_name("Category A") event = series.children.create!(:date => Date.new(2007, 10, 7)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 17) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(!series.overall.raced_minimum_events?(nil, category_a_overall_race), "Nil person should never have mnimum events") end def test_count_six_best_results series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") person = Person.create!(:name => "Kevin Hulick") date = Date.new(2008, 10, 19) [8, 3, 10, 7, 8, 7, 8].each do |place| series.children.create!(:date => date).races.create!(:category => category_a).results.create!(:place => place, :person => person) date = date + 7 end # Simulate 7 of 8 events. Last, double-point event still in future series.children.create!(:date => date).races.create!(:category => category_a) CrossCrusadeOverall.calculate!(2008) category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(6, result.scores.size, "Scores") assert_equal(16 + 12 + 12 + 11 + 11 + 11, result.points, "points") end def test_choose_best_results_by_points_not_place series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") person = Person.create!(:name => "Kevin Hulick") date = Date.new(2008, 10, 19) [8, 8, 8, 7, 6, 8, 7, 9].each do |place| series.children.create!(:date => date).races.create!(:category => category_a).results.create!(:place => place, :person => person) date = date + 7 end CrossCrusadeOverall.calculate!(2008) category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(6, result.scores.size, "Scores") assert_equal(11 + 12 + 13 + 11 + 12 + 20, result.points, "points") end def test_ensure_dnf_sorted_correctly series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") person = Person.create!(:name => "Kevin Hulick") date = Date.new(2008, 10, 19) [8, 3, 10, "DNF", 8, 7, 8].each do |place| series.children.create!(:date => date).races.create!(:category => category_a).results.create!(:place => place, :person => person) date = date + 7 end # Simulate 7 of 8 events. Last, double-point, event, still in future series.children.create!(:date => date).races.create!(:category => category_a) CrossCrusadeOverall.calculate!(2008) category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(6, result.scores.size, "Scores") assert_equal(16 + 12 + 11 + 11 + 11 + 9, result.points, "points") end def test_ignore_age_graded_bar series = Series.create!(:name => "Cross Crusade") cat_a = Category.find_or_create_by_name("Category A") series.children.create!(:date => Date.new(2007, 10, 7)) event = series.children.create!(:date => Date.new(2007, 10, 14)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 17, :person => people(:alice)) age_graded_race = AgeGradedBar.create!(:name => "Age Graded Results for BAR/Championships").races.create!(:category => cat_a) age_graded_race.results.create!(:place => 1, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert_equal(1, category_a_overall_race.results.size, "Cat A results") assert_equal(1, category_a_overall_race.results.first.scores.size, "Should ignore age-graded BAR") end def test_should_not_count_for_bar_nor_ironman series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") series.children.create!(:date => Date.new(2008)).races.create!(:category => category_a).results.create!(:place => "4", :person => people(:tonkin)) CrossCrusadeOverall.calculate!(2008) series.reload overall_results = series.overall assert(!overall_results.ironman, "Ironman") assert_equal(0, overall_results.bar_points, "BAR points") category_a_overall_race = overall_results.races.detect { |race| race.category == category_a } assert_equal(0, category_a_overall_race.bar_points, "Race BAR points") end end
alpendergrass/montanacycling-racing_on_rails
test/unit/competitions/cross_crusade_overall_test.rb
Ruby
mit
17,950
package api import ( "time" "github.com/boilingrip/boiling-api/db" ) type Release struct { ID int `json:"id"` ReleaseGroup ReleaseGroup `json:"release_group"` Edition *string `json:"edition,omitempty"` Medium string `json:"medium"` ReleaseDate time.Time `json:"release_date"` CatalogueNumber *string `json:"catalogue_number,omitempty"` //RecordLabel RecordLabel //Torrents []Torrent Added time.Time `json:"added"` AddedBy BaseUser `json:"added_by"` Original bool `json:"original"` Tags []string `json:"tags,omitempty"` // Properties lists "official" properties of releases, for example // "LossyMasterApproved", to be set by trusted users or staff. Properties map[string]string `json:"properties"` } func (a *API) releaseFromDBRelease(dbR *db.Release) Release { r := Release{ ID: dbR.ID, Medium: a.c.media.MustReverseLookUp(dbR.Medium), ReleaseDate: dbR.ReleaseDate, Added: dbR.Added, AddedBy: baseUserFromDBUser(dbR.AddedBy), Original: dbR.Original, Tags: dbR.Tags, Properties: dbR.Properties, } if dbR.Edition.Valid { r.Edition = &dbR.Edition.String } if dbR.CatalogueNumber.Valid { r.CatalogueNumber = &dbR.CatalogueNumber.String } return r } type ReleaseResponse struct { Release Release `json:"release"` }
boilingrip/boiling-api
api/release.go
GO
mit
1,389
<?php namespace SlowDB\Bundle\ApiBundle\Controller; use FOS\RestBundle\Controller\Annotations as Rest, FOS\RestBundle\Controller\FOSRestController, FOS\RestBundle\Request\ParamFetcher; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\JsonResponse; /** * @author Keith Kirk <keith@kmfk.io> * * @Route("/tables") */ class DatabaseController extends FOSRestController { /** * Searches the Collection for matching keys * * @Rest\Get("/search", name="database_search") * * @param Request $request The request object * @param string $collection The collection name * * @return JsonResponse */ public function queryAction(Request $request, $collection) { $slowdb = $this->get('slowdb'); $query = $request->get('q', null); if (is_null($query)) { return new JsonResponse(['error' => 'Must include a Query parameter, ex: ?q={some text}'], 400); } $collections = $slowdb->all(); $results = []; foreach ($collections as $collection) { $results[$collection] = $slowdb->{$collection}->query($query); } return new JsonResponse($results, 200); } /** * Returns a list of all available Collections * * @Rest\Get("", name="database_all") * * @return JsonResponse */ public function listAction() { $response = $this->get('slowdb')->all(); return new JsonResponse($response); } /** * Drops all the Collections * * @Rest\Delete("", name="database_drop") * * @return JsonResponse */ public function dropAllAction() { $response = $this->get('slowdb')->dropAll(); return new JsonResponse('', 204); } }
kmfk/slowdb-api
src/Controller/DatabaseController.php
PHP
mit
1,837
<?php // require composer autoloader for loading classes require realpath(__DIR__ . '/../vendor/autoload.php');
slimdash/payum-payeezy
tests/bootstrap.php
PHP
mit
112
var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy, linkOAuthProfile = require('./helpers').linkOAuthProfile, OAuth2 = require('oauth').OAuth2, crypto = require('crypto'); function preprocessProfile(linkedInProfile){ var skills = []; if(linkedInProfile.skills){ skills = linkedInProfile.skills.values.map(function(value){ return value.skill.name; }); } return { educations: linkedInProfile.educations && linkedInProfile.educations.values || [], positions: linkedInProfile.positions && linkedInProfile.positions.values || [], skills: skills }; } exports.name = 'kabam-core-strategies-linkedin'; exports.strategy = function (core) { if (!core.config.PASSPORT || !core.config.PASSPORT.LINKEDIN_API_KEY || !core.config.PASSPORT.LINKEDIN_SECRET_KEY){ return; } var profileURL = 'https://api.linkedin.com/v1/people/~:(skills,educations,positions)', oauth2 = new OAuth2( core.config.PASSPORT.LINKEDIN_API_KEY, core.config.PASSPORT.LINKEDIN_SECRET_KEY, '', 'https://www.linkedin.com/uas/oauth2/authorization', 'https://www.linkedin.com/uas/oauth2/accessToken', {'x-li-format': 'json'} ); return new LinkedInStrategy({ clientID: core.config.PASSPORT.LINKEDIN_API_KEY, clientSecret: core.config.PASSPORT.LINKEDIN_SECRET_KEY, scope: ['r_fullprofile', 'r_emailaddress'], callbackURL: core.config.HOST_URL + 'auth/linkedin/callback', passReqToCallback: true, stateless: true }, function (request, accessToken, refreshToken, profile, done) { linkOAuthProfile(core, 'linkedin', request, profile, true, function(err, user, created){ if(err){return done(err);} // if we already had this user we shouldn't rewrite their profile, so we skip this step if(!created){return done(null, user);} // get required profile info and populate user profile oauth2.setAccessTokenName('oauth2_access_token'); oauth2.get(profileURL, accessToken, function(err, body/*, res*/){ if(err){return done(new Error('LinkedIn error: ' + JSON.stringify(err)));} try { user.profile = preprocessProfile(JSON.parse(body)); } catch(err) { return done(err); } user.markModified('profile'); user.save(function(err){ done(err, user); }); }); }); }); }; exports.routes = function (core) { if (!core.config.PASSPORT || !core.config.PASSPORT.LINKEDIN_API_KEY || !core.config.PASSPORT.LINKEDIN_SECRET_KEY){ return; } var state = crypto.createHash('md5').update(core.config.SECRET).digest('hex').toString(); core.app.get('/auth/linkedin', core.passport.authenticate('linkedin', {state: state})); core.app.get('/auth/linkedin/callback', core.passport.authenticate('linkedin', { successRedirect: '/auth/success', failureRedirect: '/auth/failure' })); }; // TODO: test all this stuff somehow
muhammadghazali/kabam-kernel
core/strategies/linkedin.js
JavaScript
mit
2,946
const deepCopy = require('./deep-copy'); const sorting = require('./sort'); /* Sorts an array of objects by two keys ** dir = 'asc' yields sort order A, B, C or 1, 2, 3 ** dir = 'des' yields sort order C, B, A or 3, 2, 1 ** type = 'character' for character sorting, type = 'numeric' or 'bool' ** for boolean sorting for numeric sorting. */ const arrSortByTwoKeys = (arr, key1, key2, dir = 'asc', type1 = 'character', type2 = 'character') => { /* Make sure input variable is an array of objects, and that keys are defined. ** if not, simply return whatever arr is. */ if ( !Array.isArray(arr) || typeof arr[0] !== 'object' || !key1 || !key2 ) { return arr; } const multiplier = dir === 'des' ? -1 : 1; const sortArray = deepCopy(arr); const sortFunc1 = sorting[type1]; const sortFunc2 = sorting[type2]; sortArray.sort((a, b) => { const sort1 = multiplier * sortFunc1(a[key1], b[key1]); const sort2 = multiplier * sortFunc2(a[key2], b[key2]); if (sort1 < 0) { return -1; } if ( sort1 === 0 && sort2 < 0 ) { return -1; } if ( sort1 === 0 && sort2 === 0 ) { return 0; } return 1; }); return sortArray; }; module.exports = arrSortByTwoKeys;
knightjdr/gene-info
database/helpers/arr-sort-by-two-keys.js
JavaScript
mit
1,260
require "test_helper" module RuleIo class CustomizationTest < Minitest::Test def setup stub_request(:get, /#{RuleIo.base_url}\/customizations\?apikey=*/) .to_return(status: 200, body: fixture("customizations.json")) end def test_all_returns_customizations customizations = Customization.all assert_kind_of Array, customizations assert_equal 1, customizations.length customizations.each do |c| assert_kind_of Customization, c end end def test_initialization customizations = Customization.all assert_equal 1, customizations.first.id assert_equal "Address", customizations.first.name end def test_fields customizations = Customization.all assert_kind_of Array, customizations.first.fields assert_equal 3, customizations.first.fields.length assert_kind_of Customization::Field, customizations.first.fields.first end end end
varvet/rule_io
test/rule_io/customization_test.rb
Ruby
mit
955
package es.carm.mydom.filters.utils; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.naming.resources.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Dispatcher { public static void sendResourceContent(Resource resource,HttpServletResponse response){ try{ OutputStream o = response.getOutputStream(); o.write(resource.getContent()); } catch (Exception e){ e.printStackTrace(); } } public static void sendResourceStream(String fileName, Resource resource,HttpServletResponse response){ try{ //o.write(resource.getContent()); //detecto la longitud InputStream in = resource.streamContent(); System.out.println("Send resource stream: fname="+fileName+" available="+in.available()); response.setContentLength(in.available()); OutputStream o = response.getOutputStream(); int b = 1; byte[] buff = new byte[16384]; while (b>0){ b = in.read(buff); if (b>0) o.write(buff,0,b); } in.close(); } catch (Exception e){ e.printStackTrace(); } } public static void sendString(String text,String charset,HttpServletResponse response){ sendString(text,"text/html",charset,response); } public static void sendString(String text,String contentType, String charset,HttpServletResponse response){ try{ response.setContentType(contentType); response.setCharacterEncoding(charset); OutputStream o = response.getOutputStream(); o.write(text.getBytes(charset)); } catch (Exception e){ e.printStackTrace(); } } public static void sendArrayString(List<String> text,String charset,HttpServletResponse response){ sendArrayString(text,"text/html",charset,response); } public static void sendArrayString(List<String> text,String contentType, String charset,HttpServletResponse response){ try{ response.setContentType(contentType); response.setCharacterEncoding(charset); OutputStream o = response.getOutputStream(); for(String item:text) o.write(item.getBytes(charset)); } catch (Exception e){ e.printStackTrace(); } } }
maltimor/mydom-server
src/main/java/es/carm/mydom/filters/utils/Dispatcher.java
Java
mit
2,187
# coding: utf-8 from django.db import models from django.utils import timezone from .cores import OssManager _oss_manager = OssManager() class StsToken(models.Model): arn = models.CharField(max_length=500) assumed_role_id = models.CharField(max_length=500) access_key_id = models.CharField(max_length=500) access_key_secret = models.CharField(max_length=500) security_token = models.TextField() purpose = models.CharField(max_length=100) expiration = models.DateTimeField() manager = _oss_manager class Meta: db_table = 'sts_token' @property def is_effective(self): return timezone.now() <= self.expiration
zhaowenxiang/chisch
oss/models.py
Python
mit
677
/* * (C) Copyright 2015 Richard Greenlees * * 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: * * 1) The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.jumi.scene.objects; import com.jumi.data.Vector3; import java.util.ArrayList; /** * * @author RGreenlees */ public class JUMIBone { private int[] indices = new int[0]; private float[] weights = new float[0]; private float[] transforms = new float[0]; private float[] transformLinks = new float[0]; private JUMIBone parent; private final ArrayList<JUMIBone> children = new ArrayList(); private Vector3 localTranslation = new Vector3(); private Vector3 localRotation = new Vector3(); private Vector3 localScaling = new Vector3(); private String name; public JUMIBone() { super(); } public JUMIBone(String inName) { name = inName; } public JUMIBone(String inName, int[] inIndices, float[] inWeights, float[] inTransforms, float[] inTransformLinks, Vector3 inTranslation, Vector3 inRotation, Vector3 inScaling) { name = inName; indices = inIndices; weights = inWeights; transforms = inTransforms; transformLinks = inTransformLinks; localTranslation = inTranslation; localRotation = inRotation; localScaling = inScaling; } public Vector3 getLocalScaling() { return localScaling; } public JUMIBone(String inName, Vector3 inTranslation, Vector3 inRotation, Vector3 inScaling) { name = inName; localTranslation = inTranslation; localRotation = inRotation; localScaling = inScaling; } public Vector3 getLocalTranslation() { return localTranslation; } public Vector3 getLocalRotation() { return localRotation; } public float[] getTransforms() { return transforms; } public float[] getTransformLinks() { return transformLinks; } public void setParent(JUMIBone newParent) { parent = newParent; } public void addChild(JUMIBone newChild) { children.add(newChild); newChild.setParent(this); } public void removeChild(JUMIBone childToRemove) { children.remove(childToRemove); childToRemove.setParent(null); } public void removeChild(String childName) { int index = -1; for (JUMIBone a : children) { if (a.name.equals(childName)) { index = children.indexOf(a); break; } } if (index > -1) { children.remove(index); } } public String getName() { return name; } public void setName(String newName) { name = newName; } public int[] getVertexIndices() { return indices; } public float[] getWeights() { return weights; } public JUMIBone getParent() { return parent; } public JUMIBone[] getChildren() { return children.toArray(new JUMIBone[children.size()]); } public JUMIBone[] getDescendants() { ArrayList<JUMIBone> allBones = new ArrayList(); addDescendantsToList(allBones); JUMIBone[] result = new JUMIBone[allBones.size()]; allBones.toArray(result); return result; } public JUMIBone[] getFullSkeleton() { ArrayList<JUMIBone> allBones = new ArrayList(); JUMIBone root = getRoot(); allBones.add(root); root.addDescendantsToList(allBones); JUMIBone[] result = new JUMIBone[allBones.size()]; allBones.toArray(result); return result; } public JUMIBone getRoot() { if (parent == null) { return this; } else { return parent.getRoot(); } } private void addDescendantsToList(ArrayList<JUMIBone> boneList) { for (JUMIBone a : children) { boneList.add(a); a.addDescendantsToList(boneList); } } public JUMIBone findDescendantByName(String inName) { for (JUMIBone a : children) { if (a.getName().equals(inName)) { return a; } a.findDescendantByName(inName); } return null; } public String toString() { return "JUMIBone:\n\tName: " + name + "\n\tParent: " + ((parent != null) ? parent.name : "None") + "\n\tChildren: " + children.size() + "\n\tDescendants: " + getDescendants().length; } }
RGreenlees/JUMI-Java-Model-Importer
src/com/jumi/scene/objects/JUMIBone.java
Java
mit
5,488
import assert from 'assert'; import proxyquire from 'proxyquire'; import sinon from 'sinon'; import sinonStubPromise from 'sinon-stub-promise'; import mockMbaasClient from './mocks/fhMbaasClientMock'; sinonStubPromise(sinon); const appEnvVarsStub = sinon.stub(); const primaryNodeStub = sinon.stub().returnsPromise(); const dbConnectionStub = sinon.stub().returnsPromise(); const feedhenryMbaasType = proxyquire('../lib/mbaas/types/feedhenry', { 'fh-mbaas-client': { MbaasClient: mockMbaasClient(appEnvVarsStub, primaryNodeStub) } }); const openshiftMbaasType = proxyquire('../lib/mbaas/types/openshift', { 'fh-mbaas-client': { MbaasClient: mockMbaasClient(appEnvVarsStub, null, dbConnectionStub) } }); const MockMbaaS = proxyquire('../lib/mbaas', { './types': { feedhenry: feedhenryMbaasType, openshift: openshiftMbaasType } }).MBaaS; function getMockReq() { return { params: { domain: 'test-domain', envId: 101, appGuid: '12345' }, log: { debug: function() {} } }; } function getOptions(mbaasType) { return { mbaasType: mbaasType, auth: { secret: '123456' }, mbaas: { url: 'https://api.host.com', password: 'pass', username: 'user' }, ditch: { user: 'user', password: 'pass', host: '', port: '', database: 'dbname' } }; } export function getDedicatedDbConnectionConf(done) { var expectedUrl = 'dedicatedUrl'; appEnvVarsStub.yields(null, { env: { FH_MONGODB_CONN_URL: expectedUrl } }); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(conf.__dbperapp); assert.equal(conf.connectionUrl, expectedUrl); done(); }) .catch(done); } export function getSharedDbConnectionConf(done) { var expectedUrl = 'mongodb://user:pass@primaryNodeHost:primaryNodePort/dbname'; appEnvVarsStub.yields(null, {}); primaryNodeStub.yields(null, { host: 'primaryNodeHost', port: 'primaryNodePort' }); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(!conf.__dbperapp); assert.equal(conf.connectionUrl, expectedUrl); done(); }) .catch(done); } export function appEnvVarFail(done) { appEnvVarsStub.yields({}); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(!conf); done(); }) .catch(err => { assert.ok(err); done(); }); } export function mongoprimaryNodeFail(done) { appEnvVarsStub.yields(null, {}); primaryNodeStub.yields({}); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(!conf); done(); }) .catch(err => { assert.ok(err); done(); }); } export function mongoOpenshift(done) { var expectedUrl = 'mongodb://user:pass@openshiftmongohost:27017/dbname'; appEnvVarsStub.yields(null, { env: { FH_MBAAS_ENV_ACCESS_KEY: '12345', FH_APP_API_KEY: '12345' } }); dbConnectionStub.yields(null, {url: expectedUrl}); new MockMbaaS(getOptions('openshift')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(conf.__dbperapp); assert.equal(conf.connectionUrl, expectedUrl); done(); }) .catch(done); }
feedhenry/fh-dataman
src/middleware/dbConnection/test/mbaas_test.js
JavaScript
mit
3,372
import React, { Component, PropTypes } from 'react' import { Router } from 'react-router' import { Provider } from 'react-redux' import routes from 'routes' class AppContainer extends Component { static propTypes = { store : PropTypes.object.isRequired, history : PropTypes.object.isRequired } shouldComponentUpdate() { return false } render() { const { history, store } = this.props return ( <Provider store={store}> <Router history={history} children={routes} /> </Provider> ) } } export default AppContainer
bartushk/memmi
client-side/src/containers/AppContainer.js
JavaScript
mit
639
<?php /* Safe sample input : get the field userData from the variable $_GET via an object sanitize : use of ternary condition construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $tainted = $tainted == 'safe1' ? 'safe1' : 'safe2'; $query = "(&(objectCategory=person)(objectClass=user)(cn='". $tainted . "'))"; $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_90/safe/CWE_90__object-classicGet__ternary_white_list__userByCN-concatenation_simple_quote.php
PHP
mit
1,569
var sizes; var searchKey = ''; if(window.location.search!=''){ $("#searchKey").val(decodeURIComponent(window.location.search.substr(11))) } if (window.location.search != "") { searchKey = window.location.search.substr(11) } $.ajax({ url: '/sizes?searchKey=' + searchKey, async: false, method: 'get', success: function (data) { sizes = Math.ceil((data.data) / 8); if (sizes != 1) { $('#pages').show(); } } }); $(document).ready(function () { $.ajax({ url: "/islogin", async: false, type: "get", success: function (data) { if (!data.data) { location.href = "/login"; } } }); var hash = window.location.hash; if (!hash) { hash = "page=1" } var page = {pageSize: hash.split("=")[1], searchKey: searchKey}; $.ajax({ type: "post", data: page, url: "/lists", success: function (data) { var list = "<div class='item-list'>"; $.each(data.data, function (index, item) { list += ("<div class='item'><div class='icon'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)' onmouseover='des(this)' onmouseout='_des(this)' >" + "<img src='%{icon}' alt='图片未找到'></a></div>" + "<div class='item-title'><strong>%{name}</strong></div><div>作者:%{author}</div>" + "<div class='item-info'><span class='version'>%{version}</span><span class='time'>%{date}<br/>%{time}</span></div>" + "<div class='detailed'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)'>文档</a></div><div class='des'>%{detailed}</div>" + "<div class='follow'><a href='javascript:void(0)' class='%{flwed}' onclick='follow(this)' data-name='%{name}' data-follow='%{follow}' ></a></div></div>").format({ icon: '/logo/' + item.name, name: item.name, author: item.author, version: item.version, flwed: ((item.follow == true) ? 'flwed' : ''), time: item.createTime.split(" ")[1], date: item.createTime.split(" ")[0], detailed: item.description, follow: item.follow, url: item.url }) }); list += "</div>"; $("#containal").html(list).show(); userName(); //获取分页数 location.hash = "page=" + page.pageSize; if (window.location.hash.split("=")[1] == "1") { $('.firstPage').attr('disabled', true).addClass('disabled'); $('.prevPage').attr('disabled', true).addClass('disabled'); } else if (window.location.hash.split("=")[1] == sizes) { $('.lastPage').attr('disabled', true).addClass('disabled'); $('.nextPage').attr('disabled', true).addClass('disabled'); } }, error: function (data) { console.info(data); } }) followLists(); }); //读取用户名 function userName() { var userName = $.cookie("userName"); $('.user strong').text(userName) } //关注列表 function followLists() { $.ajax({ type: "GET", async: false, url: "/followList", success: function (data) { var followList = "<ul>" $.each(data.data, function (index, item) { followList += ("<li><span class='sort'><a href='javascript:void(0)' onclick='folSort(this)' class='prev'><img src='/images/up.png' alt=''></a><a href='javascript:void(0)' class='next' onclick='folSort(this)'><img src='/images/down.png' alt=''></a></span>" + "<a href='/detail#%{followName}' class='followName'>%{followName}</a><a href='javascript:void(0)' onclick='delFollow(this)' class='del-fol'>" + "<img src='/images/pro_close.png' alt=''></a></li>").format({followName: item}); }); followList += "</ul>"; $('.user-list').html(followList) }, error: function (data) { console.info(data); } }) } function user(self) { if (!$(self).hasClass('ac')) { $(self).addClass('ac'); $('.user-list').show(); followLists(); } else { $(self).removeClass('ac'); $('.user-list').hide() } } function des(_this) { $(_this).parents('.item').children('.des').show(); } function _des(_this) { $(_this).parents('.item').children('.des').hide(); } function pageBtn(self, name) { var pagination = {}; var curPage = location.hash.split("=")[1]; if (name == "first") { pagination.limit = 1; $(self).attr("disabled", true).addClass('disabled').siblings().attr("disabled", false).removeClass('disabled') $("#pages .prevPage").attr("disabled", true).addClass("disabled"); } else if (name == "prev") { pagination.limit = --curPage; $("#pages button").removeAttr("disabled").removeClass('disabled'); if (pagination.limit <= 1) { pagination.limit = 1; $("#pages .firstPage").attr("disabled", true).addClass("disabled"); $("#pages .prevPage").attr("disabled", true).addClass("disabled"); } } else if (name == "next") { pagination.limit = ++curPage; $("#pages button").removeAttr("disabled").removeClass('disabled'); if (pagination.limit >= sizes) { pagination.limit = sizes; // $("#pages button").removeAttr("disabled").removeClass('disabled'); $("#pages .lastPage").attr("disabled", true).addClass("disabled"); $("#pages .nextPage").attr("disabled", true).addClass("disabled"); } } else if (name == "end") { pagination.limit = sizes; $(self).attr("disabled", true).addClass('disabled').siblings().attr("disabled", false).removeClass('disabled'); $("#pages .nextPage").attr("disabled", true).addClass("disabled"); } $.ajax({ type: "post", url: "/pageSize", data: pagination, success: function (data) { var list = "<div class='item-list'>" $.each(data.data, function (index, item) { list += ("<div class='item'><div class='icon'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)'><img src='%{icon}' alt='图片未找到'></a></div>" + "<div class='item-title'><strong>%{name}</strong></div><div>作者:%{author}</div>" + "<div class='item-info'><span class='version'>%{version}</span><span class='time'>%{date}<br/>%{time}</span></div>" + "<div class='follow'><a href='javascript:void(0)' class='%{flwed}' onclick='follow(this)' data-follow='%{follow}'></a></div>" + "<div class='detailed'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)'>文档</a></div></div>").format({ icon: '/logo/' + item.name, name: item.name, author: item.author, version: item.version, time: item.createTime.split(" ")[1], date: item.createTime.split(" ")[0], flwed: ((item.follow == true) ? 'flwed' : ''), detailed: item.description, follow: item.follow, url: item.url }) }); list += "</div>"; $("#containal").html(list).fadeIn() location.hash = "page=" + pagination.limit; }, error: function (data) { console.info(data); } }) } //分页跳转 function logout() { $.ajax({ type: "get", url: "/userlogout", success: function (data) { window.location.href = "/login" }, error: function (data) { console.info(data); } }) } function follow(_this) { var data = {}; data.projectName = $(_this).parents('.item').children('.item-title').children().text(); if ($(_this).hasClass('flwed')) { $(_this).removeClass('flwed'); $.ajax({ type: "POST", url: "/delFollow", data: data, success: function (data) { console.info(data); }, error: function (data) { console.info(data); } }) } else { $(_this).addClass('flwed'); $.ajax({ type: "POST", url: "/addFollow", data: data, success: function (data) { // console.info(); }, error: function (data) { console.info(data); } }) } } function BindEnter(event) { if(event.code=='Enter'){ search() } } function search() { window.location.search = '?searchKey=' + $("#searchKey").val() } function delFollow(_this) { var data = {}; data.projectName = $(_this).siblings('.followName').text(); $.ajax({ type: "POST", url: "/delFollow", data: data, success: function (data) { var proName = $(_this).parent().children('.followName').text() $(_this).parent().remove(); $('.item-list .item .follow a[data-name=' + proName + ']').removeClass('flwed') }, error: function (data) { console.info(data); } }) } //关注排序 function folSort(self) { var name = $(self).attr("class"); var li = $(self).parents('li'); var sortData = {}; if (name == "next" && li.next()) { li.next().after(li) } else if (name == "prev" && li.prev()) { li.prev().before(li); } var listSort = []; for (var i = 0, len = $('.user-list li').length; i < len; i++) { var listName = $('.user-list li').eq(i).children('.followName').text(); listSort.push(listName) } sortData.projects = listSort.join(','); $.ajax({ type: "post", url: "/sortList", async: false, data: sortData, success: function (data) { }, error: function (data) { } }) } function absUrl(self) { var absUrl = $(self).attr("data-url"); $.cookie("absUrl", absUrl, {expires: 7}) }
dounine/japi
node/js/index.js
JavaScript
mit
10,577
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Polygon } from 'react-google-maps'; import {map, filter} from './../../../actions'; class Region extends React.Component { constructor(props) { super(props); this.state = { hovered: false, selected: false }; this.config = { strokeColor: '#babfc7', fillColor: '#7d899e', strokeOpacity: 0.28, strokeWeight: 1, fillOpacity: 0.1 }; } getRegionStyle() { let style = this.config; if (this.props.selected || this.state.hovered) { style = Object.assign({}, style, {fillColor: '#000'}); } return style; } onClick(event) { this.props.regionFilterClicked(this.props.region.id, !this.props.selected, { selected: this.props.selectedRegions, defaults: { routes: this.props.routes, assets: this.props.assets } }); } render() { return ( <Polygon mapHolderRef={this.props.mapHolderRef} paths={this.props.region.coordinates} options={this.getRegionStyle()} onClick={(event) => this.onClick(event)} onMouseover={(event) => {this.setState({hovered: true})}} onMouseout={(event) => {this.setState({hovered: false})}} /> ); } } const stateMap = (state, props, ownProps) => { return { selected : (state.selected.regions.indexOf(props.region.id) !== -1), selectedRegions: state.selected.regions, routes: state.data.route_options.response, assets: state.data.assets.response, }; }; function mapDispatchToProps (dispatch) { return { regionFilterClicked: bindActionCreators(filter.regionFilterClicked, dispatch), regionClick : bindActionCreators(map.regionClick, dispatch) }; } export default connect(stateMap, mapDispatchToProps)(Region);
Haaarp/geo
client/analytics/components/partials/maps/Region.js
JavaScript
mit
2,127
namespace Squirrel.Nodes { public interface INode { } }
escamilla/squirrel
src/library/Nodes/INode.cs
C#
mit
71
import { beforeEach, beforeEachProviders, ComponentFixture, describe, expect, injectAsync, it, TestComponentBuilder, } from 'angular2/testing'; import { provide } from 'angular2/core'; import { Config } from 'ionic-framework/ionic'; import { ClickerButton } from './clickerButton'; import { Clickers } from '../../services/clickers'; import { TestUtils } from '../../../test/testUtils'; import { Utils } from '../../services/utils'; let clickerButton: ClickerButton = null; let clickerButtonFixture: ComponentFixture = null; class MockClickers { public doClick(): boolean { return true; } } class MockClicker { public name: string = 'TEST CLICKER'; public getCount(): number { return 10; }; } class MockClass { public get(): any { return {}; } } export function main(): void { 'use strict'; describe('ClickerForm', () => { beforeEachProviders(() => [ provide(Clickers, {useClass: MockClickers}), provide(Config, {useClass: MockClass}), ]); beforeEach(injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { return tcb .createAsync(ClickerButton) .then((componentFixture: ComponentFixture) => { clickerButtonFixture = componentFixture; clickerButton = componentFixture.componentInstance; clickerButton['clicker'] = { name: 'TEST CLICKER' }; clickerButton['clicker'].getCount = function(): number { return 10; }; window['fixture'] = clickerButtonFixture; window['testUtils'] = TestUtils; }) .catch(Utils.promiseCatchHandler); })); it('initialises', () => { expect(clickerButton).not.toBeNull(); }); it('displays the clicker name and count', () => { clickerButtonFixture.detectChanges(); expect(clickerButtonFixture.nativeElement.querySelectorAll('.button-inner')[0].innerHTML).toEqual('TEST CLICKER (10)'); }); it('does a click', () => { clickerButtonFixture.detectChanges(); spyOn(clickerButton['clickerService'], 'doClick'); TestUtils.eventFire(clickerButtonFixture.nativeElement.querySelectorAll('button')[0], 'click'); expect(clickerButton['clickerService'].doClick).toHaveBeenCalled(); }); }); }
Fredqin/personal_task_runner
app/components/clickerButton/clickerButton.spec.ts
TypeScript
mit
2,310
<?php namespace zikmont\ContabilidadBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="ctb_movimientos_resumen") * @ORM\Entity(repositoryClass="zikmont\ContabilidadBundle\Repository\CtbMovimientosResumenRepository") */ class CtbMovimientosResumen { /** * @ORM\Id * @ORM\Column(name="codigo_movimiento_resumen_pk", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $codigoMovimientoResumenPk; /** * @ORM\Column(name="codigo_cierre_mes_fk", type="integer") */ private $codigoCierreMesFk; /** * @ORM\Column(name="annio", type="integer") */ private $annio; /** * @ORM\Column(name="mes", type="smallint") */ private $mes; /** * @ORM\Column(name="codigo_cuenta_fk", type="string", length=20) */ private $codigoCuentaFk; /** * @ORM\Column(name="debito", type="float") */ private $debito = 0; /** * @ORM\Column(name="credito", type="float") */ private $credito = 0; /** * @ORM\Column(name="base", type="float") */ private $base = 0; /** * @ORM\ManyToOne(targetEntity="CtbCuentasContables", inversedBy="CtbMovimientosResumen") * @ORM\JoinColumn(name="codigo_cuenta_fk", referencedColumnName="codigo_cuenta_pk") */ protected $cuentaRel; /** * @ORM\ManyToOne(targetEntity="CtbCierresMes", inversedBy="CtbMovimientosResumen") * @ORM\JoinColumn(name="codigo_cierre_mes_fk", referencedColumnName="codigo_cierre_mes_pk") */ protected $ciereMesContabilidadRel; /** * Get codigoMovimientoResumenPk * * @return integer */ public function getCodigoMovimientoResumenPk() { return $this->codigoMovimientoResumenPk; } /** * Set codigoCierreMesContabilidadFk * * @param integer $codigoCierreMesContabilidadFk */ public function setCodigoCierreMesContabilidadFk($codigoCierreMesContabilidadFk) { $this->codigoCierreMesContabilidadFk = $codigoCierreMesContabilidadFk; } /** * Get codigoCierreMesContabilidadFk * * @return integer */ public function getCodigoCierreMesContabilidadFk() { return $this->codigoCierreMesContabilidadFk; } /** * Set annio * * @param integer $annio */ public function setAnnio($annio) { $this->annio = $annio; } /** * Get annio * * @return integer */ public function getAnnio() { return $this->annio; } /** * Set mes * * @param smallint $mes */ public function setMes($mes) { $this->mes = $mes; } /** * Get mes * * @return smallint */ public function getMes() { return $this->mes; } /** * Set codigoCuentaFk * * @param string $codigoCuentaFk */ public function setCodigoCuentaFk($codigoCuentaFk) { $this->codigoCuentaFk = $codigoCuentaFk; } /** * Get codigoCuentaFk * * @return string */ public function getCodigoCuentaFk() { return $this->codigoCuentaFk; } /** * Set debito * * @param float $debito */ public function setDebito($debito) { $this->debito = $debito; } /** * Get debito * * @return float */ public function getDebito() { return $this->debito; } /** * Set credito * * @param float $credito */ public function setCredito($credito) { $this->credito = $credito; } /** * Get credito * * @return float */ public function getCredito() { return $this->credito; } /** * Set base * * @param float $base */ public function setBase($base) { $this->base = $base; } /** * Get base * * @return float */ public function getBase() { return $this->base; } /** * Set cuentaRel * * @param zikmont\ContabilidadBundle\Entity\CuentasContables $cuentaRel */ public function setCuentaRel(\zikmont\ContabilidadBundle\Entity\CuentasContables $cuentaRel) { $this->cuentaRel = $cuentaRel; } /** * Get cuentaRel * * @return zikmont\ContabilidadBundle\Entity\CuentasContables */ public function getCuentaRel() { return $this->cuentaRel; } /** * Set ciereMesContabilidadRel * * @param zikmont\ContabilidadBundle\Entity\CierresMesContabilidad $ciereMesContabilidadRel */ public function setCiereMesContabilidadRel(\zikmont\ContabilidadBundle\Entity\CierresMesContabilidad $ciereMesContabilidadRel) { $this->ciereMesContabilidadRel = $ciereMesContabilidadRel; } /** * Get ciereMesContabilidadRel * * @return zikmont\ContabilidadBundle\Entity\CierresMesContabilidad */ public function getCiereMesContabilidadRel() { return $this->ciereMesContabilidadRel; } /** * Set codigoCierreMesFk * * @param integer $codigoCierreMesFk */ public function setCodigoCierreMesFk($codigoCierreMesFk) { $this->codigoCierreMesFk = $codigoCierreMesFk; } /** * Get codigoCierreMesFk * * @return integer */ public function getCodigoCierreMesFk() { return $this->codigoCierreMesFk; } }
wariox3/zikmont
src/zikmont/ContabilidadBundle/Entity/CtbMovimientosResumen.php
PHP
mit
5,658
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Abp.Application.Services; using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.Domain.Entities; using Abp.Domain.Repositories; using Abp.Extensions; using Abp.IdentityFramework; using Abp.Linq.Extensions; using Abp.Localization; using Abp.Runtime.Session; using Abp.UI; using IdentityServerWithEfCoreDemo.Authorization; using IdentityServerWithEfCoreDemo.Authorization.Accounts; using IdentityServerWithEfCoreDemo.Authorization.Roles; using IdentityServerWithEfCoreDemo.Authorization.Users; using IdentityServerWithEfCoreDemo.Roles.Dto; using IdentityServerWithEfCoreDemo.Users.Dto; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace IdentityServerWithEfCoreDemo.Users { [AbpAuthorize(PermissionNames.Pages_Users)] public class UserAppService : AsyncCrudAppService<User, UserDto, long, PagedUserResultRequestDto, CreateUserDto, UserDto>, IUserAppService { private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IRepository<Role> _roleRepository; private readonly IPasswordHasher<User> _passwordHasher; private readonly IAbpSession _abpSession; private readonly LogInManager _logInManager; public UserAppService( IRepository<User, long> repository, UserManager userManager, RoleManager roleManager, IRepository<Role> roleRepository, IPasswordHasher<User> passwordHasher, IAbpSession abpSession, LogInManager logInManager) : base(repository) { _userManager = userManager; _roleManager = roleManager; _roleRepository = roleRepository; _passwordHasher = passwordHasher; _abpSession = abpSession; _logInManager = logInManager; } public override async Task<UserDto> CreateAsync(CreateUserDto input) { CheckCreatePermission(); var user = ObjectMapper.Map<User>(input); user.TenantId = AbpSession.TenantId; user.IsEmailConfirmed = true; await _userManager.InitializeOptionsAsync(AbpSession.TenantId); CheckErrors(await _userManager.CreateAsync(user, input.Password)); if (input.RoleNames != null) { CheckErrors(await _userManager.SetRolesAsync(user, input.RoleNames)); } CurrentUnitOfWork.SaveChanges(); return MapToEntityDto(user); } public override async Task<UserDto> UpdateAsync(UserDto input) { CheckUpdatePermission(); var user = await _userManager.GetUserByIdAsync(input.Id); MapToEntity(input, user); CheckErrors(await _userManager.UpdateAsync(user)); if (input.RoleNames != null) { CheckErrors(await _userManager.SetRolesAsync(user, input.RoleNames)); } return await GetAsync(input); } public override async Task DeleteAsync(EntityDto<long> input) { var user = await _userManager.GetUserByIdAsync(input.Id); await _userManager.DeleteAsync(user); } public async Task<ListResultDto<RoleDto>> GetRoles() { var roles = await _roleRepository.GetAllListAsync(); return new ListResultDto<RoleDto>(ObjectMapper.Map<List<RoleDto>>(roles)); } public async Task ChangeLanguage(ChangeUserLanguageDto input) { await SettingManager.ChangeSettingForUserAsync( AbpSession.ToUserIdentifier(), LocalizationSettingNames.DefaultLanguage, input.LanguageName ); } protected override User MapToEntity(CreateUserDto createInput) { var user = ObjectMapper.Map<User>(createInput); user.SetNormalizedNames(); return user; } protected override void MapToEntity(UserDto input, User user) { ObjectMapper.Map(input, user); user.SetNormalizedNames(); } protected override UserDto MapToEntityDto(User user) { var roleIds = user.Roles.Select(x => x.RoleId).ToArray(); var roles = _roleManager.Roles.Where(r => roleIds.Contains(r.Id)).Select(r => r.NormalizedName); var userDto = base.MapToEntityDto(user); userDto.RoleNames = roles.ToArray(); return userDto; } protected override IQueryable<User> CreateFilteredQuery(PagedUserResultRequestDto input) { return Repository.GetAllIncluding(x => x.Roles) .WhereIf(!input.Keyword.IsNullOrWhiteSpace(), x => x.UserName.Contains(input.Keyword) || x.Name.Contains(input.Keyword) || x.EmailAddress.Contains(input.Keyword)) .WhereIf(input.IsActive.HasValue, x => x.IsActive == input.IsActive); } protected override async Task<User> GetEntityByIdAsync(long id) { var user = await Repository.GetAllIncluding(x => x.Roles).FirstOrDefaultAsync(x => x.Id == id); if (user == null) { throw new EntityNotFoundException(typeof(User), id); } return user; } protected override IQueryable<User> ApplySorting(IQueryable<User> query, PagedUserResultRequestDto input) { return query.OrderBy(r => r.UserName); } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } public async Task<bool> ChangePassword(ChangePasswordDto input) { if (_abpSession.UserId == null) { throw new UserFriendlyException("Please log in before attemping to change password."); } long userId = _abpSession.UserId.Value; var user = await _userManager.GetUserByIdAsync(userId); var loginAsync = await _logInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout: false); if (loginAsync.Result != AbpLoginResultType.Success) { throw new UserFriendlyException("Your 'Existing Password' did not match the one on record. Please try again or contact an administrator for assistance in resetting your password."); } if (!new Regex(AccountAppService.PasswordRegex).IsMatch(input.NewPassword)) { throw new UserFriendlyException("Passwords must be at least 8 characters, contain a lowercase, uppercase, and number."); } user.Password = _passwordHasher.HashPassword(user, input.NewPassword); CurrentUnitOfWork.SaveChanges(); return true; } public async Task<bool> ResetPassword(ResetPasswordDto input) { if (_abpSession.UserId == null) { throw new UserFriendlyException("Please log in before attemping to reset password."); } long currentUserId = _abpSession.UserId.Value; var currentUser = await _userManager.GetUserByIdAsync(currentUserId); var loginAsync = await _logInManager.LoginAsync(currentUser.UserName, input.AdminPassword, shouldLockout: false); if (loginAsync.Result != AbpLoginResultType.Success) { throw new UserFriendlyException("Your 'Admin Password' did not match the one on record. Please try again."); } if (currentUser.IsDeleted || !currentUser.IsActive) { return false; } var roles = await _userManager.GetRolesAsync(currentUser); if (!roles.Contains(StaticRoleNames.Tenants.Admin)) { throw new UserFriendlyException("Only administrators may reset passwords."); } var user = await _userManager.GetUserByIdAsync(input.UserId); if (user != null) { user.Password = _passwordHasher.HashPassword(user, input.NewPassword); CurrentUnitOfWork.SaveChanges(); } return true; } } }
aspnetboilerplate/aspnetboilerplate-samples
IdentityServerWithEfCoreDemo/aspnet-core/src/IdentityServerWithEfCoreDemo.Application/Users/UserAppService.cs
C#
mit
8,506
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer'], function(jQuery, Renderer) { "use strict"; /** * ObjectNumber renderer. * @namespace */ var ObjectNumberRenderer = { }; /** * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oON An object representation of the control that should be rendered */ ObjectNumberRenderer.render = function(oRm, oON) { var sTooltip = oON._getEnrichedTooltip(), sTextDir = oON.getTextDirection(), sTextAlign = oON.getTextAlign(); oRm.write("<div"); oRm.writeControlData(oON); oRm.addClass("sapMObjectNumber"); oRm.addClass(oON._sCSSPrefixObjNumberStatus + oON.getState()); if (oON.getEmphasized()) { oRm.addClass("sapMObjectNumberEmph"); } if (sTooltip) { oRm.writeAttributeEscaped("title", sTooltip); } if (sTextDir !== sap.ui.core.TextDirection.Inherit) { oRm.writeAttribute("dir", sTextDir.toLowerCase()); } sTextAlign = Renderer.getTextAlign(sTextAlign, sTextDir); if (sTextAlign) { oRm.addStyle("text-align", sTextAlign); } oRm.writeClasses(); oRm.writeStyles(); // ARIA // when the status is "None" there is nothing for reading if (oON.getState() !== sap.ui.core.ValueState.None) { oRm.writeAccessibilityState({ labelledby: oON.getId() + "-state" }); } oRm.write(">"); this.renderText(oRm, oON); oRm.write(" "); // space between the number text and unit this.renderUnit(oRm, oON); this.renderHiddenARIAElement(oRm, oON); oRm.write("</div>"); }; ObjectNumberRenderer.renderText = function(oRm, oON) { oRm.write("<span"); oRm.addClass("sapMObjectNumberText"); oRm.writeClasses(); oRm.write(">"); oRm.writeEscaped(oON.getNumber()); oRm.write("</span>"); }; ObjectNumberRenderer.renderUnit = function(oRm, oON) { var sUnit = oON.getUnit() || oON.getNumberUnit(); oRm.write("<span"); oRm.addClass("sapMObjectNumberUnit"); oRm.writeClasses(); oRm.write(">"); oRm.writeEscaped(sUnit); oRm.write("</span>"); }; ObjectNumberRenderer.renderHiddenARIAElement = function(oRm, oON) { var sARIAStateText = "", oRB = sap.ui.getCore().getLibraryResourceBundle("sap.m"); if (oON.getState() == sap.ui.core.ValueState.None) { return; } oRm.write("<span id='" + oON.getId() + "-state' class='sapUiInvisibleText' aria-hidden='true'>"); switch (oON.getState()) { case sap.ui.core.ValueState.Error: sARIAStateText = oRB.getText("OBJECTNUMBER_ARIA_VALUE_STATE_ERROR"); break; case sap.ui.core.ValueState.Warning: sARIAStateText = oRB.getText("OBJECTNUMBER_ARIA_VALUE_STATE_WARNING"); break; case sap.ui.core.ValueState.Success: sARIAStateText = oRB.getText("OBJECTNUMBER_ARIA_VALUE_STATE_SUCCESS"); break; } oRm.write(sARIAStateText); oRm.write("</span>"); }; return ObjectNumberRenderer; }, /* bExport= */ true);
marinho/german-articles
webapp/resources/sap/m/ObjectNumberRenderer-dbg.js
JavaScript
mit
3,233
<?php declare(strict_types=1); /* * The MIT License (MIT) * * Copyright (c) 2014-2017 Spomky-Labs * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ namespace OAuth2Framework\Component\Server\Tests\Stub\Event; use OAuth2Framework\Component\Server\Event\AccessToken\AccessTokenRevokedEvent; final class AccessTokenRevokedEventHandler extends EventHandler { /** * @param AccessTokenRevokedEvent $event */ public function handle(AccessTokenRevokedEvent $event) { $this->save($event); } }
OAuth2-Framework/server-library
Tests/Stub/Event/AccessTokenRevokedEventHandler.php
PHP
mit
606
"""Controller for rendering pod content.""" import datetime import mimetypes import os import sys import time from grow.common import utils from grow.documents import static_document from grow.pods import errors from grow.rendering import rendered_document from grow.templates import doc_dependency from grow.templates import tags class Error(Exception): """Base rendering pool error.""" def __init__(self, message): super(Error, self).__init__(message) self.message = message class UnknownKindError(Error): """Unknown kind of information.""" pass class IgnoredPathError(Error): """Document is being served at an ignored path.""" pass class RenderController(object): """Controls how the content is rendered and evaluated.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): self.pod = pod self.serving_path = serving_path self.route_info = route_info self.params = params if params is not None else {} self.render_timer = None self.use_jinja = False self.is_threaded = is_threaded @staticmethod def clean_source_dir(source_dir): """Clean the formatting of the source dir to format correctly.""" source_dir = source_dir.strip() source_dir = source_dir.rstrip(os.path.sep) return source_dir @staticmethod def from_route_info(pod, serving_path, route_info, params=None): """Create the correct controller based on the route info.""" if params is None: params = {} if route_info.kind == 'doc': return RenderDocumentController( pod, serving_path, route_info, params=params) elif route_info.kind == 'static': return RenderStaticDocumentController( pod, serving_path, route_info, params=params) elif route_info.kind == 'sitemap': return RenderSitemapController( pod, serving_path, route_info, params=params) elif route_info.kind == 'error': return RenderErrorController( pod, serving_path, route_info, params=params) raise UnknownKindError( 'Do not have a controller for: {}'.format(route_info.kind)) @property def locale(self): """Locale to use for rendering.""" return None @property def mimetype(self): """Guess the mimetype of the content.""" return 'text/plain' def get_http_headers(self): """Determine headers to serve for https requests.""" headers = {} mimetype = self.mimetype if mimetype: headers['Content-Type'] = mimetype return headers def load(self, source_dir): """Load the pod content from file system.""" raise NotImplementedError def render(self, jinja_env, request=None): """Render the pod content.""" raise NotImplementedError def validate_path(self, *path_filters): """Validate that the path is valid against all filters.""" # Default test against the pod filter for deployment specific filtering. path_filters = list(path_filters) or [self.pod.path_filter] for path_filter in path_filters: if not path_filter.is_valid(self.serving_path): text = '{} is an ignored path.' raise errors.RouteNotFoundError(text.format(self.serving_path)) class RenderDocumentController(RenderController): """Controller for handling rendering for documents.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): super(RenderDocumentController, self).__init__( pod, serving_path, route_info, params=params, is_threaded=is_threaded) self._doc = None self.use_jinja = True def __repr__(self): return '<RenderDocumentController({})>'.format(self.route_info.meta['pod_path']) @property def doc(self): """Doc for the controller.""" if not self._doc: pod_path = self.route_info.meta['pod_path'] locale = self.route_info.meta.get( 'locale', self.params.get('locale')) self._doc = self.pod.get_doc(pod_path, locale=locale) return self._doc @property def locale(self): """Locale to use for rendering.""" if 'locale' in self.route_info.meta: return self.route_info.meta['locale'] return self.doc.locale if self.doc else None @property def mimetype(self): """Determine headers to serve for https requests.""" return mimetypes.guess_type(self.doc.view)[0] @property def pod_path(self): """Locale to use for rendering.""" if 'pod_path' in self.route_info.meta: return self.route_info.meta['pod_path'] return self.doc.pod_path if self.doc else None @property def suffix(self): """Determine headers to serve for https requests.""" _, ext = os.path.splitext(self.doc.view) if ext == '.html': return 'index.html' return '' def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderDocumentController.load', label='{} ({})'.format(self.pod_path, self.locale), meta={ 'path': self.pod_path, 'locale': str(self.locale)} ).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the config filters. self.validate_path() try: doc = self.doc serving_path = self.serving_path if serving_path.endswith('/'): serving_path = '{}{}'.format(serving_path, self.suffix) rendered_path = '{}{}'.format(source_dir, serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: exception = errors.BuildError(str(err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception def render(self, jinja_env=None, request=None): """Render the document using the render pool.""" timer = self.pod.profile.timer( 'RenderDocumentController.render', label='{} ({})'.format(self.doc.pod_path, self.doc.locale), meta={ 'path': self.doc.pod_path, 'locale': str(self.doc.locale)} ).start_timer() # Validate the path with the config filters. self.validate_path() doc = self.doc template = jinja_env['env'].get_template(doc.view.lstrip('/')) track_dependency = doc_dependency.DocDependency(doc) local_tags = tags.create_builtin_tags( self.pod, doc, track_dependency=track_dependency) # NOTE: This should be done using get_template(... globals=...) # or passed as an argument into render but # it is not available included inside macros??? # See: https://github.com/pallets/jinja/issues/688 template.globals['g'] = local_tags # Track the message stats, including untranslated strings. if self.pod.is_enabled(self.pod.FEATURE_TRANSLATION_STATS): template.globals['_'] = tags.make_doc_gettext(doc) try: doc.footnotes.reset() serving_path = doc.get_serving_path() if serving_path.endswith('/'): serving_path = '{}{}'.format(serving_path, self.suffix) content = self.pod.extensions_controller.trigger('pre_render', doc, doc.body) if content: doc.format.update(content=content) rendered_content = template.render({ 'doc': doc, 'request': request, 'env': self.pod.env, 'podspec': self.pod.podspec, '_track_dependency': track_dependency, }).lstrip() rendered_content = self.pod.extensions_controller.trigger( 'post_render', doc, rendered_content) rendered_doc = rendered_document.RenderedDocument( serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: exception = errors.BuildError(str(err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception class RenderErrorController(RenderController): """Controller for handling rendering for errors.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): super(RenderErrorController, self).__init__( pod, serving_path, route_info, params=params, is_threaded=is_threaded) self.use_jinja = True def __repr__(self): return '<RenderErrorController({})>'.format(self.route_info.meta['view']) def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderErrorController.load', label='{} ({})'.format( self.route_info.meta['key'], self.route_info.meta['view']), meta={ 'key': self.route_info.meta['key'], 'view': self.route_info.meta['view'], } ).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the config filters. self.validate_path() try: serving_path = '/{}.html'.format(self.route_info.meta['key']) rendered_path = '{}{}'.format(source_dir, serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception def render(self, jinja_env=None, request=None): """Render the document using the render pool.""" timer = self.pod.profile.timer( 'RenderErrorController.render', label='{} ({})'.format( self.route_info.meta['key'], self.route_info.meta['view']), meta={ 'key': self.route_info.meta['key'], 'view': self.route_info.meta['view'], } ).start_timer() # Validate the path with the config filters. self.validate_path() with jinja_env['lock']: template = jinja_env['env'].get_template( self.route_info.meta['view'].lstrip('/')) local_tags = tags.create_builtin_tags(self.pod, doc=None) # NOTE: This should be done using get_template(... globals=...) # or passed as an argument into render but # it is not available included inside macros??? # See: https://github.com/pallets/jinja/issues/688 template.globals['g'] = local_tags try: serving_path = '/{}.html'.format(self.route_info.meta['key']) rendered_doc = rendered_document.RenderedDocument( serving_path, template.render({ 'doc': None, 'env': self.pod.env, 'podspec': self.pod.podspec, }).lstrip()) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception class RenderSitemapController(RenderController): """Controller for handling rendering for sitemaps.""" @property def mimetype(self): """Determine headers to serve for https requests.""" return mimetypes.guess_type(self.serving_path)[0] def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderSitemapController.load', label='{}'.format(self.serving_path), meta=self.route_info.meta, ).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the config filters. self.validate_path() try: rendered_path = '{}{}'.format(source_dir, self.serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( self.serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception def render(self, jinja_env=None, request=None): """Render the document using the render pool.""" timer = self.pod.profile.timer( 'RenderSitemapController.render', label='{}'.format(self.serving_path), meta=self.route_info.meta, ).start_timer() # Validate the path with the config filters. self.validate_path() # Duplicate the routes to use the filters without messing up routing. temp_router = self.pod.router.__class__(self.pod) temp_router.add_all() # Sitemaps only show documents...? temp_router.filter('whitelist', kinds=['doc']) for sitemap_filter in self.route_info.meta.get('filters') or []: temp_router.filter( sitemap_filter['type'], collection_paths=sitemap_filter.get('collections'), paths=sitemap_filter.get('paths'), locales=sitemap_filter.get('locales')) # Need a custom root for rendering sitemap. root = os.path.join(utils.get_grow_dir(), 'pods', 'templates') jinja_env = self.pod.render_pool.custom_jinja_env(root=root) with jinja_env['lock']: if self.route_info.meta.get('template'): content = self.pod.read_file(self.route_info.meta['template']) template = jinja_env['env'].from_string(content) else: template = jinja_env['env'].get_template('sitemap.xml') try: docs = [] for _, value, _ in temp_router.routes.nodes: docs.append(self.pod.get_doc(value.meta['pod_path'], locale=value.meta['locale'])) rendered_doc = rendered_document.RenderedDocument( self.serving_path, template.render({ 'pod': self.pod, 'env': self.pod.env, 'docs': docs, 'podspec': self.pod.podspec, }).lstrip()) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception class RenderStaticDocumentController(RenderController): """Controller for handling rendering for static documents.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): super(RenderStaticDocumentController, self).__init__( pod, serving_path, route_info, params=params, is_threaded=is_threaded) self._static_doc = None self._pod_path = None def __repr__(self): return '<RenderStaticDocumentController({})>'.format(self.route_info.meta['pod_path']) @property def pod_path(self): """Static doc for the controller.""" if self._pod_path: return self._pod_path locale = self.route_info.meta.get( 'locale', self.params.get('locale')) if 'pod_path' in self.route_info.meta: self._pod_path = self.route_info.meta['pod_path'] else: for source_format in self.route_info.meta['source_formats']: path_format = '{}{}'.format(source_format, self.params['*']) self._pod_path = self.pod.path_format.format_static( path_format, locale=locale) # Strip the fingerprint to get to the raw static file. self._pod_path = static_document.StaticDocument.strip_fingerprint( self._pod_path) try: # Throws an error when the document doesn't exist. _ = self.pod.get_static(self._pod_path, locale=locale) break except errors.DocumentDoesNotExistError: self._pod_path = None return self._pod_path @property def static_doc(self): """Static doc for the controller.""" if not self._static_doc: locale = self.route_info.meta.get( 'locale', self.params.get('locale')) self._static_doc = self.pod.get_static(self.pod_path, locale=locale) return self._static_doc @property def mimetype(self): """Determine headers to serve for https requests.""" return mimetypes.guess_type(self.serving_path)[0] def get_http_headers(self): """Determine headers to serve for http requests.""" headers = super(RenderStaticDocumentController, self).get_http_headers() if self.pod_path is None: return headers path = self.pod.abs_path(self.static_doc.pod_path) self.pod.storage.update_headers(headers, path) modified = self.pod.storage.modified(path) time_obj = datetime.datetime.fromtimestamp(modified).timetuple() time_format = '%a, %d %b %Y %H:%M:%S GMT' headers['Last-Modified'] = time.strftime(time_format, time_obj) headers['ETag'] = '"{}"'.format(headers['Last-Modified']) headers['X-Grow-Pod-Path'] = self.static_doc.pod_path if self.static_doc.locale: headers['X-Grow-Locale'] = self.static_doc.locale return headers def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderStaticDocumentController.load', label=self.serving_path, meta={'path': self.serving_path}).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the static config specific filter. self.validate_path(self.route_info.meta['path_filter']) rendered_path = '{}{}'.format(source_dir, self.serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( self.serving_path, rendered_content) timer.stop_timer() return rendered_doc def render(self, jinja_env=None, request=None): """Read the static file.""" timer = self.pod.profile.timer( 'RenderStaticDocumentController.render', label=self.serving_path, meta={'path': self.serving_path}).start_timer() if not self.pod_path or not self.pod.file_exists(self.pod_path): text = '{} was not found in static files.' raise errors.RouteNotFoundError(text.format(self.serving_path)) # Validate the path with the static config specific filter. self.validate_path(self.route_info.meta['path_filter']) rendered_content = self.pod.read_file(self.pod_path) rendered_content = self.pod.extensions_controller.trigger( 'post_render', self.static_doc, rendered_content) rendered_doc = rendered_document.RenderedDocument( self.serving_path, rendered_content) timer.stop_timer() return rendered_doc
grow/grow
grow/rendering/render_controller.py
Python
mit
21,264
class AddPublishToSiteVersion < ActiveRecord::Migration[5.0] def change remove_column :author_site_storages, :publish add_column :author_site_versions, :published, :boolean end end
teamco/anthill_layout
db/migrate/20160425125336_add_publish_to_site_version.rb
Ruby
mit
193
# Copyright (C) 2012 Andy Balaam and The Pepper Developers # Released under the MIT License. See the file COPYING.txt for details. from nose.tools import * from libpepper import builtins from libpepper.environment import PepEnvironment from libpepper.vals.all_values import * def PlusEquals_increases_int_value___test(): env = PepEnvironment( None ) builtins.add_builtins( env ) PepInit( PepSymbol('int'), PepSymbol('x'), PepInt('7') ).evaluate( env ) # Sanity assert_equal( "7", PepSymbol('x').evaluate( env ).value ) PepModification( PepSymbol('x'), PepInt('3') ).evaluate( env ) assert_equal( "10", PepSymbol('x').evaluate( env ).value ) def PlusEquals_increases_float_value___test(): env = PepEnvironment( None ) builtins.add_builtins( env ) PepInit( PepSymbol('float'), PepSymbol('x'), PepFloat('7.2') ).evaluate( env ) # Sanity assert_equal( "7.2", PepSymbol('x').evaluate( env ).value ) PepModification( PepSymbol('x'), PepFloat('0.3') ).evaluate( env ) assert_equal( "7.5", PepSymbol('x').evaluate( env ).value )
andybalaam/pepper
old/pepper1/src/test/evaluation/test_plusequals.py
Python
mit
1,124
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import logging import os from clint.textui import prompt from django.core.management.base import BaseCommand from django.core.management.base import CommandError import kolibri from ...utils import dbrestore from ...utils import default_backup_folder from ...utils import get_dtm_from_backup_name from ...utils import search_latest from kolibri.utils import server logger = logging.getLogger(__name__) class Command(BaseCommand): output_transaction = True # @ReservedAssignment help = ( "Restores a database backup of Kolibri. This is not intended for " "replication across different devices, but *only* for restoring a " "single device from a local backup of the database." ) def add_arguments(self, parser): parser_group = parser.add_mutually_exclusive_group(required=True) parser_group.add_argument( "dump_file", nargs="?", type=str, help="Specifies the exact dump file to restore from", ) parser_group.add_argument( "--latest", "-l", action="store_true", dest="latest", help=( "Automatically detect and restore from latest backup matching " "the major and minor version (X.Y) of current installation." ), ) parser_group.add_argument( "--select", "-s", action="store_true", dest="select", help=( "Show the list of the last 10 backups Kolibri has done automatically " "for the user to select which one must be restored." ), ) def fetch_latest(self, dumps_root): """ Returns the latest backup file available in the dumps_root directory """ use_backup = None # Ultimately, we are okay about a backup from a minor release fallback_version = ".".join(map(str, kolibri.VERSION[:2])) if os.path.exists(dumps_root): use_backup = search_latest(dumps_root, fallback_version) if not use_backup: raise RuntimeError( "Could not find a database backup for version: {}".format( fallback_version ) ) return use_backup def select_backup(self, dumps_root): """ Returns the latest 10 dumps available in the dumps_root directory. Dumps are sorted by date, latests first """ backups = [] if os.path.exists(dumps_root): backups = os.listdir(dumps_root) backups = filter(lambda f: f.endswith(".dump"), backups) backups = list(backups) backups.sort(key=get_dtm_from_backup_name, reverse=True) backups = backups[:10] # don't show more than 10 backups if not backups: raise RuntimeError("Could not find a database backup}") # Shows a list of options to select from backup_options = [ { "selector": str(sel + 1), "prompt": get_dtm_from_backup_name(backup), "return": backup, } for sel, backup in enumerate(backups) ] selected_backup = prompt.options( "Type the number in brackets to select the backup to be restored", backup_options, ) return os.path.join(dumps_root, selected_backup) def handle(self, *args, **options): try: server.get_status() self.stderr.write( self.style.ERROR( "Cannot restore while Kolibri is running, please run:\n" "\n" " kolibri stop\n" ) ) raise SystemExit() except server.NotRunning: # Great, it's not running! pass latest = options["latest"] select = options["select"] use_backup = options.get("dump_file", None) logger.info("Beginning database restore") search_root = default_backup_folder() if latest: use_backup = self.fetch_latest(search_root) elif select: use_backup = self.select_backup(search_root) logger.info("Using backup file: {}".format(use_backup)) if not os.path.isfile(use_backup): raise CommandError("Couldn't find: {}".format(use_backup)) dbrestore(use_backup) self.stdout.write( self.style.SUCCESS("Restored database from: {path}".format(path=use_backup)) )
lyw07/kolibri
kolibri/core/deviceadmin/management/commands/dbrestore.py
Python
mit
4,759
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Search.Fluent { using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.Search.Fluent.Models; /// <summary> /// The result of checking for Search service name availability. /// </summary> public interface ICheckNameAvailabilityResult : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta, Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasInner<Models.CheckNameAvailabilityOutputInner> { /// <summary> /// Gets true if the specified name is valid and available for use, otherwise false. /// </summary> bool IsAvailable { get; } /// <summary> /// Gets the reason why the user-provided name for the search service could not be used, if any. The /// Reason element is only returned if NameAvailable is false. /// </summary> string UnavailabilityReason { get; } /// <summary> /// Gets an error message explaining the Reason value in more detail. /// </summary> string UnavailabilityMessage { get; } } }
hovsepm/azure-libraries-for-net
src/ResourceManagement/Search/Domain/ICheckNameAvailabilityResult.cs
C#
mit
1,305
# -*- encoding : utf-8 -*- require 'tmail/version' require 'tmail/mail' require 'tmail/mailbox' require 'tmail/core_extensions' require 'tmail/net'
liquidware/saasy
vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb
Ruby
mit
148
using Newtonsoft.Json.Linq; using SolrExpress.Search; using SolrExpress.Search.Parameter; using SolrExpress.Search.Parameter.Validation; using SolrExpress.Utility; namespace SolrExpress.Solr5.Search.Parameter { [AllowMultipleInstances] public sealed class FilterParameter<TDocument> : BaseFilterParameter<TDocument>, ISearchItemExecution<JObject> where TDocument : Document { private JToken _result; public void AddResultInContainer(JObject container) { var jArray = (JArray)container["filter"] ?? new JArray(); jArray.Add(this._result); container["filter"] = jArray; } public void Execute() { this._result = ParameterUtil.GetFilterWithTag(this.Query.Execute(), this.TagName); } } }
solr-express/solr-express
src/SolrExpress.Solr5/Search/Parameter/FilterParameter.cs
C#
mit
817
<?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>&lt;b&gt;GeyserCoin&lt;/b&gt; version</source> <translation>Versiune &lt;b&gt;GeyserCoin&lt;/b&gt;</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 &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:eay@cryptsoft.com&quot;&gt;eay@cryptsoft.com&lt;/a&gt;) 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>&amp;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>&amp;Copy Address</source> <translation>&amp;Copiază adresa</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation>Arată cod &amp;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 &amp;Message</source> <translation>Semnează &amp;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>&amp;Verify Message</source> <translation>&amp;Verifică mesajul</translation> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>Ște&amp;rge</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copiază &amp;eticheta</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;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 &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation>Atentie: Daca encriptezi portofelul si iti uiti parola, &lt;b&gt;VEI PIERDE TOATA MONEDELE&lt;/b&gt;!</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.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</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 &amp;message...</source> <translation>Semnează &amp;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>&amp;Transactions</source> <translation>&amp;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>&amp;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&amp;xit</source> <translation>&amp;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 &amp;Qt</source> <translation>Despre &amp;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>&amp;Options...</source> <translation>&amp;Setări...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>Criptează portofelul electronic...</translation> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Fă o copie de siguranță a portofelului...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>S&amp;chimbă parola...</translation> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation>&amp;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>&amp;Debug window</source> <translation>Fereastră &amp;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>&amp;Verify message...</source> <translation>&amp;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>&amp;About GeyserCoin</source> <translation>Despre GeyserCoin</translation> </message> <message> <location line="+9"/> <source>&amp;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>&amp;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>&amp;File</source> <translation>&amp;Fișier</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Setări</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>A&amp;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.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation>Staking. &lt;br&gt;Greutatea este %1&lt;br&gt;Greutatea retelei este %2&lt;br&gt;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&apos;t have mature coins</source> <translation>Nu este in modul stake deoarece nu sunt destule monede maturate</translation> </message> <message> <location line="-808"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation>&amp;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 &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portofelul este &lt;b&gt;criptat&lt;/b&gt; iar în momentul de față este &lt;b&gt;deblocat&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portofelul este &lt;b&gt;criptat&lt;/b&gt; iar în momentul de față este &lt;b&gt;blocat&lt;/b&gt;</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 &quot;medium&quot;. 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 &quot;medium&quot; 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>&amp;Label</source> <translation>&amp;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>&amp;Address</source> <translation>&amp;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 &quot;%1&quot; is already in the address book.</source> <translation>Adresa introdusă &quot;%1&quot; se află deja în lista de adrese.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid GeyserCoin address.</source> <translation>Adresa introdusă &quot;%1&quot; 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 &quot;de_DE&quot; (default: system locale)</source> <translation>Setează limba, de exemplu: &quot;de_DE&quot; (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>&amp;Main</source> <translation>&amp;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 &amp;fee</source> <translation>Plăteşte comision pentru tranzacţie &amp;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>&amp;Start GeyserCoin on system login</source> <translation>$Pornește GeyserCoin la logarea în sistem</translation> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;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 &amp;UPnP</source> <translation>Mapeaza portul folosind &amp;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>&amp;Connect through SOCKS proxy:</source> <translation>Conectează-te printr-un proxy socks</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;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>&amp;Port:</source> <translation>&amp;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 &amp;Version:</source> <translation>SOCKS &amp;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>&amp;Window</source> <translation>&amp;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>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;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&amp;inimize on close</source> <translation>&amp;i Ascunde fereastra în locul închiderii programului</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Afişare</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Interfata &amp; 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>&amp;Unit to show amounts in:</source> <translation>&amp;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 &amp;control features (experts only!)</source> <translation>Afiseaza &amp;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>&amp;OK</source> <translation>&amp; OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp; Renunta</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;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>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Tranzacții recente&lt;/b&gt;</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>&amp;Save As...</source> <translation>&amp;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>&amp;Information</source> <translation>&amp;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>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;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>&amp;Open</source> <translation>&amp;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>&amp;Show</source> <translation>&amp;Arată</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;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 &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Foloseste sagetile sus si jos pentru a naviga in istoric si &lt;b&gt;Ctrl-L&lt;/b&gt; pentru a curata.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrie &lt;b&gt;help&lt;/b&gt; 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 &amp;Recipient</source> <translation>&amp;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 &amp;All</source> <translation>Șterge &amp;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&amp;end</source> <translation>&amp;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>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; 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&amp;mount:</source> <translation>Su&amp;mă:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Plătește că&amp;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>&amp;Label:</source> <translation>&amp;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>&amp;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 &amp;All</source> <translation>Şterge &amp;tot</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;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 &quot;Sign Message&quot; to generate signature</source> <translation>Click &quot;Semneaza msajul&quot; 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 &quot;not accepted&quot; and it won&apos;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 &quot;nu a fost acceptat&quot;, ș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 &quot;GeyserCoin Alert&quot; 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 &lt;port&gt; (default: 16814 or testnet: 26814)</source> <translation>Ascultă pentru conectări pe &lt;port&gt; (implicit: 16814 sau testnet: 26814) </translation> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Menține cel mult &lt;n&gt; 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 &lt;port&gt; (default: 16815 or testnet: 26815)</source> <translation>Ascultă pentru conexiuni JSON-RPC pe &lt;port&gt; (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&apos;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: &apos;%s&apos;</source> <translation>Adresa -tor invalida: &apos;%s&apos;</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation>Suma invalida pentru -reservebalance=&lt;amount&gt;</translation> </message> <message> <location line="-88"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Tampon maxim pentru recepție per conexiune, &lt;n&gt;*1000 baiți (implicit: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Tampon maxim pentru transmitere per conexiune, &lt;n&gt;*1000 baiți (implicit: 1000)</translation> </message> <message> <location line="-17"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Efectuează conexiuni doar către nodurile din rețeaua &lt;net&gt; (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 &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; 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 &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Trimite comenzi la nodul care rulează la &lt;ip&gt; (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 &lt;n&gt; (default: 100)</source> <translation>Setează mărimea bazinului de chei la &lt;n&gt; (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: &apos;%s&apos;</source> <translation>Adresa -proxy nevalidă: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rețeaua specificată în -onlynet este necunoscută: &apos;%s&apos;</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: &apos;%s&apos;</source> <translation>Nu se poate rezolva adresa -bind: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Nu se poate rezolva adresa -externalip: &apos;%s&apos;</translation> </message> <message> <location line="-23"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Suma nevalidă pentru -paytxfee=&lt;amount&gt;: &apos;%s&apos;</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 &lt;n&gt; 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=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Suma invalida pentru -mininput=&lt;amount&gt;: &apos;%s&apos;</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=&lt;password&gt; 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=&lt;password&gt; î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
import pytest from click.testing import CliRunner import doitlive @pytest.fixture(scope="session") def runner(): doitlive.cli.TESTING = True return CliRunner()
sloria/doitlive
tests/conftest.py
Python
mit
171
# 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
// Žè‚ÌŒŸoƒf[ƒ^‚ð•\ަ‚·‚é #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‚µ‚Ü‚µ‚½" ); } // DepthƒXƒgƒŠ[ƒ€‚ð—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( "DepthƒXƒgƒŠ[ƒ€‚Ì—LŒø‰»‚ÉŽ¸”s‚µ‚Ü‚µ‚½" ); } // Žè‚ÌŒŸo‚ð—LŒø‚É‚·‚é sts = senseManager->EnableHand(); if ( sts < PXC_STATUS_NO_ERROR ) { throw std::runtime_error( "Žè‚ÌŒŸo‚Ì—LŒø‰»‚ÉŽ¸”s‚µ‚Ü‚µ‚½" ); } // ƒpƒCƒvƒ‰ƒCƒ“‚ð‰Šú‰»‚·‚é sts = senseManager->Init(); if ( sts<PXC_STATUS_NO_ERROR ) { throw std::runtime_error( "ƒpƒCƒvƒ‰ƒCƒ“‚̏‰Šú‰»‚ÉŽ¸”s‚µ‚Ü‚µ‚½" ); } // ƒ~ƒ‰[•\ަ‚É‚·‚é senseManager->QueryCaptureManager()->QueryDevice()->SetMirrorMode( PXCCapture::Device::MirrorMode::MIRROR_MODE_HORIZONTAL ); // Žè‚ÌŒŸo‚̏‰Šú‰» initializeHandTracking(); } void run() { // ƒƒCƒ“ƒ‹[ƒv while ( 1 ) { // ƒtƒŒ[ƒ€ƒf[ƒ^‚ðXV‚·‚é 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ƒƒ‰‚Å‚ ‚ê‚΁AƒvƒƒpƒeƒB‚ðÝ’è‚·‚é 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; } // Žè‚̍XV updateHandFrame(); // ƒtƒŒ[ƒ€‚ð‰ð•ú‚·‚é senseManager->ReleaseFrame(); } void updateHandFrame() { // Žè‚̃f[ƒ^‚ðXV‚·‚é 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; } // Žè‚̃}ƒXƒN‰æ‘œ‚ðŽæ“¾‚·‚é 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(); // ƒ}ƒXƒN‰æ‘œ‚̃TƒCƒY‚Í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‡‚¢‚ðŒˆ‚ß‚é // ¶Žè=1F0-127‚Ì”ÍˆÍ // ‰EŽè=2F0-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
# see https://github.com/cucumber/aruba#jruby-tips Aruba.configure do |config| config.before_cmd do |cmd| set_env('JRUBY_OPTS', "-X-C #{ENV['JRUBY_OPTS']}") # disable JIT since these processes are so short lived set_env('JAVA_OPTS', "-d32 #{ENV['JAVA_OPTS']}") # force jRuby to use client JVM for faster startup times end end if RUBY_PLATFORM == 'java'
alexrothenberg/ammeter
features/support/aruba_timeout.rb
Ruby
mit
365
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
import assert = require('assert'); import { ConnectionPoolTestFactory } from './ConnectionPoolTestFactory'; import { PoolConnection } from 'mysql'; export class DatabaseUtilities { public static clean(callback:(err:Error)=>void) { let pool = ConnectionPoolTestFactory.create(); let connection:PoolConnection = null; pool.getConnection(disableForeignKeyChecks); function disableForeignKeyChecks(err:Error, conn:PoolConnection) { if(err) { callback(err); } else { connection = conn; let sql = 'SET FOREIGN_KEY_CHECKS=0'; connection.query(sql, truncateProductsTable); } } function truncateProductsTable(err:Error, result:any[]) { if(err) { connection.release(); callback(err); } else { let sql = 'TRUNCATE TABLE `products`'; connection.query(sql, truncateOrdersProductsTable); } } function truncateOrdersProductsTable(err:Error, result:any[]) { if(err) { connection.release(); callback(err); } else { let sql = 'TRUNCATE TABLE `orders_products`'; connection.query(sql, enableForeignKeyChecks); } } function enableForeignKeyChecks(err:Error, result:any[]) { if(err) { connection.release(); callback(err); } else { let sql = 'SET FOREIGN_KEY_CHECKS=1'; connection.query(sql, releaseConnection); } } function releaseConnection(err:Error, result:any[]) { if(err) { assert.fail(null, null, err.message); } connection.release(); callback(err); } } public static shutdownPool() { const pool = ConnectionPoolTestFactory.create(); pool.end(); } }
joefallon/mydal
test/config/DatabaseUtilities.ts
TypeScript
mit
2,048
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