repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
paskalov/wb
vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php
11473
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\View\ChoiceView; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList; use Symfony\Component\Form\Extension\Core\EventListener\FixRadioInputListener; use Symfony\Component\Form\Extension\Core\EventListener\FixCheckboxInputListener; use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToBooleanArrayTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToBooleanArrayTransformer; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ChoiceType extends AbstractType { /** * Caches created choice lists. * * @var array */ private $choiceListCache = array(); /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { if (!$options['choice_list'] && !is_array($options['choices']) && !$options['choices'] instanceof \Traversable) { throw new LogicException('Either the option "choices" or "choice_list" must be set.'); } if ($options['expanded']) { // Initialize all choices before doing the index check below. // This helps in cases where index checks are optimized for non // initialized choice lists. For example, when using an SQL driver, // the index check would read in one SQL query and the initialization // requires another SQL query. When the initialization is done first, // one SQL query is sufficient. $preferredViews = $options['choice_list']->getPreferredViews(); $remainingViews = $options['choice_list']->getRemainingViews(); // Check if the choices already contain the empty value // Only add the empty value option if this is not the case if (null !== $options['placeholder'] && 0 === count($options['choice_list']->getChoicesForValues(array('')))) { $placeholderView = new ChoiceView(null, '', $options['placeholder']); // "placeholder" is a reserved index $this->addSubForms($builder, array('placeholder' => $placeholderView), $options); } $this->addSubForms($builder, $preferredViews, $options); $this->addSubForms($builder, $remainingViews, $options); if ($options['multiple']) { $builder->addViewTransformer(new ChoicesToBooleanArrayTransformer($options['choice_list'])); $builder->addEventSubscriber(new FixCheckboxInputListener($options['choice_list']), 10); } else { $builder->addViewTransformer(new ChoiceToBooleanArrayTransformer($options['choice_list'], $builder->has('placeholder'))); $builder->addEventSubscriber(new FixRadioInputListener($options['choice_list'], $builder->has('placeholder')), 10); } } else { if ($options['multiple']) { $builder->addViewTransformer(new ChoicesToValuesTransformer($options['choice_list'])); } else { $builder->addViewTransformer(new ChoiceToValueTransformer($options['choice_list'])); } } if ($options['multiple'] && $options['by_reference']) { // Make sure the collection created during the client->norm // transformation is merged back into the original collection $builder->addEventSubscriber(new MergeCollectionListener(true, true)); } } /** * {@inheritdoc} */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, array( 'multiple' => $options['multiple'], 'expanded' => $options['expanded'], 'preferred_choices' => $options['choice_list']->getPreferredViews(), 'choices' => $options['choice_list']->getRemainingViews(), 'separator' => '-------------------', 'placeholder' => null, )); // The decision, whether a choice is selected, is potentially done // thousand of times during the rendering of a template. Provide a // closure here that is optimized for the value of the form, to // avoid making the type check inside the closure. if ($options['multiple']) { $view->vars['is_selected'] = function ($choice, array $values) { return false !== array_search($choice, $values, true); }; } else { $view->vars['is_selected'] = function ($choice, $value) { return $choice === $value; }; } // Check if the choices already contain the empty value $view->vars['placeholder_in_choices'] = 0 !== count($options['choice_list']->getChoicesForValues(array(''))); // Only add the empty value option if this is not the case if (null !== $options['placeholder'] && !$view->vars['placeholder_in_choices']) { $view->vars['placeholder'] = $options['placeholder']; } // BC $view->vars['empty_value'] = $view->vars['placeholder']; $view->vars['empty_value_in_choices'] = $view->vars['placeholder_in_choices']; if ($options['multiple'] && !$options['expanded']) { // Add "[]" to the name in case a select tag with multiple options is // displayed. Otherwise only one of the selected options is sent in the // POST request. $view->vars['full_name'] = $view->vars['full_name'].'[]'; } } /** * {@inheritdoc} */ public function finishView(FormView $view, FormInterface $form, array $options) { if ($options['expanded']) { // Radio buttons should have the same name as the parent $childName = $view->vars['full_name']; // Checkboxes should append "[]" to allow multiple selection if ($options['multiple']) { $childName .= '[]'; } foreach ($view as $childView) { $childView->vars['full_name'] = $childName; } } } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $choiceListCache = & $this->choiceListCache; $choiceList = function (Options $options) use (&$choiceListCache) { // Harden against NULL values (like in EntityType and ModelType) $choices = null !== $options['choices'] ? $options['choices'] : array(); // Reuse existing choice lists in order to increase performance $hash = hash('sha256', serialize(array($choices, $options['preferred_choices']))); if (!isset($choiceListCache[$hash])) { $choiceListCache[$hash] = new SimpleChoiceList($choices, $options['preferred_choices']); } return $choiceListCache[$hash]; }; $emptyData = function (Options $options) { if ($options['multiple'] || $options['expanded']) { return array(); } return ''; }; $emptyValue = function (Options $options) { return $options['required'] ? null : ''; }; // for BC with the "empty_value" option $placeholder = function (Options $options) { return $options['empty_value']; }; $placeholderNormalizer = function (Options $options, $placeholder) { if ($options['multiple']) { // never use an empty value for this case return; } elseif (false === $placeholder) { // an empty value should be added but the user decided otherwise return; } elseif ($options['expanded'] && '' === $placeholder) { // never use an empty label for radio buttons return 'None'; } // empty value has been set explicitly return $placeholder; }; $compound = function (Options $options) { return $options['expanded']; }; $resolver->setDefaults(array( 'multiple' => false, 'expanded' => false, 'choice_list' => $choiceList, 'choices' => array(), 'preferred_choices' => array(), 'empty_data' => $emptyData, 'empty_value' => $emptyValue, // deprecated 'placeholder' => $placeholder, 'error_bubbling' => false, 'compound' => $compound, // The view data is always a string, even if the "data" option // is manually set to an object. // See https://github.com/symfony/symfony/pull/5582 'data_class' => null, )); $resolver->setNormalizers(array( 'empty_value' => $placeholderNormalizer, 'placeholder' => $placeholderNormalizer, )); $resolver->setAllowedTypes(array( 'choice_list' => array('null', 'Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface'), )); } /** * {@inheritdoc} */ public function getName() { return 'choice'; } /** * Adds the sub fields for an expanded choice field. * * @param FormBuilderInterface $builder The form builder. * @param array $choiceViews The choice view objects. * @param array $options The build options. */ private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options) { foreach ($choiceViews as $i => $choiceView) { if (is_array($choiceView)) { // Flatten groups $this->addSubForms($builder, $choiceView, $options); } else { $choiceOpts = array( 'value' => $choiceView->value, 'label' => $choiceView->label, 'translation_domain' => $options['translation_domain'], 'block_name' => 'entry', ); if ($options['multiple']) { $choiceType = 'checkbox'; // The user can check 0 or more checkboxes. If required // is true, he is required to check all of them. $choiceOpts['required'] = false; } else { $choiceType = 'radio'; } $builder->add($i, $choiceType, $choiceOpts); } } } }
mit
jayunit100/kubernetes
pkg/registry/core/componentstatus/doc.go
769
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package componentstatus provides interfaces and implementation for retrieving cluster // component status. package componentstatus // import "k8s.io/kubernetes/pkg/registry/core/componentstatus"
apache-2.0
IrvinAyala/fase2hdp
hdpDrupal/core/modules/aggregator/src/Form/OpmlFeedAdd.php
6779
<?php namespace Drupal\aggregator\Form; use Drupal\aggregator\FeedStorageInterface; use Drupal\Component\Utility\UrlHelper; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\ClientInterface; /** * Imports feeds from OPML. */ class OpmlFeedAdd extends FormBase { /** * The feed storage. * * @var \Drupal\aggregator\FeedStorageInterface */ protected $feedStorage; /** * The HTTP client to fetch the feed data with. * * @var \GuzzleHttp\ClientInterface */ protected $httpClient; /** * Constructs a database object. * * @param \Drupal\aggregator\FeedStorageInterface $feed_storage * The feed storage. * @param \GuzzleHttp\ClientInterface $http_client * The Guzzle HTTP client. */ public function __construct(FeedStorageInterface $feed_storage, ClientInterface $http_client) { $this->feedStorage = $feed_storage; $this->httpClient = $http_client; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('entity.manager')->getStorage('aggregator_feed'), $container->get('http_client') ); } /** * {@inheritdoc} */ public function getFormId() { return 'aggregator_opml_add'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $intervals = [900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200]; $period = array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($intervals, $intervals)); $form['upload'] = [ '#type' => 'file', '#title' => $this->t('OPML File'), '#description' => $this->t('Upload an OPML file containing a list of feeds to be imported.'), ]; $form['remote'] = [ '#type' => 'url', '#title' => $this->t('OPML Remote URL'), '#maxlength' => 1024, '#description' => $this->t('Enter the URL of an OPML file. This file will be downloaded and processed only once on submission of the form.'), ]; $form['refresh'] = [ '#type' => 'select', '#title' => $this->t('Update interval'), '#default_value' => 3600, '#options' => $period, '#description' => $this->t('The length of time between feed updates. Requires a correctly configured <a href=":cron">cron maintenance task</a>.', [':cron' => $this->url('system.status')]), ]; $form['actions'] = ['#type' => 'actions']; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Import'), ]; return $form; } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { // If both fields are empty or filled, cancel. $all_files = $this->getRequest()->files->get('files', []); if ($form_state->isValueEmpty('remote') == empty($all_files['upload'])) { $form_state->setErrorByName('remote', $this->t('<em>Either</em> upload a file or enter a URL.')); } } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $validators = ['file_validate_extensions' => ['opml xml']]; if ($file = file_save_upload('upload', $validators, FALSE, 0)) { $data = file_get_contents($file->getFileUri()); } else { // @todo Move this to a fetcher implementation. try { $response = $this->httpClient->get($form_state->getValue('remote')); $data = (string) $response->getBody(); } catch (RequestException $e) { $this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]); drupal_set_message($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()])); return; } } $feeds = $this->parseOpml($data); if (empty($feeds)) { drupal_set_message($this->t('No new feed has been added.')); return; } // @todo Move this functionality to a processor. foreach ($feeds as $feed) { // Ensure URL is valid. if (!UrlHelper::isValid($feed['url'], TRUE)) { drupal_set_message($this->t('The URL %url is invalid.', ['%url' => $feed['url']]), 'warning'); continue; } // Check for duplicate titles or URLs. $query = $this->feedStorage->getQuery(); $condition = $query->orConditionGroup() ->condition('title', $feed['title']) ->condition('url', $feed['url']); $ids = $query ->condition($condition) ->execute(); $result = $this->feedStorage->loadMultiple($ids); foreach ($result as $old) { if (strcasecmp($old->label(), $feed['title']) == 0) { drupal_set_message($this->t('A feed named %title already exists.', ['%title' => $old->label()]), 'warning'); continue 2; } if (strcasecmp($old->getUrl(), $feed['url']) == 0) { drupal_set_message($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]), 'warning'); continue 2; } } $new_feed = $this->feedStorage->create([ 'title' => $feed['title'], 'url' => $feed['url'], 'refresh' => $form_state->getValue('refresh'), ]); $new_feed->save(); } $form_state->setRedirect('aggregator.admin_overview'); } /** * Parses an OPML file. * * Feeds are recognized as <outline> elements with the attributes "text" and * "xmlurl" set. * * @param string $opml * The complete contents of an OPML document. * * @return array * An array of feeds, each an associative array with a "title" and a "url" * element, or NULL if the OPML document failed to be parsed. An empty array * will be returned if the document is valid but contains no feeds, as some * OPML documents do. * * @todo Move this to a parser in https://www.drupal.org/node/1963540. */ protected function parseOpml($opml) { $feeds = []; $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8'); if (xml_parse_into_struct($xml_parser, $opml, $values)) { foreach ($values as $entry) { if ($entry['tag'] == 'OUTLINE' && isset($entry['attributes'])) { $item = $entry['attributes']; if (!empty($item['XMLURL']) && !empty($item['TEXT'])) { $feeds[] = ['title' => $item['TEXT'], 'url' => $item['XMLURL']]; } } } } xml_parser_free($xml_parser); return $feeds; } }
apache-2.0
nguyenluan/moodle
lib/yui/src/blocks/js/blockregion.js
7144
/** * This file contains the Block Region class used by the drag and drop manager. * * Provides drag and drop functionality for blocks. * * @module moodle-core-blockdraganddrop */ /** * Constructs a new block region object. * * @namespace M.core.blockdraganddrop * @class BlockRegion * @constructor * @extends Base */ var BLOCKREGION = function() { BLOCKREGION.superclass.constructor.apply(this, arguments); }; BLOCKREGION.prototype = { /** * Called during the initialisation process of the object. * @method initializer */ initializer : function() { var node = this.get('node'); Y.log('Block region `'+this.get('region')+'` initialising', 'info'); if (!node) { Y.log('block region known about but no HTML structure found for it. Guessing structure.', 'warn'); node = this.create_and_add_node(); } var body = Y.one('body'), hasblocks = node.all('.'+CSS.BLOCK).size() > 0, hasregionclass = this.get_has_region_class(); this.set('hasblocks', hasblocks); if (!body.hasClass(hasregionclass)) { body.addClass(hasregionclass); } body.addClass((hasblocks) ? this.get_used_region_class() : this.get_empty_region_class()); body.removeClass((hasblocks) ? this.get_empty_region_class() : this.get_used_region_class()); }, /** * Creates a generic block region node and adds it to the DOM at the best guess location. * Any calling of this method is an unfortunate circumstance. * @method create_and_add_node * @return Node The newly created Node */ create_and_add_node : function() { var c = Y.Node.create, region = this.get('region'), node = c('<div id="block-region-'+region+'" data-droptarget="1"></div>') .addClass(CSS.BLOCKREGION) .setData('blockregion', region), regions = this.get('manager').get('regions'), i, haspre = false, haspost = false, added = false, pre, post; for (i in regions) { if (regions[i].match(/(pre|left)/)) { haspre = regions[i]; } else if (regions[i].match(/(post|right)/)) { haspost = regions[i]; } } if (haspre !== false && haspost !== false) { if (region === haspre) { post = Y.one('#block-region-'+haspost); if (post) { post.insert(node, 'before'); added = true; } } else { pre = Y.one('#block-region-'+haspre); if (pre) { pre.insert(node, 'after'); added = true; } } } if (added === false) { Y.one('body').append(node); } this.set('node', node); return node; }, /** * Change the move icons to enhanced drag handles and changes the cursor to a move icon when over the header. * @param M.core.dragdrop the block manager * @method change_block_move_icons */ change_block_move_icons : function(manager) { var handle, icon; this.get('node').all('.'+CSS.BLOCK+' a.'+CSS.EDITINGMOVE).each(function(moveicon){ moveicon.setStyle('cursor', 'move'); handle = manager.get_drag_handle(moveicon.getAttribute('title'), '', 'icon', true); icon = handle.one('img'); icon.addClass('iconsmall'); icon.removeClass('icon'); moveicon.replace(handle); }); }, /** * Returns the class name on the body that signifies the document knows about this region. * @method get_has_region_class * @return String */ get_has_region_class : function() { return 'has-region-'+this.get('region'); }, /** * Returns the class name to use on the body if the region contains no blocks. * @method get_empty_region_class * @return String */ get_empty_region_class : function() { return 'empty-region-'+this.get('region'); }, /** * Returns the class name to use on the body if the region contains blocks. * @method get_used_region_class * @return String */ get_used_region_class : function() { return 'used-region-'+this.get('region'); }, /** * Returns the node to use as the drop target for this region. * @method get_droptarget * @return Node */ get_droptarget : function() { var node = this.get('node'); if (node.test('[data-droptarget="1"]')) { return node; } return node.one('[data-droptarget="1"]'); }, /** * Enables the block region so that we can be sure the user can see it. * This is done even if it is empty. * @method enable */ enable : function() { Y.one('body').addClass(this.get_used_region_class()).removeClass(this.get_empty_region_class()); }, /** * Disables the region if it contains no blocks, essentially hiding it from the user. * @method disable_if_required */ disable_if_required : function() { if (this.get('node').all('.'+CSS.BLOCK).size() === 0) { Y.one('body').addClass(this.get_empty_region_class()).removeClass(this.get_used_region_class()); } } }; Y.extend(BLOCKREGION, Y.Base, BLOCKREGION.prototype, { NAME : 'core-blocks-dragdrop-blockregion', ATTRS : { /** * The drag and drop manager that created this block region instance. * @attribute manager * @type M.core.blockdraganddrop.Manager * @writeOnce */ manager : { // Can only be set during initialisation and must be set then. writeOnce : 'initOnly', validator : function (value) { return Y.Lang.isObject(value) && value instanceof MANAGER; } }, /** * The name of the block region this object represents. * @attribute region * @type String * @writeOnce */ region : { // Can only be set during initialisation and must be set then. writeOnce : 'initOnly', validator : function (value) { return Y.Lang.isString(value); } }, /** * The node the block region HTML starts at.s * @attribute region * @type Y.Node */ node : { validator : function (value) { return Y.Lang.isObject(value) || Y.Lang.isNull(value); } }, /** * True if the block region currently contains blocks. * @attribute hasblocks * @type Boolean * @default false */ hasblocks : { value : false, validator : function (value) { return Y.Lang.isBoolean(value); } } } });
gpl-3.0
anshulverma/cdnjs
ajax/libs/ionic/1.0.0-beta.5b/js/ionic.js
268583
/*! * Copyright 2014 Drifty Co. * http://drifty.com/ * * Ionic, v1.0.0-beta.5b * A powerful HTML5 mobile app framework. * http://ionicframework.com/ * * By @maxlynch, @benjsperry, @adamdbradley <3 * * Licensed under the MIT license. Please see LICENSE for more information. * */ (function() { // Create namespaces // window.ionic = { controllers: {}, views: {}, version: '1.0.0-beta.5b' }; (function(ionic) { var bezierCoord = function (x,y) { if(!x) x=0; if(!y) y=0; return {x: x, y: y}; }; function B1(t) { return t*t*t; } function B2(t) { return 3*t*t*(1-t); } function B3(t) { return 3*t*(1-t)*(1-t); } function B4(t) { return (1-t)*(1-t)*(1-t); } ionic.Animator = { // Quadratic bezier solver getQuadraticBezier: function(percent,C1,C2,C3,C4) { var pos = new bezierCoord(); pos.x = C1.x*B1(percent) + C2.x*B2(percent) + C3.x*B3(percent) + C4.x*B4(percent); pos.y = C1.y*B1(percent) + C2.y*B2(percent) + C3.y*B3(percent) + C4.y*B4(percent); return pos; }, // Cubic bezier solver from https://github.com/arian/cubic-bezier (MIT) getCubicBezier: function(x1, y1, x2, y2, duration) { // Precision epsilon = (1000 / 60 / duration) / 4; var curveX = function(t){ var v = 1 - t; return 3 * v * v * t * x1 + 3 * v * t * t * x2 + t * t * t; }; var curveY = function(t){ var v = 1 - t; return 3 * v * v * t * y1 + 3 * v * t * t * y2 + t * t * t; }; var derivativeCurveX = function(t){ var v = 1 - t; return 3 * (2 * (t - 1) * t + v * v) * x1 + 3 * (- t * t * t + 2 * v * t) * x2; }; return function(t) { var x = t, t0, t1, t2, x2, d2, i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++){ x2 = curveX(t2) - x; if (Math.abs(x2) < epsilon) return curveY(t2); d2 = derivativeCurveX(t2); if (Math.abs(d2) < 1e-6) break; t2 = t2 - x2 / d2; } t0 = 0, t1 = 1, t2 = x; if (t2 < t0) return curveY(t0); if (t2 > t1) return curveY(t1); // Fallback to the bisection method for reliability. while (t0 < t1){ x2 = curveX(t2); if (Math.abs(x2 - x) < epsilon) return curveY(t2); if (x > x2) t0 = t2; else t1 = t2; t2 = (t1 - t0) * 0.5 + t0; } // Failure return curveY(t2); }; }, animate: function(element, className, fn) { return { leave: function() { var endFunc = function() { element.classList.remove('leave'); element.classList.remove('leave-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('leave'); element.classList.add('leave-active'); return this; }, enter: function() { var endFunc = function() { element.classList.remove('enter'); element.classList.remove('enter-active'); element.removeEventListener('webkitTransitionEnd', endFunc); element.removeEventListener('transitionEnd', endFunc); }; element.addEventListener('webkitTransitionEnd', endFunc); element.addEventListener('transitionEnd', endFunc); element.classList.add('enter'); element.classList.add('enter-active'); return this; } }; } }; })(ionic); (function(window, document, ionic) { var readyCallbacks = []; var isDomReady = false; function domReady() { isDomReady = true; for(var x=0; x<readyCallbacks.length; x++) { ionic.requestAnimationFrame(readyCallbacks[x]); } readyCallbacks = []; document.removeEventListener('DOMContentLoaded', domReady); } document.addEventListener('DOMContentLoaded', domReady); // From the man himself, Mr. Paul Irish. // The requestAnimationFrame polyfill // Put it on window just to preserve its context // without having to use .call window._rAF = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 16); }; })(); var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; /** * @ngdoc utility * @name ionic.DomUtil * @module ionic */ ionic.DomUtil = { //Call with proper context /** * @ngdoc method * @name ionic.DomUtil#requestAnimationFrame * @alias ionic.requestAnimationFrame * @description Calls [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame), or a polyfill if not available. * @param {function} callback The function to call when the next frame * happens. */ requestAnimationFrame: function(cb) { window._rAF(cb); }, cancelAnimationFrame: function(cb) { }, /** * @ngdoc method * @name ionic.DomUtil#animationFrameThrottle * @alias ionic.animationFrameThrottle * @description * When given a callback, if that callback is called 100 times between * animation frames, adding Throttle will make it only run the last of * the 100 calls. * * @param {function} callback a function which will be throttled to * requestAnimationFrame * @returns {function} A function which will then call the passed in callback. * The passed in callback will receive the context the returned function is * called with. */ animationFrameThrottle: function(cb) { var args, isQueued, context; return function() { args = arguments; context = this; if (!isQueued) { isQueued = true; ionic.requestAnimationFrame(function() { cb.apply(context, args); isQueued = false; }); } }; }, /** * @ngdoc method * @name ionic.DomUtil#getPositionInParent * @description * Find an element's scroll offset within its container. * @param {DOMElement} element The element to find the offset of. * @returns {object} A position object with the following properties: * - `{number}` `left` The left offset of the element. * - `{number}` `top` The top offset of the element. */ getPositionInParent: function(el) { return { left: el.offsetLeft, top: el.offsetTop }; }, /** * @ngdoc method * @name ionic.DomUtil#ready * @description * Call a function when the DOM is ready, or if it is already ready * call the function immediately. * @param {function} callback The function to be called. */ ready: function(cb) { if(isDomReady || document.readyState === "complete") { ionic.requestAnimationFrame(cb); } else { readyCallbacks.push(cb); } }, /** * @ngdoc method * @name ionic.DomUtil#getTextBounds * @description * Get a rect representing the bounds of the given textNode. * @param {DOMElement} textNode The textNode to find the bounds of. * @returns {object} An object representing the bounds of the node. Properties: * - `{number}` `left` The left positton of the textNode. * - `{number}` `right` The right positton of the textNode. * - `{number}` `top` The top positton of the textNode. * - `{number}` `bottom` The bottom position of the textNode. * - `{number}` `width` The width of the textNode. * - `{number}` `height` The height of the textNode. */ getTextBounds: function(textNode) { if(document.createRange) { var range = document.createRange(); range.selectNodeContents(textNode); if(range.getBoundingClientRect) { var rect = range.getBoundingClientRect(); if(rect) { var sx = window.scrollX; var sy = window.scrollY; return { top: rect.top + sy, left: rect.left + sx, right: rect.left + sx + rect.width, bottom: rect.top + sy + rect.height, width: rect.width, height: rect.height }; } } } return null; }, /** * @ngdoc method * @name ionic.DomUtil#getChildIndex * @description * Get the first index of a child node within the given element of the * specified type. * @param {DOMElement} element The element to find the index of. * @param {string} type The nodeName to match children of element against. * @returns {number} The index, or -1, of a child with nodeName matching type. */ getChildIndex: function(element, type) { if(type) { var ch = element.parentNode.children; var c; for(var i = 0, k = 0, j = ch.length; i < j; i++) { c = ch[i]; if(c.nodeName && c.nodeName.toLowerCase() == type) { if(c == element) { return k; } k++; } } } return Array.prototype.slice.call(element.parentNode.children).indexOf(element); }, /** * @private */ swapNodes: function(src, dest) { dest.parentNode.insertBefore(src, dest); }, /** * @private */ centerElementByMargin: function(el) { el.style.marginLeft = (-el.offsetWidth) / 2 + 'px'; el.style.marginTop = (-el.offsetHeight) / 2 + 'px'; }, //Center twice, after raf, to fix a bug with ios and showing elements //that have just been attached to the DOM. centerElementByMarginTwice: function(el) { ionic.requestAnimationFrame(function() { ionic.DomUtil.centerElementByMargin(el); setTimeout(function() { ionic.DomUtil.centerElementByMargin(el); setTimeout(function() { ionic.DomUtil.centerElementByMargin(el); }); }); }); }, /** * @ngdoc method * @name ionic.DomUtil#getParentWithClass * @param {DOMElement} element * @param {string} className * @returns {DOMElement} The closest parent of element matching the * className, or null. */ getParentWithClass: function(e, className, depth) { depth = depth || 10; while(e.parentNode && depth--) { if(e.parentNode.classList && e.parentNode.classList.contains(className)) { return e.parentNode; } e = e.parentNode; } return null; }, /** * @ngdoc method * @name ionic.DomUtil#getParentWithClass * @param {DOMElement} element * @param {string} className * @returns {DOMElement} The closest parent or self matching the * className, or null. */ getParentOrSelfWithClass: function(e, className, depth) { depth = depth || 10; while(e && depth--) { if(e.classList && e.classList.contains(className)) { return e; } e = e.parentNode; } return null; }, /** * @ngdoc method * @name ionic.DomUtil#rectContains * @param {number} x * @param {number} y * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @returns {boolean} Whether {x,y} fits within the rectangle defined by * {x1,y1,x2,y2}. */ rectContains: function(x, y, x1, y1, x2, y2) { if(x < x1 || x > x2) return false; if(y < y1 || y > y2) return false; return true; } }; //Shortcuts ionic.requestAnimationFrame = ionic.DomUtil.requestAnimationFrame; ionic.cancelAnimationFrame = ionic.DomUtil.cancelAnimationFrame; ionic.animationFrameThrottle = ionic.DomUtil.animationFrameThrottle; })(window, document, ionic); /** * ion-events.js * * Author: Max Lynch <max@drifty.com> * * Framework events handles various mobile browser events, and * detects special events like tap/swipe/etc. and emits them * as custom events that can be used in an app. * * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys! */ (function(ionic) { // Custom event polyfill ionic.CustomEvent = (function() { if( typeof window.CustomEvent === 'function' ) return CustomEvent; var customEvent = function(event, params) { var evt; params = params || { bubbles: false, cancelable: false, detail: undefined }; try { evt = document.createEvent("CustomEvent"); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); } catch (error) { // fallback for browsers that don't support createEvent('CustomEvent') evt = document.createEvent("Event"); for (var param in params) { evt[param] = params[param]; } evt.initEvent(event, params.bubbles, params.cancelable); } return evt; }; customEvent.prototype = window.Event.prototype; return customEvent; })(); /** * @ngdoc utility * @name ionic.EventController * @module ionic */ ionic.EventController = { VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'], /** * @ngdoc method * @name ionic.EventController#trigger * @alias ionic.trigger * @param {string} eventType The event to trigger. * @param {object} data The data for the event. Hint: pass in * `{target: targetElement}` * @param {boolean=} bubbles Whether the event should bubble up the DOM. * @param {boolean=} cancelable Whether the event should be cancelable. */ // Trigger a new event trigger: function(eventType, data, bubbles, cancelable) { var event = new ionic.CustomEvent(eventType, { detail: data, bubbles: !!bubbles, cancelable: !!cancelable }); // Make sure to trigger the event on the given target, or dispatch it from // the window if we don't have an event target data && data.target && data.target.dispatchEvent && data.target.dispatchEvent(event) || window.dispatchEvent(event); }, /** * @ngdoc method * @name ionic.EventController#on * @alias ionic.on * @description Listen to an event on an element. * @param {string} type The event to listen for. * @param {function} callback The listener to be called. * @param {DOMElement} element The element to listen for the event on. */ on: function(type, callback, element) { var e = element || window; // Bind a gesture if it's a virtual event for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) { if(type == this.VIRTUALIZED_EVENTS[i]) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; } } // Otherwise bind a normal event e.addEventListener(type, callback); }, /** * @ngdoc method * @name ionic.EventController#off * @alias ionic.off * @description Remove an event listener. * @param {string} type * @param {function} callback * @param {DOMElement} element */ off: function(type, callback, element) { element.removeEventListener(type, callback); }, /** * @ngdoc method * @name ionic.EventController#onGesture * @alias ionic.onGesture * @description Add an event listener for a gesture on an element. * * Available eventTypes (from [hammer.js](http://eightmedia.github.io/hammer.js/)): * * `hold`, `tap`, `doubletap`, `drag`, `dragstart`, `dragend`, `dragup`, `dragdown`, <br/> * `dragleft`, `dragright`, `swipe`, `swipeup`, `swipedown`, `swipeleft`, `swiperight`, <br/> * `transform`, `transformstart`, `transformend`, `rotate`, `pinch`, `pinchin`, `pinchout`, </br> * `touch`, `release` * * @param {string} eventType The gesture event to listen for. * @param {function(e)} callback The function to call when the gesture * happens. * @param {DOMElement} element The angular element to listen for the event on. */ onGesture: function(type, callback, element) { var gesture = new ionic.Gesture(element); gesture.on(type, callback); return gesture; }, /** * @ngdoc method * @name ionic.EventController#offGesture * @alias ionic.offGesture * @description Remove an event listener for a gesture on an element. * @param {string} eventType The gesture event. * @param {function(e)} callback The listener that was added earlier. * @param {DOMElement} element The element the listener was added on. */ offGesture: function(gesture, type, callback) { gesture.off(type, callback); }, handlePopState: function(event) {} }; // Map some convenient top-level functions for event handling ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); }; ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); }; ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); }; ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); }; ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); }; })(window.ionic); /** * Simple gesture controllers with some common gestures that emit * gesture events. * * Ported from github.com/EightMedia/hammer.js Gestures - thanks! */ (function(ionic) { /** * ionic.Gestures * use this to create instances * @param {HTMLElement} element * @param {Object} options * @returns {ionic.Gestures.Instance} * @constructor */ ionic.Gesture = function(element, options) { return new ionic.Gestures.Instance(element, options || {}); }; ionic.Gestures = {}; // default settings ionic.Gestures.defaults = { // add css to the element to prevent the browser from doing // its native behavior. this doesnt prevent the scrolling, // but cancels the contextmenu, tap highlighting etc // set to false to disable this stop_browser_behavior: 'disable-user-behavior' }; // detect touchevents ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled; ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window); // dont use mouseevents on mobile devices ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i; ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX); // eventtypes per touchevent (start, move, end) // are filled by ionic.Gestures.event.determineEventTypes on setup ionic.Gestures.EVENT_TYPES = {}; // direction defines ionic.Gestures.DIRECTION_DOWN = 'down'; ionic.Gestures.DIRECTION_LEFT = 'left'; ionic.Gestures.DIRECTION_UP = 'up'; ionic.Gestures.DIRECTION_RIGHT = 'right'; // pointer type ionic.Gestures.POINTER_MOUSE = 'mouse'; ionic.Gestures.POINTER_TOUCH = 'touch'; ionic.Gestures.POINTER_PEN = 'pen'; // touch event defines ionic.Gestures.EVENT_START = 'start'; ionic.Gestures.EVENT_MOVE = 'move'; ionic.Gestures.EVENT_END = 'end'; // hammer document where the base events are added at ionic.Gestures.DOCUMENT = window.document; // plugins namespace ionic.Gestures.plugins = {}; // if the window events are set... ionic.Gestures.READY = false; /** * setup events to detect gestures on the document */ function setup() { if(ionic.Gestures.READY) { return; } // find what eventtypes we add listeners to ionic.Gestures.event.determineEventTypes(); // Register all gestures inside ionic.Gestures.gestures for(var name in ionic.Gestures.gestures) { if(ionic.Gestures.gestures.hasOwnProperty(name)) { ionic.Gestures.detection.register(ionic.Gestures.gestures[name]); } } // Add touch events on the document ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect); ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect); // ionic.Gestures is ready...! ionic.Gestures.READY = true; } /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * @param {HTMLElement} element * @param {Object} [options={}] * @returns {ionic.Gestures.Instance} * @name Gesture.Instance * @constructor */ ionic.Gestures.Instance = function(element, options) { var self = this; // A null element was passed into the instance, which means // whatever lookup was done to find this element failed to find it // so we can't listen for events on it. if(element === null) { void 0; return; } // setup ionic.GesturesJS window events and register all gestures // this also sets up the default options setup(); this.element = element; // start/stop detection option this.enabled = true; // merge options this.options = ionic.Gestures.utils.extend( ionic.Gestures.utils.extend({}, ionic.Gestures.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.stop_browser_behavior) { ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior); } // start detection on touchstart ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) { if(self.enabled) { ionic.Gestures.detection.startDetect(self, ev); } }); // return instance return this; }; ionic.Gestures.Instance.prototype = { /** * bind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ on: function onEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.addEventListener(gestures[t], handler, false); } return this; }, /** * unbind events to the instance * @param {String} gesture * @param {Function} handler * @returns {ionic.Gestures.Instance} */ off: function offEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.removeEventListener(gestures[t], handler, false); } return this; }, /** * trigger gesture event * @param {String} gesture * @param {Object} eventData * @returns {ionic.Gestures.Instance} */ trigger: function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @param {Boolean} state * @returns {ionic.Gestures.Instance} */ enable: function enable(state) { this.enabled = state; return this; } }; /** * this holds the last move event, * used to fix empty touchend issue * see the onTouch event for an explanation * type {Object} */ var last_move_event = null; /** * when the mouse is hold down, this is true * type {Boolean} */ var enable_detect = false; /** * when touch events have been fired, this is true * type {Boolean} */ var touch_triggered = false; ionic.Gestures.event = { /** * simple addEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ bindDom: function(element, type, handler) { var types = type.split(' '); for(var t=0; t<types.length; t++) { element.addEventListener(types[t], handler, false); } }, /** * touch events with mouse fallback * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Function} handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) { var sourceEventType = ev.type.toLowerCase(); // onmouseup, but when touchend has been fired we do nothing. // this is for touchdevices which also fire a mouseup on touchend if(sourceEventType.match(/mouse/) && touch_triggered) { return; } // mousebutton must be down or a touch event else if( sourceEventType.match(/touch/) || // touch events are always on screen sourceEventType.match(/pointerdown/) || // pointerevents touch (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed ){ enable_detect = true; } // mouse isn't pressed else if(sourceEventType.match(/mouse/) && ev.which !== 1) { enable_detect = false; } // we are in a touch event, set the touch triggered bool to true, // this for the conflicts that may occur on ios and android if(sourceEventType.match(/touch|pointer/)) { touch_triggered = true; } // count the total touches on the screen var count_touches = 0; // when touch has been triggered in this detection session // and we are now handling a mouse event, we stop that to prevent conflicts if(enable_detect) { // update pointerevent if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } // touch else if(sourceEventType.match(/touch/)) { count_touches = ev.touches.length; } // mouse else if(!touch_triggered) { count_touches = sourceEventType.match(/up/) ? 0 : 1; } // if we are in a end event, but when we remove one touch and // we still have enough, set eventType to move if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) { eventType = ionic.Gestures.EVENT_MOVE; } // no touches, force the end event else if(!count_touches) { eventType = ionic.Gestures.EVENT_END; } // store the last move event if(count_touches || last_move_event === null) { last_move_event = ev; } // trigger the handler handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev)); // remove pointerevent from list if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) { count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev); } } //debug(sourceEventType +" "+ eventType); // on the end we reset everything if(!count_touches) { last_move_event = null; enable_detect = false; touch_triggered = false; ionic.Gestures.PointerEvent.reset(); } }); }, /** * we have different events for each device/browser * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant */ determineEventTypes: function determineEventTypes() { // determine the eventtype we want to set var types; // pointerEvents magic if(ionic.Gestures.HAS_POINTEREVENTS) { types = ionic.Gestures.PointerEvent.getEvents(); } // on Android, iOS, blackberry, windows mobile we dont want any mouseevents else if(ionic.Gestures.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel']; } // for non pointer events browsers and mixed browsers, // like chrome on windows8 touch laptop else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup']; } ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1]; ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2]; }, /** * create touchlist depending on the event * @param {Object} ev * @param {String} eventType used by the fakemultitouch plugin */ getTouchList: function getTouchList(ev/*, eventType*/) { // get the fake pointerEvent touchlist if(ionic.Gestures.HAS_POINTEREVENTS) { return ionic.Gestures.PointerEvent.getTouchList(); } // get the touchlist else if(ev.touches) { return ev.touches; } // make fake touchlist from mouse position else { ev.indentifier = 1; return [ev]; } }, /** * collect event data for ionic.Gestures js * @param {HTMLElement} element * @param {String} eventType like ionic.Gestures.EVENT_MOVE * @param {Object} eventData */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = ionic.Gestures.POINTER_TOUCH; if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) { pointerType = ionic.Gestures.POINTER_MOUSE; } return { center : ionic.Gestures.utils.getCenter(touches), timeStamp : new Date().getTime(), target : ev.target, touches : touches, eventType : eventType, pointerType : pointerType, srcEvent : ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { if(this.srcEvent.preventManipulation) { this.srcEvent.preventManipulation(); } if(this.srcEvent.preventDefault) { //this.srcEvent.preventDefault(); } }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return ionic.Gestures.detection.stopDetect(); } }; } }; ionic.Gestures.PointerEvent = { /** * holds all pointers * type {Object} */ pointers: {}, /** * get a list of pointers * @returns {Array} touchlist */ getTouchList: function() { var self = this; var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Object.keys(self.pointers).sort().forEach(function(id) { touchlist.push(self.pointers[id]); }); return touchlist; }, /** * update the position of a pointer * @param {String} type ionic.Gestures.EVENT_END * @param {Object} pointerEvent */ updatePointer: function(type, pointerEvent) { if(type == ionic.Gestures.EVENT_END) { this.pointers = {}; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } return Object.keys(this.pointers).length; }, /** * check if ev matches pointertype * @param {String} pointerType ionic.Gestures.POINTER_MOUSE * @param {PointerEvent} ev */ matchType: function(pointerType, ev) { if(!ev.pointerType) { return false; } var types = {}; types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE); types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH); types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN); return types[pointerType]; }, /** * get events */ getEvents: function() { return [ 'pointerdown MSPointerDown', 'pointermove MSPointerMove', 'pointerup pointercancel MSPointerUp MSPointerCancel' ]; }, /** * reset the list */ reset: function() { this.pointers = {}; } }; ionic.Gestures.utils = { /** * extend method, * also used for cloning when dest is an empty object * @param {Object} dest * @param {Object} src * @param {Boolean} merge do a merge * @returns {Object} dest */ extend: function extend(dest, src, merge) { for (var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }, /** * find if a node is in the given parent * used for event delegation tricks * @param {HTMLElement} node * @param {HTMLElement} parent * @returns {boolean} has_parent */ hasParent: function(node, parent) { while(node){ if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @param {Array} touches * @returns {Object} center */ getCenter: function getCenter(touches) { var valuesX = [], valuesY = []; for(var t= 0,len=touches.length; t<len; t++) { valuesX.push(touches[t].pageX); valuesY.push(touches[t].pageY); } return { pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2), pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2) }; }, /** * calculate the velocity between two points * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y * @returns {Object} velocity */ getVelocity: function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }, /** * calculate the angle between two coordinates * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} angle */ getAngle: function getAngle(touch1, touch2) { var y = touch2.pageY - touch1.pageY, x = touch2.pageX - touch1.pageX; return Math.atan2(y, x) * 180 / Math.PI; }, /** * angle to direction define * @param {Touch} touch1 * @param {Touch} touch2 * @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.pageX - touch1.pageX, y = touch2.pageY - touch1.pageY; return Math.sqrt((x*x) + (y*y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists (fingers) * @param {Array} start * @param {Array} end * @returns {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * boolean if the direction is vertical * @param {String} direction * @returns {Boolean} is_vertical */ isVertical: function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }, /** * stop browser default behavior with css class * @param {HtmlElement} element * @param {Object} css_class */ stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_class) { // changed from making many style changes to just adding a preset classname // less DOM manipulations, less code, and easier to control in the CSS side of things // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method if(element && element.classList) { element.classList.add(css_class); element.onselectstart = function() { return false; }; } } }; ionic.Gestures.detection = { // contains all registred ionic.Gestures.gestures in the correct order gestures: [], // data of the current ionic.Gestures.gesture detection session current: null, // the previous ionic.Gestures.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start ionic.Gestures.gesture detection * @param {ionic.Gestures.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a ionic.Gestures.gesture detection on an element if(this.current) { return; } this.stopped = false; this.current = { inst : inst, // reference to ionic.GesturesInstance we're working for startEvent : ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent : false, // last eventData name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * ionic.Gestures.gesture detection * @param {Object} eventData */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }, /** * clear the ionic.Gestures.gesture vars * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected * to stop other ionic.Gestures.gestures from being fired */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }, /** * extend eventData for ionic.Gestures.gestures * @param {Object} ev * @returns {Object} ev */ extendEventData: function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }, /** * register new gesture * @param {Object} gesture object, see gestures.js for documentation * @returns {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend ionic.Gestures default options with the ionic.Gestures.gesture options ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add ionic.Gestures.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if (a.index < b.index) { return -1; } if (a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; ionic.Gestures.gestures = ionic.Gestures.gestures || {}; /** * Custom gestures * ============================== * * Gesture object * -------------------- * The object structure of a gesture: * * { name: 'mygesture', * index: 1337, * defaults: { * mygesture_option: true * } * handler: function(type, ev, inst) { * // trigger gesture event * inst.trigger(this.name, ev); * } * } * @param {String} name * this should be the name of the gesture, lowercase * it is also being used to disable/enable the gesture per instance config. * * @param {Number} [index=1000] * the index of the gesture, where it is going to be in the stack of gestures detection * like when you build an gesture that depends on the drag gesture, it is a good * idea to place it after the index of the drag gesture. * * @param {Object} [defaults={}] * the default settings of the gesture. these are added to the instance settings, * and can be overruled per instance. you can also add the name of the gesture, * but this is also added by default (and set to true). * * @param {Function} handler * this handles the gesture detection of your custom gesture and receives the * following arguments: * * @param {Object} eventData * event data containing the following properties: * timeStamp {Number} time the event occurred * target {HTMLElement} target element * touches {Array} touches (fingers, pointers, mouse) on the screen * pointerType {String} kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH * center {Object} center position of the touches. contains pageX and pageY * deltaTime {Number} the total time of the touches in the screen * deltaX {Number} the delta on x axis we haved moved * deltaY {Number} the delta on y axis we haved moved * velocityX {Number} the velocity on the x * velocityY {Number} the velocity on y * angle {Number} the angle we are moving * direction {String} the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT * distance {Number} the distance we haved moved * scale {Number} scaling of the touches, needs 2 touches * rotation {Number} rotation of the touches, needs 2 touches * * eventType {String} matches ionic.Gestures.EVENT_START|MOVE|END * srcEvent {Object} the source event, like TouchStart or MouseDown * * startEvent {Object} contains the same properties as above, * but from the first touch. this is used to calculate * distances, deltaTime, scaling etc * * @param {ionic.Gestures.Instance} inst * the instance we are doing the detection for. you can get the options from * the inst.options object and trigger the gesture event by calling inst.trigger * * * Handle gestures * -------------------- * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current * detection sessionic. It has the following properties * @param {String} name * contains the name of the gesture we have detected. it has not a real function, * only to check in other gestures if something is detected. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can * check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name * * readonly * @param {ionic.Gestures.Instance} inst * the instance we do the detection for * * readonly * @param {Object} startEvent * contains the properties of the first gesture detection in this sessionic. * Used for calculations about timing, distance, etc. * * readonly * @param {Object} lastEvent * contains all the properties of the last gesture detect in this sessionic. * * after the gesture detection session has been completed (user has released the screen) * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous, * this is usefull for gestures like doubletap, where you need to know if the * previous gesture was a tap * * options that have been set by the instance can be received by calling inst.options * * You can trigger a gesture event by calling inst.trigger("mygesture", event). * The first param is the name of your gesture, the second the event argument * * * Register gestures * -------------------- * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register * manually and pass your gesture object as a param * */ /** * Hold * Touch stays at the same place for x time * events hold */ ionic.Gestures.gestures.Hold = { name: 'hold', index: 10, defaults: { hold_timeout : 500, hold_threshold : 1 }, timer: null, handler: function holdGesture(ev, inst) { switch(ev.eventType) { case ionic.Gestures.EVENT_START: // clear any running timers clearTimeout(this.timer); // set the gesture so we can check in the timeout if it still is ionic.Gestures.detection.current.name = this.name; // set timer and if after the timeout it still is hold, // we trigger the hold event this.timer = setTimeout(function() { if(ionic.Gestures.detection.current.name == 'hold') { inst.trigger('hold', ev); } }, inst.options.hold_timeout); break; // when you move or end we clear the timer case ionic.Gestures.EVENT_MOVE: if(ev.distance > inst.options.hold_threshold) { clearTimeout(this.timer); } break; case ionic.Gestures.EVENT_END: clearTimeout(this.timer); break; } } }; /** * Tap/DoubleTap * Quick touch at a place or double at the same place * events tap, doubletap */ ionic.Gestures.gestures.Tap = { name: 'tap', index: 100, defaults: { tap_max_touchtime : 250, tap_max_distance : 10, tap_always : true, doubletap_distance : 20, doubletap_interval : 300 }, handler: function tapGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END && ev.srcEvent.type != 'touchcancel') { // previous gesture, for the double tap since these are two different gesture detections var prev = ionic.Gestures.detection.previous, did_doubletap = false; // when the touchtime is higher then the max touch time // or when the moving distance is too much if(ev.deltaTime > inst.options.tap_max_touchtime || ev.distance > inst.options.tap_max_distance) { return; } // check if double tap if(prev && prev.name == 'tap' && (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval && ev.distance < inst.options.doubletap_distance) { inst.trigger('doubletap', ev); did_doubletap = true; } // do a single tap if(!did_doubletap || inst.options.tap_always) { ionic.Gestures.detection.current.name = 'tap'; inst.trigger(ionic.Gestures.detection.current.name, ev); } } } }; /** * Swipe * triggers swipe events when the end velocity is above the threshold * events swipe, swipeleft, swiperight, swipeup, swipedown */ ionic.Gestures.gestures.Swipe = { name: 'swipe', index: 40, defaults: { // set 0 for unlimited, but this can conflict with transform swipe_max_touches : 1, swipe_velocity : 0.7 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { // max touches if(inst.options.swipe_max_touches > 0 && ev.touches.length > inst.options.swipe_max_touches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > inst.options.swipe_velocity || ev.velocityY > inst.options.swipe_velocity) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * Drag * Move with x fingers (default 1) around on the page. Blocking the scrolling when * moving left and right is a good practice. When all the drag events are blocking * you disable scrolling on that area. * events drag, drapleft, dragright, dragup, dragdown */ ionic.Gestures.gestures.Drag = { name: 'drag', index: 50, defaults: { drag_min_distance : 10, // Set correct_for_drag_min_distance to true to make the starting point of the drag // be calculated from where the drag was triggered, not from where the touch started. // Useful to avoid a jerk-starting drag, which can make fine-adjustments // through dragging difficult, and be visually unappealing. correct_for_drag_min_distance : true, // set 0 for unlimited, but this can conflict with transform drag_max_touches : 1, // prevent default browser behavior when dragging occurs // be careful with it, it makes the element a blocking element // when you are using the drag gesture, it is a good practice to set this true drag_block_horizontal : true, drag_block_vertical : true, // drag_lock_to_axis keeps the drag gesture on the axis that it started on, // It disallows vertical directions if the initial direction was horizontal, and vice versa. drag_lock_to_axis : false, // drag lock only kicks in when distance > drag_lock_min_distance // This way, locking occurs only when the distance has become large enough to reliably determine the direction drag_lock_min_distance : 25 }, triggered: false, handler: function dragGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // max touches if(inst.options.drag_max_touches > 0 && ev.touches.length > inst.options.drag_max_touches) { return; } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.drag_min_distance && ionic.Gestures.detection.current.name != this.name) { return; } // we are dragging! if(ionic.Gestures.detection.current.name != this.name) { ionic.Gestures.detection.current.name = this.name; if (inst.options.correct_for_drag_min_distance) { // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.drag_min_distance/ev.distance); ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor; ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor; // recalculate event data using new start point ev = ionic.Gestures.detection.extendEventData(ev); } } // lock drag to axis? if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) { ev.drag_locked_to_axis = true; } var last_direction = ionic.Gestures.detection.current.lastEvent.direction; if(ev.drag_locked_to_axis && last_direction !== ev.direction) { // keep direction on the axis that the drag gesture started on if(ionic.Gestures.utils.isVertical(last_direction)) { ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } // trigger normal event inst.trigger(this.name, ev); // direction event, like dragdown inst.trigger(this.name + ev.direction, ev); // block the browser events if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) || (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) { ev.preventDefault(); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Transform * User want to scale or rotate with 2 fingers * events transform, pinch, pinchin, pinchout, rotate */ ionic.Gestures.gestures.Transform = { name: 'transform', index: 45, defaults: { // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 transform_min_scale : 0.01, // rotation in degrees transform_min_rotation : 1, // prevent default browser behavior when two touches are on the screen // but it makes the element a blocking element // when you are using the transform gesture, it is a good practice to set this true transform_always_block : false }, triggered: false, handler: function transformGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(ionic.Gestures.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // atleast multitouch if(ev.touches.length < 2) { return; } // prevent default when two fingers are on the screen if(inst.options.transform_always_block) { ev.preventDefault(); } switch(ev.eventType) { case ionic.Gestures.EVENT_START: this.triggered = false; break; case ionic.Gestures.EVENT_MOVE: var scale_threshold = Math.abs(1-ev.scale); var rotation_threshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scale_threshold < inst.options.transform_min_scale && rotation_threshold < inst.options.transform_min_rotation) { return; } // we are transforming! ionic.Gestures.detection.current.name = this.name; // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } inst.trigger(this.name, ev); // basic transform event // trigger rotate event if(rotation_threshold > inst.options.transform_min_rotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scale_threshold > inst.options.transform_min_scale) { inst.trigger('pinch', ev); inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev); } break; case ionic.Gestures.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Touch * Called as first, tells the user has touched the screen * events touch */ ionic.Gestures.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { // call preventDefault at touchstart, and makes the element blocking by // disabling the scrolling of the page, but it improves gestures like // transforming and dragging. // be careful with using this, it can be very annoying for users to be stuck // on the page prevent_default: false, // disable mouse events, so only touch (or pen!) input triggers events prevent_mouseevents: false }, handler: function touchGesture(ev, inst) { if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.prevent_default) { ev.preventDefault(); } if(ev.eventType == ionic.Gestures.EVENT_START) { inst.trigger(this.name, ev); } } }; /** * Release * Called as last, tells the user has released the screen * events release */ ionic.Gestures.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == ionic.Gestures.EVENT_END) { inst.trigger(this.name, ev); } } }; })(window.ionic); (function(window, document, ionic) { var IOS = 'ios'; var ANDROID = 'android'; var WINDOWS_PHONE = 'windowsphone'; /** * @ngdoc utility * @name ionic.Platform * @module ionic */ ionic.Platform = { /** * @ngdoc property * @name ionic.Platform#isReady * @returns {boolean} Whether the device is ready. */ isReady: false, /** * @ngdoc property * @name ionic.Platform#isFullScreen * @returns {boolean} Whether the device is fullscreen. */ isFullScreen: false, /** * @ngdoc property * @name ionic.Platform#platforms * @returns {Array(string)} An array of all platforms found. */ platforms: null, /** * @ngdoc property * @name ionic.Platform#grade * @returns {string} What grade the current platform is. */ grade: null, ua: navigator.userAgent, /** * @ngdoc method * @name ionic.Platform#ready * @description * Trigger a callback once the device is ready, or immediately * if the device is already ready. This method can be run from * anywhere and does not need to be wrapped by any additonal methods. * When the app is within a WebView (Cordova), it'll fire * the callback once the device is ready. If the app is within * a web browser, it'll fire the callback after `window.load`. * @param {function} callback The function to call. */ ready: function(cb) { // run through tasks to complete now that the device is ready if(this.isReady) { cb(); } else { // the platform isn't ready yet, add it to this array // which will be called once the platform is ready readyCallbacks.push(cb); } }, /** * @private */ detect: function() { ionic.Platform._checkPlatforms(); ionic.requestAnimationFrame(function(){ // only add to the body class if we got platform info for(var i = 0; i < ionic.Platform.platforms.length; i++) { document.body.classList.add('platform-' + ionic.Platform.platforms[i]); } document.body.classList.add('grade-' + ionic.Platform.grade); }); }, /** * @ngdoc method * @name ionic.Platform#device * @description Return the current device (given by cordova). * @returns {object} The device object. */ device: function() { if(window.device) return window.device; if(this.isWebView()) void 0; return {}; }, _checkPlatforms: function(platforms) { this.platforms = []; this.grade = 'a'; if(this.isWebView()) { this.platforms.push('webview'); this.platforms.push('cordova'); } else { this.platforms.push('browser'); } if(this.isIPad()) this.platforms.push('ipad'); var platform = this.platform(); if(platform) { this.platforms.push(platform); var version = this.version(); if(version) { var v = version.toString(); if(v.indexOf('.') > 0) { v = v.replace('.', '_'); } else { v += '_0'; } this.platforms.push(platform + v.split('_')[0]); this.platforms.push(platform + v); if(this.isAndroid() && version < 4.4) { this.grade = (version < 4 ? 'c' : 'b'); } else if(this.isWindowsPhone()) { this.grade = 'b'; } } } }, /** * @ngdoc method * @name ionic.Platform#isWebView * @returns {boolean} Check if we are running within a WebView (such as Cordova). */ isWebView: function() { return !(!window.cordova && !window.PhoneGap && !window.phonegap); }, /** * @ngdoc method * @name ionic.Platform#isIPad * @returns {boolean} Whether we are running on iPad. */ isIPad: function() { if( /iPad/i.test(window.navigator.platform) ) { return true; } return /iPad/i.test(this.ua); }, /** * @ngdoc method * @name ionic.Platform#isIOS * @returns {boolean} Whether we are running on iOS. */ isIOS: function() { return this.is(IOS); }, /** * @ngdoc method * @name ionic.Platform#isAndroid * @returns {boolean} Whether we are running on Android. */ isAndroid: function() { return this.is(ANDROID); }, /** * @ngdoc method * @name ionic.Platform#isWindowsPhone * @returns {boolean} Whether we are running on Windows Phone. */ isWindowsPhone: function() { return this.is(WINDOWS_PHONE); }, /** * @ngdoc method * @name ionic.Platform#platform * @returns {string} The name of the current platform. */ platform: function() { // singleton to get the platform name if(platformName === null) this.setPlatform(this.device().platform); return platformName; }, /** * @private */ setPlatform: function(n) { if(typeof n != 'undefined' && n !== null && n.length) { platformName = n.toLowerCase(); } else if(this.ua.indexOf('Android') > 0) { platformName = ANDROID; } else if(this.ua.indexOf('iPhone') > -1 || this.ua.indexOf('iPad') > -1 || this.ua.indexOf('iPod') > -1) { platformName = IOS; } else if(this.ua.indexOf('Windows Phone') > -1) { platformName = WINDOWS_PHONE; } else { platformName = window.navigator.platform && navigator.platform.toLowerCase().split(' ')[0] || ''; } }, /** * @ngdoc method * @name ionic.Platform#version * @returns {string} The version of the current device platform. */ version: function() { // singleton to get the platform version if(platformVersion === null) this.setVersion(this.device().version); return platformVersion; }, /** * @private */ setVersion: function(v) { if(typeof v != 'undefined' && v !== null) { v = v.split('.'); v = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0)); if(!isNaN(v)) { platformVersion = v; return; } } platformVersion = 0; // fallback to user-agent checking var pName = this.platform(); var versionMatch = { 'android': /Android (\d+).(\d+)?/, 'ios': /OS (\d+)_(\d+)?/, 'windowsphone': /Windows Phone (\d+).(\d+)?/ }; if(versionMatch[pName]) { v = this.ua.match( versionMatch[pName] ); if(v.length > 2) { platformVersion = parseFloat( v[1] + '.' + v[2] ); } } }, // Check if the platform is the one detected by cordova is: function(type) { type = type.toLowerCase(); // check if it has an array of platforms if(this.platforms) { for(var x = 0; x < this.platforms.length; x++) { if(this.platforms[x] === type) return true; } } // exact match var pName = this.platform(); if(pName) { return pName === type.toLowerCase(); } // A quick hack for to check userAgent return this.ua.toLowerCase().indexOf(type) >= 0; }, /** * @ngdoc method * @name ionic.Platform#exitApp * @description Exit the app. */ exitApp: function() { this.ready(function(){ navigator.app && navigator.app.exitApp && navigator.app.exitApp(); }); }, /** * @ngdoc method * @name ionic.Platform#showStatusBar * @description Shows or hides the device status bar (in Cordova). * @param {boolean} shouldShow Whether or not to show the status bar. */ showStatusBar: function(val) { // Only useful when run within cordova this._showStatusBar = val; this.ready(function(){ // run this only when or if the platform (cordova) is ready ionic.requestAnimationFrame(function(){ if(ionic.Platform._showStatusBar) { // they do not want it to be full screen window.StatusBar && window.StatusBar.show(); document.body.classList.remove('status-bar-hide'); } else { // it should be full screen window.StatusBar && window.StatusBar.hide(); document.body.classList.add('status-bar-hide'); } }); }); }, /** * @ngdoc method * @name ionic.Platform#fullScreen * @description * Sets whether the app is fullscreen or not (in Cordova). * @param {boolean=} showFullScreen Whether or not to set the app to fullscreen. Defaults to true. * @param {boolean=} showStatusBar Whether or not to show the device's status bar. Defaults to false. */ fullScreen: function(showFullScreen, showStatusBar) { // showFullScreen: default is true if no param provided this.isFullScreen = (showFullScreen !== false); // add/remove the fullscreen classname to the body ionic.DomUtil.ready(function(){ // run this only when or if the DOM is ready ionic.requestAnimationFrame(function(){ if(ionic.Platform.isFullScreen) { document.body.classList.add('fullscreen'); } else { document.body.classList.remove('fullscreen'); } }); // showStatusBar: default is false if no param provided ionic.Platform.showStatusBar( (showStatusBar === true) ); }); } }; var platformName = null, // just the name, like iOS or Android platformVersion = null, // a float of the major and minor, like 7.1 readyCallbacks = []; // setup listeners to know when the device is ready to go function onWindowLoad() { if(ionic.Platform.isWebView()) { // the window and scripts are fully loaded, and a cordova/phonegap // object exists then let's listen for the deviceready document.addEventListener("deviceready", onPlatformReady, false); } else { // the window and scripts are fully loaded, but the window object doesn't have the // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova onPlatformReady(); } window.removeEventListener("load", onWindowLoad, false); } window.addEventListener("load", onWindowLoad, false); function onPlatformReady() { // the device is all set to go, init our own stuff then fire off our event ionic.Platform.isReady = true; ionic.Platform.detect(); for(var x=0; x<readyCallbacks.length; x++) { // fire off all the callbacks that were added before the platform was ready readyCallbacks[x](); } readyCallbacks = []; ionic.trigger('platformready', { target: document }); ionic.requestAnimationFrame(function(){ document.body.classList.add('platform-ready'); }); } })(this, document, ionic); (function(document, ionic) { 'use strict'; // Ionic CSS polyfills ionic.CSS = {}; (function() { // transform var i, keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform', '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform', 'msTransform']; for(i = 0; i < keys.length; i++) { if(document.documentElement.style[keys[i]] !== undefined) { ionic.CSS.TRANSFORM = keys[i]; break; } } // transition keys = ['webkitTransition', 'mozTransition', 'msTransition', 'transition']; for(i = 0; i < keys.length; i++) { if(document.documentElement.style[keys[i]] !== undefined) { ionic.CSS.TRANSITION = keys[i]; break; } } })(); // classList polyfill for them older Androids // https://gist.github.com/devongovett/1381839 if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') { Object.defineProperty(HTMLElement.prototype, 'classList', { get: function() { var self = this; function update(fn) { return function() { var x, classes = self.className.split(/\s+/); for(x=0; x<arguments.length; x++) { fn(classes, classes.indexOf(arguments[x]), arguments[x]); } self.className = classes.join(" "); }; } return { add: update(function(classes, index, value) { ~index || classes.push(value); }), remove: update(function(classes, index) { ~index && classes.splice(index, 1); }), toggle: update(function(classes, index, value) { ~index ? classes.splice(index, 1) : classes.push(value); }), contains: function(value) { return !!~self.className.split(/\s+/).indexOf(value); }, item: function(i) { return self.className.split(/\s+/)[i] || null; } }; } }); } })(document, ionic); /** * @ngdoc page * @name tap * @module ionic * @description * On touch devices such as a phone or tablet, some browsers implement a 300ms delay between * the time the user stops touching the display and the moment the browser executes the * click. This delay was initially introduced so the browser can know whether the user wants to * double-tap to zoom in on the webpage. Basically, the browser waits roughly 300ms to see if * the user is double-tapping, or just tapping on the display once. * * Out of the box, Ionic automatically removes the 300ms delay in order to make Ionic apps * feel more "native" like. Resultingly, other solutions such as * [fastclick](https://github.com/ftlabs/fastclick) and Angular's * [ngTouch](https://docs.angularjs.org/api/ngTouch) should not be included, to avoid conflicts. * * Some browsers already remove the delay with certain settings, such as the CSS property * `touch-events: none` or with specific meta tag viewport values. However, each of these * browsers still handle clicks differently, such as when to fire off or cancel the event * (like scrolling when the target is a button, or holding a button down). * For browsers that already remove the 300ms delay, consider Ionic's tap system as a way to * normalize how clicks are handled across the various devices so there's an expected response * no matter what the device, platform or version. Additionally, Ionic will prevent * ghostclicks which even browsers that remove the delay still experience. * * In some cases, third-party libraries may also be working with touch events which can interfere * with the tap system. For example, mapping libraries like Google or Leaflet Maps often implement * a touch detection system which conflicts with Ionic's tap system. * * ### Disabling the tap system * * To disable the tap for an element and all of its children elements, * add the attribute `data-tap-disabled="true"`. * * ```html * <div data-tap-disabled="true"> * <div id="google-map"></div> * </div> * ``` * * ### Additional Notes: * * - Ionic tap works with Ionic's JavaScript scrolling * - Elements can come and go from the DOM and Ionic tap doesn't keep adding and removing * listeners * - No "tap delay" after the first "tap" (you can tap as fast as you want, they all click) * - Minimal events listeners, only being added to document * - Correct focus in/out on each input type (select, textearea, range) on each platform/device * - Shows and hides virtual keyboard correctly for each platform/device * - Works with labels surrounding inputs * - Does not fire off a click if the user moves the pointer too far * - Adds and removes an 'activated' css class * - Multiple [unit tests](https://github.com/driftyco/ionic/blob/master/test/unit/utils/tap.unit.js) for each scenario * */ /* IONIC TAP --------------- - Both touch and mouse events are added to the document.body on DOM ready - If a touch event happens, it does not use mouse event listeners - On touchend, if the distance between start and end was small, trigger a click - In the triggered click event, add a 'isIonicTap' property - The triggered click receives the same x,y coordinates as as the end event - On document.body click listener (with useCapture=true), only allow clicks with 'isIonicTap' - Triggering clicks with mouse events work the same as touch, except with mousedown/mouseup - Tapping inputs is disabled during scrolling */ var tapDoc; // the element which the listeners are on (document.body) var tapActiveEle; // the element which is active (probably has focus) var tapEnabledTouchEvents; var tapMouseResetTimer; var tapPointerMoved; var tapPointerStart; var tapTouchFocusedInput; var tapLastTouchTarget; var tapTouchMoveListener = 'touchmove'; var TAP_RELEASE_TOLERANCE = 6; // how much the coordinates can be off between start/end, but still a click var tapEventListeners = { 'click': tapClickGateKeeper, 'mousedown': tapMouseDown, 'mouseup': tapMouseUp, 'mousemove': tapMouseMove, 'touchstart': tapTouchStart, 'touchend': tapTouchEnd, 'touchcancel': tapTouchCancel, 'touchmove': tapTouchMove, 'pointerdown': tapTouchStart, 'pointerup': tapTouchEnd, 'pointercancel': tapTouchCancel, 'pointermove': tapTouchMove, 'MSPointerDown': tapTouchStart, 'MSPointerUp': tapTouchEnd, 'MSPointerCancel': tapTouchCancel, 'MSPointerMove': tapTouchMove, 'focusin': tapFocusIn, 'focusout': tapFocusOut }; ionic.tap = { register: function(ele) { tapDoc = ele; tapEventListener('click', true, true); tapEventListener('mouseup'); tapEventListener('mousedown'); if( window.navigator.pointerEnabled ) { tapEventListener('pointerdown'); tapEventListener('pointerup'); tapEventListener('pointcancel'); tapTouchMoveListener = 'pointermove'; } else if (window.navigator.msPointerEnabled) { tapEventListener('MSPointerDown'); tapEventListener('MSPointerUp'); tapEventListener('MSPointerCancel'); tapTouchMoveListener = 'MSPointerMove'; } else { tapEventListener('touchstart'); tapEventListener('touchend'); tapEventListener('touchcancel'); } tapEventListener('focusin'); tapEventListener('focusout'); return function() { for(var type in tapEventListeners) { tapEventListener(type, false); } tapDoc = null; tapActiveEle = null; tapEnabledTouchEvents = false; tapPointerMoved = false; tapPointerStart = null; }; }, ignoreScrollStart: function(e) { return (e.defaultPrevented) || // defaultPrevented has been assigned by another component handling the event (e.target.isContentEditable) || (/file|range/i).test(e.target.type) || (e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-default')) == 'true' || // manually set within an elements attributes (!!(/object|embed/i).test(e.target.tagName)); // flash/movie/object touches should not try to scroll }, isTextInput: function(ele) { return !!ele && (ele.tagName == 'TEXTAREA' || ele.contentEditable === 'true' || (ele.tagName == 'INPUT' && !(/radio|checkbox|range|file|submit|reset/i).test(ele.type)) ); }, isLabelWithTextInput: function(ele) { var container = tapContainingElement(ele, false); return !!container && ionic.tap.isTextInput( tapTargetElement( container ) ); }, containsOrIsTextInput: function(ele) { return ionic.tap.isTextInput(ele) || ionic.tap.isLabelWithTextInput(ele); }, cloneFocusedInput: function(container, scrollIntance) { if(ionic.tap.hasCheckedClone) return; ionic.tap.hasCheckedClone = true; ionic.requestAnimationFrame(function(){ var focusInput = container.querySelector(':focus'); if( ionic.tap.isTextInput(focusInput) ) { var clonedInput = focusInput.parentElement.querySelector('.cloned-text-input'); if(!clonedInput) { clonedInput = document.createElement(focusInput.tagName); clonedInput.type = focusInput.type; clonedInput.value = focusInput.value; clonedInput.className = 'cloned-text-input'; clonedInput.readOnly = true; focusInput.parentElement.insertBefore(clonedInput, focusInput); focusInput.style.top = focusInput.offsetTop; focusInput.classList.add('previous-input-focus'); } } }); }, hasCheckedClone: false, removeClonedInputs: function(container, scrollIntance) { ionic.tap.hasCheckedClone = false; ionic.requestAnimationFrame(function(){ var clonedInputs = container.querySelectorAll('.cloned-text-input'); var previousInputFocus = container.querySelectorAll('.previous-input-focus'); var x; for(x=0; x<clonedInputs.length; x++) { clonedInputs[x].parentElement.removeChild( clonedInputs[x] ); } for(x=0; x<previousInputFocus.length; x++) { previousInputFocus[x].classList.remove('previous-input-focus'); previousInputFocus[x].style.top = ''; previousInputFocus[x].focus(); } }); }, requiresNativeClick: function(ele) { if(!ele || ele.disabled || (/file|range/i).test(ele.type) || (/object|video/i).test(ele.tagName) ) { return true; } if(ele.nodeType === 1) { var element = ele; while(element) { if( (element.dataset ? element.dataset.tapDisabled : element.getAttribute('data-tap-disabled')) == 'true' ) { return true; } element = element.parentElement; } } return false; }, setTolerance: function(val) { TAP_RELEASE_TOLERANCE = val; } }; function tapEventListener(type, enable, useCapture) { if(enable !== false) { tapDoc.addEventListener(type, tapEventListeners[type], useCapture); } else { tapDoc.removeEventListener(type, tapEventListeners[type]); } } function tapClick(e) { // simulate a normal click by running the element's click method then focus on it var container = tapContainingElement(e.target); var ele = tapTargetElement(container); if( ionic.tap.requiresNativeClick(ele) || tapPointerMoved ) return false; var c = getPointerCoordinates(e); void 0; triggerMouseEvent('click', ele, c.x, c.y); // if it's an input, focus in on the target, otherwise blur tapHandleFocus(ele); } function triggerMouseEvent(type, ele, x, y) { // using initMouseEvent instead of MouseEvent for our Android friends var clickEvent = document.createEvent("MouseEvents"); clickEvent.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, false, false, false, false, 0, null); clickEvent.isIonicTap = true; ele.dispatchEvent(clickEvent); } function tapClickGateKeeper(e) { if(e.target.type == 'submit' && e.detail === 0) { // do not prevent click if it came from an "Enter" or "Go" keypress submit return; } // do not allow through any click events that were not created by ionic.tap if( (ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target) ) || (!e.isIonicTap && !ionic.tap.requiresNativeClick(e.target)) ) { void 0; e.stopPropagation(); if( !ionic.tap.isLabelWithTextInput(e.target) ) { // labels clicks from native should not preventDefault othersize keyboard will not show on input focus e.preventDefault(); } return false; } } // MOUSE function tapMouseDown(e) { if(e.isIonicTap || tapIgnoreEvent(e)) return; if(tapEnabledTouchEvents) { void 0; e.stopPropagation(); if( !ionic.tap.isTextInput(e.target) || tapLastTouchTarget !== e.target ) { // If you preventDefault on a text input then you cannot move its text caret/cursor. // Allow through only the text input default. However, without preventDefault on an // input the 300ms delay can change focus on inputs after the keyboard shows up. // The focusin event handles the chance of focus changing after the keyboard shows. e.preventDefault(); } return false; } tapPointerMoved = false; tapPointerStart = getPointerCoordinates(e); tapEventListener('mousemove'); ionic.activator.start(e); } function tapMouseUp(e) { if(tapEnabledTouchEvents) { e.stopPropagation(); e.preventDefault(); return false; } if( tapIgnoreEvent(e) || (/select|option/i).test(e.target.tagName) ) return; if( !tapHasPointerMoved(e) ) { tapClick(e); } tapEventListener('mousemove', false); ionic.activator.end(); tapPointerMoved = false; } function tapMouseMove(e) { if( tapHasPointerMoved(e) ) { tapEventListener('mousemove', false); ionic.activator.end(); tapPointerMoved = true; return false; } } // TOUCH function tapTouchStart(e) { if( tapIgnoreEvent(e) ) return; tapPointerMoved = false; tapEnableTouchEvents(); tapPointerStart = getPointerCoordinates(e); tapEventListener(tapTouchMoveListener); ionic.activator.start(e); if( ionic.Platform.isIOS() && ionic.tap.isLabelWithTextInput(e.target) ) { // if the tapped element is a label, which has a child input // then preventDefault so iOS doesn't ugly auto scroll to the input // but do not prevent default on Android or else you cannot move the text caret // and do not prevent default on Android or else no virtual keyboard shows up var textInput = tapTargetElement( tapContainingElement(e.target) ); if( textInput !== tapActiveEle ) { // don't preventDefault on an already focused input or else iOS's text caret isn't usable e.preventDefault(); } } } function tapTouchEnd(e) { if( tapIgnoreEvent(e) ) return; tapEnableTouchEvents(); if( !tapHasPointerMoved(e) ) { tapClick(e); if( (/select|option/i).test(e.target.tagName) ) { e.preventDefault(); } } tapLastTouchTarget = e.target; tapTouchCancel(); } function tapTouchMove(e) { if( tapHasPointerMoved(e) ) { tapPointerMoved = true; tapEventListener(tapTouchMoveListener, false); ionic.activator.end(); return false; } } function tapTouchCancel(e) { tapEventListener(tapTouchMoveListener, false); ionic.activator.end(); tapPointerMoved = false; } function tapEnableTouchEvents() { tapEnabledTouchEvents = true; clearTimeout(tapMouseResetTimer); tapMouseResetTimer = setTimeout(function(){ tapEnabledTouchEvents = false; }, 2000); } function tapIgnoreEvent(e) { if(e.isTapHandled) return true; e.isTapHandled = true; if( ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target) ) { e.preventDefault(); return true; } } function tapHandleFocus(ele) { tapTouchFocusedInput = null; var triggerFocusIn = false; if(ele.tagName == 'SELECT') { // trick to force Android options to show up triggerMouseEvent('mousedown', ele, 0, 0); ele.focus && ele.focus(); triggerFocusIn = true; } else if(tapActiveElement() === ele) { // already is the active element and has focus triggerFocusIn = true; } else if( (/input|textarea/i).test(ele.tagName) ) { triggerFocusIn = true; ele.focus && ele.focus(); ele.value = ele.value; if( tapEnabledTouchEvents ) { tapTouchFocusedInput = ele; } } else { tapFocusOutActive(); } if(triggerFocusIn) { tapActiveElement(ele); ionic.trigger('ionic.focusin', { target: ele }, true); } } function tapFocusOutActive() { var ele = tapActiveElement(); if(ele && (/input|textarea|select/i).test(ele.tagName) ) { void 0; ele.blur(); } tapActiveElement(null); } function tapFocusIn(e) { // Because a text input doesn't preventDefault (so the caret still works) there's a chance // that it's mousedown event 300ms later will change the focus to another element after // the keyboard shows up. if( tapEnabledTouchEvents && ionic.tap.isTextInput( tapActiveElement() ) && ionic.tap.isTextInput(tapTouchFocusedInput) && tapTouchFocusedInput !== e.target ) { // 1) The pointer is from touch events // 2) There is an active element which is a text input // 3) A text input was just set to be focused on by a touch event // 4) A new focus has been set, however the target isn't the one the touch event wanted void 0; tapTouchFocusedInput.focus(); tapTouchFocusedInput = null; } ionic.scroll.isScrolling = false; } function tapFocusOut() { tapActiveElement(null); } function tapActiveElement(ele) { if(arguments.length) { tapActiveEle = ele; } return tapActiveEle || document.activeElement; } function tapHasPointerMoved(endEvent) { if(!endEvent || !tapPointerStart || ( tapPointerStart.x === 0 && tapPointerStart.y === 0 )) { return false; } var endCoordinates = getPointerCoordinates(endEvent); return Math.abs(tapPointerStart.x - endCoordinates.x) > TAP_RELEASE_TOLERANCE || Math.abs(tapPointerStart.y - endCoordinates.y) > TAP_RELEASE_TOLERANCE; } function getPointerCoordinates(event) { // This method can get coordinates for both a mouse click // or a touch depending on the given event var c = { x:0, y:0 }; if(event) { var touches = event.touches && event.touches.length ? event.touches : [event]; var e = (event.changedTouches && event.changedTouches[0]) || touches[0]; if(e) { c.x = e.clientX || e.pageX || 0; c.y = e.clientY || e.pageY || 0; } } return c; } function tapContainingElement(ele, allowSelf) { var climbEle = ele; for(var x=0; x<6; x++) { if(!climbEle) break; if(climbEle.tagName === 'LABEL') return climbEle; climbEle = ele.parentElement; } if(allowSelf !== false) return ele; } function tapTargetElement(ele) { if(ele && ele.tagName === 'LABEL') { if(ele.control) return ele.control; // older devices do not support the "control" property if(ele.querySelector) { var control = ele.querySelector('input,textarea,select'); if(control) return control; } } return ele; } ionic.DomUtil.ready(function(){ //do nothing for e2e tests if (!angular.scenario) { ionic.tap.register(document); } }); (function(document, ionic) { 'use strict'; var queueElements = {}; // elements that should get an active state in XX milliseconds var activeElements = {}; // elements that are currently active var keyId = 0; // a counter for unique keys for the above ojects var ACTIVATED_CLASS = 'activated'; ionic.activator = { start: function(e) { var self = this; // when an element is touched/clicked, it climbs up a few // parents to see if it is an .item or .button element ionic.requestAnimationFrame(function(){ if ( ionic.tap.requiresNativeClick(e.target) ) return; var ele = e.target; var eleToActivate; for(var x=0; x<4; x++) { if(!ele || ele.nodeType !== 1) break; if(eleToActivate && ele.classList.contains('item')) { eleToActivate = ele; break; } if( ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click') ) { eleToActivate = ele; break; } if( ele.classList.contains('button') ) { eleToActivate = ele; break; } ele = ele.parentElement; } if(eleToActivate) { // queue that this element should be set to active queueElements[keyId] = eleToActivate; // in XX milliseconds, set the queued elements to active if(e.type === 'touchstart') { self._activateTimeout = setTimeout(activateElements, 80); } else { ionic.requestAnimationFrame(activateElements); } keyId = (keyId > 19 ? 0 : keyId + 1); } }); }, end: function() { // clear out any active/queued elements after XX milliseconds clearTimeout(this._activateTimeout); setTimeout(clear, 200); } }; function clear() { // clear out any elements that are queued to be set to active queueElements = {}; // in the next frame, remove the active class from all active elements ionic.requestAnimationFrame(deactivateElements); } function activateElements() { // activate all elements in the queue for(var key in queueElements) { if(queueElements[key]) { queueElements[key].classList.add(ACTIVATED_CLASS); activeElements[key] = queueElements[key]; } } queueElements = {}; } function deactivateElements() { for(var key in activeElements) { if(activeElements[key]) { activeElements[key].classList.remove(ACTIVATED_CLASS); delete activeElements[key]; } } } })(document, ionic); (function(ionic) { /* for nextUid() function below */ var uid = ['0','0','0']; /** * Various utilities used throughout Ionic * * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed. */ ionic.Utils = { arrayMove: function (arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length; while ((k--) + 1) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; }, /** * Return a function that will be called with the given context */ proxy: function(func, context) { var args = Array.prototype.slice.call(arguments, 2); return function() { return func.apply(context, args.concat(Array.prototype.slice.call(arguments))); }; }, /** * Only call a function once in the given interval. * * @param func {Function} the function to call * @param wait {int} how long to wait before/after to allow function calls * @param immediate {boolean} whether to call immediately or after the wait interval */ debounce: function(func, wait, immediate) { var timeout, args, context, timestamp, result; return function() { context = this; args = arguments; timestamp = new Date(); var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }, /** * Throttle the given fun, only allowing it to be * called at most every `wait` ms. */ throttle: function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); }; return function() { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }, // Borrowed from Backbone.js's extend // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. inherit: function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. ionic.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) ionic.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }, // Extend adapted from Underscore.js extend: function(obj) { var args = Array.prototype.slice.call(arguments, 1); for(var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }, /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ nextUid: function() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } }; // Bind a few of the most useful functions to the ionic scope ionic.inherit = ionic.Utils.inherit; ionic.extend = ionic.Utils.extend; ionic.throttle = ionic.Utils.throttle; ionic.proxy = ionic.Utils.proxy; ionic.debounce = ionic.Utils.debounce; })(window.ionic); /** * @ngdoc page * @name keyboard * @module ionic * @description * On both Android and iOS, Ionic will attempt to prevent the keyboard from obscuring inputs and * focusable elements when it appears by scrolling them into view. In order for this to work, * any focusable elements must be within a [Scroll View](http://ionicframework.com/docs/api/directive/ionScroll/) * or a directive such as [Content](http://ionicframework.com/docs/api/directive/ionContent/) that has a Scroll View. * * It will also attempt to prevent the native overflow scrolling on focus, which can cause layout issues such as * pushing headers up and out of view. * * The keyboard fixes work best in conjunction with the [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard), * although it will perform reasonably well without. However, if you are using Cordova there is no reason not to use the plugin. * * ### Hide when keyboard shows * * To hide an element when the keyboard is open, add the class `hide-on-keyboard-open`. * * ```html * <div class="hide-on-keyboard-open"> * <div id="google-map"></div> * </div> * ``` * ---------- * * ### Plugin Usage * Information on using the plugin can be found at [https://github.com/driftyco/ionic-plugins-keyboard](https://github.com/driftyco/ionic-plugins-keyboard). * * ---------- * * ### Android Notes * - If your app is running in fullscreen, i.e. you have `<preference name="Fullscreen" value="true" />` in your `config.xml` file * you will need to set `ionic.Platform.isFullScreen = true` manually. * * - You can configure the behavior of the web view when the keyboard shows by setting * [android:windowSoftInputMode](http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode) to either `adjustPan`, `adjustResize` or `adjustNothing` in your app's activity in `AndroidManifest.xml`. `adjustResize` is the recommended setting for Ionic, but if for some reason you do use `adjustPan` you will need to set `ionic.Platform.isFullScreen = true`. * * ```xml * <activity android:windowSoftInputMode="adjustResize"> * * ``` * * ### iOS Notes * - if you are not using the keyboard plugin, switching to inputs below the keyboard using the accessory bar will automatically use the native browser's * overflow scrolling and push headers out of view * */ /* IONIC KEYBOARD --------------- */ var keyboardViewportHeight = window.innerHeight; var keyboardIsOpen; var keyboardActiveElement; var keyboardFocusOutTimer; var keyboardFocusInTimer; var keyboardLastShow = 0; var KEYBOARD_OPEN_CSS = 'keyboard-open'; var SCROLL_CONTAINER_CSS = 'scroll'; ionic.keyboard = { isOpen: false, height: null, landscape: false, }; function keyboardInit() { if( keyboardHasPlugin() ) { window.addEventListener('native.showkeyboard', keyboardNativeShow); window.addEventListener('native.hidekeyboard', keyboardFocusOut); } else { document.body.addEventListener('focusout', keyboardFocusOut); } document.body.addEventListener('ionic.focusin', keyboardBrowserFocusIn); document.body.addEventListener('focusin', keyboardBrowserFocusIn); document.body.addEventListener('orientationchange', keyboardOrientationChange); document.removeEventListener('touchstart', keyboardInit); } function keyboardNativeShow(e) { clearTimeout(keyboardFocusOutTimer); ionic.keyboard.height = e.keyboardHeight; } function keyboardBrowserFocusIn(e) { if( !e.target || !ionic.tap.isTextInput(e.target) || !keyboardIsWithinScroll(e.target) ) return; document.addEventListener('keydown', keyboardOnKeyDown, false); document.body.scrollTop = 0; document.body.querySelector('.scroll-content').scrollTop = 0; keyboardActiveElement = e.target; keyboardSetShow(e); } function keyboardSetShow(e) { clearTimeout(keyboardFocusInTimer); clearTimeout(keyboardFocusOutTimer); keyboardFocusInTimer = setTimeout(function(){ if ( keyboardLastShow + 350 > Date.now() ) return; keyboardLastShow = Date.now(); var keyboardHeight; var elementBounds = keyboardActiveElement.getBoundingClientRect(); var count = 0; var pollKeyboardHeight = setInterval(function(){ keyboardHeight = keyboardGetHeight(); if (count > 10){ clearInterval(pollKeyboardHeight); //waited long enough, just guess keyboardHeight = 275; } if (keyboardHeight){ keyboardShow(e.target, elementBounds.top, elementBounds.bottom, keyboardViewportHeight, keyboardHeight); clearInterval(pollKeyboardHeight); } count++; }, 100); }, 32); } function keyboardShow(element, elementTop, elementBottom, viewportHeight, keyboardHeight) { var details = { target: element, elementTop: Math.round(elementTop), elementBottom: Math.round(elementBottom), keyboardHeight: keyboardHeight, viewportHeight: viewportHeight }; details.hasPlugin = keyboardHasPlugin(); details.contentHeight = viewportHeight - keyboardHeight; void 0; // figure out if the element is under the keyboard details.isElementUnderKeyboard = (details.elementBottom > details.contentHeight); ionic.keyboard.isOpen = true; // send event so the scroll view adjusts keyboardActiveElement = element; ionic.trigger('scrollChildIntoView', details, true); ionic.requestAnimationFrame(function(){ document.body.classList.add(KEYBOARD_OPEN_CSS); }); // any showing part of the document that isn't within the scroll the user // could touchmove and cause some ugly changes to the app, so disable // any touchmove events while the keyboard is open using e.preventDefault() document.addEventListener('touchmove', keyboardPreventDefault, false); return details; } function keyboardFocusOut(e) { clearTimeout(keyboardFocusOutTimer); keyboardFocusOutTimer = setTimeout(keyboardHide, 350); } function keyboardHide() { void 0; ionic.keyboard.isOpen = false; ionic.trigger('resetScrollView', { target: keyboardActiveElement }, true); ionic.requestAnimationFrame(function(){ document.body.classList.remove(KEYBOARD_OPEN_CSS); }); // the keyboard is gone now, remove the touchmove that disables native scroll document.removeEventListener('touchmove', keyboardPreventDefault); document.removeEventListener('keydown', keyboardOnKeyDown); } function keyboardUpdateViewportHeight() { if( window.innerHeight > keyboardViewportHeight ) { keyboardViewportHeight = window.innerHeight; } } function keyboardOnKeyDown(e) { if( ionic.scroll.isScrolling ) { keyboardPreventDefault(e); } } function keyboardPreventDefault(e) { if( e.target.tagName !== 'TEXTAREA' ) { e.preventDefault(); } } function keyboardOrientationChange() { var updatedViewportHeight = window.innerHeight; //too slow, have to wait for updated height if (updatedViewportHeight === keyboardViewportHeight){ var count = 0; var pollViewportHeight = setInterval(function(){ //give up if (count > 10){ clearInterval(pollViewportHeight); } updatedViewportHeight = window.innerHeight; if (updatedViewportHeight !== keyboardViewportHeight){ if (updatedViewportHeight < keyboardViewportHeight){ ionic.keyboard.landscape = true; } else { ionic.keyboard.landscape = false; } keyboardViewportHeight = updatedViewportHeight; clearInterval(pollViewportHeight); } count++; }, 50); } else { keyboardViewportHeight = updatedViewportHeight; } } function keyboardGetHeight() { // check if we are already have a keyboard height from the plugin if ( ionic.keyboard.height ) { return ionic.keyboard.height; } if ( ionic.Platform.isAndroid() ){ //should be using the plugin, no way to know how big the keyboard is, so guess if ( ionic.Platform.isFullScreen ){ return 275; } //otherwise, wait for the screen to resize if ( window.innerHeight < keyboardViewportHeight ){ return keyboardViewportHeight - window.innerHeight; } else { return 0; } } // fallback for when its the webview without the plugin // or for just the standard web browser if( ionic.Platform.isIOS() ) { if ( ionic.keyboard.landscape ){ return 206; } if (!ionic.Platform.isWebView()){ return 216; } return 260; } // safe guess return 275; } function keyboardIsWithinScroll(ele) { while(ele) { if(ele.classList.contains(SCROLL_CONTAINER_CSS)) { return true; } ele = ele.parentElement; } return false; } function keyboardHasPlugin() { return !!(window.cordova && cordova.plugins && cordova.plugins.Keyboard); } ionic.Platform.ready(function() { keyboardUpdateViewportHeight(); // Android sometimes reports bad innerHeight on window.load // try it again in a lil bit to play it safe setTimeout(keyboardUpdateViewportHeight, 999); // only initialize the adjustments for the virtual keyboard // if a touchstart event happens document.addEventListener('touchstart', keyboardInit, false); }); var viewportTag; var viewportProperties = {}; ionic.viewport = { orientation: function() { // 0 = Portrait // 90 = Landscape // not using window.orientation because each device has a different implementation return (window.innerWidth > window.innerHeight ? 90 : 0); } }; function viewportLoadTag() { var x; for(x=0; x<document.head.children.length; x++) { if(document.head.children[x].name == 'viewport') { viewportTag = document.head.children[x]; break; } } if(viewportTag) { var props = viewportTag.content.toLowerCase().replace(/\s+/g, '').split(','); var keyValue; for(x=0; x<props.length; x++) { if(props[x]) { keyValue = props[x].split('='); viewportProperties[ keyValue[0] ] = (keyValue.length > 1 ? keyValue[1] : '_'); } } viewportUpdate(); } } function viewportUpdate() { // unit tests in viewport.unit.js var initWidth = viewportProperties.width; var initHeight = viewportProperties.height; var p = ionic.Platform; var version = p.version(); var DEVICE_WIDTH = 'device-width'; var DEVICE_HEIGHT = 'device-height'; var orientation = ionic.viewport.orientation(); // Most times we're removing the height and adding the width // So this is the default to start with, then modify per platform/version/oreintation delete viewportProperties.height; viewportProperties.width = DEVICE_WIDTH; if( p.isIPad() ) { // iPad if( version > 7 ) { // iPad >= 7.1 // https://issues.apache.org/jira/browse/CB-4323 delete viewportProperties.width; } else { // iPad <= 7.0 if( p.isWebView() ) { // iPad <= 7.0 WebView if( orientation == 90 ) { // iPad <= 7.0 WebView Landscape viewportProperties.height = '0'; } else if(version == 7) { // iPad <= 7.0 WebView Portait viewportProperties.height = DEVICE_HEIGHT; } } else { // iPad <= 6.1 Browser if(version < 7) { viewportProperties.height = '0'; } } } } else if( p.isIOS() ) { // iPhone if( p.isWebView() ) { // iPhone WebView if(version > 7) { // iPhone >= 7.1 WebView delete viewportProperties.width; } else if(version < 7) { // iPhone <= 6.1 WebView // if height was set it needs to get removed with this hack for <= 6.1 if( initHeight ) viewportProperties.height = '0'; } else if(version == 7) { //iPhone == 7.0 WebView viewportProperties.height = DEVICE_HEIGHT; } } else { // iPhone Browser if (version < 7) { // iPhone <= 6.1 Browser // if height was set it needs to get removed with this hack for <= 6.1 if( initHeight ) viewportProperties.height = '0'; } } } // only update the viewport tag if there was a change if(initWidth !== viewportProperties.width || initHeight !== viewportProperties.height) { viewportTagUpdate(); } } function viewportTagUpdate() { var key, props = []; for(key in viewportProperties) { if( viewportProperties[key] ) { props.push(key + (viewportProperties[key] == '_' ? '' : '=' + viewportProperties[key]) ); } } viewportTag.content = props.join(', '); } ionic.Platform.ready(function() { viewportLoadTag(); window.addEventListener("orientationchange", function(){ setTimeout(viewportUpdate, 1000); }, false); }); (function(ionic) { 'use strict'; ionic.views.View = function() { this.initialize.apply(this, arguments); }; ionic.views.View.inherit = ionic.inherit; ionic.extend(ionic.views.View.prototype, { initialize: function() {} }); })(window.ionic); /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ /* jshint eqnull: true */ /** * Generic animation class with support for dropped frames both optional easing and duration. * * Optional duration is useful when the lifetime is defined by another condition than time * e.g. speed of an animating object, etc. * * Dropped frame logic allows to keep using the same updater logic independent from the actual * rendering. This eases a lot of cases where it might be pretty complex to break down a state * based on the pure time difference. */ var zyngaCore = { effect: {} }; (function(global) { var time = Date.now || function() { return +new Date(); }; var desiredFrames = 60; var millisecondsPerSecond = 1000; var running = {}; var counter = 1; zyngaCore.effect.Animate = { /** * A requestAnimationFrame wrapper / polyfill. * * @param callback {Function} The callback to be invoked before the next repaint. * @param root {HTMLElement} The root element for the repaint */ requestAnimationFrame: (function() { // Check for request animation Frame support var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame; var isNative = !!requestFrame; if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) { isNative = false; } if (isNative) { return function(callback, root) { requestFrame(callback, root); }; } var TARGET_FPS = 60; var requests = {}; var requestCount = 0; var rafHandle = 1; var intervalHandle = null; var lastActive = +new Date(); return function(callback, root) { var callbackHandle = rafHandle++; // Store callback requests[callbackHandle] = callback; requestCount++; // Create timeout at first request if (intervalHandle === null) { intervalHandle = setInterval(function() { var time = +new Date(); var currentRequests = requests; // Reset data structure before executing callbacks requests = {}; requestCount = 0; for(var key in currentRequests) { if (currentRequests.hasOwnProperty(key)) { currentRequests[key](time); lastActive = time; } } // Disable the timeout when nothing happens for a certain // period of time if (time - lastActive > 2500) { clearInterval(intervalHandle); intervalHandle = null; } }, 1000 / TARGET_FPS); } return callbackHandle; }; })(), /** * Stops the given animation. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation was stopped (aka, was running before) */ stop: function(id) { var cleared = running[id] != null; if (cleared) { running[id] = null; } return cleared; }, /** * Whether the given animation is still running. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation is still running */ isRunning: function(id) { return running[id] != null; }, /** * Start the animation. * * @param stepCallback {Function} Pointer to function which is executed on every step. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }` * @param verifyCallback {Function} Executed before every animation step. * Signature of the method should be `function() { return continueWithAnimation; }` * @param completedCallback {Function} * Signature of the method should be `function(droppedFrames, finishedAnimation) {}` * @param duration {Integer} Milliseconds to run the animation * @param easingMethod {Function} Pointer to easing function * Signature of the method should be `function(percent) { return modifiedValue; }` * @param root {Element} Render root, when available. Used for internal * usage of requestAnimationFrame. * @return {Integer} Identifier of animation. Can be used to stop it any time. */ start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; zyngaCore.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step zyngaCore.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; } }; })(this); /* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ var Scroller; (function(ionic) { var NOOP = function(){}; // Easing Equations (c) 2003 Robert Penner, all rights reserved. // Open source under the BSD License. /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeOutCubic = function(pos) { return (Math.pow((pos - 1), 3) + 1); }; /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeInOutCubic = function(pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } return 0.5 * (Math.pow((pos - 2), 3) + 2); }; /** * ionic.views.Scroll * A powerful scroll view with support for bouncing, pull to refresh, and paging. * @param {Object} options options for the scroll view * @class A scroll view system * @memberof ionic.views */ ionic.views.Scroll = ionic.views.View.inherit({ initialize: function(options) { var self = this; this.__container = options.el; this.__content = options.el.firstElementChild; //Remove any scrollTop attached to these elements; they are virtual scroll now //This also stops on-load-scroll-to-window.location.hash that the browser does setTimeout(function() { if (self.__container && self.__content) { self.__container.scrollTop = 0; self.__content.scrollTop = 0; } }); this.options = { /** Disable scrolling on x-axis by default */ scrollingX: false, scrollbarX: true, /** Enable scrolling on y-axis */ scrollingY: true, scrollbarY: true, startX: 0, startY: 0, /** The amount to dampen mousewheel events */ wheelDampen: 6, /** The minimum size the scrollbars scale to while scrolling */ minScrollbarSizeX: 5, minScrollbarSizeY: 5, /** Scrollbar fading after scrolling */ scrollbarsFade: true, scrollbarFadeDelay: 300, /** The initial fade delay when the pane is resized or initialized */ scrollbarResizeFadeDelay: 1000, /** Enable animations for deceleration, snap back, zooming and scrolling */ animating: true, /** duration for animations triggered by scrollTo/zoomTo */ animationDuration: 250, /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */ bouncing: true, /** Enable locking to the main axis if user moves only slightly on one of them at start */ locking: true, /** Enable pagination mode (switching between full page content panes) */ paging: false, /** Enable snapping of content to a configured pixel grid */ snapping: false, /** Enable zooming of content via API, fingers and mouse wheel */ zooming: false, /** Minimum zoom level */ minZoom: 0.5, /** Maximum zoom level */ maxZoom: 3, /** Multiply or decrease scrolling speed **/ speedMultiplier: 1, /** Callback that is fired on the later of touch end or deceleration end, provided that another scrolling action has not begun. Used to know when to fade out a scrollbar. */ scrollingComplete: NOOP, /** This configures the amount of change applied to deceleration when reaching boundaries **/ penetrationDeceleration : 0.03, /** This configures the amount of change applied to acceleration when reaching boundaries **/ penetrationAcceleration : 0.08, // The ms interval for triggering scroll events scrollEventInterval: 10, getContentWidth: function() { return Math.max(self.__content.scrollWidth, self.__content.offsetWidth); }, getContentHeight: function() { return Math.max(self.__content.scrollHeight, self.__content.offsetHeight); } }; for (var key in options) { this.options[key] = options[key]; } this.hintResize = ionic.debounce(function() { self.resize(); }, 1000, true); this.onScroll = function() { if(!ionic.scroll.isScrolling) { setTimeout(self.setScrollStart, 50); } else { clearTimeout(self.scrollTimer); self.scrollTimer = setTimeout(self.setScrollStop, 80); } }; this.setScrollStart = function() { ionic.scroll.isScrolling = Math.abs(ionic.scroll.lastTop - self.__scrollTop) > 1; clearTimeout(self.scrollTimer); self.scrollTimer = setTimeout(self.setScrollStop, 80); }; this.setScrollStop = function() { ionic.scroll.isScrolling = false; ionic.scroll.lastTop = self.__scrollTop; }; this.triggerScrollEvent = ionic.throttle(function() { self.onScroll(); ionic.trigger('scroll', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }, this.options.scrollEventInterval); this.triggerScrollEndEvent = function() { ionic.trigger('scrollend', { scrollTop: self.__scrollTop, scrollLeft: self.__scrollLeft, target: self.__container }); }; this.__scrollLeft = this.options.startX; this.__scrollTop = this.options.startY; // Get the render update function, initialize event handlers, // and calculate the size of the scroll container this.__callback = this.getRenderFn(); this.__initEventHandlers(); this.__createScrollbars(); }, run: function() { this.resize(); // Fade them out this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay); }, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: STATUS --------------------------------------------------------------------------- */ /** Whether only a single finger is used in touch handling */ __isSingleTouch: false, /** Whether a touch event sequence is in progress */ __isTracking: false, /** Whether a deceleration animation went to completion. */ __didDecelerationComplete: false, /** * Whether a gesture zoom/rotate event is in progress. Activates when * a gesturestart event happens. This has higher priority than dragging. */ __isGesturing: false, /** * Whether the user has moved by such a distance that we have enabled * dragging mode. Hint: It's only enabled after some pixels of movement to * not interrupt with clicks etc. */ __isDragging: false, /** * Not touching and dragging anymore, and smoothly animating the * touch sequence using deceleration. */ __isDecelerating: false, /** * Smoothly animating the currently configured change */ __isAnimating: false, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DIMENSIONS --------------------------------------------------------------------------- */ /** Available outer left position (from document perspective) */ __clientLeft: 0, /** Available outer top position (from document perspective) */ __clientTop: 0, /** Available outer width */ __clientWidth: 0, /** Available outer height */ __clientHeight: 0, /** Outer width of content */ __contentWidth: 0, /** Outer height of content */ __contentHeight: 0, /** Snapping width for content */ __snapWidth: 100, /** Snapping height for content */ __snapHeight: 100, /** Height to assign to refresh area */ __refreshHeight: null, /** Whether the refresh process is enabled when the event is released now */ __refreshActive: false, /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */ __refreshActivate: null, /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */ __refreshDeactivate: null, /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */ __refreshStart: null, /** Zoom level */ __zoomLevel: 1, /** Scroll position on x-axis */ __scrollLeft: 0, /** Scroll position on y-axis */ __scrollTop: 0, /** Maximum allowed scroll position on x-axis */ __maxScrollLeft: 0, /** Maximum allowed scroll position on y-axis */ __maxScrollTop: 0, /* Scheduled left position (final position when animating) */ __scheduledLeft: 0, /* Scheduled top position (final position when animating) */ __scheduledTop: 0, /* Scheduled zoom level (final scale when animating) */ __scheduledZoom: 0, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: LAST POSITIONS --------------------------------------------------------------------------- */ /** Left position of finger at start */ __lastTouchLeft: null, /** Top position of finger at start */ __lastTouchTop: null, /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */ __lastTouchMove: null, /** List of positions, uses three indexes for each state: left, top, timestamp */ __positions: null, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DECELERATION SUPPORT --------------------------------------------------------------------------- */ /** Minimum left scroll position during deceleration */ __minDecelerationScrollLeft: null, /** Minimum top scroll position during deceleration */ __minDecelerationScrollTop: null, /** Maximum left scroll position during deceleration */ __maxDecelerationScrollLeft: null, /** Maximum top scroll position during deceleration */ __maxDecelerationScrollTop: null, /** Current factor to modify horizontal scroll position with on every step */ __decelerationVelocityX: null, /** Current factor to modify vertical scroll position with on every step */ __decelerationVelocityY: null, /** the browser-specific property to use for transforms */ __transformProperty: null, __perspectiveProperty: null, /** scrollbar indicators */ __indicatorX: null, __indicatorY: null, /** Timeout for scrollbar fading */ __scrollbarFadeTimeout: null, /** whether we've tried to wait for size already */ __didWaitForSize: null, __sizerTimeout: null, __initEventHandlers: function() { var self = this; // Event Handler var container = this.__container; //Broadcasted when keyboard is shown on some platforms. //See js/utils/keyboard.js container.addEventListener('scrollChildIntoView', function(e) { //distance from bottom of scrollview to top of viewport var scrollBottomOffsetToTop; if( !self.isScrolledIntoView ) { // shrink scrollview so we can actually scroll if the input is hidden // if it isn't shrink so we can scroll to inputs under the keyboard if (ionic.Platform.isIOS() || ionic.Platform.isFullScreen){ // if there are things below the scroll view account for them and // subtract them from the keyboard height when resizing scrollBottomOffsetToTop = container.getBoundingClientRect().bottom; var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop; var keyboardOffset = Math.max(0, e.detail.keyboardHeight - scrollBottomOffsetToBottom); container.style.height = (container.clientHeight - keyboardOffset) + "px"; container.style.overflow = "visible"; //update scroll view self.resize(); } self.isScrolledIntoView = true; } //If the element is positioned under the keyboard... if( e.detail.isElementUnderKeyboard ) { var delay; // Wait on android for web view to resize if ( ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen ) { // android y u resize so slow if ( ionic.Platform.version() < 4.4) { delay = 500; } else { // probably overkill for chrome delay = 350; } } else { delay = 80; } //Put element in middle of visible screen //Wait for android to update view height and resize() to reset scroll position ionic.scroll.isScrolling = true; setTimeout(function(){ //middle of the scrollview, where we want to scroll to var scrollMidpointOffset = container.clientHeight * 0.5; scrollBottomOffsetToTop = container.getBoundingClientRect().bottom; //distance from top of focused element to the bottom of the scroll view var elementTopOffsetToScrollBottom = e.detail.elementTop - scrollBottomOffsetToTop; var scrollTop = elementTopOffsetToScrollBottom + scrollMidpointOffset; ionic.tap.cloneFocusedInput(container, self); self.scrollBy(0, scrollTop, true); self.onScroll(); }, delay); } //Only the first scrollView parent of the element that broadcasted this event //(the active element that needs to be shown) should receive this event e.stopPropagation(); }); container.addEventListener('resetScrollView', function(e) { //return scrollview to original height once keyboard has hidden self.isScrolledIntoView = false; container.style.height = ""; container.style.overflow = ""; self.resize(); ionic.scroll.isScrolling = false; }); function getEventTouches(e) { return e.touches && e.touches.length ? e.touches : [{ pageX: e.pageX, pageY: e.pageY }]; } self.touchStart = function(e) { self.startCoordinates = getPointerCoordinates(e); if ( ionic.tap.ignoreScrollStart(e) ) { return; } self.__isDown = true; if( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) { // do not start if the target is a text input // if there is a touchmove on this input, then we can start the scroll self.__hasStarted = false; return; } self.__isSelectable = true; self.__enableScrollY = true; self.__hasStarted = true; self.doTouchStart(getEventTouches(e), e.timeStamp); e.preventDefault(); }; self.touchMove = function(e) { if(!self.__isDown || e.defaultPrevented || (e.target.tagName === 'TEXTAREA' && e.target.parentElement.querySelector(':focus')) ) { return; } if( !self.__hasStarted && ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) ) { // the target is a text input and scroll has started // since the text input doesn't start on touchStart, do it here self.__hasStarted = true; self.doTouchStart(getEventTouches(e), e.timeStamp); e.preventDefault(); return; } if(self.startCoordinates) { // we have start coordinates, so get this touch move's current coordinates var currentCoordinates = getPointerCoordinates(e); if( self.__isSelectable && ionic.tap.isTextInput(e.target) && Math.abs(self.startCoordinates.x - currentCoordinates.x) > 20 ) { // user slid the text input's caret on its x axis, disable any future y scrolling self.__enableScrollY = false; self.__isSelectable = true; } if( self.__enableScrollY && Math.abs(self.startCoordinates.y - currentCoordinates.y) > 10 ) { // user scrolled the entire view on the y axis // disabled being able to select text on an input // hide the input which has focus, and show a cloned one that doesn't have focus self.__isSelectable = false; ionic.tap.cloneFocusedInput(container, self); } } self.doTouchMove(getEventTouches(e), e.timeStamp, e.scale); self.__isDown = true; }; self.touchEnd = function(e) { if(!self.__isDown) return; self.doTouchEnd(e.timeStamp); self.__isDown = false; self.__hasStarted = false; self.__isSelectable = true; self.__enableScrollY = true; if( !self.__isDragging && !self.__isDecelerating && !self.__isAnimating ) { ionic.tap.removeClonedInputs(container, self); } }; self.options.orgScrollingComplete = self.options.scrollingComplete; self.options.scrollingComplete = function() { ionic.tap.removeClonedInputs(container, self); self.options.orgScrollingComplete(); }; if ('ontouchstart' in window) { // Touch Events container.addEventListener("touchstart", self.touchStart, false); document.addEventListener("touchmove", self.touchMove, false); document.addEventListener("touchend", self.touchEnd, false); document.addEventListener("touchcancel", self.touchEnd, false); } else if (window.navigator.pointerEnabled) { // Pointer Events container.addEventListener("pointerdown", self.touchStart, false); document.addEventListener("pointermove", self.touchMove, false); document.addEventListener("pointerup", self.touchEnd, false); document.addEventListener("pointercancel", self.touchEnd, false); } else if (window.navigator.msPointerEnabled) { // IE10, WP8 (Pointer Events) container.addEventListener("MSPointerDown", self.touchStart, false); document.addEventListener("MSPointerMove", self.touchMove, false); document.addEventListener("MSPointerUp", self.touchEnd, false); document.addEventListener("MSPointerCancel", self.touchEnd, false); } else { // Mouse Events var mousedown = false; container.addEventListener("mousedown", function(e) { if ( ionic.tap.ignoreScrollStart(e) || e.target.tagName === 'SELECT' ) { return; } self.doTouchStart(getEventTouches(e), e.timeStamp); e.preventDefault(); mousedown = true; }, false); document.addEventListener("mousemove", function(e) { if (!mousedown || e.defaultPrevented) { return; } self.doTouchMove(getEventTouches(e), e.timeStamp); mousedown = true; }, false); document.addEventListener("mouseup", function(e) { if (!mousedown) { return; } self.doTouchEnd(e.timeStamp); mousedown = false; }, false); var wheelShowBarFn = ionic.debounce(function() { self.__fadeScrollbars('in'); }, 500, true); var wheelHideBarFn = ionic.debounce(function() { self.__fadeScrollbars('out'); }, 100, false); //For Firefox document.addEventListener('mousewheel', onMouseWheel); } function onMouseWheel(e) { self.hintResize(); wheelShowBarFn(); self.scrollBy(e.wheelDeltaX/self.options.wheelDampen, -e.wheelDeltaY/self.options.wheelDampen); wheelHideBarFn(); } }, /** Create a scroll bar div with the given direction **/ __createScrollbar: function(direction) { var bar = document.createElement('div'), indicator = document.createElement('div'); indicator.className = 'scroll-bar-indicator'; if(direction == 'h') { bar.className = 'scroll-bar scroll-bar-h'; } else { bar.className = 'scroll-bar scroll-bar-v'; } bar.appendChild(indicator); return bar; }, __createScrollbars: function() { var indicatorX, indicatorY; if(this.options.scrollingX) { indicatorX = { el: this.__createScrollbar('h'), sizeRatio: 1 }; indicatorX.indicator = indicatorX.el.children[0]; if(this.options.scrollbarX) { this.__container.appendChild(indicatorX.el); } this.__indicatorX = indicatorX; } if(this.options.scrollingY) { indicatorY = { el: this.__createScrollbar('v'), sizeRatio: 1 }; indicatorY.indicator = indicatorY.el.children[0]; if(this.options.scrollbarY) { this.__container.appendChild(indicatorY.el); } this.__indicatorY = indicatorY; } }, __resizeScrollbars: function() { var self = this; // Update horiz bar if(self.__indicatorX) { var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20); if(width > self.__contentWidth) { width = 0; } self.__indicatorX.size = width; self.__indicatorX.minScale = this.options.minScrollbarSizeX / width; self.__indicatorX.indicator.style.width = width + 'px'; self.__indicatorX.maxPos = self.__clientWidth - width; self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1; } // Update vert bar if(self.__indicatorY) { var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20); if(height > self.__contentHeight) { height = 0; } self.__indicatorY.size = height; self.__indicatorY.minScale = this.options.minScrollbarSizeY / height; self.__indicatorY.maxPos = self.__clientHeight - height; self.__indicatorY.indicator.style.height = height + 'px'; self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1; } }, /** * Move and scale the scrollbars as the page scrolls. */ __repositionScrollbars: function() { var self = this, width, heightScale, widthDiff, heightDiff, x, y, xstop = 0, ystop = 0; if(self.__indicatorX) { // Handle the X scrollbar // Don't go all the way to the right if we have a vertical scrollbar as well if(self.__indicatorY) xstop = 10; x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0, // The the difference between the last content X position, and our overscrolled one widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop); if(self.__scrollLeft < 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size); // Stay at left x = 0; // Make sure scale is transformed from the left/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center'; } else if(widthDiff > 0) { widthScale = Math.max(self.__indicatorX.minScale, (self.__indicatorX.size - widthDiff) / self.__indicatorX.size); // Stay at the furthest x for the scrollable viewport x = self.__indicatorX.maxPos - xstop; // Make sure scale is transformed from the right/center origin point self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center'; } else { // Normal motion x = Math.min(self.__maxScrollLeft, Math.max(0, x)); widthScale = 1; } self.__indicatorX.indicator.style[self.__transformProperty] = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')'; } if(self.__indicatorY) { y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0; // Don't go all the way to the right if we have a vertical scrollbar as well if(self.__indicatorX) ystop = 10; heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop); if(self.__scrollTop < 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size); // Stay at top y = 0; // Make sure scale is transformed from the center/top origin point self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top'; } else if(heightDiff > 0) { heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size); // Stay at bottom of scrollable viewport y = self.__indicatorY.maxPos - ystop; // Make sure scale is transformed from the center/bottom origin point self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom'; } else { // Normal motion y = Math.min(self.__maxScrollTop, Math.max(0, y)); heightScale = 1; } self.__indicatorY.indicator.style[self.__transformProperty] = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')'; } }, __fadeScrollbars: function(direction, delay) { var self = this; if(!this.options.scrollbarsFade) { return; } var className = 'scroll-bar-fade-out'; if(self.options.scrollbarsFade === true) { clearTimeout(self.__scrollbarFadeTimeout); if(direction == 'in') { if(self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); } if(self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); } } else { self.__scrollbarFadeTimeout = setTimeout(function() { if(self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); } if(self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); } }, delay || self.options.scrollbarFadeDelay); } } }, __scrollingComplete: function() { var self = this; self.options.scrollingComplete(); self.__fadeScrollbars('out'); }, resize: function() { // Update Scroller dimensions for changed content // Add padding to bottom of content this.setDimensions( this.__container.clientWidth, this.__container.clientHeight, this.options.getContentWidth(), this.options.getContentHeight() ); }, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ getRenderFn: function() { var self = this; var content = this.__content; var docStyle = document.documentElement.style; var engine; if ('MozAppearance' in docStyle) { engine = 'gecko'; } else if ('WebkitAppearance' in docStyle) { engine = 'webkit'; } else if (typeof navigator.cpuClass === 'string') { engine = 'trident'; } var vendorPrefix = { trident: 'ms', gecko: 'Moz', webkit: 'Webkit', presto: 'O' }[engine]; var helperElem = document.createElement("div"); var undef; var perspectiveProperty = vendorPrefix + "Perspective"; var transformProperty = vendorPrefix + "Transform"; var transformOriginProperty = vendorPrefix + 'TransformOrigin'; self.__perspectiveProperty = transformProperty; self.__transformProperty = transformProperty; self.__transformOriginProperty = transformOriginProperty; if (helperElem.style[perspectiveProperty] !== undef) { return function(left, top, zoom, wasResize) { content.style[transformProperty] = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')'; self.__repositionScrollbars(); if(!wasResize) { self.triggerScrollEvent(); } }; } else if (helperElem.style[transformProperty] !== undef) { return function(left, top, zoom, wasResize) { content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')'; self.__repositionScrollbars(); if(!wasResize) { self.triggerScrollEvent(); } }; } else { return function(left, top, zoom, wasResize) { content.style.marginLeft = left ? (-left/zoom) + 'px' : ''; content.style.marginTop = top ? (-top/zoom) + 'px' : ''; content.style.zoom = zoom || ''; self.__repositionScrollbars(); if(!wasResize) { self.triggerScrollEvent(); } }; } }, /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer} Inner width of outer element * @param clientHeight {Integer} Inner height of outer element * @param contentWidth {Integer} Outer width of inner element * @param contentHeight {Integer} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) { var self = this; // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); self.__resizeScrollbars(); // Refresh scroll position self.scrollTo(self.__scrollLeft, self.__scrollTop, true, null, true); }, /** * Sets the client coordinates in relation to the document. * * @param left {Integer} Left position of outer element * @param top {Integer} Top position of outer element */ setPosition: function(left, top) { var self = this; self.__clientLeft = left || 0; self.__clientTop = top || 0; }, /** * Configures the snapping (when snapping is active) * * @param width {Integer} Snapping width * @param height {Integer} Snapping height */ setSnapSize: function(width, height) { var self = this; self.__snapWidth = width; self.__snapHeight = height; }, /** * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever * the user event is released during visibility of this zone. This was introduced by some apps on iOS like * the official Twitter client. * * @param height {Integer} Height of pull-to-refresh zone on top of rendered list * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh. */ activatePullToRefresh: function(height, activateCallback, deactivateCallback, startCallback) { var self = this; self.__refreshHeight = height; self.__refreshActivate = activateCallback; self.__refreshDeactivate = deactivateCallback; self.__refreshStart = startCallback; }, /** * Starts pull-to-refresh manually. */ triggerPullToRefresh: function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); if (this.__refreshStart) { this.__refreshStart(); } }, /** * Signalizes that pull-to-refresh is finished. */ finishPullToRefresh: function() { var self = this; self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { var self = this; return { left: self.__scrollLeft, top: self.__scrollTop, zoom: self.__zoomLevel }; }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { var self = this; return { left: self.__maxScrollLeft, top: self.__maxScrollTop }; }, /** * Zooms to the given level. Supports optional animation. Zooms * the center when no coordinates are given. * * @param level {Number} Level to zoom to * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomTo: function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }, /** * Zooms the content by the given factor. * * @param factor {Number} Zoom by given factor * @param animate {Boolean} Whether to use animation * @param originLeft {Number} Zoom in at given left coordinate * @param originTop {Number} Zoom in at given top coordinate */ zoomBy: function(factor, animate, originLeft, originTop) { var self = this; self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop); }, /** * Scrolls to the given position. Respect limitations and snapping automatically. * * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean} Whether the scrolling should happen using an animation * @param zoom {Number} Zoom level to go to */ scrollTo: function(left, top, animate, zoom, wasResize) { var self = this; // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate, wasResize); }, /** * Scroll by the given offset * * @param left {Number} Scroll x-axis by given offset * @param top {Number} Scroll y-axis by given offset * @param animate {Boolean} Whether to animate the given change */ scrollBy: function(left, top, animate) { var self = this; var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /* --------------------------------------------------------------------------- EVENT CALLBACKS --------------------------------------------------------------------------- */ /** * Mouse wheel handler for zooming support */ doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) { var self = this; var change = wheelDelta > 0 ? 0.97 : 1.03; return self.zoomTo(self.__zoomLevel * change, false, pageX - self.__clientLeft, pageY - self.__clientTop); }, /** * Touch start handler for scrolling support */ doTouchStart: function(touches, timeStamp) { this.hintResize(); if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { timeStamp = Date.now(); } var self = this; // Reset interruptedAnimation flag self.__interruptedAnimation = true; // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; self.__interruptedAnimation = true; } // Stop animation if (self.__isAnimating) { zyngaCore.effect.Animate.stop(self.__isAnimating); self.__isAnimating = false; self.__interruptedAnimation = true; } // Use center point when dealing with two fingers var currentTouchLeft, currentTouchTop; var isSingleTouch = touches.length === 1; if (isSingleTouch) { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } else { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } // Store initial positions self.__initialTouchLeft = currentTouchLeft; self.__initialTouchTop = currentTouchTop; // Store current zoom level self.__zoomLevelStart = self.__zoomLevel; // Store initial touch positions self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; // Store initial move time stamp self.__lastTouchMove = timeStamp; // Reset initial scale self.__lastScale = 1; // Reset locking flags self.__enableScrollX = !isSingleTouch && self.options.scrollingX; self.__enableScrollY = !isSingleTouch && self.options.scrollingY; // Reset tracking flag self.__isTracking = true; // Reset deceleration complete flag self.__didDecelerationComplete = false; // Dragging starts directly with two fingers, otherwise lazy with an offset self.__isDragging = !isSingleTouch; // Some features are disabled in multi touch scenarios self.__isSingleTouch = isSingleTouch; // Clearing data structure self.__positions = []; }, /** * Touch move handler for scrolling support */ doTouchMove: function(touches, timeStamp, scale) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { timeStamp = Date.now(); } var self = this; // Ignore event when tracking is not enabled (event might be outside of element) if (!self.__isTracking) { return; } var currentTouchLeft, currentTouchTop; // Compute move based around of center of fingers if (touches.length === 2) { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } else { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } var positions = self.__positions; // Are we already is dragging mode? if (self.__isDragging) { // Compute move distance var moveX = currentTouchLeft - self.__lastTouchLeft; var moveY = currentTouchTop - self.__lastTouchTop; // Read previous scroll position and zooming var scrollLeft = self.__scrollLeft; var scrollTop = self.__scrollTop; var level = self.__zoomLevel; // Work with scaling if (scale != null && self.options.zooming) { var oldLevel = level; // Recompute level based on previous scale and new scale level = level / self.__lastScale * scale; // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Only do further compution when change happened if (oldLevel !== level) { // Compute relative event position to container var currentTouchLeftRel = currentTouchLeft - self.__clientLeft; var currentTouchTopRel = currentTouchTop - self.__clientTop; // Recompute left and top coordinates based on new zoom level scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel; scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel; // Recompute max scroll values self.__computeScrollMax(level); } } if (self.__enableScrollX) { scrollLeft -= moveX * this.options.speedMultiplier; var maxScrollLeft = self.__maxScrollLeft; if (scrollLeft > maxScrollLeft || scrollLeft < 0) { // Slow down on the edges if (self.options.bouncing) { scrollLeft += (moveX / 2 * this.options.speedMultiplier); } else if (scrollLeft > maxScrollLeft) { scrollLeft = maxScrollLeft; } else { scrollLeft = 0; } } } // Compute new vertical scroll position if (self.__enableScrollY) { scrollTop -= moveY * this.options.speedMultiplier; var maxScrollTop = self.__maxScrollTop; if (scrollTop > maxScrollTop || scrollTop < 0) { // Slow down on the edges if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) { scrollTop += (moveY / 2 * this.options.speedMultiplier); // Support pull-to-refresh (only when only y is scrollable) if (!self.__enableScrollX && self.__refreshHeight != null) { if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) { self.__refreshActive = true; if (self.__refreshActivate) { self.__refreshActivate(); } } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } else if (scrollTop > maxScrollTop) { scrollTop = maxScrollTop; } else { scrollTop = 0; } } } // Keep list from growing infinitely (holding min 10, max 20 measure points) if (positions.length > 60) { positions.splice(0, 30); } // Track scroll movement for decleration positions.push(scrollLeft, scrollTop, timeStamp); // Sync scroll position self.__publish(scrollLeft, scrollTop, level); // Otherwise figure out whether we are switching into dragging mode now. } else { var minimumTrackingForScroll = self.options.locking ? 3 : 0; var minimumTrackingForDrag = 5; var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft); var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop); self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll; self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll; positions.push(self.__scrollLeft, self.__scrollTop, timeStamp); self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag); if (self.__isDragging) { self.__interruptedAnimation = false; self.__fadeScrollbars('in'); } } // Update last touch positions and time stamp for next event self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; self.__lastTouchMove = timeStamp; self.__lastScale = scale; }, /** * Touch end handler for scrolling support */ doTouchEnd: function(timeStamp) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { timeStamp = Date.now(); } var self = this; // Ignore event when tracking is not enabled (no touchstart event on element) // This is required as this listener ('touchmove') sits on the document and not on the element itself. if (!self.__isTracking) { return; } // Not touching anymore (when two finger hit the screen there are two touch end events) self.__isTracking = false; // Be sure to reset the dragging flag now. Here we also detect whether // the finger has moved fast enough to switch into a deceleration animation. if (self.__isDragging) { // Reset dragging flag self.__isDragging = false; // Start deceleration // Verify that the last move detected was in some relevant time frame if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) { // Then figure out what the scroll position was about 100ms ago var positions = self.__positions; var endPos = positions.length - 1; var startPos = endPos; // Move pointer to position measured 100ms ago for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) { startPos = i; } // If start and stop position is identical in a 100ms timeframe, // we cannot compute any useful deceleration. if (startPos !== endPos) { // Compute relative movement between these two points var timeOffset = positions[endPos] - positions[startPos]; var movedLeft = self.__scrollLeft - positions[startPos - 2]; var movedTop = self.__scrollTop - positions[startPos - 1]; // Based on 50ms compute the movement to apply for each render step self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60); self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60); // How much velocity is required to start the deceleration var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? 4 : 1; // Verify that we have enough velocity to start deceleration if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) { // Deactivate pull-to-refresh when decelerating if (!self.__refreshActive) { self.__startDeceleration(timeStamp); } } } else { self.__scrollingComplete(); } } else if ((timeStamp - self.__lastTouchMove) > 100) { self.__scrollingComplete(); } } // If this was a slower move it is per default non decelerated, but this // still means that we want snap back to the bounds which is done here. // This is placed outside the condition above to improve edge case stability // e.g. touchend fired without enabled dragging. This should normally do not // have modified the scroll positions or even showed the scrollbars though. if (!self.__isDecelerating) { if (self.__refreshActive && self.__refreshStart) { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true); if (self.__refreshStart) { self.__refreshStart(); } } else { if (self.__interruptedAnimation || self.__isDragging) { self.__scrollingComplete(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel); // Directly signalize deactivation (nothing todo on refresh?) if (self.__refreshActive) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } // Fully cleanup list self.__positions.length = 0; }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * Applies the scroll position to the content element * * @param left {Number} Left scroll position * @param top {Number} Top scroll position * @param animate {Boolean} Whether animation should be used to move to the new coordinates */ __publish: function(left, top, zoom, animate, wasResize) { var self = this; // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation var wasAnimating = self.__isAnimating; if (wasAnimating) { zyngaCore.effect.Animate.stop(wasAnimating); self.__isAnimating = false; } if (animate && self.options.animating) { // Keep scheduled positions for scrollBy/zoomBy functionality self.__scheduledLeft = left; self.__scheduledTop = top; self.__scheduledZoom = zoom; var oldLeft = self.__scrollLeft; var oldTop = self.__scrollTop; var oldZoom = self.__zoomLevel; var diffLeft = left - oldLeft; var diffTop = top - oldTop; var diffZoom = zoom - oldZoom; var step = function(percent, now, render) { if (render) { self.__scrollLeft = oldLeft + (diffLeft * percent); self.__scrollTop = oldTop + (diffTop * percent); self.__zoomLevel = oldZoom + (diffZoom * percent); // Push values out if (self.__callback) { self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel, wasResize); } } }; var verify = function(id) { return self.__isAnimating === id; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { if (animationId === self.__isAnimating) { self.__isAnimating = false; } if (self.__didDecelerationComplete || wasFinished) { self.__scrollingComplete(); } if (self.options.zooming) { self.__computeScrollMax(); } }; // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out self.__isAnimating = zyngaCore.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic); } else { self.__scheduledLeft = self.__scrollLeft = left; self.__scheduledTop = self.__scrollTop = top; self.__scheduledZoom = self.__zoomLevel = zoom; // Push values out if (self.__callback) { self.__callback(left, top, zoom, wasResize); } // Fix max scroll ranges if (self.options.zooming) { self.__computeScrollMax(); } } }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function(zoomLevel) { var self = this; if (zoomLevel == null) { zoomLevel = self.__zoomLevel; } self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0); if(!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) { self.__didWaitForSize = true; self.__waitForSize(); } }, /** * If the scroll view isn't sized correctly on start, wait until we have at least some size */ __waitForSize: function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(); if((self.options.scrollingX && !self.__maxScrollLeft) || (self.options.scrollingY && !self.__maxScrollTop)) { //self.__sizerTimeout = setTimeout(sizer, 1000); } }; sizer(); self.__sizerTimeout = setTimeout(sizer, 1000); }, /* --------------------------------------------------------------------------- ANIMATION (DECELERATION) SUPPORT --------------------------------------------------------------------------- */ /** * Called when a touch sequence end and the speed of the finger was high enough * to switch into deceleration mode. */ __startDeceleration: function(timeStamp) { var self = this; if (self.options.paging) { var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0); var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0); var clientWidth = self.__clientWidth; var clientHeight = self.__clientHeight; // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area. // Each page should have exactly the size of the client area. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth; self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight; self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth; self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight; } else { self.__minDecelerationScrollLeft = 0; self.__minDecelerationScrollTop = 0; self.__maxDecelerationScrollLeft = self.__maxScrollLeft; self.__maxDecelerationScrollTop = self.__maxScrollTop; } // Wrap class method var step = function(percent, now, render) { self.__stepThroughDeceleration(render); }; // How much velocity is required to keep the deceleration running self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1; // Detect whether it's still worth to continue animating steps // If we are already slow enough to not being user perceivable anymore, we stop the whole process here. var verify = function() { var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating; if (!shouldContinue) { self.__didDecelerationComplete = true; } return shouldContinue; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { self.__isDecelerating = false; if (self.__didDecelerationComplete) { self.__scrollingComplete(); } // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions if(self.options.paging) { self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping); } }; // Start animation and switch on flag self.__isDecelerating = zyngaCore.effect.Animate.start(step, verify, completed); }, /** * Called on every step of the animation * * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only! */ __stepThroughDeceleration: function(render) { var self = this; // // COMPUTE NEXT SCROLL POSITION // // Add deceleration to scroll position var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX; var scrollTop = self.__scrollTop + self.__decelerationVelocityY; // // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE // if (!self.options.bouncing) { var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft); if (scrollLeftFixed !== scrollLeft) { scrollLeft = scrollLeftFixed; self.__decelerationVelocityX = 0; } var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop); if (scrollTopFixed !== scrollTop) { scrollTop = scrollTopFixed; self.__decelerationVelocityY = 0; } } // // UPDATE SCROLL POSITION // if (render) { self.__publish(scrollLeft, scrollTop, self.__zoomLevel); } else { self.__scrollLeft = scrollLeft; self.__scrollTop = scrollTop; } // // SLOW DOWN // // Slow down velocity on every iteration if (!self.options.paging) { // This is the factor applied to every iteration of the animation // to slow down the process. This should emulate natural behavior where // objects slow down when the initiator of the movement is removed var frictionFactor = 0.95; self.__decelerationVelocityX *= frictionFactor; self.__decelerationVelocityY *= frictionFactor; } // // BOUNCING SUPPORT // if (self.options.bouncing) { var scrollOutsideX = 0; var scrollOutsideY = 0; // This configures the amount of change applied to deceleration/acceleration when reaching boundaries var penetrationDeceleration = self.options.penetrationDeceleration; var penetrationAcceleration = self.options.penetrationAcceleration; // Check limits if (scrollLeft < self.__minDecelerationScrollLeft) { scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft; } else if (scrollLeft > self.__maxDecelerationScrollLeft) { scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft; } if (scrollTop < self.__minDecelerationScrollTop) { scrollOutsideY = self.__minDecelerationScrollTop - scrollTop; } else if (scrollTop > self.__maxDecelerationScrollTop) { scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop; } // Slow down until slow enough, then flip back to snap position if (scrollOutsideX !== 0) { var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft; if (isHeadingOutwardsX) { self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration; } var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsX || isStoppedX) { self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration; } } if (scrollOutsideY !== 0) { var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop; if (isHeadingOutwardsY) { self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration; } var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating; //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds if (!isHeadingOutwardsY || isStoppedY) { self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration; } } } } }); ionic.scroll = { isScrolling: false, lastTop: 0 }; })(ionic); (function(ionic) { 'use strict'; /** * An ActionSheet is the slide up menu popularized on iOS. * * You see it all over iOS apps, where it offers a set of options * triggered after an action. */ ionic.views.ActionSheet = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; }, show: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.add('active'); }, hide: function() { // Force a reflow so the animation will actually run this.el.offsetWidth; this.el.classList.remove('active'); } }); })(ionic); (function(ionic) { 'use strict'; ionic.views.HeaderBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; ionic.extend(this, { alignTitle: 'center' }, opts); this.align(); }, align: function(align) { align || (align = this.alignTitle); // Find the titleEl element var titleEl = this.el.querySelector('.title'); if(!titleEl) { return; } var self = this; //We have to rAF here so all of the elements have time to initialize ionic.requestAnimationFrame(function() { var i, c, childSize; var childNodes = self.el.childNodes; var leftWidth = 0; var rightWidth = 0; var isCountingRightWidth = false; // Compute how wide the left children are // Skip all titles (there may still be two titles, one leaving the dom) // Once we encounter a titleEl, realize we are now counting the right-buttons, not left for(i = 0; i < childNodes.length; i++) { c = childNodes[i]; if (c.tagName && c.tagName.toLowerCase() == 'h1') { isCountingRightWidth = true; continue; } childSize = null; if(c.nodeType == 3) { childSize = ionic.DomUtil.getTextBounds(c).width; } else if(c.nodeType == 1) { childSize = c.offsetWidth; } if(childSize) { if (isCountingRightWidth) { rightWidth += childSize; } else { leftWidth += childSize; } } } var margin = Math.max(leftWidth, rightWidth) + 10; //Reset left and right before setting again titleEl.style.left = titleEl.style.right = ''; // Size and align the header titleEl based on the sizes of the left and // right children, and the desired alignment mode if(align == 'center') { if(margin > 10) { titleEl.style.left = margin + 'px'; titleEl.style.right = margin + 'px'; } if(titleEl.offsetWidth < titleEl.scrollWidth) { if(rightWidth > 0) { titleEl.style.right = (rightWidth + 5) + 'px'; } } } else if(align == 'left') { titleEl.classList.add('title-left'); if(leftWidth > 0) { titleEl.style.left = (leftWidth + 15) + 'px'; } } else if(align == 'right') { titleEl.classList.add('title-right'); if(rightWidth > 0) { titleEl.style.right = (rightWidth + 15) + 'px'; } } }); } }); })(ionic); (function(ionic) { 'use strict'; var ITEM_CLASS = 'item'; var ITEM_CONTENT_CLASS = 'item-content'; var ITEM_SLIDING_CLASS = 'item-sliding'; var ITEM_OPTIONS_CLASS = 'item-options'; var ITEM_PLACEHOLDER_CLASS = 'item-placeholder'; var ITEM_REORDERING_CLASS = 'item-reordering'; var ITEM_REORDER_BTN_CLASS = 'item-reorder'; var DragOp = function() {}; DragOp.prototype = { start: function(e) { }, drag: function(e) { }, end: function(e) { }, isSameItem: function(item) { return false; } }; var SlideDrag = function(opts) { this.dragThresholdX = opts.dragThresholdX || 10; this.el = opts.el; this.canSwipe = opts.canSwipe; }; SlideDrag.prototype = new DragOp(); SlideDrag.prototype.start = function(e) { var content, buttons, offsetX, buttonsWidth; if (!this.canSwipe()) { return; } if(e.target.classList.contains(ITEM_CONTENT_CLASS)) { content = e.target; } else if(e.target.classList.contains(ITEM_CLASS)) { content = e.target.querySelector('.' + ITEM_CONTENT_CLASS); } else { content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS); } // If we don't have a content area as one of our children (or ourselves), skip if(!content) { return; } // Make sure we aren't animating as we slide content.classList.remove(ITEM_SLIDING_CLASS); // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start) offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0; // Grab the buttons buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS); if(!buttons) { return; } buttons.classList.remove('invisible'); buttonsWidth = buttons.offsetWidth; this._currentDrag = { buttons: buttons, buttonsWidth: buttonsWidth, content: content, startOffsetX: offsetX }; }; /** * Check if this is the same item that was previously dragged. */ SlideDrag.prototype.isSameItem = function(op) { if(op._lastDrag && this._currentDrag) { return this._currentDrag.content == op._lastDrag.content; } return false; }; SlideDrag.prototype.clean = function(e) { var lastDrag = this._lastDrag; if(!lastDrag) return; ionic.requestAnimationFrame(function() { lastDrag.content.style[ionic.CSS.TRANSITION] = ''; lastDrag.content.style[ionic.CSS.TRANSFORM] = ''; setTimeout(function() { lastDrag.buttons && lastDrag.buttons.classList.add('invisible'); }, 250); }); }; SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { var buttonsWidth; // We really aren't dragging if(!this._currentDrag) { return; } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!this._isDragging && ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) || (Math.abs(this._currentDrag.startOffsetX) > 0))) { this._isDragging = true; } if(this._isDragging) { buttonsWidth = this._currentDrag.buttonsWidth; // Grab the new X point, capping it at zero var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX); // If the new X position is past the buttons, we need to slow down the drag (rubber band style) if(newX < -buttonsWidth) { // Calculate the new X position, capped at the top of the buttons newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4))); } this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)'; this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none'; } }); SlideDrag.prototype.end = function(e, doneCallback) { var _this = this; // There is no drag, just end immediately if(!this._currentDrag) { doneCallback && doneCallback(); return; } // If we are currently dragging, we want to snap back into place // The final resting point X will be the width of the exposed buttons var restingPoint = -this._currentDrag.buttonsWidth; // Check if the drag didn't clear the buttons mid-point // and we aren't moving fast enough to swipe open if(e.gesture.deltaX > -(this._currentDrag.buttonsWidth/2)) { // If we are going left but too slow, or going right, go back to resting if(e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) { restingPoint = 0; } else if(e.gesture.direction == "right") { restingPoint = 0; } } ionic.requestAnimationFrame(function() { if(restingPoint === 0) { _this._currentDrag.content.style[ionic.CSS.TRANSFORM] = ''; var buttons = _this._currentDrag.buttons; setTimeout(function() { buttons && buttons.classList.add('invisible'); }, 250); } else { _this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px, 0, 0)'; } _this._currentDrag.content.style[ionic.CSS.TRANSITION] = ''; // Kill the current drag _this._lastDrag = _this._currentDrag; _this._currentDrag = null; // We are done, notify caller doneCallback && doneCallback(); }); }; var ReorderDrag = function(opts) { this.dragThresholdY = opts.dragThresholdY || 0; this.onReorder = opts.onReorder; this.listEl = opts.listEl; this.el = opts.el; this.scrollEl = opts.scrollEl; this.scrollView = opts.scrollView; }; ReorderDrag.prototype = new DragOp(); ReorderDrag.prototype._moveElement = function(e) { var y = e.gesture.center.pageY + this.scrollView.getValues().top - this.scrollView.__container.offsetTop - (this._currentDrag.elementHeight / 2) - this.listEl.offsetTop; this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, '+y+'px, 0)'; }; ReorderDrag.prototype.start = function(e) { var content; var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase()); var elementHeight = this.el.scrollHeight; var placeholder = this.el.cloneNode(true); placeholder.classList.add(ITEM_PLACEHOLDER_CLASS); this.el.parentNode.insertBefore(placeholder, this.el); this.el.classList.add(ITEM_REORDERING_CLASS); this._currentDrag = { elementHeight: elementHeight, startIndex: startIndex, placeholder: placeholder, scrollHeight: scroll, list: placeholder.parentNode }; this._moveElement(e); }; ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) { // We really aren't dragging var self = this; if(!this._currentDrag) { return; } var scrollY = 0; var pageY = e.gesture.center.pageY; var offset = this.listEl.offsetTop + this.scrollView.__container.offsetTop; //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary if (this.scrollView) { var container = this.scrollView.__container; scrollY = this.scrollView.getValues().top; var containerTop = container.offsetTop; var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight/2; var pixelsPastBottom = pageY + this._currentDrag.elementHeight/2 - containerTop - container.offsetHeight; if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) { this.scrollView.scrollBy(null, -pixelsPastTop); //Trigger another drag so the scrolling keeps going setTimeout(function() { self.drag(e); }.bind(this)); } if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) { if (scrollY < this.scrollView.getScrollMax().top) { this.scrollView.scrollBy(null, pixelsPastBottom); //Trigger another drag so the scrolling keeps going setTimeout(function() { self.drag(e); }.bind(this)); } } } // Check if we should start dragging. Check if we've dragged past the threshold, // or we are starting from the open state. if(!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) { this._isDragging = true; } if(this._isDragging) { this._moveElement(e); this._currentDrag.currentY = scrollY + pageY - offset; this._reorderItems(); } }); // When an item is dragged, we need to reorder any items for sorting purposes ReorderDrag.prototype._reorderItems = function() { var self = this; var placeholder = this._currentDrag.placeholder; var siblings = Array.prototype.slice.call(this._currentDrag.placeholder.parentNode.children) .filter(function(el) { return el !== self.el; }); var index = siblings.indexOf(this._currentDrag.placeholder); var topSibling = siblings[Math.max(0, index - 1)]; var bottomSibling = siblings[Math.min(siblings.length, index+1)]; var thisOffsetTop = this._currentDrag.currentY;// + this._currentDrag.startOffsetTop; if(topSibling && (thisOffsetTop < topSibling.offsetTop + topSibling.offsetHeight)) { ionic.DomUtil.swapNodes(this._currentDrag.placeholder, topSibling); return index - 1; } else if(bottomSibling && thisOffsetTop > (bottomSibling.offsetTop)) { ionic.DomUtil.swapNodes(bottomSibling, this._currentDrag.placeholder); return index + 1; } }; ReorderDrag.prototype.end = function(e, doneCallback) { if(!this._currentDrag) { doneCallback && doneCallback(); return; } var placeholder = this._currentDrag.placeholder; var finalPosition = ionic.DomUtil.getChildIndex(placeholder, placeholder.nodeName.toLowerCase()); // Reposition the element this.el.classList.remove(ITEM_REORDERING_CLASS); this.el.style[ionic.CSS.TRANSFORM] = ''; placeholder.parentNode.insertBefore(this.el, placeholder); placeholder.parentNode.removeChild(placeholder); this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalPosition); this._currentDrag = null; doneCallback && doneCallback(); }; /** * The ListView handles a list of items. It will process drag animations, edit mode, * and other operations that are common on mobile lists or table views. */ ionic.views.ListView = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; opts = ionic.extend({ onReorder: function(el, oldIndex, newIndex) {}, virtualRemoveThreshold: -200, virtualAddThreshold: 200, canSwipe: function() { return true; } }, opts); ionic.extend(this, opts); if(!this.itemHeight && this.listEl) { this.itemHeight = this.listEl.children[0] && parseInt(this.listEl.children[0].style.height, 10); } //ionic.views.ListView.__super__.initialize.call(this, opts); this.onRefresh = opts.onRefresh || function() {}; this.onRefreshOpening = opts.onRefreshOpening || function() {}; this.onRefreshHolding = opts.onRefreshHolding || function() {}; window.ionic.onGesture('release', function(e) { _this._handleEndDrag(e); }, this.el); window.ionic.onGesture('drag', function(e) { _this._handleDrag(e); }, this.el); // Start the drag states this._initDrag(); }, /** * Called to tell the list to stop refreshing. This is useful * if you are refreshing the list and are done with refreshing. */ stopRefreshing: function() { var refresher = this.el.querySelector('.list-refresher'); refresher.style.height = '0px'; }, /** * If we scrolled and have virtual mode enabled, compute the window * of active elements in order to figure out the viewport to render. */ didScroll: function(e) { if(this.isVirtual) { var itemHeight = this.itemHeight; // TODO: This would be inaccurate if we are windowed var totalItems = this.listEl.children.length; // Grab the total height of the list var scrollHeight = e.target.scrollHeight; // Get the viewport height var viewportHeight = this.el.parentNode.offsetHeight; // scrollTop is the current scroll position var scrollTop = e.scrollTop; // High water is the pixel position of the first element to include (everything before // that will be removed) var highWater = Math.max(0, e.scrollTop + this.virtualRemoveThreshold); // Low water is the pixel position of the last element to include (everything after // that will be removed) var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + this.virtualAddThreshold); // Compute how many items per viewport size can show var itemsPerViewport = Math.floor((lowWater - highWater) / itemHeight); // Get the first and last elements in the list based on how many can fit // between the pixel range of lowWater and highWater var first = parseInt(Math.abs(highWater / itemHeight), 10); var last = parseInt(Math.abs(lowWater / itemHeight), 10); // Get the items we need to remove this._virtualItemsToRemove = Array.prototype.slice.call(this.listEl.children, 0, first); // Grab the nodes we will be showing var nodes = Array.prototype.slice.call(this.listEl.children, first, first + itemsPerViewport); this.renderViewport && this.renderViewport(highWater, lowWater, first, last); } }, didStopScrolling: function(e) { if(this.isVirtual) { for(var i = 0; i < this._virtualItemsToRemove.length; i++) { var el = this._virtualItemsToRemove[i]; //el.parentNode.removeChild(el); this.didHideItem && this.didHideItem(i); } // Once scrolling stops, check if we need to remove old items } }, /** * Clear any active drag effects on the list. */ clearDragEffects: function() { if(this._lastDragOp) { this._lastDragOp.clean && this._lastDragOp.clean(); this._lastDragOp = null; } }, _initDrag: function() { //ionic.views.ListView.__super__._initDrag.call(this); // Store the last one this._lastDragOp = this._dragOp; this._dragOp = null; }, // Return the list item from the given target _getItem: function(target) { while(target) { if(target.classList && target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }, _startDrag: function(e) { var _this = this; var didStart = false; this._isDragging = false; var lastDragOp = this._lastDragOp; var item; // Check if this is a reorder drag if(ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_REORDER_BTN_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) { item = this._getItem(e.target); if(item) { this._dragOp = new ReorderDrag({ listEl: this.el, el: item, scrollEl: this.scrollEl, scrollView: this.scrollView, onReorder: function(el, start, end) { _this.onReorder && _this.onReorder(el, start, end); } }); this._dragOp.start(e); e.preventDefault(); } } // Or check if this is a swipe to the side drag else if(!this._didDragUpOrDown && (e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) { // Make sure this is an item with buttons item = this._getItem(e.target); if(item && item.querySelector('.item-options')) { this._dragOp = new SlideDrag({ el: this.el, canSwipe: this.canSwipe }); this._dragOp.start(e); e.preventDefault(); } } // If we had a last drag operation and this is a new one on a different item, clean that last one if(lastDragOp && this._dragOp && !this._dragOp.isSameItem(lastDragOp) && e.defaultPrevented) { lastDragOp.clean && lastDragOp.clean(); } }, _handleEndDrag: function(e) { var _this = this; this._didDragUpOrDown = false; if(!this._dragOp) { //ionic.views.ListView.__super__._handleEndDrag.call(this, e); return; } this._dragOp.end(e, function() { _this._initDrag(); }); }, /** * Process the drag event to move the item to the left or right. */ _handleDrag: function(e) { var _this = this, content, buttons; if(Math.abs(e.gesture.deltaY) > 5) { this._didDragUpOrDown = true; } // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if(!this.isDragging && !this._dragOp) { this._startDrag(e); } // No drag still, pass it up if(!this._dragOp) { //ionic.views.ListView.__super__._handleDrag.call(this, e); return; } e.gesture.srcEvent.preventDefault(); this._dragOp.drag(e); } }); })(ionic); (function(ionic) { 'use strict'; ionic.views.Modal = ionic.views.View.inherit({ initialize: function(opts) { opts = ionic.extend({ focusFirstInput: false, unfocusOnHide: true, focusFirstDelay: 600, backdropClickToClose: true, }, opts); ionic.extend(this, opts); this.el = opts.el; }, show: function() { var self = this; if(self.focusFirstInput) { // Let any animations run first window.setTimeout(function() { var input = self.el.querySelector('input, textarea'); input && input.focus && input.focus(); }, self.focusFirstDelay); } }, hide: function() { // Unfocus all elements if(this.unfocusOnHide) { var inputs = this.el.querySelectorAll('input, textarea'); // Let any animations run first window.setTimeout(function() { for(var i = 0; i < inputs.length; i++) { inputs[i].blur && inputs[i].blur(); } }); } } }); })(ionic); (function(ionic) { 'use strict'; /** * The side menu view handles one of the side menu's in a Side Menu Controller * configuration. * It takes a DOM reference to that side menu element. */ ionic.views.SideMenu = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; this.isEnabled = (typeof opts.isEnabled === 'undefined') ? true : opts.isEnabled; this.setWidth(opts.width); }, getFullWidth: function() { return this.width; }, setWidth: function(width) { this.width = width; this.el.style.width = width + 'px'; }, setIsEnabled: function(isEnabled) { this.isEnabled = isEnabled; }, bringUp: function() { if(this.el.style.zIndex !== '0') { this.el.style.zIndex = '0'; } }, pushDown: function() { if(this.el.style.zIndex !== '-1') { this.el.style.zIndex = '-1'; } } }); ionic.views.SideMenuContent = ionic.views.View.inherit({ initialize: function(opts) { var _this = this; ionic.extend(this, { animationClass: 'menu-animated', onDrag: function(e) {}, onEndDrag: function(e) {}, }, opts); ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el); ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el); }, _onDrag: function(e) { this.onDrag && this.onDrag(e); }, _onEndDrag: function(e) { this.onEndDrag && this.onEndDrag(e); }, disableAnimation: function() { this.el.classList.remove(this.animationClass); }, enableAnimation: function() { this.el.classList.add(this.animationClass); }, getTranslateX: function() { return parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]); }, setTranslateX: ionic.animationFrameThrottle(function(x) { this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)'; }) }); })(ionic); /* * Adapted from Swipe.js 2.0 * * Brad Birdsall * Copyright 2013, MIT License * */ (function(ionic) { 'use strict'; ionic.views.Slider = ionic.views.View.inherit({ initialize: function (options) { var slider = this; // utilities var noop = function() {}; // simple no operation function var offloadFn = function(fn) { setTimeout(fn || noop, 0); }; // offload a functions execution // check browser capabilities var browser = { addEventListener: !!window.addEventListener, touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch, transitions: (function(temp) { var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition']; for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true; return false; })(document.createElement('swipe')) }; var container = options.el; // quit if no root element if (!container) return; var element = container.children[0]; var slides, slidePos, width, length; options = options || {}; var index = parseInt(options.startSlide, 10) || 0; var speed = options.speed || 300; options.continuous = options.continuous !== undefined ? options.continuous : true; function setup() { // cache slides slides = element.children; length = slides.length; // set continuous to false if only one slide if (slides.length < 2) options.continuous = false; //special case if two slides if (browser.transitions && options.continuous && slides.length < 3) { element.appendChild(slides[0].cloneNode(true)); element.appendChild(element.children[1].cloneNode(true)); slides = element.children; } // create an array to store current positions of each slide slidePos = new Array(slides.length); // determine width of each slide width = container.getBoundingClientRect().width || container.offsetWidth; element.style.width = (slides.length * width) + 'px'; // stack elements var pos = slides.length; while(pos--) { var slide = slides[pos]; slide.style.width = width + 'px'; slide.setAttribute('data-index', pos); if (browser.transitions) { slide.style.left = (pos * -width) + 'px'; move(pos, index > pos ? -width : (index < pos ? width : 0), 0); } } // reposition elements before and after index if (options.continuous && browser.transitions) { move(circle(index-1), -width, 0); move(circle(index+1), width, 0); } if (!browser.transitions) element.style.left = (index * -width) + 'px'; container.style.visibility = 'visible'; options.slidesChanged && options.slidesChanged(); } function prev() { if (options.continuous) slide(index-1); else if (index) slide(index-1); } function next() { if (options.continuous) slide(index+1); else if (index < slides.length - 1) slide(index+1); } function circle(index) { // a simple positive modulo using slides.length return (slides.length + (index % slides.length)) % slides.length; } function slide(to, slideSpeed) { // do nothing if already on requested slide if (index == to) return; if (browser.transitions) { var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward // get the actual position of the slide if (options.continuous) { var natural_direction = direction; direction = -slidePos[circle(to)] / width; // if going forward but to < index, use to = slides.length + to // if going backward but to > index, use to = -slides.length + to if (direction !== natural_direction) to = -direction * slides.length + to; } var diff = Math.abs(index-to) - 1; // move all the slides between index and to in the right direction while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0); to = circle(to); move(index, width * direction, slideSpeed || speed); move(to, 0, slideSpeed || speed); if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place } else { to = circle(to); animate(index * -width, to * -width, slideSpeed || speed); //no fallback for a circular continuous if the browser does not accept transitions } index = to; offloadFn(options.callback && options.callback(index, slides[index])); } function move(index, dist, speed) { translate(index, dist, speed); slidePos[index] = dist; } function translate(index, dist, speed) { var slide = slides[index]; var style = slide && slide.style; if (!style) return; style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration = speed + 'ms'; style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)'; style.msTransform = style.MozTransform = style.OTransform = 'translateX(' + dist + 'px)'; } function animate(from, to, speed) { // if not an animation, just reposition if (!speed) { element.style.left = to + 'px'; return; } var start = +new Date(); var timer = setInterval(function() { var timeElap = +new Date() - start; if (timeElap > speed) { element.style.left = to + 'px'; if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); clearInterval(timer); return; } element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px'; }, 4); } // setup auto slideshow var delay = options.auto || 0; var interval; function begin() { interval = setTimeout(next, delay); } function stop() { delay = options.auto || 0; clearTimeout(interval); } // setup initial vars var start = {}; var delta = {}; var isScrolling; // setup event capturing var events = { handleEvent: function(event) { if(event.type == 'mousedown' || event.type == 'mouseup' || event.type == 'mousemove') { event.touches = [{ pageX: event.pageX, pageY: event.pageY }]; } switch (event.type) { case 'mousedown': this.start(event); break; case 'touchstart': this.start(event); break; case 'touchmove': this.touchmove(event); break; case 'mousemove': this.touchmove(event); break; case 'touchend': offloadFn(this.end(event)); break; case 'mouseup': offloadFn(this.end(event)); break; case 'webkitTransitionEnd': case 'msTransitionEnd': case 'oTransitionEnd': case 'otransitionend': case 'transitionend': offloadFn(this.transitionEnd(event)); break; case 'resize': offloadFn(setup); break; } if (options.stopPropagation) event.stopPropagation(); }, start: function(event) { var touches = event.touches[0]; // measure start values start = { // get initial touch coords x: touches.pageX, y: touches.pageY, // store time to determine touch duration time: +new Date() }; // used for testing first move event isScrolling = undefined; // reset delta and end measurements delta = {}; // attach touchmove and touchend listeners if(browser.touch) { element.addEventListener('touchmove', this, false); element.addEventListener('touchend', this, false); } else { element.addEventListener('mousemove', this, false); element.addEventListener('mouseup', this, false); document.addEventListener('mouseup', this, false); } }, touchmove: function(event) { // ensure swiping with one touch and not pinching // ensure sliding is enabled if (event.touches.length > 1 || event.scale && event.scale !== 1 || slider.slideIsDisabled) { return; } if (options.disableScroll) event.preventDefault(); var touches = event.touches[0]; // measure change in x and y delta = { x: touches.pageX - start.x, y: touches.pageY - start.y }; // determine if scrolling test has run - one time test if ( typeof isScrolling == 'undefined') { isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) ); } // if user is not trying to scroll vertically if (!isScrolling) { // prevent native scrolling event.preventDefault(); // stop slideshow stop(); // increase resistance if first or last slide if (options.continuous) { // we don't add resistance at the end translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0); translate(index, delta.x + slidePos[index], 0); translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0); } else { delta.x = delta.x / ( (!index && delta.x > 0 || // if first slide and sliding left index == slides.length - 1 && // or if last slide and sliding right delta.x < 0 // and if sliding at all ) ? ( Math.abs(delta.x) / width + 1 ) // determine resistance level : 1 ); // no resistance if false // translate 1:1 translate(index-1, delta.x + slidePos[index-1], 0); translate(index, delta.x + slidePos[index], 0); translate(index+1, delta.x + slidePos[index+1], 0); } } }, end: function(event) { // measure duration var duration = +new Date() - start.time; // determine if slide attempt triggers next/prev slide var isValidSlide = Number(duration) < 250 && // if slide duration is less than 250ms Math.abs(delta.x) > 20 || // and if slide amt is greater than 20px Math.abs(delta.x) > width/2; // or if slide amt is greater than half the width // determine if slide attempt is past start and end var isPastBounds = !index && delta.x > 0 | // if first slide and slide amt is greater than 0 index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0 if (options.continuous) isPastBounds = false; // determine direction of swipe (true:right, false:left) var direction = delta.x < 0; // if not scrolling vertically if (!isScrolling) { if (isValidSlide && !isPastBounds) { if (direction) { if (options.continuous) { // we need to get the next in this direction in place move(circle(index-1), -width, 0); move(circle(index+2), width, 0); } else { move(index-1, -width, 0); } move(index, slidePos[index]-width, speed); move(circle(index+1), slidePos[circle(index+1)]-width, speed); index = circle(index+1); } else { if (options.continuous) { // we need to get the next in this direction in place move(circle(index+1), width, 0); move(circle(index-2), -width, 0); } else { move(index+1, width, 0); } move(index, slidePos[index]+width, speed); move(circle(index-1), slidePos[circle(index-1)]+width, speed); index = circle(index-1); } options.callback && options.callback(index, slides[index]); } else { if (options.continuous) { move(circle(index-1), -width, speed); move(index, 0, speed); move(circle(index+1), width, speed); } else { move(index-1, -width, speed); move(index, 0, speed); move(index+1, width, speed); } } } // kill touchmove and touchend event listeners until touchstart called again if(browser.touch) { element.removeEventListener('touchmove', events, false); element.removeEventListener('touchend', events, false); } else { element.removeEventListener('mousemove', events, false); element.removeEventListener('mouseup', events, false); document.removeEventListener('mouseup', events, false); } }, transitionEnd: function(event) { if (parseInt(event.target.getAttribute('data-index'), 10) == index) { if (delay) begin(); options.transitionEnd && options.transitionEnd.call(event, index, slides[index]); } } }; // Public API this.update = function() { setTimeout(setup); }; this.setup = function() { setup(); }; this.enableSlide = function(shouldEnable) { if (arguments.length) { this.slideIsDisabled = !shouldEnable; } return !this.slideIsDisabled; }, this.slide = function(to, speed) { // cancel slideshow stop(); slide(to, speed); }; this.prev = this.previous = function() { // cancel slideshow stop(); prev(); }; this.next = function() { // cancel slideshow stop(); next(); }; this.stop = function() { // cancel slideshow stop(); }; this.currentIndex = function() { // return current index position return index; }; this.slidesCount = function() { // return total number of slides return length; }; this.kill = function() { // cancel slideshow stop(); // reset element element.style.width = ''; element.style.left = ''; // reset slides var pos = slides.length; while(pos--) { var slide = slides[pos]; slide.style.width = ''; slide.style.left = ''; if (browser.transitions) translate(pos, 0, 0); } // removed event listeners if (browser.addEventListener) { // remove current event listeners element.removeEventListener('touchstart', events, false); element.removeEventListener('webkitTransitionEnd', events, false); element.removeEventListener('msTransitionEnd', events, false); element.removeEventListener('oTransitionEnd', events, false); element.removeEventListener('otransitionend', events, false); element.removeEventListener('transitionend', events, false); window.removeEventListener('resize', events, false); } else { window.onresize = null; } }; this.load = function() { // trigger setup setup(); // start auto slideshow if applicable if (delay) begin(); // add event listeners if (browser.addEventListener) { // set touchstart event on element if (browser.touch) { element.addEventListener('touchstart', events, false); } else { element.addEventListener('mousedown', events, false); } if (browser.transitions) { element.addEventListener('webkitTransitionEnd', events, false); element.addEventListener('msTransitionEnd', events, false); element.addEventListener('oTransitionEnd', events, false); element.addEventListener('otransitionend', events, false); element.addEventListener('transitionend', events, false); } // set resize event on window window.addEventListener('resize', events, false); } else { window.onresize = function () { setup(); }; // to play nice with old IE } }; } }); })(ionic); (function(ionic) { 'use strict'; ionic.views.Toggle = ionic.views.View.inherit({ initialize: function(opts) { var self = this; this.el = opts.el; this.checkbox = opts.checkbox; this.track = opts.track; this.handle = opts.handle; this.openPercent = -1; this.onChange = opts.onChange || function() {}; this.triggerThreshold = opts.triggerThreshold || 20; this.dragStartHandler = function(e) { self.dragStart(e); }; this.dragHandler = function(e) { self.drag(e); }; this.holdHandler = function(e) { self.hold(e); }; this.releaseHandler = function(e) { self.release(e); }; this.dragStartGesture = ionic.onGesture('dragstart', this.dragStartHandler, this.el); this.dragGesture = ionic.onGesture('drag', this.dragHandler, this.el); this.dragHoldGesture = ionic.onGesture('hold', this.holdHandler, this.el); this.dragReleaseGesture = ionic.onGesture('release', this.releaseHandler, this.el); }, destroy: function() { ionic.offGesture(this.dragStartGesture, 'dragstart', this.dragStartGesture); ionic.offGesture(this.dragGesture, 'drag', this.dragGesture); ionic.offGesture(this.dragHoldGesture, 'hold', this.holdHandler); ionic.offGesture(this.dragReleaseGesture, 'release', this.releaseHandler); }, tap: function(e) { if(this.el.getAttribute('disabled') !== 'disabled') { this.val( !this.checkbox.checked ); } }, dragStart: function(e) { if(this.checkbox.disabled) return; this._dragInfo = { width: this.el.offsetWidth, left: this.el.offsetLeft, right: this.el.offsetLeft + this.el.offsetWidth, triggerX: this.el.offsetWidth / 2, initialState: this.checkbox.checked }; // Stop any parent dragging e.gesture.srcEvent.preventDefault(); // Trigger hold styles this.hold(e); }, drag: function(e) { var self = this; if(!this._dragInfo) { return; } // Stop any parent dragging e.gesture.srcEvent.preventDefault(); ionic.requestAnimationFrame(function(amount) { if (!self._dragInfo) { return; } var slidePageLeft = self.track.offsetLeft + (self.handle.offsetWidth / 2); var slidePageRight = self.track.offsetLeft + self.track.offsetWidth - (self.handle.offsetWidth / 2); var dx = e.gesture.deltaX; var px = e.gesture.touches[0].pageX - self._dragInfo.left; var mx = self._dragInfo.width - self.triggerThreshold; // The initial state was on, so "tend towards" on if(self._dragInfo.initialState) { if(px < self.triggerThreshold) { self.setOpenPercent(0); } else if(px > self._dragInfo.triggerX) { self.setOpenPercent(100); } } else { // The initial state was off, so "tend towards" off if(px < self._dragInfo.triggerX) { self.setOpenPercent(0); } else if(px > mx) { self.setOpenPercent(100); } } }); }, endDrag: function(e) { this._dragInfo = null; }, hold: function(e) { this.el.classList.add('dragging'); }, release: function(e) { this.el.classList.remove('dragging'); this.endDrag(e); }, setOpenPercent: function(openPercent) { // only make a change if the new open percent has changed if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) { this.openPercent = openPercent; if(openPercent === 0) { this.val(false); } else if(openPercent === 100) { this.val(true); } else { var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) ); openPixel = (openPixel < 1 ? 0 : openPixel); this.handle.style[ionic.CSS.TRANSFORM] = 'translate3d(' + openPixel + 'px,0,0)'; } } }, val: function(value) { if(value === true || value === false) { if(this.handle.style[ionic.CSS.TRANSFORM] !== "") { this.handle.style[ionic.CSS.TRANSFORM] = ""; } this.checkbox.checked = value; this.openPercent = (value ? 100 : 0); this.onChange && this.onChange(); } return this.checkbox.checked; } }); })(ionic); (function(ionic) { 'use strict'; ionic.controllers.ViewController = function(options) { this.initialize.apply(this, arguments); }; ionic.controllers.ViewController.inherit = ionic.inherit; ionic.extend(ionic.controllers.ViewController.prototype, { initialize: function() {}, // Destroy this view controller, including all child views destroy: function() { } }); })(window.ionic); (function(ionic) { 'use strict'; /** * The SideMenuController is a controller with a left and/or right menu that * can be slid out and toggled. Seen on many an app. * * The right or left menu can be disabled or not used at all, if desired. */ ionic.controllers.SideMenuController = ionic.controllers.ViewController.inherit({ initialize: function(options) { var self = this; this.left = options.left; this.right = options.right; this.content = options.content; this.dragThresholdX = options.dragThresholdX || 10; this._rightShowing = false; this._leftShowing = false; this._isDragging = false; if(this.content) { this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.onEndDrag =function(e) { self._endDrag(e); }; } }, /** * Set the content view controller if not passed in the constructor options. * * @param {object} content */ setContent: function(content) { var self = this; this.content = content; this.content.onDrag = function(e) { self._handleDrag(e); }; this.content.endDrag = function(e) { self._endDrag(e); }; }, isOpenLeft: function() { return this.getOpenAmount() > 0; }, isOpenRight: function() { return this.getOpenAmount() < 0; }, /** * Toggle the left menu to open 100% */ toggleLeft: function(shouldOpen) { var openAmount = this.getOpenAmount(); if (arguments.length === 0) { shouldOpen = openAmount <= 0; } this.content.enableAnimation(); if(!shouldOpen) { this.openPercentage(0); } else { this.openPercentage(100); } }, /** * Toggle the right menu to open 100% */ toggleRight: function(shouldOpen) { var openAmount = this.getOpenAmount(); if (arguments.length === 0) { shouldOpen = openAmount >= 0; } this.content.enableAnimation(); if(!shouldOpen) { this.openPercentage(0); } else { this.openPercentage(-100); } }, /** * Close all menus. */ close: function() { this.openPercentage(0); }, /** * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative) */ getOpenAmount: function() { return this.content && this.content.getTranslateX() || 0; }, /** * @return {float} The ratio of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative * for right menu. */ getOpenRatio: function() { var amount = this.getOpenAmount(); if(amount >= 0) { return amount / this.left.width; } return amount / this.right.width; }, isOpen: function() { return this.getOpenAmount() !== 0; }, /** * @return {float} The percentage of open amount over menu width. For example, a * menu of width 100 open 50 pixels would be open 50%. Value is negative * for right menu. */ getOpenPercentage: function() { return this.getOpenRatio() * 100; }, /** * Open the menu with a given percentage amount. * @param {float} percentage The percentage (positive or negative for left/right) to open the menu. */ openPercentage: function(percentage) { var p = percentage / 100; if(this.left && percentage >= 0) { this.openAmount(this.left.width * p); } else if(this.right && percentage < 0) { var maxRight = this.right.width; this.openAmount(this.right.width * p); } if(percentage !== 0) { document.body.classList.add('menu-open'); } else { document.body.classList.remove('menu-open'); } }, /** * Open the menu the given pixel amount. * @param {float} amount the pixel amount to open the menu. Positive value for left menu, * negative value for right menu (only one menu will be visible at a time). */ openAmount: function(amount) { var maxLeft = this.left && this.left.width || 0; var maxRight = this.right && this.right.width || 0; // Check if we can move to that side, depending if the left/right panel is enabled if(!(this.left && this.left.isEnabled) && amount > 0) { this.content.setTranslateX(0); return; } if(!(this.right && this.right.isEnabled) && amount < 0) { this.content.setTranslateX(0); return; } if(this._leftShowing && amount > maxLeft) { this.content.setTranslateX(maxLeft); return; } if(this._rightShowing && amount < -maxRight) { this.content.setTranslateX(-maxRight); return; } this.content.setTranslateX(amount); if(amount >= 0) { this._leftShowing = true; this._rightShowing = false; if(amount > 0) { // Push the z-index of the right menu down this.right && this.right.pushDown && this.right.pushDown(); // Bring the z-index of the left menu up this.left && this.left.bringUp && this.left.bringUp(); } } else { this._rightShowing = true; this._leftShowing = false; // Bring the z-index of the right menu up this.right && this.right.bringUp && this.right.bringUp(); // Push the z-index of the left menu down this.left && this.left.pushDown && this.left.pushDown(); } }, /** * Given an event object, find the final resting position of this side * menu. For example, if the user "throws" the content to the right and * releases the touch, the left menu should snap open (animated, of course). * * @param {Event} e the gesture event to use for snapping */ snapToRest: function(e) { // We want to animate at the end of this this.content.enableAnimation(); this._isDragging = false; // Check how much the panel is open after the drag, and // what the drag velocity is var ratio = this.getOpenRatio(); if(ratio === 0) { // Just to be safe this.openPercentage(0); return; } var velocityThreshold = 0.3; var velocityX = e.gesture.velocityX; var direction = e.gesture.direction; // Less than half, going left //if(ratio > 0 && ratio < 0.5 && direction == 'left' && velocityX < velocityThreshold) { //this.openPercentage(0); //} // Going right, less than half, too slow (snap back) if(ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going left, more than half, too slow (snap back) else if(ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(100); } // Going left, less than half, too slow (snap back) else if(ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) { this.openPercentage(0); } // Going right, more than half, too slow (snap back) else if(ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) { this.openPercentage(-100); } // Going right, more than half, or quickly (snap open) else if(direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) { this.openPercentage(100); } // Going left, more than half, or quickly (span open) else if(direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) { this.openPercentage(-100); } // Snap back for safety else { this.openPercentage(0); } }, // End a drag with the given event _endDrag: function(e) { if(this._isDragging) { this.snapToRest(e); } this._startX = null; this._lastX = null; this._offsetX = null; }, // Handle a drag event _handleDrag: function(e) { // If we don't have start coords, grab and store them if(!this._startX) { this._startX = e.gesture.touches[0].pageX; this._lastX = this._startX; } else { // Grab the current tap coords this._lastX = e.gesture.touches[0].pageX; } // Calculate difference from the tap points if(!this._isDragging && Math.abs(this._lastX - this._startX) > this.dragThresholdX) { // if the difference is greater than threshold, start dragging using the current // point as the starting point this._startX = this._lastX; this._isDragging = true; // Initialize dragging this.content.disableAnimation(); this._offsetX = this.getOpenAmount(); } if(this._isDragging) { this.openAmount(this._offsetX + (this._lastX - this._startX)); } } }); })(ionic); (function(window) { var counter = 1; var running = {}; // Namespace ionic.Animation = ionic.Animation || {}; /** * The main animation system manager. Treated as a singleton. */ ionic.Animation = { create: function(opts) { var tf; if(typeof opts.curve === 'string') { tf = ionic.Animation.TimingFn[opts.curve] || ionic.Animation.TimingFn.linear; if(opts.curve.indexOf('cubic-bezier(') >= 0) { var parts = opts.curve.replace('cubic-bezier(', '').replace(')', '').split(','); tf = ionic.Animation.TimingFn['cubic-bezier']; tf = tf(parts[0], parts[1], parts[2], parts[3], opts.duration); } else { tf = tf(opts.duration); } } else { tf = opts.curve; tf = tf(opts.duration); } opts.curveFn = tf; if(opts.dynamicsType) { opts.dynamic = new opts.dynamicsType(opts); } return new ionic.Animation.Animation(opts); }, animationStarted: function(instance) { var id = counter++; // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // Mark as running running[id] = true; instance.isRunning = true; instance._animationId = id; // Return unique animation ID return id; }, animationStopped: function(instance) { instance.isRunning = false; } /* TODO: Move animation set management here instead of instance anims: [], add: function(animation) { this.anims.push(animation); }, remove: function(animation) { var i, j; for(i = 0, j = this.anims.length; i < j; i++) { if(this.anims[i] === animation) { return this.anims.splice(i, 1); } } }, clear: function(shouldStop) { while(this.anims.length) { var anim = this.anims.pop(); if(shouldStop === true) { anim.stop(); } } }, */ /** * Stops the given animation. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation was stopped (aka, was running before) * TODO: Requires above fix stop: function(id) { var cleared = running[id] != null; if (cleared) { running[id] = null; } return cleared; }, */ /** * Whether the given animation is still running. * * @param id {Integer} Unique animation ID * @return {Boolean} Whether the animation is still running isRunning: function(id) { return running[id] != null; }, */ }; })(window); /* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function(ionic) { var bezierCoord = function (x,y) { if(!x) x=0; if(!y) y=0; return {x: x, y: y}; }; function B1(t) { return t*t*t; } function B2(t) { return 3*t*t*(1-t); } function B3(t) { return 3*t*(1-t)*(1-t); } function B4(t) { return (1-t)*(1-t)*(1-t); } ionic.Animation = ionic.Animation || {}; /** * JavaScript port of Webkit implementation of CSS cubic-bezier(p1x.p1y,p2x,p2y) by http://mck.me * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h */ ionic.Animation.Bezier = (function(){ 'use strict'; /** * Duration value to use when one is not specified (400ms is a common value). * @const * @type {number} */ var DEFAULT_DURATION = 400;//ms /** * The epsilon value we pass to UnitBezier::solve given that the animation is going to run over |dur| seconds. * The longer the animation, the more precision we need in the timing function result to avoid ugly discontinuities. * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/page/animation/AnimationBase.cpp */ var solveEpsilon = function(duration) { return 1.0 / (200.0 * duration); }; /** * Defines a cubic-bezier curve given the middle two control points. * NOTE: first and last control points are implicitly (0,0) and (1,1). * @param p1x {number} X component of control point 1 * @param p1y {number} Y component of control point 1 * @param p2x {number} X component of control point 2 * @param p2y {number} Y component of control point 2 */ var unitBezier = function(p1x, p1y, p2x, p2y) { // private members -------------------------------------------- // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). /** * X component of Bezier coefficient C * @const * @type {number} */ var cx = 3.0 * p1x; /** * X component of Bezier coefficient B * @const * @type {number} */ var bx = 3.0 * (p2x - p1x) - cx; /** * X component of Bezier coefficient A * @const * @type {number} */ var ax = 1.0 - cx -bx; /** * Y component of Bezier coefficient C * @const * @type {number} */ var cy = 3.0 * p1y; /** * Y component of Bezier coefficient B * @const * @type {number} */ var by = 3.0 * (p2y - p1y) - cy; /** * Y component of Bezier coefficient A * @const * @type {number} */ var ay = 1.0 - cy - by; /** * @param t {number} parametric timing value * @return {number} */ var sampleCurveX = function(t) { // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. return ((ax * t + bx) * t + cx) * t; }; /** * @param t {number} parametric timing value * @return {number} */ var sampleCurveY = function(t) { return ((ay * t + by) * t + cy) * t; }; /** * @param t {number} parametric timing value * @return {number} */ var sampleCurveDerivativeX = function(t) { return (3.0 * ax * t + 2.0 * bx) * t + cx; }; /** * Given an x value, find a parametric value it came from. * @param x {number} value of x along the bezier curve, 0.0 <= x <= 1.0 * @param epsilon {number} accuracy limit of t for the given x * @return {number} the t value corresponding to x */ var solveCurveX = function(x, epsilon) { var t0; var t1; var t2; var x2; var d2; var i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; if (Math.abs (x2) < epsilon) { return t2; } d2 = sampleCurveDerivativeX(t2); if (Math.abs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } // Fall back to the bisection method for reliability. t0 = 0.0; t1 = 1.0; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = sampleCurveX(t2); if (Math.abs(x2 - x) < epsilon) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) * 0.5 + t0; } // Failure. return t2; }; /** * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param epsilon {number} the accuracy of t for the given x * @return {number} the y value along the bezier curve */ var solve = function(x, epsilon) { return sampleCurveY(solveCurveX(x, epsilon)); }; // public interface -------------------------------------------- /** * Find the y of the cubic-bezier for a given x with accuracy determined by the animation duration. * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param duration {number} the duration of the animation in milliseconds * @return {number} the y value along the bezier curve */ return function(x, duration) { return solve(x, solveEpsilon(+duration || DEFAULT_DURATION)); }; }; // http://www.w3.org/TR/css3-transitions/#transition-timing-function return { /** * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param duration {number} the duration of the animation in milliseconds * @return {number} the y value along the bezier curve */ linear: unitBezier(0.0, 0.0, 1.0, 1.0), /** * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param duration {number} the duration of the animation in milliseconds * @return {number} the y value along the bezier curve */ ease: unitBezier(0.25, 0.1, 0.25, 1.0), /** * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param duration {number} the duration of the animation in milliseconds * @return {number} the y value along the bezier curve */ easeIn: unitBezier(0.42, 0, 1.0, 1.0), /** * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param duration {number} the duration of the animation in milliseconds * @return {number} the y value along the bezier curve */ easeOut: unitBezier(0, 0, 0.58, 1.0), /** * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param duration {number} the duration of the animation in milliseconds * @return {number} the y value along the bezier curve */ easeInOut: unitBezier(0.42, 0, 0.58, 1.0), /** * @param p1x {number} X component of control point 1 * @param p1y {number} Y component of control point 1 * @param p2x {number} X component of control point 2 * @param p2y {number} Y component of control point 2 * @param x {number} the value of x along the bezier curve, 0.0 <= x <= 1.0 * @param duration {number} the duration of the animation in milliseconds * @return {number} the y value along the bezier curve */ cubicBezier: function(p1x, p1y, p2x, p2y) { return unitBezier(p1x, p1y, p2x, p2y); } }; })(); /** * Various fast approximations and alternates to cubic-bezier easing functions. * http://www.w3.org/TR/css3-transitions/#transition-timing-function */ var Easing = (function(){ 'use strict'; /** * @const */ var EASE_IN_OUT_CONST = 0.5 * Math.pow(0.5, 1.925); return { /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ linear: function(x) { return x; }, // /** // * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 // * @return {number} the y value along the curve // */ // ease: function(x) { // // TODO: find fast approximations // return x; // }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInApprox: function(x) { // very close approximation to cubic-bezier(0.42, 0, 1.0, 1.0) return Math.pow(x, 1.685); }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInQuadratic: function(x) { return (x * x); }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInCubic: function(x) { return (x * x * x); }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeOutApprox: function(x) { // very close approximation to cubic-bezier(0, 0, 0.58, 1.0) return 1 - Math.pow(1-x, 1.685); }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeOutQuadratic: function(x) { x -= 1; return 1 - (x * x); }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeOutCubic: function(x) { x -= 1; return 1 + (x * x * x); }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInOutApprox: function(x) { // very close approximation to cubic-bezier(0.42, 0, 0.58, 1.0) if (x < 0.5) { return EASE_IN_OUT_CONST * Math.pow(x, 1.925); } else { return 1 - EASE_IN_OUT_CONST * Math.pow(1-x, 1.925); } }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInOutQuadratic: function(x) { if (x < 0.5) { return (2 * x * x); } else { x -= 1; return 1 - (2 * x * x); } }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInOutCubic: function(x) { if (x < 0.5) { return (4 * x * x * x); } else { x -= 1; return 1 + (4 * x * x * x); } }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInOutQuartic: function(x) { if (x < 0.5) { return (8 * x * x * x * x); } else { x -= 1; return 1 + (8 * x * x * x * x); } }, /** * @param x {number} the value of x along the curve, 0.0 <= x <= 1.0 * @return {number} the y value along the curve */ easeInOutQuintic: function(x) { if (x < 0.5) { return (16 * x * x * x * x * x); } else { x -= 1; return 1 + (16 * x * x * x * x * x); } } }; })(); })(ionic); (function(window) { /** * A HUGE thank you to dynamics.js which inspired these dynamics simulations. * https://github.com/michaelvillar/dynamics.js * * Also licensed under MIT */ // Namespace ionic.Animation = ionic.Animation || {}; ionic.Animation.Dynamics = {}; ionic.Animation.Dynamics.Spring = function(opts) { var defaults = { frequency: 15, friction: 200, anticipationStrength: 0, anticipationSize: 0 }; ionic.extend(this, defaults); var maxs = { frequency: 100, friction: 1000, anticipationStrength: 1000, anticipationSize: 99 }; var mins = { frequency: 0, friction: 1, anticipationStrength: 0, anticipationSize: 0 }; ionic.extend(this, opts); }; ionic.Animation.Dynamics.Spring.prototype = { at: function(t) { var A, At, a, angle, b, decal, frequency, friction, frictionT, s, v, y0, yS, _this = this; frequency = Math.max(1, this.frequency); friction = Math.pow(20, this.friction / 100); s = this.anticipationSize / 100; decal = Math.max(0, s); frictionT = (t / (1 - s)) - (s / (1 - s)); if (t < s) { A = function(t) { var M, a, b, x0, x1; M = 0.8; x0 = s / (1 - s); x1 = 0; b = (x0 - (M * x1)) / (x0 - x1); a = (M - b) / x0; return (a * t * _this.anticipationStrength / 100) + b; }; yS = (s / (1 - s)) - (s / (1 - s)); y0 = (0 / (1 - s)) - (s / (1 - s)); b = Math.acos(1 / A(yS)); a = (Math.acos(1 / A(y0)) - b) / (frequency * (-s)); } else { A = function(t) { return Math.pow(friction / 10, -t) * (1 - t); }; b = 0; a = 1; } At = A(frictionT); angle = frequency * (t - s) * a + b; v = 1 - (At * Math.cos(angle)); //return [t, v, At, frictionT, angle]; return v; } }; ionic.Animation.Dynamics.Gravity = function(opts) { this.options = { bounce: 40, gravity: 1000, initialForce: false }; ionic.extend(this.options, opts); this.curves = []; this.init(); }; ionic.Animation.Dynamics.Gravity.prototype = { length: function() { var L, b, bounce, curve, gravity; bounce = Math.min(this.options.bounce / 100, 80); gravity = this.options.gravity / 100; b = Math.sqrt(2 / gravity); curve = { a: -b, b: b, H: 1 }; if (this.options.initialForce) { curve.a = 0; curve.b = curve.b * 2; } while (curve.H > 0.001) { L = curve.b - curve.a; curve = { a: curve.b, b: curve.b + L * bounce, H: curve.H * bounce * bounce }; } return curve.b; }, init: function() { var L, b, bounce, curve, gravity, _results; L = this.length(); gravity = (this.options.gravity / 100) * L * L; bounce = Math.min(this.options.bounce / 100, 80); b = Math.sqrt(2 / gravity); this.curves = []; curve = { a: -b, b: b, H: 1 }; if (this.options.initialForce) { curve.a = 0; curve.b = curve.b * 2; } this.curves.push(curve); _results = []; while (curve.b < 1 && curve.H > 0.001) { L = curve.b - curve.a; curve = { a: curve.b, b: curve.b + L * bounce, H: curve.H * bounce * bounce }; _results.push(this.curves.push(curve)); } return _results; }, curve: function(a, b, H, t){ var L, c, t2; L = b - a; t2 = (2 / L) * t - 1 - (a * 2 / L); c = t2 * t2 * H - H + 1; if (this.initialForce) { c = 1 - c; } return c; }, at: function(t) { var bounce, curve, gravity, i, v; bounce = this.options.bounce / 100; gravity = this.options.gravity; i = 0; curve = this.curves[i]; while (!(t >= curve.a && t <= curve.b)) { i += 1; curve = this.curves[i]; if (!curve) { break; } } if (!curve) { v = this.options.initialForce ? 0 : 1; } else { v = this.curve(curve.a, curve.b, curve.H, t); } //return [t, v]; return v; } }; })(window); (function(window) { // Namespace ionic.Animation = ionic.Animation || {}; ionic.Animation.TimingFn = { 'spring': function(duration) { return function(t) { return ionic.Animation.Dynamics.Spring(t, duration); }; }, 'gravity': function(duration) { return function(t) { return ionic.Animation.Dynamics.Gravity(t, duration); }; }, 'linear': function(duration) { return function(t) { return ionic.Animation.Bezier.linear(t, duration); }; }, 'ease': function(duration) { return function(t) { return ionic.Animation.Bezier.ease(t, duration); }; }, 'ease-in': function(duration) { return function(t) { return ionic.Animation.Bezier.easeIn(t, duration); }; }, 'ease-out': function(duration) { return function(t) { return ionic.Animation.Bezier.easeOut(t, duration); }; }, 'ease-in-out': function(duration) { return function(t) { return ionic.Animation.Bezier.easeInOut(t, duration); }; }, 'cubic-bezier': function(x1, y1, x2, y2, duration) { var bz = ionic.Animation.Bezier.cubicBezier(x1, y1, x2, y2);//, t, duration); return function(t) { return bz(t, duration); }; } }; })(window); (function(window) { var time = Date.now || function() { return +new Date(); }; var desiredFrames = 60; var millisecondsPerSecond = 1000; // Namespace ionic.Animation = ionic.Animation || {}; /** * Animation instance */ ionic.Animation.Animation = function(opts) { ionic.extend(this, opts); if(opts.useSlowAnimations) { void 0; this.delay *= 3; this.duration *= 3; } }; ionic.Animation.Animation.prototype = { clone: function() { return new ionic.Animation.Animation({ curve: this.curve, curveFn: this.curveFn, duration: this.duration, delay: this.delay, repeat: this.repeat, reverse: this.reverse, autoReverse: this.autoReverse, onComplete: this.onComplete, step: this.step }); }, curve: 'linear', curveFn: ionic.Animation.TimingFn.linear, duration: 500, delay: 0, repeat: -1, reverse: false, autoReverse: false, onComplete: function(didComplete, droppedFrames) {}, // Overridable step: function(percent) {}, setPercent: function(percent, doesSetState) { this.pause(); var v = this.curveFn(percent); // Check if we should change any internal saved state (to resume // from this value later on, for example. Defaults to true) if(doesSetState !== false && this._pauseState) { // Not sure yet on this } this.step(v); //var value = easingMethod ? easingMethod(percent) : percent; }, stop: function() { this.isRunning = false; this.shouldEnd = true; }, play: function() { this.isPaused = false; if(this._lastStepFn) { this._unpausedAnimation = true; ionic.cancelAnimationFrame(this._lastStepFn); ionic.requestAnimationFrame(this._lastStepFn); } }, pause: function() { this.isPaused = true; }, _saveState: function(now, closure) { this._pauseState = { pausedAt: now, }; this._lastStepFn = closure; window.cancelAnimationFrame(closure); }, restart: function() { var self = this; this.isRunning = false; // TODO: Verify this isn't totally stupid ionic.requestAnimationFrame(function() { self.start(); }); }, start: function() { var self = this; // Set up the initial animation state var animState = { startPercent: this.reverse === true ? 1 : 0, endPercent: this.reverse === true ? 0 : 1, duration: this.duration, easingMethod: this.curveFn, delay: this.delay, reverse: this.reverse, repeat: this.repeat, autoReverse: this.autoReverse, dynamic: this.dynamic }; ionic.Animation.animationStarted(this); return this._run(function(percent, now, render) { if(render) { self.step(percent); } }, function(droppedFrames, finishedAnimation) { ionic.Animation.animationStopped(self); self.onComplete && self.onComplete(finishedAnimation, droppedFrames); void 0; }, animState); }, /** * Start the animation. * * @param stepCallback {Function} Pointer to function which is executed on every step. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }` * @param completedCallback {Function} * Signature of the method should be `function(droppedFrames, finishedAnimation) {}` * @param duration {Integer} Milliseconds to run the animation * @param easingMethod {Function} Pointer to easing function * Signature of the method should be `function(percent) { return modifiedValue; }` * @return {Integer} Identifier of animation. Can be used to stop it any time. */ _run: function(stepCallback, completedCallback, state) { var self = this; var start = time(); var lastFrame = start; var startTime = start + state.delay; var percent = state.startPercent; var startPercent = state.startPercent; var endPercent = state.endPercent; var autoReverse = state.autoReverse; var delay = state.delay; var duration = state.duration; var easingMethod = state.easingMethod; var repeat = state.repeat; var reverse = state.reverse; var dropCounter = 0; var iteration = 0; var perhapsAutoreverse = function() { // Check if we hit the end and should auto reverse if(percent === endPercent && autoReverse) { // Flip the start and end values var sp = endPercent; reverse = !reverse; endPercent = startPercent; startPercent = sp; if(repeat === 0) { autoReverse = false; } } else { // Otherwise, just start over percent = startPercent; } // Start fresh either way start = time(); ionic.requestAnimationFrame(step); }; // This is the internal step method which is called every few milliseconds var step = function(virtual) { var now = time(); if(self._unpausedAnimation) { // We unpaused. Increase the start time to account // for the gap in playback (to keep timing the same) var t = self._pauseState.pausedAt; start = start + (now - t); lastFrame = now; } // Normalize virtual value var render = virtual !== true; // Get current time var diff = now - start; // Verification is executed before next animation step if(self.isPaused) { self._saveState(now, step);//percent, iteration, reverse); return; } if (!self.isRunning) {// || (verifyCallback && !verifyCallback(id))) { completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), self._animationId, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; if(self._unpausedAnimation) { void 0; } for (var j = 0; j < Math.min(droppedFrames, 4); j++) { void 0; step(true); dropCounter++; } } // Compute percent value if (diff > delay && duration) { percent = (diff - delay) / duration; // If we are animating in the opposite direction, // the percentage is 1 minus this perc val if(reverse === true) { percent = 1 - percent; if (percent < 0) { percent = 0; } } else { if (percent > 1) { percent = 1; } } } self._unpausedAnimation = false; // Execute step callback, then... var value; if(state.dynamic) { value = state.dynamic.at(percent); } else { value = easingMethod ? easingMethod(percent) : percent; } if ((stepCallback(value, now, render) === false || percent === endPercent) && render) { if(repeat === -1) { perhapsAutoreverse(); } else if(iteration < repeat) { // Track iterations iteration++; perhapsAutoreverse(); } else if(repeat === 0 && autoReverse) { perhapsAutoreverse(); } else { completedCallback && completedCallback( desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), self._animationId, percent === endPercent || duration === null ); } } else if (render) { lastFrame = now; ionic.requestAnimationFrame(step); } }; // Init first step ionic.requestAnimationFrame(step); } }; })(window); })();
mit
liggitt/origin
vendor/github.com/golang/protobuf/proto/text.go
21215
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto // Functions for writing the text protocol buffer format. import ( "bufio" "bytes" "encoding" "errors" "fmt" "io" "log" "math" "reflect" "sort" "strings" ) var ( newline = []byte("\n") spaces = []byte(" ") endBraceNewline = []byte("}\n") backslashN = []byte{'\\', 'n'} backslashR = []byte{'\\', 'r'} backslashT = []byte{'\\', 't'} backslashDQ = []byte{'\\', '"'} backslashBS = []byte{'\\', '\\'} posInf = []byte("inf") negInf = []byte("-inf") nan = []byte("nan") ) type writer interface { io.Writer WriteByte(byte) error } // textWriter is an io.Writer that tracks its indentation level. type textWriter struct { ind int complete bool // if the current position is a complete line compact bool // whether to write out as a one-liner w writer } func (w *textWriter) WriteString(s string) (n int, err error) { if !strings.Contains(s, "\n") { if !w.compact && w.complete { w.writeIndent() } w.complete = false return io.WriteString(w.w, s) } // WriteString is typically called without newlines, so this // codepath and its copy are rare. We copy to avoid // duplicating all of Write's logic here. return w.Write([]byte(s)) } func (w *textWriter) Write(p []byte) (n int, err error) { newlines := bytes.Count(p, newline) if newlines == 0 { if !w.compact && w.complete { w.writeIndent() } n, err = w.w.Write(p) w.complete = false return n, err } frags := bytes.SplitN(p, newline, newlines+1) if w.compact { for i, frag := range frags { if i > 0 { if err := w.w.WriteByte(' '); err != nil { return n, err } n++ } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } } return n, nil } for i, frag := range frags { if w.complete { w.writeIndent() } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } if i+1 < len(frags) { if err := w.w.WriteByte('\n'); err != nil { return n, err } n++ } } w.complete = len(frags[len(frags)-1]) == 0 return n, nil } func (w *textWriter) WriteByte(c byte) error { if w.compact && c == '\n' { c = ' ' } if !w.compact && w.complete { w.writeIndent() } err := w.w.WriteByte(c) w.complete = c == '\n' return err } func (w *textWriter) indent() { w.ind++ } func (w *textWriter) unindent() { if w.ind == 0 { log.Print("proto: textWriter unindented too far") return } w.ind-- } func writeName(w *textWriter, props *Properties) error { if _, err := w.WriteString(props.OrigName); err != nil { return err } if props.Wire != "group" { return w.WriteByte(':') } return nil } func requiresQuotes(u string) bool { // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. for _, ch := range u { switch { case ch == '.' || ch == '/' || ch == '_': continue case '0' <= ch && ch <= '9': continue case 'A' <= ch && ch <= 'Z': continue case 'a' <= ch && ch <= 'z': continue default: return true } } return false } // isAny reports whether sv is a google.protobuf.Any message func isAny(sv reflect.Value) bool { type wkt interface { XXX_WellKnownType() string } t, ok := sv.Addr().Interface().(wkt) return ok && t.XXX_WellKnownType() == "Any" } // writeProto3Any writes an expanded google.protobuf.Any message. // // It returns (false, nil) if sv value can't be unmarshaled (e.g. because // required messages are not linked in). // // It returns (true, error) when sv was written in expanded format or an error // was encountered. func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { turl := sv.FieldByName("TypeUrl") val := sv.FieldByName("Value") if !turl.IsValid() || !val.IsValid() { return true, errors.New("proto: invalid google.protobuf.Any message") } b, ok := val.Interface().([]byte) if !ok { return true, errors.New("proto: invalid google.protobuf.Any message") } parts := strings.Split(turl.String(), "/") mt := MessageType(parts[len(parts)-1]) if mt == nil { return false, nil } m := reflect.New(mt.Elem()) if err := Unmarshal(b, m.Interface().(Message)); err != nil { return false, nil } w.Write([]byte("[")) u := turl.String() if requiresQuotes(u) { writeString(w, u) } else { w.Write([]byte(u)) } if w.compact { w.Write([]byte("]:<")) } else { w.Write([]byte("]: <\n")) w.ind++ } if err := tm.writeStruct(w, m.Elem()); err != nil { return true, err } if w.compact { w.Write([]byte("> ")) } else { w.ind-- w.Write([]byte(">\n")) } return true, nil } func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { if tm.ExpandAny && isAny(sv) { if canExpand, err := tm.writeProto3Any(w, sv); canExpand { return err } } st := sv.Type() sprops := GetProperties(st) for i := 0; i < sv.NumField(); i++ { fv := sv.Field(i) props := sprops.Prop[i] name := st.Field(i).Name if name == "XXX_NoUnkeyedLiteral" { continue } if strings.HasPrefix(name, "XXX_") { // There are two XXX_ fields: // XXX_unrecognized []byte // XXX_extensions map[int32]proto.Extension // The first is handled here; // the second is handled at the bottom of this function. if name == "XXX_unrecognized" && !fv.IsNil() { if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { return err } } continue } if fv.Kind() == reflect.Ptr && fv.IsNil() { // Field not filled in. This could be an optional field or // a required field that wasn't filled in. Either way, there // isn't anything we can show for it. continue } if fv.Kind() == reflect.Slice && fv.IsNil() { // Repeated field that is empty, or a bytes field that is unused. continue } if props.Repeated && fv.Kind() == reflect.Slice { // Repeated field. for j := 0; j < fv.Len(); j++ { if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } v := fv.Index(j) if v.Kind() == reflect.Ptr && v.IsNil() { // A nil message in a repeated field is not valid, // but we can handle that more gracefully than panicking. if _, err := w.Write([]byte("<nil>\n")); err != nil { return err } continue } if err := tm.writeAny(w, v, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if fv.Kind() == reflect.Map { // Map fields are rendered as a repeated struct with key/value fields. keys := fv.MapKeys() sort.Sort(mapKeys(keys)) for _, key := range keys { val := fv.MapIndex(key) if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } // open struct if err := w.WriteByte('<'); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() // key if _, err := w.WriteString("key:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, key, props.mkeyprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } // nil values aren't legal, but we can avoid panicking because of them. if val.Kind() != reflect.Ptr || !val.IsNil() { // value if _, err := w.WriteString("value:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, val, props.mvalprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // close struct w.unindent() if err := w.WriteByte('>'); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { // empty bytes field continue } if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { // proto3 non-repeated scalar field; skip if zero value if isProto3Zero(fv) { continue } } if fv.Kind() == reflect.Interface { // Check if it is a oneof. if st.Field(i).Tag.Get("protobuf_oneof") != "" { // fv is nil, or holds a pointer to generated struct. // That generated struct has exactly one field, // which has a protobuf struct tag. if fv.IsNil() { continue } inner := fv.Elem().Elem() // interface -> *T -> T tag := inner.Type().Field(0).Tag.Get("protobuf") props = new(Properties) // Overwrite the outer props var, but not its pointee. props.Parse(tag) // Write the value in the oneof, not the oneof itself. fv = inner.Field(0) // Special case to cope with malformed messages gracefully: // If the value in the oneof is a nil pointer, don't panic // in writeAny. if fv.Kind() == reflect.Ptr && fv.IsNil() { // Use errors.New so writeAny won't render quotes. msg := errors.New("/* nil */") fv = reflect.ValueOf(&msg).Elem() } } } if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } // Enums have a String method, so writeAny will work fine. if err := tm.writeAny(w, fv, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // Extensions (the XXX_extensions field). pv := sv.Addr() if _, err := extendable(pv.Interface()); err == nil { if err := tm.writeExtensions(w, pv); err != nil { return err } } return nil } // writeAny writes an arbitrary field. func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { v = reflect.Indirect(v) // Floats have special cases. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { x := v.Float() var b []byte switch { case math.IsInf(x, 1): b = posInf case math.IsInf(x, -1): b = negInf case math.IsNaN(x): b = nan } if b != nil { _, err := w.Write(b) return err } // Other values are handled below. } // We don't attempt to serialise every possible value type; only those // that can occur in protocol buffers. switch v.Kind() { case reflect.Slice: // Should only be a []byte; repeated fields are handled in writeStruct. if err := writeString(w, string(v.Bytes())); err != nil { return err } case reflect.String: if err := writeString(w, v.String()); err != nil { return err } case reflect.Struct: // Required/optional group/message. var bra, ket byte = '<', '>' if props != nil && props.Wire == "group" { bra, ket = '{', '}' } if err := w.WriteByte(bra); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() if v.CanAddr() { // Calling v.Interface on a struct causes the reflect package to // copy the entire struct. This is racy with the new Marshaler // since we atomically update the XXX_sizecache. // // Thus, we retrieve a pointer to the struct if possible to avoid // a race since v.Interface on the pointer doesn't copy the struct. // // If v is not addressable, then we are not worried about a race // since it implies that the binary Marshaler cannot possibly be // mutating this value. v = v.Addr() } if etm, ok := v.Interface().(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { return err } if _, err = w.Write(text); err != nil { return err } } else { if v.Kind() == reflect.Ptr { v = v.Elem() } if err := tm.writeStruct(w, v); err != nil { return err } } w.unindent() if err := w.WriteByte(ket); err != nil { return err } default: _, err := fmt.Fprint(w, v.Interface()) return err } return nil } // equivalent to C's isprint. func isprint(c byte) bool { return c >= 0x20 && c < 0x7f } // writeString writes a string in the protocol buffer text format. // It is similar to strconv.Quote except we don't use Go escape sequences, // we treat the string as a byte sequence, and we use octal escapes. // These differences are to maintain interoperability with the other // languages' implementations of the text format. func writeString(w *textWriter, s string) error { // use WriteByte here to get any needed indent if err := w.WriteByte('"'); err != nil { return err } // Loop over the bytes, not the runes. for i := 0; i < len(s); i++ { var err error // Divergence from C++: we don't escape apostrophes. // There's no need to escape them, and the C++ parser // copes with a naked apostrophe. switch c := s[i]; c { case '\n': _, err = w.w.Write(backslashN) case '\r': _, err = w.w.Write(backslashR) case '\t': _, err = w.w.Write(backslashT) case '"': _, err = w.w.Write(backslashDQ) case '\\': _, err = w.w.Write(backslashBS) default: if isprint(c) { err = w.w.WriteByte(c) } else { _, err = fmt.Fprintf(w.w, "\\%03o", c) } } if err != nil { return err } } return w.WriteByte('"') } func writeUnknownStruct(w *textWriter, data []byte) (err error) { if !w.compact { if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { return err } } b := NewBuffer(data) for b.index < len(b.buf) { x, err := b.DecodeVarint() if err != nil { _, err := fmt.Fprintf(w, "/* %v */\n", err) return err } wire, tag := x&7, x>>3 if wire == WireEndGroup { w.unindent() if _, err := w.Write(endBraceNewline); err != nil { return err } continue } if _, err := fmt.Fprint(w, tag); err != nil { return err } if wire != WireStartGroup { if err := w.WriteByte(':'); err != nil { return err } } if !w.compact || wire == WireStartGroup { if err := w.WriteByte(' '); err != nil { return err } } switch wire { case WireBytes: buf, e := b.DecodeRawBytes(false) if e == nil { _, err = fmt.Fprintf(w, "%q", buf) } else { _, err = fmt.Fprintf(w, "/* %v */", e) } case WireFixed32: x, err = b.DecodeFixed32() err = writeUnknownInt(w, x, err) case WireFixed64: x, err = b.DecodeFixed64() err = writeUnknownInt(w, x, err) case WireStartGroup: err = w.WriteByte('{') w.indent() case WireVarint: x, err = b.DecodeVarint() err = writeUnknownInt(w, x, err) default: _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) } if err != nil { return err } if err = w.WriteByte('\n'); err != nil { return err } } return nil } func writeUnknownInt(w *textWriter, x uint64, err error) error { if err == nil { _, err = fmt.Fprint(w, x) } else { _, err = fmt.Fprintf(w, "/* %v */", err) } return err } type int32Slice []int32 func (s int32Slice) Len() int { return len(s) } func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // writeExtensions writes all the extensions in pv. // pv is assumed to be a pointer to a protocol message struct that is extendable. func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { emap := extensionMaps[pv.Type().Elem()] ep, _ := extendable(pv.Interface()) // Order the extensions by ID. // This isn't strictly necessary, but it will give us // canonical output, which will also make testing easier. m, mu := ep.extensionsRead() if m == nil { return nil } mu.Lock() ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) mu.Unlock() for _, extNum := range ids { ext := m[extNum] var desc *ExtensionDesc if emap != nil { desc = emap[extNum] } if desc == nil { // Unknown extension. if err := writeUnknownStruct(w, ext.enc); err != nil { return err } continue } pb, err := GetExtension(ep, desc) if err != nil { return fmt.Errorf("failed getting extension: %v", err) } // Repeated extensions will appear as a slice. if !desc.repeated() { if err := tm.writeExtension(w, desc.Name, pb); err != nil { return err } } else { v := reflect.ValueOf(pb) for i := 0; i < v.Len(); i++ { if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { return err } } } } return nil } func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } return nil } func (w *textWriter) writeIndent() { if !w.complete { return } remain := w.ind * 2 for remain > 0 { n := remain if n > len(spaces) { n = len(spaces) } w.w.Write(spaces[:n]) remain -= n } w.complete = false } // TextMarshaler is a configurable text format marshaler. type TextMarshaler struct { Compact bool // use compact text format (one line). ExpandAny bool // expand google.protobuf.Any messages of known types } // Marshal writes a given protocol buffer in text format. // The only errors returned are from w. func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { val := reflect.ValueOf(pb) if pb == nil || val.IsNil() { w.Write([]byte("<nil>")) return nil } var bw *bufio.Writer ww, ok := w.(writer) if !ok { bw = bufio.NewWriter(w) ww = bw } aw := &textWriter{ w: ww, complete: true, compact: tm.Compact, } if etm, ok := pb.(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { return err } if _, err = aw.Write(text); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Dereference the received pointer so we don't have outer < and >. v := reflect.Indirect(val) if err := tm.writeStruct(aw, v); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Text is the same as Marshal, but returns the string directly. func (tm *TextMarshaler) Text(pb Message) string { var buf bytes.Buffer tm.Marshal(&buf, pb) return buf.String() } var ( defaultTextMarshaler = TextMarshaler{} compactTextMarshaler = TextMarshaler{Compact: true} ) // TODO: consider removing some of the Marshal functions below. // MarshalText writes a given protocol buffer in text format. // The only errors returned are from w. func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } // MarshalTextString is the same as MarshalText, but returns the string directly. func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } // CompactText writes a given protocol buffer in compact text format (one line). func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } // CompactTextString is the same as CompactText, but returns the string directly. func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
apache-2.0
CTres/jsdelivr
files/qoopido.js/3.6.2/polyfill/document/queryselectorall.js
720
/*! * Qoopido.js library v3.6.2, 2015-4-21 * https://github.com/dlueth/qoopido.js * (c) 2015 Dirk Lueth * Dual licensed under MIT and GPL */ !function(e){window.qoopido.register("polyfill/document/queryselectorall",e)}(function(e,t,r,s,l,o){"use strict";return o.querySelectorAll||(o.querySelectorAll=function(e){var t,r=l.document.getElementsByTagName("script")[0],s=o.createElement("style"),n=[];for(r.parentNode.insertBefore(s,r),o._qsa=[],s.styleSheet.cssText=e+"{x-qsa:expression(document._qsa && document._qsa.push(this))}",l.scrollBy(0,0),s.parentNode.removeChild(s);o._qsa.length;)t=o._qsa.shift(),t.style.removeAttribute("x-qsa"),n.push(t);try{delete o._qsa}catch(c){o._qsa=null}return n}),o.querySelectorAll});
mit
kood1/cdnjs
ajax/libs/openlayers/2.12/lib/OpenLayers/Control/ZoomToMaxExtent.min.js
215
OpenLayers.Control.ZoomToMaxExtent=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,trigger:function(){this.map&&this.map.zoomToMaxExtent()},CLASS_NAME:"OpenLayers.Control.ZoomToMaxExtent"});
mit
adoosii/edx-platform
common/djangoapps/external_auth/admin.py
314
''' django admin pages for courseware model ''' from external_auth.models import * from ratelimitbackend import admin class ExternalAuthMapAdmin(admin.ModelAdmin): search_fields = ['external_id', 'user__username'] date_hierarchy = 'dtcreated' admin.site.register(ExternalAuthMap, ExternalAuthMapAdmin)
agpl-3.0
ruo91/cdnjs
ajax/libs/dojo/1.10.0/cldr/nls/en-au/chinese.js
931
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/cldr/nls/en-au/chinese",{"dateFormat-medium":"d MMM U","field-year-relative+-1":"Last year","field-month-relative+-1":"Last month","field-day-relative+-1":"Yesterday","timeFormat-full":"h:mm:ss a zzzz","field-week-relative+0":"This week","field-week-relative+1":"Next week","timeFormat-medium":"h:mm:ss a","field-week-relative+-1":"Last week","field-day-relative+0":"Today","field-day-relative+1":"Tomorrow","dateFormat-long":"d MMMM U","field-month-relative+0":"This month","field-month-relative+1":"Next month","dateFormat-short":"d/MM/yy","field-year-relative+0":"This year","field-year-relative+1":"Next year","timeFormat-short":"h:mm a","timeFormat-long":"h:mm:ss a z","dateFormat-full":"EEEE, d MMMM U"});
mit
tvnweb/grandprix
node_modules/node-gyp/test/test-find-python.js
8253
'use strict' var test = require('tape') var configure = require('../lib/configure') var execFile = require('child_process').execFile var PythonFinder = configure.test.PythonFinder test('find python', function (t) { t.plan(4) configure.test.findPython('python', function (err, found) { t.strictEqual(err, null) var proc = execFile(found, ['-V'], function (err, stdout, stderr) { t.strictEqual(err, null) t.strictEqual(stdout, '') t.ok(/Python 2/.test(stderr)) }) proc.stdout.setEncoding('utf-8') proc.stderr.setEncoding('utf-8') }) }) function poison(object, property) { function fail() { throw new Error('Property ' + property + ' should not have been accessed.') } var descriptor = { configurable: true, enumerable: false, writable: true, getter: fail, setter: fail, } Object.defineProperty(object, property, descriptor) } function TestPythonFinder() { PythonFinder.apply(this, arguments) } TestPythonFinder.prototype = Object.create(PythonFinder.prototype) poison(TestPythonFinder.prototype, 'env') poison(TestPythonFinder.prototype, 'execFile') poison(TestPythonFinder.prototype, 'stat') poison(TestPythonFinder.prototype, 'which') poison(TestPythonFinder.prototype, 'win') test('find python - python', function (t) { t.plan(5) var f = new TestPythonFinder('python', done) f.which = function(program, cb) { t.strictEqual(program, 'python') cb(null, program) } f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'python') t.ok(/import platform/.test(args[1])) cb(null, '2.7.0') } f.checkPython() function done(err, python) { t.strictEqual(err, null) t.strictEqual(python, 'python') } }) test('find python - python too old', function (t) { t.plan(4) var f = new TestPythonFinder('python', done) f.which = function(program, cb) { t.strictEqual(program, 'python') cb(null, program) } f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'python') t.ok(/import platform/.test(args[1])) cb(null, '2.3.4') } f.checkPython() function done(err, python) { t.ok(/is not supported by gyp/.test(err)) } }) test('find python - python too new', function (t) { t.plan(4) var f = new TestPythonFinder('python', done) f.which = function(program, cb) { t.strictEqual(program, 'python') cb(null, program) } f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'python') t.ok(/import platform/.test(args[1])) cb(null, '3.0.0') } f.checkPython() function done(err, python) { t.ok(/is not supported by gyp/.test(err)) } }) test('find python - no python', function (t) { t.plan(2) var f = new TestPythonFinder('python', done) f.which = function(program, cb) { t.strictEqual(program, 'python') cb(new Error('not found')) } f.checkPython() function done(err, python) { t.ok(/Can't find Python executable/.test(err)) } }) test('find python - no python2', function (t) { t.plan(6) var f = new TestPythonFinder('python2', done) f.which = function(program, cb) { f.which = function(program, cb) { t.strictEqual(program, 'python') cb(null, program) } t.strictEqual(program, 'python2') cb(new Error('not found')) } f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'python') t.ok(/import platform/.test(args[1])) cb(null, '2.7.0') } f.checkPython() function done(err, python) { t.strictEqual(err, null) t.strictEqual(python, 'python') } }) test('find python - no python2, no python, unix', function (t) { t.plan(3) var f = new TestPythonFinder('python2', done) poison(f, 'checkPythonLauncher') f.win = false f.which = function(program, cb) { f.which = function(program, cb) { t.strictEqual(program, 'python') cb(new Error('not found')) } t.strictEqual(program, 'python2') cb(new Error('not found')) } f.checkPython() function done(err, python) { t.ok(/Can't find Python executable/.test(err)) } }) test('find python - no python, use python launcher', function (t) { t.plan(8) var f = new TestPythonFinder('python', done) f.env = {} f.win = true f.which = function(program, cb) { t.strictEqual(program, 'python') cb(new Error('not found')) } f.execFile = function(program, args, opts, cb) { f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'Z:\\snake.exe') t.ok(/import platform/.test(args[1])) cb(null, '2.7.0') } t.strictEqual(program, 'py.exe') t.notEqual(args.indexOf('-2'), -1) t.notEqual(args.indexOf('-c'), -1) cb(null, 'Z:\\snake.exe') } f.checkPython() function done(err, python) { t.strictEqual(err, null) t.strictEqual(python, 'Z:\\snake.exe') } }) test('find python - python 3, use python launcher', function (t) { t.plan(10) var f = new TestPythonFinder('python', done) f.env = {} f.win = true f.which = function(program, cb) { t.strictEqual(program, 'python') cb(null, program) } f.execFile = function(program, args, opts, cb) { f.execFile = function(program, args, opts, cb) { f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'Z:\\snake.exe') t.ok(/import platform/.test(args[1])) cb(null, '2.7.0') } t.strictEqual(program, 'py.exe') t.notEqual(args.indexOf('-2'), -1) t.notEqual(args.indexOf('-c'), -1) cb(null, 'Z:\\snake.exe') } t.strictEqual(program, 'python') t.ok(/import platform/.test(args[1])) cb(null, '3.0.0') } f.checkPython() function done(err, python) { t.strictEqual(err, null) t.strictEqual(python, 'Z:\\snake.exe') } }) test('find python - python 3, use python launcher, python 2 too old', function (t) { t.plan(9) var f = new TestPythonFinder('python', done) f.checkedPythonLauncher = false f.env = {} f.win = true f.which = function(program, cb) { t.strictEqual(program, 'python') cb(null, program) } f.execFile = function(program, args, opts, cb) { f.execFile = function(program, args, opts, cb) { f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'Z:\\snake.exe') t.ok(/import platform/.test(args[1])) cb(null, '2.3.4') } t.strictEqual(program, 'py.exe') t.notEqual(args.indexOf('-2'), -1) t.notEqual(args.indexOf('-c'), -1) cb(null, 'Z:\\snake.exe') } t.strictEqual(program, 'python') t.ok(/import platform/.test(args[1])) cb(null, '3.0.0') } f.checkPython() function done(err, python) { t.ok(/is not supported by gyp/.test(err)) } }) test('find python - no python, no python launcher, good guess', function (t) { t.plan(6) var re = /C:[\\\/]Python27[\\\/]python[.]exe/ var f = new TestPythonFinder('python', done) f.env = {} f.win = true f.which = function(program, cb) { t.strictEqual(program, 'python') cb(new Error('not found')) } f.execFile = function(program, args, opts, cb) { f.execFile = function(program, args, opts, cb) { t.ok(re.test(program)) t.ok(/import platform/.test(args[1])) cb(null, '2.7.0') } t.strictEqual(program, 'py.exe') cb(new Error('not found')) } f.stat = function(path, cb) { t.ok(re.test(path)) cb(null, {}) } f.checkPython() function done(err, python) { t.ok(re.test(python)) } }) test('find python - no python, no python launcher, bad guess', function (t) { t.plan(4) var f = new TestPythonFinder('python', done) f.env = { SystemDrive: 'Z:\\' } f.win = true f.which = function(program, cb) { t.strictEqual(program, 'python') cb(new Error('not found')) } f.execFile = function(program, args, opts, cb) { t.strictEqual(program, 'py.exe') cb(new Error('not found')) } f.stat = function(path, cb) { t.ok(/Z:[\\\/]Python27[\\\/]python.exe/.test(path)) var err = new Error('not found') err.code = 'ENOENT' cb(err) } f.checkPython() function done(err, python) { t.ok(/Can't find Python executable/.test(err)) } })
mit
mouna16/Drupal8
core/modules/file/src/Tests/FileFieldRevisionTest.php
8082
<?php namespace Drupal\file\Tests; use Drupal\file\Entity\File; /** * Tests creating and deleting revisions with files attached. * * @group file */ class FileFieldRevisionTest extends FileFieldTestBase { /** * Tests creating multiple revisions of a node and managing attached files. * * Expected behaviors: * - Adding a new revision will make another entry in the field table, but * the original file will not be duplicated. * - Deleting a revision should not delete the original file if the file * is in use by another revision. * - When the last revision that uses a file is deleted, the original file * should be deleted also. */ function testRevisions() { $node_storage = $this->container->get('entity.manager')->getStorage('node'); $type_name = 'article'; $field_name = strtolower($this->randomMachineName()); $this->createFileField($field_name, 'node', $type_name); // Create the same fields for users. $this->createFileField($field_name, 'user', 'user'); $test_file = $this->getTestFile('text'); // Create a new node with the uploaded file. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file exists on disk and in the database. $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file_r1 = File::load($node->{$field_name}->target_id); $node_vid_r1 = $node->getRevisionId(); $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.'); $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.'); $this->assertFileIsPermanent($node_file_r1, 'File is permanent.'); // Upload another file to the same node in a new revision. $this->replaceNodeFile($test_file, $field_name, $nid); $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file_r2 = File::load($node->{$field_name}->target_id); $node_vid_r2 = $node->getRevisionId(); $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.'); $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.'); $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.'); // Check that the original file is still in place on the first revision. $node = node_revision_load($node_vid_r1); $current_file = File::load($node->{$field_name}->target_id); $this->assertEqual($node_file_r1->id(), $current_file->id(), 'Original file still in place after replacing file in new revision.'); $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.'); $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision'); $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.'); // Save a new version of the node without any changes. // Check that the file is still the same as the previous revision. $this->drupalPostForm('node/' . $nid . '/edit', array('revision' => '1'), t('Save and keep published')); $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file_r3 = File::load($node->{$field_name}->target_id); $node_vid_r3 = $node->getRevisionId(); $this->assertEqual($node_file_r2->id(), $node_file_r3->id(), 'Previous revision file still in place after creating a new revision without a new file.'); $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.'); // Revert to the first revision and check that the original file is active. $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert')); $node_storage->resetCache(array($nid)); $node = $node_storage->load($nid); $node_file_r4 = File::load($node->{$field_name}->target_id); $this->assertEqual($node_file_r1->id(), $node_file_r4->id(), 'Original revision file still in place after reverting to the original revision.'); $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.'); // Delete the second revision and check that the file is kept (since it is // still being used by the third revision). $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete')); $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.'); $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.'); $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.'); // Attach the second file to a user. $user = $this->drupalCreateUser(); $user->$field_name->target_id = $node_file_r3->id(); $user->$field_name->display = 1; $user->save(); $this->drupalGet('user/' . $user->id() . '/edit'); // Delete the third revision and check that the file is not deleted yet. $this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete')); $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.'); $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.'); $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.'); // Delete the user and check that the file is also deleted. $user->delete(); // TODO: This seems like a bug in File API. Clearing the stat cache should // not be necessary here. The file really is deleted, but stream wrappers // doesn't seem to think so unless we clear the PHP file stat() cache. clearstatcache($node_file_r1->getFileUri()); clearstatcache($node_file_r2->getFileUri()); clearstatcache($node_file_r3->getFileUri()); clearstatcache($node_file_r4->getFileUri()); // Call file_cron() to clean up the file. Make sure the changed timestamp // of the file is older than the system.file.temporary_maximum_age // configuration value. db_update('file_managed') ->fields(array( 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), )) ->condition('fid', $node_file_r3->id()) ->execute(); \Drupal::service('cron')->run(); $this->assertFileNotExists($node_file_r3, 'Second file is now deleted after deleting third revision, since it is no longer being used by any other nodes.'); $this->assertFileEntryNotExists($node_file_r3, 'Second file entry is now deleted after deleting third revision, since it is no longer being used by any other nodes.'); // Delete the entire node and check that the original file is deleted. $this->drupalPostForm('node/' . $nid . '/delete', array(), t('Delete')); // Call file_cron() to clean up the file. Make sure the changed timestamp // of the file is older than the system.file.temporary_maximum_age // configuration value. db_update('file_managed') ->fields(array( 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), )) ->condition('fid', $node_file_r1->id()) ->execute(); \Drupal::service('cron')->run(); $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.'); $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.'); } }
gpl-2.0
cloud-chiu/mhk
lib/htmlpurifier/HTMLPurifier/URIScheme.php
3360
<?php /** * Validator for the components of a URI for a specific scheme */ abstract class HTMLPurifier_URIScheme { /** * Scheme's default port (integer). If an explicit port number is * specified that coincides with the default port, it will be * elided. */ public $default_port = null; /** * Whether or not URIs of this schem are locatable by a browser * http and ftp are accessible, while mailto and news are not. */ public $browsable = false; /** * Whether or not data transmitted over this scheme is encrypted. * https is secure, http is not. */ public $secure = false; /** * Whether or not the URI always uses <hier_part>, resolves edge cases * with making relative URIs absolute */ public $hierarchical = false; /** * Whether or not the URI may omit a hostname when the scheme is * explicitly specified, ala file:///path/to/file. As of writing, * 'file' is the only scheme that browsers support his properly. */ public $may_omit_host = false; /** * Validates the components of a URI for a specific scheme. * @param $uri Reference to a HTMLPurifier_URI object * @param $config HTMLPurifier_Config object * @param $context HTMLPurifier_Context object * @return Bool success or failure */ public abstract function doValidate(&$uri, $config, $context); /** * Public interface for validating components of a URI. Performs a * bunch of default actions. Don't overload this method. * @param $uri Reference to a HTMLPurifier_URI object * @param $config HTMLPurifier_Config object * @param $context HTMLPurifier_Context object * @return Bool success or failure */ public function validate(&$uri, $config, $context) { if ($this->default_port == $uri->port) $uri->port = null; // kludge: browsers do funny things when the scheme but not the // authority is set if (!$this->may_omit_host && // if the scheme is present, a missing host is always in error (!is_null($uri->scheme) && ($uri->host === '' || is_null($uri->host))) || // if the scheme is not present, a *blank* host is in error, // since this translates into '///path' which most browsers // interpret as being 'http://path'. (is_null($uri->scheme) && $uri->host === '') ) { do { if (is_null($uri->scheme)) { if (substr($uri->path, 0, 2) != '//') { $uri->host = null; break; } // URI is '////path', so we cannot nullify the // host to preserve semantics. Try expanding the // hostname instead (fall through) } // first see if we can manually insert a hostname $host = $config->get('URI.Host'); if (!is_null($host)) { $uri->host = $host; } else { // we can't do anything sensible, reject the URL. return false; } } while (false); } return $this->doValidate($uri, $config, $context); } } // vim: et sw=4 sts=4
gpl-3.0
silverli/lee-dentist
node_modules/bower/lib/node_modules/shell-quote/example/op.js
91
var parse = require('../').parse; var xs = parse('beep || boop > /byte'); console.dir(xs);
mit
yblee85/todomvc
examples/firebase-angular/js/directives/todoBlur.js
364
/*global todomvc */ 'use strict'; /** * Directive that executes an expression when the element it is applied to loses focus */ todomvc.directive('todoBlur', function () { return function (scope, elem, attrs) { elem.bind('blur', function () { scope.$apply(attrs.todoBlur); }); scope.$on('$destroy', function () { elem.unbind('blur'); }); }; });
mit
taimir/dashboard
Godeps/_workspace/src/k8s.io/kubernetes/pkg/controller/job/doc.go
670
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package job contains logic for watching and synchronizing jobs. package job
apache-2.0
liggitt/origin
vendor/k8s.io/kubernetes/staging/src/k8s.io/apiserver/pkg/storage/etcd3/errors.go
1288
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package etcd3 import ( "k8s.io/apimachinery/pkg/api/errors" etcdrpc "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes" ) func interpretWatchError(err error) error { switch { case err == etcdrpc.ErrCompacted: return errors.NewResourceExpired("The resourceVersion for the provided watch is too old.") } return err } func interpretListError(err error, paging bool) error { switch { case err == etcdrpc.ErrCompacted: if paging { return errors.NewResourceExpired("The provided from parameter is too old to display a consistent list result. You must start a new list without the from.") } return errors.NewResourceExpired("The resourceVersion for the provided list is too old.") } return err }
apache-2.0
soniacq/LearningReact
node_modules/react-scripts/node_modules/sockjs-client/lib/utils/url.js
975
'use strict'; var URL = require('url-parse'); var debug = function() {}; if (process.env.NODE_ENV !== 'production') { debug = require('debug')('sockjs-client:utils:url'); } module.exports = { getOrigin: function(url) { if (!url) { return null; } var p = new URL(url); if (p.protocol === 'file:') { return null; } var port = p.port; if (!port) { port = (p.protocol === 'https:') ? '443' : '80'; } return p.protocol + '//' + p.hostname + ':' + port; } , isOriginEqual: function(a, b) { var res = this.getOrigin(a) === this.getOrigin(b); debug('same', a, b, res); return res; } , isSchemeEqual: function(a, b) { return (a.split(':')[0] === b.split(':')[0]); } , addPath: function (url, path) { var qs = url.split('?'); return qs[0] + path + (qs[1] ? '?' + qs[1] : ''); } , addQuery: function (url, q) { return url + (url.indexOf('?') === -1 ? ('?' + q) : ('&' + q)); } };
gpl-3.0
thorgate/django-project-template
{{cookiecutter.repo_name}}/app/src/decorators/withView.js
204
import { connectView } from '@thorgate/spa-view'; import { onComponentError } from 'services/sentry'; export default (props = {}) => (target) => connectView({ ...props, onComponentError })(target);
isc
agvision/Angular_Seed_Karma
src/test/routing.ts
1182
import {it, describe, expect, inject, injectAsync, beforeEach, beforeEachProviders} from 'angular2/testing'; import {provide} from 'angular2/core'; import {RouteRegistry, Router, ROUTER_PRIMARY_COMPONENT, Location} from 'angular2/router'; import {RootRouter} from 'angular2/src/router/router'; import {AppComponent} from '../app/components/app'; describe('Routing', () => { let location: Location; let router: Router; beforeEachProviders(() => [ RouteRegistry, Location, provide(Router, {useClass: RootRouter}), provide(ROUTER_PRIMARY_COMPONENT, {useValue: AppComponent}) ]); beforeEach(inject([Router, Location], (r, l) => { router = r; location = l; })); it('Should navigate to Login', (done) => { router.navigate(['Login']).then(() => { expect(location.path()).toBe('/login'); done(); }).catch(e => done.fail(e)); }); it('Should navigate to Register', (done) => { router.navigate(['Register']).then(() => { expect(location.path()).toBe('/register'); done(); }).catch(e => done.fail(e)); }); });
isc
ryleykimmel/brandywine
network/src/main/java/me/ryleykimmel/brandywine/network/frame/DataType.java
986
package me.ryleykimmel.brandywine.network.frame; /** * Represents primitive data types, used to indicate to a frame buffer what value to read or write. */ public enum DataType { /** * Represents a {@code byte}. */ BYTE(Byte.BYTES), /** * Represents a {@code short}. */ SHORT(Short.BYTES), /** * Represents an {@code int}. */ INT(Integer.BYTES), /** * Represents a {@code long}. */ LONG(Long.BYTES); /** * The amount of {@code byte}s a single data type consumes. */ private final int bytes; /** * Constructs a new {@link DataType} with the specified amount of {@code byte}s it consumes. * * @param bytes The amount of {@code byte}s a signle data type consumes. */ DataType(int bytes) { this.bytes = bytes; } /** * Gets the amount of {@code byte}s this data type consumes. * * @return The amount of {@code byte}s this data type consumes. */ public int getBytes() { return bytes; } }
isc
ripple/ripple-lib
webpack.config.js
3449
'use strict'; const path = require('path'); const webpack = require('webpack'); const assert = require('assert'); const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer'); function getDefaultConfiguration() { return { cache: true, performance: { hints: false }, stats: 'errors-only', entry: './dist/npm/index.js', output: { library: 'ripple', path: path.join(__dirname, 'build/'), filename: `ripple-lib.default.js`, }, plugins: [ new webpack.NormalModuleReplacementPlugin(/^ws$/, './wswrapper'), new webpack.NormalModuleReplacementPlugin(/^\.\/wallet$/, './wallet-web'), new webpack.NormalModuleReplacementPlugin(/^.*setup-api$/, './setup-api-web'), new webpack.ProvidePlugin({ process: 'process/browser' }), new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] }) ], module: { rules: [] }, resolve: { extensions: ['.js', '.json'], fallback: { "buffer": require.resolve("buffer/"), "assert": require.resolve("assert/"), "url": require.resolve("url/"), "stream": require.resolve("stream-browserify"), "crypto": require.resolve("crypto-browserify"), "https": require.resolve("https-browserify"), "http": require.resolve('stream-http') } }, }; } function webpackForTest(testFileName) { const match = testFileName.match(/\/?([^\/]*)-test.ts$/); if (!match) { assert(false, 'wrong filename:' + testFileName); } const test = { cache: true, externals: [{ 'lodash': '_', 'ripple-api': 'ripple', 'net': 'null' }], entry: testFileName, output: { library: match[1].replace(/-/g, '_'), path: path.join(__dirname, './test-compiled-for-web/'), filename: match[1] + '-test.js' }, plugins: [ new webpack.ProvidePlugin({ process: 'process/browser' }), new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] }) ], module: { rules: [{ test: /jayson/, use: 'null', }, { test: /\.ts$/, use: [{ loader: 'ts-loader', options: { compilerOptions: { composite: false, declaration: false, declarationMap: false } }, }], }] }, node: { global: true, __filename: false, __dirname: true, }, resolve: { extensions: [ '.ts', '.js', '.json' ], fallback: { "buffer": require.resolve("buffer/"), "assert": require.resolve("assert/"), "url": require.resolve("url/"), "stream": require.resolve("stream-browserify"), "crypto": require.resolve("crypto-browserify"), "path": require.resolve("path-browserify"), "http": require.resolve("stream-http"), "fs": false } } }; return Object.assign({}, getDefaultConfiguration(), test); } module.exports = [ (env, argv) => { const config = getDefaultConfiguration(); config.mode = 'development'; config.output.filename = `ripple-latest.js`; return config; }, (env, argv) => { const config = getDefaultConfiguration(); config.mode = 'production'; config.output.filename = `ripple-latest-min.js`; if (process.argv.includes('--analyze')) { config.plugins.push(new BundleAnalyzerPlugin()); } return config; }, (env, argv) => webpackForTest('./test/integration/integration-test.ts'), ];
isc
MirekSz/webpack-es6-ts
app/mods/mod1285.js
76
import mod1284 from './mod1284'; var value=mod1284+1; export default value;
isc
data-axle/cassandra_object
test/unit/schema/tasks_test.rb
630
require 'test_helper' class CassandraObject::Schema::TasksTest < CassandraObject::TestCase test "table_names" do assert_equal ['Issues'], CassandraObject::Schema.table_names end test "dump" do io = StringIO.new CassandraObject::Schema.dump(io) io.rewind assert_match /Issues/, io.read end test "load" do CassandraObject::Schema.expects(:keyspace_execute).with("DO STUFF;") CassandraObject::Schema.expects(:keyspace_execute).with("AND MORE;") CassandraObject::Schema.load StringIO.new( "DO\n" + " STUFF;\n" + "\n" + "AND\n" + " MORE;\n" ) end end
isc
fparma/fparma-web
server/config/express.js
1252
import express from 'express' import nconf from 'nconf' import mongoose from 'mongoose' import session from 'express-session' import logger from 'morgan' import favicon from 'serve-favicon' import compression from 'compression' import bodyParser from 'body-parser' import MongoStore from 'connect-mongo' import {join} from 'path' const SessionStore = MongoStore(session) export default function (app, root, IS_DEV) { app.set('x-powered-by', false) // View engine app.set('views', join(root, 'views')) app.set('view engine', 'jade') // Middlewares app.use(compression()) app.use(favicon(join(root, '../public/favicon.ico'))) app.use(logger(IS_DEV ? 'dev' : 'combined')) app.use(express.static('public', {maxage: IS_DEV ? 0 : '7d'})) app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) app.use(session({ name: 'connect.fparma', // trust reverse proxy from heroku proxy: !IS_DEV, // enable rolling sessions rolling: true, secret: nconf.get('SESSION:SECRET'), store: new SessionStore({ mongooseConnection: mongoose.connection, touchAfter: 600 // 10 min }), resave: false, saveUninitialized: false })) }
isc
simonwrafter/OMXInvest
JamaPart/LUDecomposition.java
2953
/* Copyright Notice * This software is a cooperative product of The MathWorks and the National * Institute of Standards and Technology (NIST) which has been released to the * public domain. Neither The MathWorks nor NIST assumes any responsibility * whatsoever for its use by other parties, and makes no guarantees, expressed * or implied, about its quality, reliability, or any other characteristic. */ /* * Simon Wrafter <simon.wrafter@gmail.com> * As part of OMXInvest, this class has been minimised and stripped of unused code. */ package JamaPart; public class LUDecomposition { private Double[][] LU; private int m, n, pivsign; private int[] piv; public LUDecomposition (Matrix A) { // Use a "left-looking", dot-product, Crout/Doolittle algorithm. LU = A.getArrayCopy(); m = A.getRowDimension(); n = A.getColumnDimension(); piv = new int[m]; for (int i = 0; i < m; i++) { piv[i] = i; } pivsign = 1; Double[] LUrowi; Double[] LUcolj = new Double[m]; // Outer loop. for (int j = 0; j < n; j++) { // Make a copy of the j-th column to localize references. for (int i = 0; i < m; i++) { LUcolj[i] = LU[i][j]; } // Apply previous transformations. for (int i = 0; i < m; i++) { LUrowi = LU[i]; // Most of the time is spent in the following dot product. int kmax = Math.min(i,j); double s = 0.0; for (int k = 0; k < kmax; k++) { s += LUrowi[k]*LUcolj[k]; } LUrowi[j] = LUcolj[i] -= s; } // Find pivot and exchange if necessary. int p = j; for (int i = j+1; i < m; i++) { if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { p = i; } } if (p != j) { for (int k = 0; k < n; k++) { double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t; } int k = piv[p]; piv[p] = piv[j]; piv[j] = k; pivsign = -pivsign; } // Compute multipliers. if (j < m & LU[j][j] != 0.0) { for (int i = j+1; i < m; i++) { LU[i][j] /= LU[j][j]; } } } } public boolean isNonsingular () { for (int j = 0; j < n; j++) { if (LU[j][j] == 0) return false; } return true; } public Matrix solve (Matrix B) { if (B.getRowDimension() != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isNonsingular()) { throw new RuntimeException("Matrix is singular."); } // Copy right hand side with pivoting int nx = B.getColumnDimension(); Matrix Xmat = B.getMatrix(piv,0,nx-1); Double[][] X = Xmat.getArray(); // Solve L*Y = B(piv,:) for (int k = 0; k < n; k++) { for (int i = k+1; i < n; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } // Solve U*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= LU[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } return Xmat; } }
isc
io7m/jvvfs
io7m-jvvfs-shell/src/main/java/com/io7m/jvvfs/shell/ShellCommandHelpNoArguments.java
1301
/* * Copyright © 2014 <code@io7m.com> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jvvfs.shell; import java.io.PrintStream; import com.io7m.jlog.LogUsableType; import com.io7m.jvvfs.FilesystemError; import com.io7m.jvvfs.FilesystemType; final class ShellCommandHelpNoArguments extends ShellCommand { public ShellCommandHelpNoArguments() { } @Override void run( final LogUsableType log, final PrintStream out, final ShellConfig config, final FilesystemType fs) throws FilesystemError { out.println(ShellCommand.makeHelpText()); } }
isc
grind086/js-noise
src/utils/deserialize.js
2862
'use strict'; var modules = require('../modules'); function mkModule(obj) { if (!modules.hasOwnProperty(obj.type)) { throw new Error('Invalid module type "' + obj.type + '"'); } var mod = new (modules[obj.type])(); switch (obj.type) { // Generators case 'Constant': mod.value = obj.value; break; case 'Echo': mod.arg = obj.arg; break; case 'Simplex': mod.seed = obj.seed; break; case 'Voronoi': mod.seed = obj.seed; mod.meanPoints = obj.meanPoints; break; // Modifiers case 'Clamp': mod.min = obj.min; mod.max = obj.max; break; case 'Exponent': mod.exponent = obj.exponent; break; case 'FBM': mod.octaves = obj.octaves; mod.persistence = obj.persistence; mod.lacunarity = obj.lacunarity; break; case 'ScaleBias': mod.scale = obj.scale; mod.bias = obj.bias; break; // Selectors case 'Blend': // TODO // mod.ease = obj.ease; break; case 'Select': mod.threshold = obj.threshold; mod.edgeFalloff = obj.edgeFalloff; // TODO // mod.ease = obj.ease; break; // Transformers case 'ScalePoint': mod.scaleX = obj.scaleX; mod.scaleY = obj.scaleY; mod.scaleZ = obj.scaleZ; break; case 'TranslatePoint': mod.transX = obj.transX; mod.transY = obj.transY; mod.transZ = obj.transZ; break; } return mod; } function deserialize(json) { var obj = JSON.parse(json); if (!obj.hasOwnProperty('root')) { return mkModule(obj); } var collection = {}; // Create modules obj.collection.forEach((moduleObj) => { collection[moduleObj.uid] = mkModule(moduleObj); }); // Set sources obj.collection.forEach((moduleObj) => { if (moduleObj.children) { var children = moduleObj.children, sources = [], uid = moduleObj.uid; for (var i = 0; i < children.length; i++) { if (!collection.hasOwnProperty(children[i])) { throw new Error('Module "' + uid + '" missing child "' + children[i] + '"'); } sources[i] = collection[children[i]]; } collection[uid].setSourceModules(sources); } }); return collection[obj.root]; } module.exports = deserialize;
isc
axmatthew/react
system/src/routes/Enquiry/containers/EnquiryListViewContainer/index.js
1495
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import enquiryModule from '../../../../modules/enquiries'; import EnquiryListView from '../../components/EnquiryListView'; import { baseMapStateToProps } from '../../../../common/container-helpers'; class EnquiryListViewContainer extends Component { static propTypes = Object.assign({}, EnquiryListView.propTypes, { fetchAll: React.PropTypes.func.isRequired }); componentDidMount() { // fetchAll if no entities, and do not unlisten on unmount if (this.props.data.get('entities').size === 0) { this.props.fetchAll(); } } componentWillReceiveProps(nextProps) { // fetch data after login if (this.props.user !== nextProps.user) { if (this.props.data.get('entities').size === 0) { this.props.fetchAll(); } } } render() { return React.createElement(EnquiryListView, Object.assign({}, this.props, { fetchAll: undefined })); } } export default connect(baseMapStateToProps.bind(null, enquiryModule.entityUrl, 'listView'), { fetchAll: enquiryModule.fetchAll, // Transfer to presentation component push, listSearch: enquiryModule.listSearch, setListFilter: enquiryModule.setListFilter, setPage: enquiryModule.setPage, toggleClosedDone: enquiryModule.toggleClosedDone, showContextMenu: enquiryModule.showContextMenu, remove: enquiryModule.remove })(EnquiryListViewContainer);
isc
MirekSz/webpack-es6-ts
app/mods/mod1333.js
76
import mod1332 from './mod1332'; var value=mod1332+1; export default value;
isc
AWildridge/ProtoScape
src/org/apollo/game/model/World.java
11745
package org.apollo.game.model; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import org.apollo.Service; import org.apollo.fs.IndexedFileSystem; import org.apollo.fs.parser.ItemDefinitionParser; import org.apollo.fs.parser.NPCDefinitionParser; import org.apollo.fs.parser.StaticObjectDefinitionParser; import org.apollo.fs.parser.StaticObjectParser; import org.apollo.game.action.impl.DoorAction; import org.apollo.game.command.CommandDispatcher; import org.apollo.game.event.impl.CreateObjectEvent; import org.apollo.game.model.def.EquipmentDefinition; import org.apollo.game.model.def.ItemDefinition; import org.apollo.game.model.def.NPCDefinition; import org.apollo.game.model.def.StaticObjectDefinition; import org.apollo.game.model.obj.StaticObject; import org.apollo.game.model.region.RegionRepository; import org.apollo.game.scheduling.ScheduledTask; import org.apollo.game.scheduling.Scheduler; import org.apollo.game.scheduling.impl.ProcessPrivateChatTask; import org.apollo.game.scheduling.impl.SpawnGroundItemsTask; import org.apollo.io.EquipmentDefinitionParser; import org.apollo.net.release.r317.CreateObjectEventEncoder; import org.apollo.util.CharacterRepository; import org.apollo.util.XStreamUtil; import org.apollo.util.plugin.PluginManager; /** * The world class is a singleton which contains objects like the * {@link CharacterRepository} for players and NPCs. It should only contain * things relevant to the in-game world and not classes which deal with I/O and * such (these may be better off inside some custom {@link Service} or other * code, however, the circumstances are rare). * @author Graham */ public final class World { /** * The logger for this class. */ private static final Logger logger = Logger.getLogger(World.class.getName()); /** * The world. */ private static final World world = new World(); /** * The region repository. */ private final RegionRepository regionRepository = new RegionRepository(); /** * Represents the different status codes for registering a player. * @author Graham */ public enum RegistrationStatus { /** * Indicates the world is full. */ WORLD_FULL, /** * Indicates that the player is already online. */ ALREADY_ONLINE, /** * Indicates that the player was registered successfully. */ OK; } /** * Gets the world. * @return The world. */ public static World getWorld() { return world; } public RegionRepository getRegionRepository() { return regionRepository; } /** * The scheduler. */ // TODO: better place than here? private final Scheduler scheduler = new Scheduler(); /** * The command dispatcher. */ // TODO: better place than here? private final CommandDispatcher dispatcher = new CommandDispatcher(); // TODO: better place than here!! private PluginManager pluginManager; /** * The {@link CharacterRepository} of {@link Player}s. */ private final CharacterRepository<Player> playerRepository = new CharacterRepository<Player>(WorldConstants.MAXIMUM_PLAYERS); /** * A character repository of both. */ private final CharacterRepository<Character> characterRepository = new CharacterRepository<Character>(WorldConstants.MAXIMUM_NPCS + WorldConstants.MAXIMUM_PLAYERS); /** * The {@link CharacterRepository} of {@link NPC}s. */ private final CharacterRepository<NPC> npcRepository = new CharacterRepository<NPC>(WorldConstants.MAXIMUM_NPCS); /** * Creates the world. */ private World() { } /** * Initialises the world by loading definitions from the specified file * system. * @param release The release number. * @param fs The file system. * @param mgr The plugin manager. TODO move this. * @throws IOException if an I/O error occurs. */ public void init(int release, IndexedFileSystem fs, PluginManager mgr) throws IOException { logger.info("Loading item definitions..."); ItemDefinitionParser itemParser = new ItemDefinitionParser(fs); ItemDefinition[] itemDefs = itemParser.parse(); ItemDefinition.init(itemDefs); logger.info("Done (loaded " + itemDefs.length + " item definitions)."); int nonNull = 0; InputStream is = new BufferedInputStream(new FileInputStream("data/equipment-" + release + ".dat")); try { EquipmentDefinitionParser equipParser = new EquipmentDefinitionParser(is); EquipmentDefinition[] equipDefs = equipParser.parse(); for (EquipmentDefinition def : equipDefs) { if (def != null) { nonNull++; } } EquipmentDefinition.init(equipDefs); } finally { is.close(); } logger.info("Done (loaded " + nonNull + " equipment definitions)."); logger.info("Loading npc definitions..."); NPCDefinitionParser npcParser = new NPCDefinitionParser(fs); NPCDefinition[] npcDefs = npcParser.parse(); NPCDefinition.init(npcDefs); NPCManager.loadHP(); logger.info("Done (loaded " + npcDefs.length + " npc definitions."); logger.info("Loading object definitions..."); StaticObjectDefinitionParser objParser = new StaticObjectDefinitionParser(fs); StaticObjectDefinition[] objDefs = objParser.parse(); StaticObjectDefinition.init(objDefs); logger.info("Done (loaded " + objDefs.length + " object definitions)."); DoorAction.init(); logger.info("Parsing landscape archives..."); StaticObjectParser objectParser = new StaticObjectParser(fs); StaticObject[] staticObjects = objectParser.parse(); StaticObject.init(staticObjects); logger.info("Loaded " + staticObjects.length + " static objects!"); XStreamUtil.loadAllFiles(); logger.info("Loading npc spawns..."); NPCManager.load(); NPCDropLoader drops = new NPCDropLoader(); drops.load(); initalizeTasks(); this.pluginManager = mgr; // TODO move!! } public void initalizeTasks() { World.getWorld().schedule(new ProcessPrivateChatTask()); World.getWorld().schedule(new SpawnGroundItemsTask()); } /** * Gets the character repository. NOTE: * {@link CharacterRepository#add(Character)} and * {@link CharacterRepository#remove(Character)} should not be called * directly! These mutation methods are not guaranteed to work in future * releases! * <p> * Instead, use the {@link World#register(Player)} and * {@link World#unregister(Player)} methods which do the same thing and * will continue to work as normal in future releases. * @return The character repository. */ public CharacterRepository<Player> getPlayerRepository() { return playerRepository; } public CharacterRepository<NPC> getNPCRepository() { return npcRepository; } public CharacterRepository<Character> getCharacterRepository() { return characterRepository; } /** * Registers the specified player. * @param player The player. * @return A {@link RegistrationStatus}. */ public RegistrationStatus register(final Player player) { boolean success = playerRepository.add(player); if (success) { logger.log(Level.INFO, "Registered player: {0} [online={1}] [Ip Address={2}]", new Object[]{player, playerRepository.size(), player.getPlayerhost()}); return RegistrationStatus.OK; } else { logger.log(Level.WARNING, "Failed to register player (server full): {0} [online={1}]", new Object[]{player, playerRepository.size()}); return RegistrationStatus.WORLD_FULL; } } /** * Registers the specified player. * @param player The player. * @return A {@link RegistrationStatus}. */ public void register(final NPC npc) { boolean success = npcRepository.add(npc); if (!success) { logger.warning("Failed to register npc"); } } /** * Checks if the specified player is online. * @param name The player's name. * @return {@code true} if so, {@code false} if not. */ public boolean isPlayerOnline(String name) { // TODO: use a hash set or map in the future? for (Player player : playerRepository) { if (player.getUndefinedName().equalsIgnoreCase(name)) { return true; } } return false; } /** * Unregisters the specified player. * @param player The player. */ public void unregister(Player player) { if (playerRepository.remove(player)) { logger.info("Unregistered player: " + player + " [online=" + playerRepository.size() + "]"); } else { logger.warning("Could not find player to unregister: " + player + "!"); } } /** * Unregisters the specified npc. * @param player The npc. */ public void unregister(NPC npc) { if (npcRepository.remove(npc)) { } else { logger.warning("Could not find npc to unregister: " + npc + "!"); } } /** * Registers a new object. * @param object The object to register. */ public void register(final StaticObject object) { getRegionRepository().getRegionByPosition(object.getPosition()).addObject(object); getRegionRepository().getRegionByPosition(object.getPosition()).getTile(object.getPosition()).setStaticObject(object.getType(), object); for (Player player : getRegionRepository().getRegionByPosition(object.getPosition()).getPlayers()) { if (object.isOwnedBy(player.getUndefinedName())) { player.sendNewObject(object.getPosition(), object.getDefinition().getId(), object.getRotation(), object.getType()); } } } /** * Unregisters a new ground object. * @param object The object to unregister. */ public void unregister(StaticObject object) { getRegionRepository().getRegionByPosition(object.getPosition()).removeObject(object); getRegionRepository().getRegionByPosition(object.getPosition()).getTile(object.getPosition()).setStaticObject(object.getType(), null); for (Player player : getRegionRepository().getRegionByPosition(object.getPosition()).getPlayers()) { if (object.isOwnedBy(player.getUndefinedName())) { player.sendRemoveObject(object.getPosition(), object.getRotation(), object.getType()); } } } /** * Schedules a new task. * @param task The {@link ScheduledTask}. */ public void schedule(ScheduledTask task) { scheduler.schedule(task); } /** * Calls the {@link Scheduler#pulse()} method. */ public void pulse() { scheduler.pulse(); } /** * Gets the command dispatcher. TODO should this be here? * @return The command dispatcher. */ public CommandDispatcher getCommandDispatcher() { return dispatcher; } /** * Gets the plugin manager. TODO should this be here? * @return The plugin manager. */ public PluginManager getPluginManager() { return pluginManager; } }
isc
rolandpoulter/shipster
lib/config.js
1845
// [index.js](index.html) > lib/config.js var config, expect = require('chai').expect; var common = require('./common.js').init({}); exports.init = function (self) { 'use strict'; self.domain = common.domain_setup('lib/config', function () { try { config = require('' + 'config'); } catch (err) { config = require('../config/client.js'); } self.config = config; self.get = function (key) { if (typeof this.config.get === 'function') { return this.config.get(key); } key = key.split('.'); var val = this.config; key.some(function (k) { try { val = val[k]; } catch (err) { return true; } }); return val; }; }); self.test = function () { common.domain_setup('lib/config:test', function () { console.log('Running', this.name, 'tests...'); expect(self).to.be.an('object'); expect(self.config).to.be.an('object'); console.log('Passed', this.name, 'tests.'); }); return self; }; return self; }; if (!module.parent) { exports.init({}).test(); } // ## ISC LICENSE // Permission to use, copy, modify, and/or distribute this software for any purpose // with or without fee is hereby granted, provided that no above copyright notice // and this permission notice appear in all copies. // **THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE // OF THIS SOFTWARE.**
isc
kevinxu/xiaobudian
app/lib/mqttHelper/mqttws31.js
82199
/******************************************************************************* * Copyright (c) 2013 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Andrew Banks - initial API and implementation and initial documentation *******************************************************************************/ // Only expose a single object name in the global namespace. // Everything must go through this module. Global Paho.MQTT module // only has a single public function, client, which returns // a Paho.MQTT client object given connection details. /** * Send and receive messages using web browsers. * <p> * This programming interface lets a JavaScript client application use the MQTT V3.1 or * V3.1.1 protocol to connect to an MQTT-supporting messaging server. * * The function supported includes: * <ol> * <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number. * <li>Specifying options that relate to the communications link with the server, * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required. * <li>Subscribing to and receiving messages from MQTT Topics. * <li>Publishing messages to MQTT Topics. * </ol> * <p> * The API consists of two main objects: * <dl> * <dt><b>{@link Paho.MQTT.Client}</b></dt> * <dd>This contains methods that provide the functionality of the API, * including provision of callbacks that notify the application when a message * arrives from or is delivered to the messaging server, * or when the status of its connection to the messaging server changes.</dd> * <dt><b>{@link Paho.MQTT.Message}</b></dt> * <dd>This encapsulates the payload of the message along with various attributes * associated with its delivery, in particular the destination to which it has * been (or is about to be) sent.</dd> * </dl> * <p> * The programming interface validates parameters passed to it, and will throw * an Error containing an error message intended for developer use, if it detects * an error with any parameter. * <p> * Example: * * <code><pre> client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId"); client.onConnectionLost = onConnectionLost; client.onMessageArrived = onMessageArrived; client.connect({onSuccess:onConnect}); function onConnect() { // Once a connection has been made, make a subscription and send a message. console.log("onConnect"); client.subscribe("/World"); message = new Paho.MQTT.Message("Hello"); message.destinationName = "/World"; client.send(message); }; function onConnectionLost(responseObject) { if (responseObject.errorCode !== 0) console.log("onConnectionLost:"+responseObject.errorMessage); }; function onMessageArrived(message) { console.log("onMessageArrived:"+message.payloadString); client.disconnect(); }; * </pre></code> * @namespace Paho.MQTT */ if (typeof Paho === "undefined") { Paho = {}; } Paho.MQTT = (function (global) { // Private variables below, these are only visible inside the function closure // which is used to define the module. var version = "@VERSION@"; var buildLevel = "@BUILDLEVEL@"; /** * Unique message type identifiers, with associated * associated integer values. * @private */ var MESSAGE_TYPE = { CONNECT: 1, CONNACK: 2, PUBLISH: 3, PUBACK: 4, PUBREC: 5, PUBREL: 6, PUBCOMP: 7, SUBSCRIBE: 8, SUBACK: 9, UNSUBSCRIBE: 10, UNSUBACK: 11, PINGREQ: 12, PINGRESP: 13, DISCONNECT: 14 }; // Collection of utility methods used to simplify module code // and promote the DRY pattern. /** * Validate an object's parameter names to ensure they * match a list of expected variables name for this option * type. Used to ensure option object passed into the API don't * contain erroneous parameters. * @param {Object} obj - User options object * @param {Object} keys - valid keys and types that may exist in obj. * @throws {Error} Invalid option parameter found. * @private */ var validate = function(obj, keys) { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (keys.hasOwnProperty(key)) { if (typeof obj[key] !== keys[key]) throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key])); } else { var errorStr = "Unknown property, " + key + ". Valid properties are:"; for (var key in keys) if (keys.hasOwnProperty(key)) errorStr = errorStr+" "+key; throw new Error(errorStr); } } } }; /** * Return a new function which runs the user function bound * to a fixed scope. * @param {function} User function * @param {object} Function scope * @return {function} User function bound to another scope * @private */ var scope = function (f, scope) { return function () { return f.apply(scope, arguments); }; }; /** * Unique message type identifiers, with associated * associated integer values. * @private */ var ERROR = { OK: {code:0, text:"AMQJSC0000I OK."}, CONNECT_TIMEOUT: {code:1, text:"AMQJSC0001E Connect timed out."}, SUBSCRIBE_TIMEOUT: {code:2, text:"AMQJS0002E Subscribe timed out."}, UNSUBSCRIBE_TIMEOUT: {code:3, text:"AMQJS0003E Unsubscribe timed out."}, PING_TIMEOUT: {code:4, text:"AMQJS0004E Ping timed out."}, INTERNAL_ERROR: {code:5, text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"}, CONNACK_RETURNCODE: {code:6, text:"AMQJS0006E Bad Connack return code:{0} {1}."}, SOCKET_ERROR: {code:7, text:"AMQJS0007E Socket error:{0}."}, SOCKET_CLOSE: {code:8, text:"AMQJS0008I Socket closed."}, MALFORMED_UTF: {code:9, text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."}, UNSUPPORTED: {code:10, text:"AMQJS0010E {0} is not supported by this browser."}, INVALID_STATE: {code:11, text:"AMQJS0011E Invalid state {0}."}, INVALID_TYPE: {code:12, text:"AMQJS0012E Invalid type {0} for {1}."}, INVALID_ARGUMENT: {code:13, text:"AMQJS0013E Invalid argument {0} for {1}."}, UNSUPPORTED_OPERATION: {code:14, text:"AMQJS0014E Unsupported operation."}, INVALID_STORED_DATA: {code:15, text:"AMQJS0015E Invalid data in local storage key={0} value={1}."}, INVALID_MQTT_MESSAGE_TYPE: {code:16, text:"AMQJS0016E Invalid MQTT message type {0}."}, MALFORMED_UNICODE: {code:17, text:"AMQJS0017E Malformed Unicode string:{0} {1}."}, }; /** CONNACK RC Meaning. */ var CONNACK_RC = { 0:"Connection Accepted", 1:"Connection Refused: unacceptable protocol version", 2:"Connection Refused: identifier rejected", 3:"Connection Refused: server unavailable", 4:"Connection Refused: bad user name or password", 5:"Connection Refused: not authorized" }; /** * Format an error message text. * @private * @param {error} ERROR.KEY value above. * @param {substitutions} [array] substituted into the text. * @return the text with the substitutions made. */ var format = function(error, substitutions) { var text = error.text; if (substitutions) { var field,start; for (var i=0; i<substitutions.length; i++) { field = "{"+i+"}"; start = text.indexOf(field); if(start > 0) { var part1 = text.substring(0,start); var part2 = text.substring(start+field.length); text = part1+substitutions[i]+part2; } } } return text; }; //MQTT protocol and version 6 M Q I s d p 3 var MqttProtoIdentifierv3 = [0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03]; //MQTT proto/version for 311 4 M Q T T 4 var MqttProtoIdentifierv4 = [0x00,0x04,0x4d,0x51,0x54,0x54,0x04]; /** * Construct an MQTT wire protocol message. * @param type MQTT packet type. * @param options optional wire message attributes. * * Optional properties * * messageIdentifier: message ID in the range [0..65535] * payloadMessage: Application Message - PUBLISH only * connectStrings: array of 0 or more Strings to be put into the CONNECT payload * topics: array of strings (SUBSCRIBE, UNSUBSCRIBE) * requestQoS: array of QoS values [0..2] * * "Flag" properties * cleanSession: true if present / false if absent (CONNECT) * willMessage: true if present / false if absent (CONNECT) * isRetained: true if present / false if absent (CONNECT) * userName: true if present / false if absent (CONNECT) * password: true if present / false if absent (CONNECT) * keepAliveInterval: integer [0..65535] (CONNECT) * * @private * @ignore */ var WireMessage = function (type, options) { this.type = type; for (var name in options) { if (options.hasOwnProperty(name)) { this[name] = options[name]; } } }; WireMessage.prototype.encode = function() { // Compute the first byte of the fixed header var first = ((this.type & 0x0f) << 4); /* * Now calculate the length of the variable header + payload by adding up the lengths * of all the component parts */ var remLength = 0; var topicStrLength = new Array(); var destinationNameLength = 0; // if the message contains a messageIdentifier then we need two bytes for that if (this.messageIdentifier != undefined) remLength += 2; switch(this.type) { // If this a Connect then we need to include 12 bytes for its header case MESSAGE_TYPE.CONNECT: switch(this.mqttVersion) { case 3: remLength += MqttProtoIdentifierv3.length + 3; break; case 4: remLength += MqttProtoIdentifierv4.length + 3; break; } remLength += UTF8Length(this.clientId) + 2; if (this.willMessage != undefined) { remLength += UTF8Length(this.willMessage.destinationName) + 2; // Will message is always a string, sent as UTF-8 characters with a preceding length. var willMessagePayloadBytes = this.willMessage.payloadBytes; if (!(willMessagePayloadBytes instanceof Uint8Array)) willMessagePayloadBytes = new Uint8Array(payloadBytes); remLength += willMessagePayloadBytes.byteLength +2; } if (this.userName != undefined) remLength += UTF8Length(this.userName) + 2; if (this.password != undefined) remLength += UTF8Length(this.password) + 2; break; // Subscribe, Unsubscribe can both contain topic strings case MESSAGE_TYPE.SUBSCRIBE: first |= 0x02; // Qos = 1; for ( var i = 0; i < this.topics.length; i++) { topicStrLength[i] = UTF8Length(this.topics[i]); remLength += topicStrLength[i] + 2; } remLength += this.requestedQos.length; // 1 byte for each topic's Qos // QoS on Subscribe only break; case MESSAGE_TYPE.UNSUBSCRIBE: first |= 0x02; // Qos = 1; for ( var i = 0; i < this.topics.length; i++) { topicStrLength[i] = UTF8Length(this.topics[i]); remLength += topicStrLength[i] + 2; } break; case MESSAGE_TYPE.PUBREL: first |= 0x02; // Qos = 1; break; case MESSAGE_TYPE.PUBLISH: if (this.payloadMessage.duplicate) first |= 0x08; first = first |= (this.payloadMessage.qos << 1); if (this.payloadMessage.retained) first |= 0x01; destinationNameLength = UTF8Length(this.payloadMessage.destinationName); remLength += destinationNameLength + 2; var payloadBytes = this.payloadMessage.payloadBytes; remLength += payloadBytes.byteLength; if (payloadBytes instanceof ArrayBuffer) payloadBytes = new Uint8Array(payloadBytes); else if (!(payloadBytes instanceof Uint8Array)) payloadBytes = new Uint8Array(payloadBytes.buffer); break; case MESSAGE_TYPE.DISCONNECT: break; default: ; } // Now we can allocate a buffer for the message var mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format var pos = mbi.length + 1; // Offset of start of variable header var buffer = new ArrayBuffer(remLength + pos); var byteStream = new Uint8Array(buffer); // view it as a sequence of bytes //Write the fixed header into the buffer byteStream[0] = first; byteStream.set(mbi,1); // If this is a PUBLISH then the variable header starts with a topic if (this.type == MESSAGE_TYPE.PUBLISH) pos = writeString(this.payloadMessage.destinationName, destinationNameLength, byteStream, pos); // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time else if (this.type == MESSAGE_TYPE.CONNECT) { switch (this.mqttVersion) { case 3: byteStream.set(MqttProtoIdentifierv3, pos); pos += MqttProtoIdentifierv3.length; break; case 4: byteStream.set(MqttProtoIdentifierv4, pos); pos += MqttProtoIdentifierv4.length; break; } var connectFlags = 0; if (this.cleanSession) connectFlags = 0x02; if (this.willMessage != undefined ) { connectFlags |= 0x04; connectFlags |= (this.willMessage.qos<<3); if (this.willMessage.retained) { connectFlags |= 0x20; } } if (this.userName != undefined) connectFlags |= 0x80; if (this.password != undefined) connectFlags |= 0x40; byteStream[pos++] = connectFlags; pos = writeUint16 (this.keepAliveInterval, byteStream, pos); } // Output the messageIdentifier - if there is one if (this.messageIdentifier != undefined) pos = writeUint16 (this.messageIdentifier, byteStream, pos); switch(this.type) { case MESSAGE_TYPE.CONNECT: pos = writeString(this.clientId, UTF8Length(this.clientId), byteStream, pos); if (this.willMessage != undefined) { pos = writeString(this.willMessage.destinationName, UTF8Length(this.willMessage.destinationName), byteStream, pos); pos = writeUint16(willMessagePayloadBytes.byteLength, byteStream, pos); byteStream.set(willMessagePayloadBytes, pos); pos += willMessagePayloadBytes.byteLength; } if (this.userName != undefined) pos = writeString(this.userName, UTF8Length(this.userName), byteStream, pos); if (this.password != undefined) pos = writeString(this.password, UTF8Length(this.password), byteStream, pos); break; case MESSAGE_TYPE.PUBLISH: // PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters. byteStream.set(payloadBytes, pos); break; // case MESSAGE_TYPE.PUBREC: // case MESSAGE_TYPE.PUBREL: // case MESSAGE_TYPE.PUBCOMP: // break; case MESSAGE_TYPE.SUBSCRIBE: // SUBSCRIBE has a list of topic strings and request QoS for (var i=0; i<this.topics.length; i++) { pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); byteStream[pos++] = this.requestedQos[i]; } break; case MESSAGE_TYPE.UNSUBSCRIBE: // UNSUBSCRIBE has a list of topic strings for (var i=0; i<this.topics.length; i++) pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); break; default: // Do nothing. } return buffer; } function decodeMessage(input,pos) { var startingPos = pos; var first = input[pos]; var type = first >> 4; var messageInfo = first &= 0x0f; pos += 1; // Decode the remaining length (MBI format) var digit; var remLength = 0; var multiplier = 1; do { if (pos == input.length) { return [null,startingPos]; } digit = input[pos++]; remLength += ((digit & 0x7F) * multiplier); multiplier *= 128; } while ((digit & 0x80) != 0); var endPos = pos+remLength; if (endPos > input.length) { return [null,startingPos]; } var wireMessage = new WireMessage(type); switch(type) { case MESSAGE_TYPE.CONNACK: var connectAcknowledgeFlags = input[pos++]; if (connectAcknowledgeFlags & 0x01) wireMessage.sessionPresent = true; wireMessage.returnCode = input[pos++]; break; case MESSAGE_TYPE.PUBLISH: var qos = (messageInfo >> 1) & 0x03; var len = readUint16(input, pos); pos += 2; var topicName = parseUTF8(input, pos, len); pos += len; // If QoS 1 or 2 there will be a messageIdentifier if (qos > 0) { wireMessage.messageIdentifier = readUint16(input, pos); pos += 2; } var message = new Paho.MQTT.Message(input.subarray(pos, endPos)); if ((messageInfo & 0x01) == 0x01) message.retained = true; if ((messageInfo & 0x08) == 0x08) message.duplicate = true; message.qos = qos; message.destinationName = topicName; wireMessage.payloadMessage = message; break; case MESSAGE_TYPE.PUBACK: case MESSAGE_TYPE.PUBREC: case MESSAGE_TYPE.PUBREL: case MESSAGE_TYPE.PUBCOMP: case MESSAGE_TYPE.UNSUBACK: wireMessage.messageIdentifier = readUint16(input, pos); break; case MESSAGE_TYPE.SUBACK: wireMessage.messageIdentifier = readUint16(input, pos); pos += 2; wireMessage.returnCode = input.subarray(pos, endPos); break; default: ; } return [wireMessage,endPos]; } function writeUint16(input, buffer, offset) { buffer[offset++] = input >> 8; //MSB buffer[offset++] = input % 256; //LSB return offset; } function writeString(input, utf8Length, buffer, offset) { offset = writeUint16(utf8Length, buffer, offset); stringToUTF8(input, buffer, offset); return offset + utf8Length; } function readUint16(buffer, offset) { return 256*buffer[offset] + buffer[offset+1]; } /** * Encodes an MQTT Multi-Byte Integer * @private */ function encodeMBI(number) { var output = new Array(1); var numBytes = 0; do { var digit = number % 128; number = number >> 7; if (number > 0) { digit |= 0x80; } output[numBytes++] = digit; } while ( (number > 0) && (numBytes<4) ); return output; } /** * Takes a String and calculates its length in bytes when encoded in UTF8. * @private */ function UTF8Length(input) { var output = 0; for (var i = 0; i<input.length; i++) { var charCode = input.charCodeAt(i); if (charCode > 0x7FF) { // Surrogate pair means its a 4 byte character if (0xD800 <= charCode && charCode <= 0xDBFF) { i++; output++; } output +=3; } else if (charCode > 0x7F) output +=2; else output++; } return output; } /** * Takes a String and writes it into an array as UTF8 encoded bytes. * @private */ function stringToUTF8(input, output, start) { var pos = start; for (var i = 0; i<input.length; i++) { var charCode = input.charCodeAt(i); // Check for a surrogate pair. if (0xD800 <= charCode && charCode <= 0xDBFF) { var lowCharCode = input.charCodeAt(++i); if (isNaN(lowCharCode)) { throw new Error(format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode])); } charCode = ((charCode - 0xD800)<<10) + (lowCharCode - 0xDC00) + 0x10000; } if (charCode <= 0x7F) { output[pos++] = charCode; } else if (charCode <= 0x7FF) { output[pos++] = charCode>>6 & 0x1F | 0xC0; output[pos++] = charCode & 0x3F | 0x80; } else if (charCode <= 0xFFFF) { output[pos++] = charCode>>12 & 0x0F | 0xE0; output[pos++] = charCode>>6 & 0x3F | 0x80; output[pos++] = charCode & 0x3F | 0x80; } else { output[pos++] = charCode>>18 & 0x07 | 0xF0; output[pos++] = charCode>>12 & 0x3F | 0x80; output[pos++] = charCode>>6 & 0x3F | 0x80; output[pos++] = charCode & 0x3F | 0x80; }; } return output; } function parseUTF8(input, offset, length) { var output = ""; var utf16; var pos = offset; while (pos < offset+length) { var byte1 = input[pos++]; if (byte1 < 128) utf16 = byte1; else { var byte2 = input[pos++]-128; if (byte2 < 0) throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16),""])); if (byte1 < 0xE0) // 2 byte character utf16 = 64*(byte1-0xC0) + byte2; else { var byte3 = input[pos++]-128; if (byte3 < 0) throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16)])); if (byte1 < 0xF0) // 3 byte character utf16 = 4096*(byte1-0xE0) + 64*byte2 + byte3; else { var byte4 = input[pos++]-128; if (byte4 < 0) throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); if (byte1 < 0xF8) // 4 byte character utf16 = 262144*(byte1-0xF0) + 4096*byte2 + 64*byte3 + byte4; else // longer encodings are not supported throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); } } } if (utf16 > 0xFFFF) // 4 byte character - express as a surrogate pair { utf16 -= 0x10000; output += String.fromCharCode(0xD800 + (utf16 >> 10)); // lead character utf16 = 0xDC00 + (utf16 & 0x3FF); // trail character } output += String.fromCharCode(utf16); } return output; } /** * Repeat keepalive requests, monitor responses. * @ignore */ var Pinger = function(client, window, keepAliveInterval) { this._client = client; this._window = window; this._keepAliveInterval = keepAliveInterval*1000; this.isReset = false; var pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode(); var doTimeout = function (pinger) { return function () { return doPing.apply(pinger); }; }; /** @ignore */ var doPing = function() { if (!this.isReset) { this._client._trace("Pinger.doPing", "Timed out"); this._client._disconnected( ERROR.PING_TIMEOUT.code , format(ERROR.PING_TIMEOUT)); } else { this.isReset = false; this._client._trace("Pinger.doPing", "send PINGREQ"); this._client.socket.send(pingReq); this.timeout = this._window.setTimeout(doTimeout(this), this._keepAliveInterval); } } this.reset = function() { this.isReset = true; this._window.clearTimeout(this.timeout); if (this._keepAliveInterval > 0) this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval); } this.cancel = function() { this._window.clearTimeout(this.timeout); } }; /** * Monitor request completion. * @ignore */ var Timeout = function(client, window, timeoutSeconds, action, args) { this._window = window; if (!timeoutSeconds) timeoutSeconds = 30; var doTimeout = function (action, client, args) { return function () { return action.apply(client, args); }; }; this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000); this.cancel = function() { this._window.clearTimeout(this.timeout); } }; /* * Internal implementation of the Websockets MQTT V3.1 client. * * @name Paho.MQTT.ClientImpl @constructor * @param {String} host the DNS nameof the webSocket host. * @param {Number} port the port number for that host. * @param {String} clientId the MQ client identifier. */ var ClientImpl = function (uri, host, port, path, clientId) { // Check dependencies are satisfied in this browser. if (!("WebSocket" in global && global["WebSocket"] !== null)) { throw new Error(format(ERROR.UNSUPPORTED, ["WebSocket"])); } if (!("localStorage" in global && global["localStorage"] !== null)) { throw new Error(format(ERROR.UNSUPPORTED, ["localStorage"])); } if (!("ArrayBuffer" in global && global["ArrayBuffer"] !== null)) { throw new Error(format(ERROR.UNSUPPORTED, ["ArrayBuffer"])); } this._trace("Paho.MQTT.Client", uri, host, port, path, clientId); this.host = host; this.port = port; this.path = path; this.uri = uri; this.clientId = clientId; // Local storagekeys are qualified with the following string. // The conditional inclusion of path in the key is for backward // compatibility to when the path was not configurable and assumed to // be /mqtt this._localKey=host+":"+port+(path!="/mqtt"?":"+path:"")+":"+clientId+":"; // Create private instance-only message queue // Internal queue of messages to be sent, in sending order. this._msg_queue = []; // Messages we have sent and are expecting a response for, indexed by their respective message ids. this._sentMessages = {}; // Messages we have received and acknowleged and are expecting a confirm message for // indexed by their respective message ids. this._receivedMessages = {}; // Internal list of callbacks to be executed when messages // have been successfully sent over web socket, e.g. disconnect // when it doesn't have to wait for ACK, just message is dispatched. this._notify_msg_sent = {}; // Unique identifier for SEND messages, incrementing // counter as messages are sent. this._message_identifier = 1; // Used to determine the transmission sequence of stored sent messages. this._sequence = 0; // Load the local state, if any, from the saved version, only restore state relevant to this client. for (var key in localStorage) if ( key.indexOf("Sent:"+this._localKey) == 0 || key.indexOf("Received:"+this._localKey) == 0) this.restore(key); }; // Messaging Client public instance members. ClientImpl.prototype.host; ClientImpl.prototype.port; ClientImpl.prototype.path; ClientImpl.prototype.uri; ClientImpl.prototype.clientId; // Messaging Client private instance members. ClientImpl.prototype.socket; /* true once we have received an acknowledgement to a CONNECT packet. */ ClientImpl.prototype.connected = false; /* The largest message identifier allowed, may not be larger than 2**16 but * if set smaller reduces the maximum number of outbound messages allowed. */ ClientImpl.prototype.maxMessageIdentifier = 65536; ClientImpl.prototype.connectOptions; ClientImpl.prototype.hostIndex; ClientImpl.prototype.onConnectionLost; ClientImpl.prototype.onMessageDelivered; ClientImpl.prototype.onMessageArrived; ClientImpl.prototype.traceFunction; ClientImpl.prototype._msg_queue = null; ClientImpl.prototype._connectTimeout; /* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */ ClientImpl.prototype.sendPinger = null; /* The receivePinger monitors how long we allow before we require evidence that the server is alive. */ ClientImpl.prototype.receivePinger = null; ClientImpl.prototype.receiveBuffer = null; ClientImpl.prototype._traceBuffer = null; ClientImpl.prototype._MAX_TRACE_ENTRIES = 100; ClientImpl.prototype.connect = function (connectOptions) { var connectOptionsMasked = this._traceMask(connectOptions, "password"); this._trace("Client.connect", connectOptionsMasked, this.socket, this.connected); if (this.connected) throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); if (this.socket) throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); this.connectOptions = connectOptions; if (connectOptions.uris) { this.hostIndex = 0; this._doConnect(connectOptions.uris[0]); } else { this._doConnect(this.uri); } }; ClientImpl.prototype.subscribe = function (filter, subscribeOptions) { this._trace("Client.subscribe", filter, subscribeOptions); if (!this.connected) throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); var wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE); wireMessage.topics=[filter]; if (subscribeOptions.qos != undefined) wireMessage.requestedQos = [subscribeOptions.qos]; else wireMessage.requestedQos = [0]; if (subscribeOptions.onSuccess) { wireMessage.onSuccess = function(grantedQos) {subscribeOptions.onSuccess({invocationContext:subscribeOptions.invocationContext,grantedQos:grantedQos});}; } if (subscribeOptions.onFailure) { wireMessage.onFailure = function(errorCode) {subscribeOptions.onFailure({invocationContext:subscribeOptions.invocationContext,errorCode:errorCode});}; } if (subscribeOptions.timeout) { wireMessage.timeOut = new Timeout(this, window, subscribeOptions.timeout, subscribeOptions.onFailure , [{invocationContext:subscribeOptions.invocationContext, errorCode:ERROR.SUBSCRIBE_TIMEOUT.code, errorMessage:format(ERROR.SUBSCRIBE_TIMEOUT)}]); } // All subscriptions return a SUBACK. this._requires_ack(wireMessage); this._schedule_message(wireMessage); }; /** @ignore */ ClientImpl.prototype.unsubscribe = function(filter, unsubscribeOptions) { this._trace("Client.unsubscribe", filter, unsubscribeOptions); if (!this.connected) throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); var wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE); wireMessage.topics = [filter]; if (unsubscribeOptions.onSuccess) { wireMessage.callback = function() {unsubscribeOptions.onSuccess({invocationContext:unsubscribeOptions.invocationContext});}; } if (unsubscribeOptions.timeout) { wireMessage.timeOut = new Timeout(this, window, unsubscribeOptions.timeout, unsubscribeOptions.onFailure , [{invocationContext:unsubscribeOptions.invocationContext, errorCode:ERROR.UNSUBSCRIBE_TIMEOUT.code, errorMessage:format(ERROR.UNSUBSCRIBE_TIMEOUT)}]); } // All unsubscribes return a SUBACK. this._requires_ack(wireMessage); this._schedule_message(wireMessage); }; ClientImpl.prototype.send = function (message) { this._trace("Client.send", message); if (!this.connected) throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH); wireMessage.payloadMessage = message; if (message.qos > 0) this._requires_ack(wireMessage); else if (this.onMessageDelivered) this._notify_msg_sent[wireMessage] = this.onMessageDelivered(wireMessage.payloadMessage); this._schedule_message(wireMessage); }; ClientImpl.prototype.disconnect = function () { this._trace("Client.disconnect"); if (!this.socket) throw new Error(format(ERROR.INVALID_STATE, ["not connecting or connected"])); wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT); // Run the disconnected call back as soon as the message has been sent, // in case of a failure later on in the disconnect processing. // as a consequence, the _disconected call back may be run several times. this._notify_msg_sent[wireMessage] = scope(this._disconnected, this); this._schedule_message(wireMessage); }; ClientImpl.prototype.getTraceLog = function () { if ( this._traceBuffer !== null ) { this._trace("Client.getTraceLog", new Date()); this._trace("Client.getTraceLog in flight messages", this._sentMessages.length); for (var key in this._sentMessages) this._trace("_sentMessages ",key, this._sentMessages[key]); for (var key in this._receivedMessages) this._trace("_receivedMessages ",key, this._receivedMessages[key]); return this._traceBuffer; } }; ClientImpl.prototype.startTrace = function () { if ( this._traceBuffer === null ) { this._traceBuffer = []; } this._trace("Client.startTrace", new Date(), version); }; ClientImpl.prototype.stopTrace = function () { delete this._traceBuffer; }; ClientImpl.prototype._doConnect = function (wsurl) { // When the socket is open, this client will send the CONNECT WireMessage using the saved parameters. if (this.connectOptions.useSSL) { var uriParts = wsurl.split(":"); uriParts[0] = "wss"; wsurl = uriParts.join(":"); } this.connected = false; if (this.connectOptions.mqttVersion < 4) { this.socket = new WebSocket(wsurl, ["mqttv3.1"]); } else { this.socket = new WebSocket(wsurl, ["mqtt"]); } this.socket.binaryType = 'arraybuffer'; this.socket.onopen = scope(this._on_socket_open, this); this.socket.onmessage = scope(this._on_socket_message, this); this.socket.onerror = scope(this._on_socket_error, this); this.socket.onclose = scope(this._on_socket_close, this); this.sendPinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); this.receivePinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); this._connectTimeout = new Timeout(this, window, this.connectOptions.timeout, this._disconnected, [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)]); }; // Schedule a new message to be sent over the WebSockets // connection. CONNECT messages cause WebSocket connection // to be started. All other messages are queued internally // until this has happened. When WS connection starts, process // all outstanding messages. ClientImpl.prototype._schedule_message = function (message) { this._msg_queue.push(message); // Process outstanding messages in the queue if we have an open socket, and have received CONNACK. if (this.connected) { this._process_queue(); } }; ClientImpl.prototype.store = function(prefix, wireMessage) { var storedMessage = {type:wireMessage.type, messageIdentifier:wireMessage.messageIdentifier, version:1}; switch(wireMessage.type) { case MESSAGE_TYPE.PUBLISH: if(wireMessage.pubRecReceived) storedMessage.pubRecReceived = true; // Convert the payload to a hex string. storedMessage.payloadMessage = {}; var hex = ""; var messageBytes = wireMessage.payloadMessage.payloadBytes; for (var i=0; i<messageBytes.length; i++) { if (messageBytes[i] <= 0xF) hex = hex+"0"+messageBytes[i].toString(16); else hex = hex+messageBytes[i].toString(16); } storedMessage.payloadMessage.payloadHex = hex; storedMessage.payloadMessage.qos = wireMessage.payloadMessage.qos; storedMessage.payloadMessage.destinationName = wireMessage.payloadMessage.destinationName; if (wireMessage.payloadMessage.duplicate) storedMessage.payloadMessage.duplicate = true; if (wireMessage.payloadMessage.retained) storedMessage.payloadMessage.retained = true; // Add a sequence number to sent messages. if ( prefix.indexOf("Sent:") == 0 ) { if ( wireMessage.sequence === undefined ) wireMessage.sequence = ++this._sequence; storedMessage.sequence = wireMessage.sequence; } break; default: throw Error(format(ERROR.INVALID_STORED_DATA, [key, storedMessage])); } localStorage.setItem(prefix+this._localKey+wireMessage.messageIdentifier, JSON.stringify(storedMessage)); }; ClientImpl.prototype.restore = function(key) { var value = localStorage.getItem(key); var storedMessage = JSON.parse(value); var wireMessage = new WireMessage(storedMessage.type, storedMessage); switch(storedMessage.type) { case MESSAGE_TYPE.PUBLISH: // Replace the payload message with a Message object. var hex = storedMessage.payloadMessage.payloadHex; var buffer = new ArrayBuffer((hex.length)/2); var byteStream = new Uint8Array(buffer); var i = 0; while (hex.length >= 2) { var x = parseInt(hex.substring(0, 2), 16); hex = hex.substring(2, hex.length); byteStream[i++] = x; } var payloadMessage = new Paho.MQTT.Message(byteStream); payloadMessage.qos = storedMessage.payloadMessage.qos; payloadMessage.destinationName = storedMessage.payloadMessage.destinationName; if (storedMessage.payloadMessage.duplicate) payloadMessage.duplicate = true; if (storedMessage.payloadMessage.retained) payloadMessage.retained = true; wireMessage.payloadMessage = payloadMessage; break; default: throw Error(format(ERROR.INVALID_STORED_DATA, [key, value])); } if (key.indexOf("Sent:"+this._localKey) == 0) { wireMessage.payloadMessage.duplicate = true; this._sentMessages[wireMessage.messageIdentifier] = wireMessage; } else if (key.indexOf("Received:"+this._localKey) == 0) { this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; } }; ClientImpl.prototype._process_queue = function () { var message = null; // Process messages in order they were added var fifo = this._msg_queue.reverse(); // Send all queued messages down socket connection while ((message = fifo.pop())) { this._socket_send(message); // Notify listeners that message was successfully sent if (this._notify_msg_sent[message]) { this._notify_msg_sent[message](); delete this._notify_msg_sent[message]; } } }; /** * Expect an ACK response for this message. Add message to the set of in progress * messages and set an unused identifier in this message. * @ignore */ ClientImpl.prototype._requires_ack = function (wireMessage) { var messageCount = Object.keys(this._sentMessages).length; if (messageCount > this.maxMessageIdentifier) throw Error ("Too many messages:"+messageCount); while(this._sentMessages[this._message_identifier] !== undefined) { this._message_identifier++; } wireMessage.messageIdentifier = this._message_identifier; this._sentMessages[wireMessage.messageIdentifier] = wireMessage; if (wireMessage.type === MESSAGE_TYPE.PUBLISH) { this.store("Sent:", wireMessage); } if (this._message_identifier === this.maxMessageIdentifier) { this._message_identifier = 1; } }; /** * Called when the underlying websocket has been opened. * @ignore */ ClientImpl.prototype._on_socket_open = function () { // Create the CONNECT message object. var wireMessage = new WireMessage(MESSAGE_TYPE.CONNECT, this.connectOptions); wireMessage.clientId = this.clientId; this._socket_send(wireMessage); }; /** * Called when the underlying websocket has received a complete packet. * @ignore */ ClientImpl.prototype._on_socket_message = function (event) { this._trace("Client._on_socket_message", event.data); // Reset the receive ping timer, we now have evidence the server is alive. this.receivePinger.reset(); var messages = this._deframeMessages(event.data); for (var i = 0; i < messages.length; i+=1) { this._handleMessage(messages[i]); } } ClientImpl.prototype._deframeMessages = function(data) { var byteArray = new Uint8Array(data); if (this.receiveBuffer) { var newData = new Uint8Array(this.receiveBuffer.length+byteArray.length); newData.set(this.receiveBuffer); newData.set(byteArray,this.receiveBuffer.length); byteArray = newData; delete this.receiveBuffer; } try { var offset = 0; var messages = []; while(offset < byteArray.length) { var result = decodeMessage(byteArray,offset); var wireMessage = result[0]; offset = result[1]; if (wireMessage !== null) { messages.push(wireMessage); } else { break; } } if (offset < byteArray.length) { this.receiveBuffer = byteArray.subarray(offset); } } catch (error) { this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,error.stack.toString()])); return; } return messages; } ClientImpl.prototype._handleMessage = function(wireMessage) { this._trace("Client._handleMessage", wireMessage); try { switch(wireMessage.type) { case MESSAGE_TYPE.CONNACK: this._connectTimeout.cancel(); // If we have started using clean session then clear up the local state. if (this.connectOptions.cleanSession) { for (var key in this._sentMessages) { var sentMessage = this._sentMessages[key]; localStorage.removeItem("Sent:"+this._localKey+sentMessage.messageIdentifier); } this._sentMessages = {}; for (var key in this._receivedMessages) { var receivedMessage = this._receivedMessages[key]; localStorage.removeItem("Received:"+this._localKey+receivedMessage.messageIdentifier); } this._receivedMessages = {}; } // Client connected and ready for business. if (wireMessage.returnCode === 0) { this.connected = true; // Jump to the end of the list of uris and stop looking for a good host. if (this.connectOptions.uris) this.hostIndex = this.connectOptions.uris.length; } else { this._disconnected(ERROR.CONNACK_RETURNCODE.code , format(ERROR.CONNACK_RETURNCODE, [wireMessage.returnCode, CONNACK_RC[wireMessage.returnCode]])); break; } // Resend messages. var sequencedMessages = new Array(); for (var msgId in this._sentMessages) { if (this._sentMessages.hasOwnProperty(msgId)) sequencedMessages.push(this._sentMessages[msgId]); } // Sort sentMessages into the original sent order. var sequencedMessages = sequencedMessages.sort(function(a,b) {return a.sequence - b.sequence;} ); for (var i=0, len=sequencedMessages.length; i<len; i++) { var sentMessage = sequencedMessages[i]; if (sentMessage.type == MESSAGE_TYPE.PUBLISH && sentMessage.pubRecReceived) { var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:sentMessage.messageIdentifier}); this._schedule_message(pubRelMessage); } else { this._schedule_message(sentMessage); }; } // Execute the connectOptions.onSuccess callback if there is one. if (this.connectOptions.onSuccess) { this.connectOptions.onSuccess({invocationContext:this.connectOptions.invocationContext}); } // Process all queued messages now that the connection is established. this._process_queue(); break; case MESSAGE_TYPE.PUBLISH: this._receivePublish(wireMessage); break; case MESSAGE_TYPE.PUBACK: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; // If this is a re flow of a PUBACK after we have restarted receivedMessage will not exist. if (sentMessage) { delete this._sentMessages[wireMessage.messageIdentifier]; localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier); if (this.onMessageDelivered) this.onMessageDelivered(sentMessage.payloadMessage); } break; case MESSAGE_TYPE.PUBREC: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; // If this is a re flow of a PUBREC after we have restarted receivedMessage will not exist. if (sentMessage) { sentMessage.pubRecReceived = true; var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:wireMessage.messageIdentifier}); this.store("Sent:", sentMessage); this._schedule_message(pubRelMessage); } break; case MESSAGE_TYPE.PUBREL: var receivedMessage = this._receivedMessages[wireMessage.messageIdentifier]; localStorage.removeItem("Received:"+this._localKey+wireMessage.messageIdentifier); // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist. if (receivedMessage) { this._receiveMessage(receivedMessage); delete this._receivedMessages[wireMessage.messageIdentifier]; } // Always flow PubComp, we may have previously flowed PubComp but the server lost it and restarted. var pubCompMessage = new WireMessage(MESSAGE_TYPE.PUBCOMP, {messageIdentifier:wireMessage.messageIdentifier}); this._schedule_message(pubCompMessage); break; case MESSAGE_TYPE.PUBCOMP: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; delete this._sentMessages[wireMessage.messageIdentifier]; localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier); if (this.onMessageDelivered) this.onMessageDelivered(sentMessage.payloadMessage); break; case MESSAGE_TYPE.SUBACK: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; if (sentMessage) { if(sentMessage.timeOut) sentMessage.timeOut.cancel(); wireMessage.returnCode.indexOf = Array.prototype.indexOf; if (wireMessage.returnCode.indexOf(0x80) !== -1) { if (sentMessage.onFailure) { sentMessage.onFailure(wireMessage.returnCode); } } else if (sentMessage.onSuccess) { sentMessage.onSuccess(wireMessage.returnCode); } delete this._sentMessages[wireMessage.messageIdentifier]; } break; case MESSAGE_TYPE.UNSUBACK: var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; if (sentMessage) { if (sentMessage.timeOut) sentMessage.timeOut.cancel(); if (sentMessage.callback) { sentMessage.callback(); } delete this._sentMessages[wireMessage.messageIdentifier]; } break; case MESSAGE_TYPE.PINGRESP: /* The sendPinger or receivePinger may have sent a ping, the receivePinger has already been reset. */ this.sendPinger.reset(); break; case MESSAGE_TYPE.DISCONNECT: // Clients do not expect to receive disconnect packets. this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); break; default: this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); }; } catch (error) { this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,error.stack.toString()])); return; } }; /** @ignore */ ClientImpl.prototype._on_socket_error = function (error) { this._disconnected(ERROR.SOCKET_ERROR.code , format(ERROR.SOCKET_ERROR, [error.data])); }; /** @ignore */ ClientImpl.prototype._on_socket_close = function () { this._disconnected(ERROR.SOCKET_CLOSE.code , format(ERROR.SOCKET_CLOSE)); }; /** @ignore */ ClientImpl.prototype._socket_send = function (wireMessage) { if (wireMessage.type == 1) { var wireMessageMasked = this._traceMask(wireMessage, "password"); this._trace("Client._socket_send", wireMessageMasked); } else this._trace("Client._socket_send", wireMessage); this.socket.send(wireMessage.encode()); /* We have proved to the server we are alive. */ this.sendPinger.reset(); }; /** @ignore */ ClientImpl.prototype._receivePublish = function (wireMessage) { switch(wireMessage.payloadMessage.qos) { case "undefined": case 0: this._receiveMessage(wireMessage); break; case 1: var pubAckMessage = new WireMessage(MESSAGE_TYPE.PUBACK, {messageIdentifier:wireMessage.messageIdentifier}); this._schedule_message(pubAckMessage); this._receiveMessage(wireMessage); break; case 2: this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; this.store("Received:", wireMessage); var pubRecMessage = new WireMessage(MESSAGE_TYPE.PUBREC, {messageIdentifier:wireMessage.messageIdentifier}); this._schedule_message(pubRecMessage); break; default: throw Error("Invaild qos="+wireMmessage.payloadMessage.qos); }; }; /** @ignore */ ClientImpl.prototype._receiveMessage = function (wireMessage) { if (this.onMessageArrived) { this.onMessageArrived(wireMessage.payloadMessage); } }; /** * Client has disconnected either at its own request or because the server * or network disconnected it. Remove all non-durable state. * @param {errorCode} [number] the error number. * @param {errorText} [string] the error text. * @ignore */ ClientImpl.prototype._disconnected = function (errorCode, errorText) { this._trace("Client._disconnected", errorCode, errorText); this.sendPinger.cancel(); this.receivePinger.cancel(); if (this._connectTimeout) this._connectTimeout.cancel(); // Clear message buffers. this._msg_queue = []; this._notify_msg_sent = {}; if (this.socket) { // Cancel all socket callbacks so that they cannot be driven again by this socket. this.socket.onopen = null; this.socket.onmessage = null; this.socket.onerror = null; this.socket.onclose = null; if (this.socket.readyState === 1) this.socket.close(); delete this.socket; } if (this.connectOptions.uris && this.hostIndex < this.connectOptions.uris.length-1) { // Try the next host. this.hostIndex++; this._doConnect(this.connectOptions.uris[this.hostIndex]); } else { if (errorCode === undefined) { errorCode = ERROR.OK.code; errorText = format(ERROR.OK); } // Run any application callbacks last as they may attempt to reconnect and hence create a new socket. if (this.connected) { this.connected = false; // Execute the connectionLostCallback if there is one, and we were connected. if (this.onConnectionLost) this.onConnectionLost({errorCode:errorCode, errorMessage:errorText}); } else { // Otherwise we never had a connection, so indicate that the connect has failed. if (this.connectOptions.mqttVersion === 4 && this.connectOptions.mqttVersionExplicit === false) { //×¢ÊÍ by syz 2016.10.11 ²»ÐèÒª»ØÍË°æ±¾ÖØÁ¬ //this._trace("Failed to connect V4, dropping back to V3") //this.connectOptions.mqttVersion = 3; //if (this.connectOptions.uris) { // this.hostIndex = 0; // this._doConnect(this.connectOptions.uris[0]); //} else { // this._doConnect(this.uri); //} this.connectOptions.onFailure({ invocationContext: this.connectOptions.invocationContext, errorCode: errorCode, errorMessage: errorText }); } else if(this.connectOptions.onFailure) { this.connectOptions.onFailure({invocationContext:this.connectOptions.invocationContext, errorCode:errorCode, errorMessage:errorText}); } } } }; /** @ignore */ ClientImpl.prototype._trace = function () { // Pass trace message back to client's callback function if (this.traceFunction) { for (var i in arguments) { if (typeof arguments[i] !== "undefined") arguments[i] = JSON.stringify(arguments[i]); } var record = Array.prototype.slice.call(arguments).join(""); this.traceFunction ({severity: "Debug", message: record }); } //buffer style trace if ( this._traceBuffer !== null ) { for (var i = 0, max = arguments.length; i < max; i++) { if ( this._traceBuffer.length == this._MAX_TRACE_ENTRIES ) { this._traceBuffer.shift(); } if (i === 0) this._traceBuffer.push(arguments[i]); else if (typeof arguments[i] === "undefined" ) this._traceBuffer.push(arguments[i]); else this._traceBuffer.push(" "+JSON.stringify(arguments[i])); }; }; }; /** @ignore */ ClientImpl.prototype._traceMask = function (traceObject, masked) { var traceObjectMasked = {}; for (var attr in traceObject) { if (traceObject.hasOwnProperty(attr)) { if (attr == masked) traceObjectMasked[attr] = "******"; else traceObjectMasked[attr] = traceObject[attr]; } } return traceObjectMasked; }; // ------------------------------------------------------------------------ // Public Programming interface. // ------------------------------------------------------------------------ /** * The JavaScript application communicates to the server using a {@link Paho.MQTT.Client} object. * <p> * Most applications will create just one Client object and then call its connect() method, * however applications can create more than one Client object if they wish. * In this case the combination of host, port and clientId attributes must be different for each Client object. * <p> * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods * (even though the underlying protocol exchange might be synchronous in nature). * This means they signal their completion by calling back to the application, * via Success or Failure callback functions provided by the application on the method in question. * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime * of the script that made the invocation. * <p> * In contrast there are some callback functions, most notably <i>onMessageArrived</i>, * that are defined on the {@link Paho.MQTT.Client} object. * These may get called multiple times, and aren't directly related to specific method invocations made by the client. * * @name Paho.MQTT.Client * * @constructor * * @param {string} host - the address of the messaging server, as a fully qualified WebSocket URI, as a DNS name or dotted decimal IP address. * @param {number} port - the port number to connect to - only required if host is not a URI * @param {string} path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'. * @param {string} clientId - the Messaging client identifier, between 1 and 23 characters in length. * * @property {string} host - <i>read only</i> the server's DNS hostname or dotted decimal IP address. * @property {number} port - <i>read only</i> the server's port. * @property {string} path - <i>read only</i> the server's path. * @property {string} clientId - <i>read only</i> used when connecting to the server. * @property {function} onConnectionLost - called when a connection has been lost. * after a connect() method has succeeded. * Establish the call back used when a connection has been lost. The connection may be * lost because the client initiates a disconnect or because the server or network * cause the client to be disconnected. The disconnect call back may be called without * the connectionComplete call back being invoked if, for example the client fails to * connect. * A single response object parameter is passed to the onConnectionLost callback containing the following fields: * <ol> * <li>errorCode * <li>errorMessage * </ol> * @property {function} onMessageDelivered called when a message has been delivered. * All processing that this Client will ever do has been completed. So, for example, * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server * and the message has been removed from persistent storage before this callback is invoked. * Parameters passed to the onMessageDelivered callback are: * <ol> * <li>{@link Paho.MQTT.Message} that was delivered. * </ol> * @property {function} onMessageArrived called when a message has arrived in this Paho.MQTT.client. * Parameters passed to the onMessageArrived callback are: * <ol> * <li>{@link Paho.MQTT.Message} that has arrived. * </ol> */ var Client = function (host, port, path, clientId) { var uri; if (typeof host !== "string") throw new Error(format(ERROR.INVALID_TYPE, [typeof host, "host"])); if (arguments.length == 2) { // host: must be full ws:// uri // port: clientId clientId = port; uri = host; var match = uri.match(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/); if (match) { host = match[4]||match[2]; port = parseInt(match[7]); path = match[8]; } else { throw new Error(format(ERROR.INVALID_ARGUMENT,[host,"host"])); } } else { if (arguments.length == 3) { clientId = path; path = "/mqtt"; } if (typeof port !== "number" || port < 0) throw new Error(format(ERROR.INVALID_TYPE, [typeof port, "port"])); if (typeof path !== "string") throw new Error(format(ERROR.INVALID_TYPE, [typeof path, "path"])); var ipv6AddSBracket = (host.indexOf(":") != -1 && host.slice(0,1) != "[" && host.slice(-1) != "]"); uri = "ws://"+(ipv6AddSBracket?"["+host+"]":host)+":"+port+path; } var clientIdLength = 0; for (var i = 0; i<clientId.length; i++) { var charCode = clientId.charCodeAt(i); if (0xD800 <= charCode && charCode <= 0xDBFF) { i++; // Surrogate pair. } clientIdLength++; } if (typeof clientId !== "string" || clientIdLength > 65535) throw new Error(format(ERROR.INVALID_ARGUMENT, [clientId, "clientId"])); var client = new ClientImpl(uri, host, port, path, clientId); this._getHost = function() { return host; }; this._setHost = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getPort = function() { return port; }; this._setPort = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getPath = function() { return path; }; this._setPath = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getURI = function() { return uri; }; this._setURI = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getClientId = function() { return client.clientId; }; this._setClientId = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; this._getOnConnectionLost = function() { return client.onConnectionLost; }; this._setOnConnectionLost = function(newOnConnectionLost) { if (typeof newOnConnectionLost === "function") client.onConnectionLost = newOnConnectionLost; else throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnectionLost, "onConnectionLost"])); }; this._getOnMessageDelivered = function() { return client.onMessageDelivered; }; this._setOnMessageDelivered = function(newOnMessageDelivered) { if (typeof newOnMessageDelivered === "function") client.onMessageDelivered = newOnMessageDelivered; else throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageDelivered, "onMessageDelivered"])); }; this._getOnMessageArrived = function() { return client.onMessageArrived; }; this._setOnMessageArrived = function(newOnMessageArrived) { if (typeof newOnMessageArrived === "function") client.onMessageArrived = newOnMessageArrived; else throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageArrived, "onMessageArrived"])); }; this._getTrace = function() { return client.traceFunction; }; this._setTrace = function(trace) { if(typeof trace === "function"){ client.traceFunction = trace; }else{ throw new Error(format(ERROR.INVALID_TYPE, [typeof trace, "onTrace"])); } }; /** * Connect this Messaging client to its server. * * @name Paho.MQTT.Client#connect * @function * @param {Object} connectOptions - attributes used with the connection. * @param {number} connectOptions.timeout - If the connect has not succeeded within this * number of seconds, it is deemed to have failed. * The default is 30 seconds. * @param {string} connectOptions.userName - Authentication username for this connection. * @param {string} connectOptions.password - Authentication password for this connection. * @param {Paho.MQTT.Message} connectOptions.willMessage - sent by the server when the client * disconnects abnormally. * @param {Number} connectOptions.keepAliveInterval - the server disconnects this client if * there is no activity for this number of seconds. * The default value of 60 seconds is assumed if not set. * @param {boolean} connectOptions.cleanSession - if true(default) the client and server * persistent state is deleted on successful connect. * @param {boolean} connectOptions.useSSL - if present and true, use an SSL Websocket connection. * @param {object} connectOptions.invocationContext - passed to the onSuccess callback or onFailure callback. * @param {function} connectOptions.onSuccess - called when the connect acknowledgement * has been received from the server. * A single response object parameter is passed to the onSuccess callback containing the following fields: * <ol> * <li>invocationContext as passed in to the onSuccess method in the connectOptions. * </ol> * @config {function} [onFailure] called when the connect request has failed or timed out. * A single response object parameter is passed to the onFailure callback containing the following fields: * <ol> * <li>invocationContext as passed in to the onFailure method in the connectOptions. * <li>errorCode a number indicating the nature of the error. * <li>errorMessage text describing the error. * </ol> * @config {Array} [hosts] If present this contains either a set of hostnames or fully qualified * WebSocket URIs (ws://example.com:1883/mqtt), that are tried in order in place * of the host and port paramater on the construtor. The hosts are tried one at at time in order until * one of then succeeds. * @config {Array} [ports] If present the set of ports matching the hosts. If hosts contains URIs, this property * is not used. * @throws {InvalidState} if the client is not in disconnected state. The client must have received connectionLost * or disconnected before calling connect for a second or subsequent time. */ this.connect = function (connectOptions) { connectOptions = connectOptions || {} ; validate(connectOptions, {timeout:"number", userName:"string", password:"string", willMessage:"object", keepAliveInterval:"number", cleanSession:"boolean", useSSL:"boolean", invocationContext:"object", onSuccess:"function", onFailure:"function", hosts:"object", ports:"object", mqttVersion: "number", mqttVersionExplicit: "boolean" }); // If no keep alive interval is set, assume 60 seconds. if (connectOptions.keepAliveInterval === undefined) connectOptions.keepAliveInterval = 60; if (connectOptions.mqttVersion > 4 || connectOptions.mqttVersion < 3) { throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.mqttVersion, "connectOptions.mqttVersion"])); } if (connectOptions.mqttVersion === undefined) { connectOptions.mqttVersionExplicit = false; connectOptions.mqttVersion = 4; } else { connectOptions.mqttVersionExplicit = true; } //Check that if password is set, so is username if (connectOptions.password === undefined && connectOptions.userName !== undefined) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.password, "connectOptions.password"])) if (connectOptions.willMessage) { if (!(connectOptions.willMessage instanceof Message)) throw new Error(format(ERROR.INVALID_TYPE, [connectOptions.willMessage, "connectOptions.willMessage"])); // The will message must have a payload that can be represented as a string. // Cause the willMessage to throw an exception if this is not the case. connectOptions.willMessage.stringPayload; if (typeof connectOptions.willMessage.destinationName === "undefined") throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.willMessage.destinationName, "connectOptions.willMessage.destinationName"])); } if (typeof connectOptions.cleanSession === "undefined") connectOptions.cleanSession = true; if (connectOptions.hosts) { if (!(connectOptions.hosts instanceof Array) ) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); if (connectOptions.hosts.length <1 ) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); var usingURIs = false; for (var i = 0; i<connectOptions.hosts.length; i++) { if (typeof connectOptions.hosts[i] !== "string") throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); if (/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(connectOptions.hosts[i])) { if (i == 0) { usingURIs = true; } else if (!usingURIs) { throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); } } else if (usingURIs) { throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); } } if (!usingURIs) { if (!connectOptions.ports) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); if (!(connectOptions.ports instanceof Array) ) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); if (connectOptions.hosts.length != connectOptions.ports.length) throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); connectOptions.uris = []; for (var i = 0; i<connectOptions.hosts.length; i++) { if (typeof connectOptions.ports[i] !== "number" || connectOptions.ports[i] < 0) throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.ports[i], "connectOptions.ports["+i+"]"])); var host = connectOptions.hosts[i]; var port = connectOptions.ports[i]; var ipv6 = (host.indexOf(":") != -1); uri = "ws://"+(ipv6?"["+host+"]":host)+":"+port+path; connectOptions.uris.push(uri); } } else { connectOptions.uris = connectOptions.hosts; } } client.connect(connectOptions); }; /** * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the filter. * * @name Paho.MQTT.Client#subscribe * @function * @param {string} filter describing the destinations to receive messages from. * <br> * @param {object} subscribeOptions - used to control the subscription * * @param {number} subscribeOptions.qos - the maiximum qos of any publications sent * as a result of making this subscription. * @param {object} subscribeOptions.invocationContext - passed to the onSuccess callback * or onFailure callback. * @param {function} subscribeOptions.onSuccess - called when the subscribe acknowledgement * has been received from the server. * A single response object parameter is passed to the onSuccess callback containing the following fields: * <ol> * <li>invocationContext if set in the subscribeOptions. * </ol> * @param {function} subscribeOptions.onFailure - called when the subscribe request has failed or timed out. * A single response object parameter is passed to the onFailure callback containing the following fields: * <ol> * <li>invocationContext - if set in the subscribeOptions. * <li>errorCode - a number indicating the nature of the error. * <li>errorMessage - text describing the error. * </ol> * @param {number} subscribeOptions.timeout - which, if present, determines the number of * seconds after which the onFailure calback is called. * The presence of a timeout does not prevent the onSuccess * callback from being called when the subscribe completes. * @throws {InvalidState} if the client is not in connected state. */ this.subscribe = function (filter, subscribeOptions) { if (typeof filter !== "string") throw new Error("Invalid argument:"+filter); subscribeOptions = subscribeOptions || {} ; validate(subscribeOptions, {qos:"number", invocationContext:"object", onSuccess:"function", onFailure:"function", timeout:"number" }); if (subscribeOptions.timeout && !subscribeOptions.onFailure) throw new Error("subscribeOptions.timeout specified with no onFailure callback."); if (typeof subscribeOptions.qos !== "undefined" && !(subscribeOptions.qos === 0 || subscribeOptions.qos === 1 || subscribeOptions.qos === 2 )) throw new Error(format(ERROR.INVALID_ARGUMENT, [subscribeOptions.qos, "subscribeOptions.qos"])); client.subscribe(filter, subscribeOptions); }; /** * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter. * * @name Paho.MQTT.Client#unsubscribe * @function * @param {string} filter - describing the destinations to receive messages from. * @param {object} unsubscribeOptions - used to control the subscription * @param {object} unsubscribeOptions.invocationContext - passed to the onSuccess callback or onFailure callback. * @param {function} unsubscribeOptions.onSuccess - called when the unsubscribe acknowledgement has been received from the server. * A single response object parameter is passed to the * onSuccess callback containing the following fields: * <ol> * <li>invocationContext - if set in the unsubscribeOptions. * </ol> * @param {function} unsubscribeOptions.onFailure called when the unsubscribe request has failed or timed out. * A single response object parameter is passed to the onFailure callback containing the following fields: * <ol> * <li>invocationContext - if set in the unsubscribeOptions. * <li>errorCode - a number indicating the nature of the error. * <li>errorMessage - text describing the error. * </ol> * @param {number} unsubscribeOptions.timeout - which, if present, determines the number of seconds * after which the onFailure callback is called. The presence of * a timeout does not prevent the onSuccess callback from being * called when the unsubscribe completes * @throws {InvalidState} if the client is not in connected state. */ this.unsubscribe = function (filter, unsubscribeOptions) { if (typeof filter !== "string") throw new Error("Invalid argument:"+filter); unsubscribeOptions = unsubscribeOptions || {} ; validate(unsubscribeOptions, {invocationContext:"object", onSuccess:"function", onFailure:"function", timeout:"number" }); if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure) throw new Error("unsubscribeOptions.timeout specified with no onFailure callback."); client.unsubscribe(filter, unsubscribeOptions); }; /** * Send a message to the consumers of the destination in the Message. * * @name Paho.MQTT.Client#send * @function * @param {string|Paho.MQTT.Message} topic - <b>mandatory</b> The name of the destination to which the message is to be sent. * - If it is the only parameter, used as Paho.MQTT.Message object. * @param {String|ArrayBuffer} payload - The message data to be sent. * @param {number} qos The Quality of Service used to deliver the message. * <dl> * <dt>0 Best effort (default). * <dt>1 At least once. * <dt>2 Exactly once. * </dl> * @param {Boolean} retained If true, the message is to be retained by the server and delivered * to both current and future subscriptions. * If false the server only delivers the message to current subscribers, this is the default for new Messages. * A received message has the retained boolean set to true if the message was published * with the retained boolean set to true * and the subscrption was made after the message has been published. * @throws {InvalidState} if the client is not connected. */ this.send = function (topic,payload,qos,retained) { var message ; if(arguments.length == 0){ throw new Error("Invalid argument."+"length"); }else if(arguments.length == 1) { if (!(topic instanceof Message) && (typeof topic !== "string")) throw new Error("Invalid argument:"+ typeof topic); message = topic; if (typeof message.destinationName === "undefined") throw new Error(format(ERROR.INVALID_ARGUMENT,[message.destinationName,"Message.destinationName"])); client.send(message); }else { //parameter checking in Message object message = new Message(payload); message.destinationName = topic; if(arguments.length >= 3) message.qos = qos; if(arguments.length >= 4) message.retained = retained; client.send(message); } }; /** * Normal disconnect of this Messaging client from its server. * * @name Paho.MQTT.Client#disconnect * @function * @throws {InvalidState} if the client is already disconnected. */ this.disconnect = function () { client.disconnect(); }; /** * Get the contents of the trace log. * * @name Paho.MQTT.Client#getTraceLog * @function * @return {Object[]} tracebuffer containing the time ordered trace records. */ this.getTraceLog = function () { return client.getTraceLog(); } /** * Start tracing. * * @name Paho.MQTT.Client#startTrace * @function */ this.startTrace = function () { client.startTrace(); }; /** * Stop tracing. * * @name Paho.MQTT.Client#stopTrace * @function */ this.stopTrace = function () { client.stopTrace(); }; this.isConnected = function() { return client.connected; }; }; Client.prototype = { get host() { return this._getHost(); }, set host(newHost) { this._setHost(newHost); }, get port() { return this._getPort(); }, set port(newPort) { this._setPort(newPort); }, get path() { return this._getPath(); }, set path(newPath) { this._setPath(newPath); }, get clientId() { return this._getClientId(); }, set clientId(newClientId) { this._setClientId(newClientId); }, get onConnectionLost() { return this._getOnConnectionLost(); }, set onConnectionLost(newOnConnectionLost) { this._setOnConnectionLost(newOnConnectionLost); }, get onMessageDelivered() { return this._getOnMessageDelivered(); }, set onMessageDelivered(newOnMessageDelivered) { this._setOnMessageDelivered(newOnMessageDelivered); }, get onMessageArrived() { return this._getOnMessageArrived(); }, set onMessageArrived(newOnMessageArrived) { this._setOnMessageArrived(newOnMessageArrived); }, get trace() { return this._getTrace(); }, set trace(newTraceFunction) { this._setTrace(newTraceFunction); } }; /** * An application message, sent or received. * <p> * All attributes may be null, which implies the default values. * * @name Paho.MQTT.Message * @constructor * @param {String|ArrayBuffer} payload The message data to be sent. * <p> * @property {string} payloadString <i>read only</i> The payload as a string if the payload consists of valid UTF-8 characters. * @property {ArrayBuffer} payloadBytes <i>read only</i> The payload as an ArrayBuffer. * <p> * @property {string} destinationName <b>mandatory</b> The name of the destination to which the message is to be sent * (for messages about to be sent) or the name of the destination from which the message has been received. * (for messages received by the onMessage function). * <p> * @property {number} qos The Quality of Service used to deliver the message. * <dl> * <dt>0 Best effort (default). * <dt>1 At least once. * <dt>2 Exactly once. * </dl> * <p> * @property {Boolean} retained If true, the message is to be retained by the server and delivered * to both current and future subscriptions. * If false the server only delivers the message to current subscribers, this is the default for new Messages. * A received message has the retained boolean set to true if the message was published * with the retained boolean set to true * and the subscrption was made after the message has been published. * <p> * @property {Boolean} duplicate <i>read only</i> If true, this message might be a duplicate of one which has already been received. * This is only set on messages received from the server. * */ var Message = function (newPayload) { var payload; if ( typeof newPayload === "string" || newPayload instanceof ArrayBuffer || newPayload instanceof Int8Array || newPayload instanceof Uint8Array || newPayload instanceof Int16Array || newPayload instanceof Uint16Array || newPayload instanceof Int32Array || newPayload instanceof Uint32Array || newPayload instanceof Float32Array || newPayload instanceof Float64Array ) { payload = newPayload; } else { throw (format(ERROR.INVALID_ARGUMENT, [newPayload, "newPayload"])); } this._getPayloadString = function () { if (typeof payload === "string") return payload; else return parseUTF8(payload, 0, payload.length); }; this._getPayloadBytes = function() { if (typeof payload === "string") { var buffer = new ArrayBuffer(UTF8Length(payload)); var byteStream = new Uint8Array(buffer); stringToUTF8(payload, byteStream, 0); return byteStream; } else { return payload; }; }; var destinationName = undefined; this._getDestinationName = function() { return destinationName; }; this._setDestinationName = function(newDestinationName) { if (typeof newDestinationName === "string") destinationName = newDestinationName; else throw new Error(format(ERROR.INVALID_ARGUMENT, [newDestinationName, "newDestinationName"])); }; var qos = 0; this._getQos = function() { return qos; }; this._setQos = function(newQos) { if (newQos === 0 || newQos === 1 || newQos === 2 ) qos = newQos; else throw new Error("Invalid argument:"+newQos); }; var retained = false; this._getRetained = function() { return retained; }; this._setRetained = function(newRetained) { if (typeof newRetained === "boolean") retained = newRetained; else throw new Error(format(ERROR.INVALID_ARGUMENT, [newRetained, "newRetained"])); }; var duplicate = false; this._getDuplicate = function() { return duplicate; }; this._setDuplicate = function(newDuplicate) { duplicate = newDuplicate; }; }; Message.prototype = { get payloadString() { return this._getPayloadString(); }, get payloadBytes() { return this._getPayloadBytes(); }, get destinationName() { return this._getDestinationName(); }, set destinationName(newDestinationName) { this._setDestinationName(newDestinationName); }, get qos() { return this._getQos(); }, set qos(newQos) { this._setQos(newQos); }, get retained() { return this._getRetained(); }, set retained(newRetained) { this._setRetained(newRetained); }, get duplicate() { return this._getDuplicate(); }, set duplicate(newDuplicate) { this._setDuplicate(newDuplicate); } }; // Module contents. return { Client: Client, Message: Message }; })(window);
isc
jlmadurga/listenclosely-telegram
setup.py
1535
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'twx.botapi==2.0.1', 'listenclosely==0.1.0' ] test_requirements = [ 'mock==1.3.0', 'factory-boy==2.6.0' ] setup( name='listenclosely-telegram', version='0.1.0', description="ListenClosely service backenTelegram", long_description=readme + '\n\n' + history, author="Juan Madurga", author_email='jlmadurga@gmail.com', url='https://github.com/jlmadurga/listenclosely-telegram', packages=[ 'listenclosely_telegram', ], package_dir={'listenclosely_telegram': 'listenclosely_telegram'}, include_package_data=True, install_requires=requirements, license="ISCL", zip_safe=False, keywords='listenclosely-telegram', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements )
isc
QualiSystems/AWS-Shell
package/tests/test_domain_services/test_vpc.py
15466
from unittest import TestCase from mock import Mock, call from cloudshell.cp.aws.domain.services.ec2.vpc import VPCService from cloudshell.cp.aws.domain.services.waiters.vpc_peering import VpcPeeringConnectionWaiter class TestVPCService(TestCase): def setUp(self): self.tag_service = Mock() self.tags = Mock() self.tag_service.get_default_tags = Mock(return_value=self.tags) self.subnet_service = Mock() self.logger = Mock() self.aws_ec2_datamodel = Mock() self.ec2_client= Mock() self.ec2_session = Mock() self.vpc = Mock() self.vpc_id = Mock() self.ec2_session.create_vpc = Mock(return_value=self.vpc) self.ec2_session.Vpc = Mock(return_value=self.vpc) self.s3_session = Mock() self.reservation = Mock() self.cidr = Mock() self.vpc_waiter = Mock() self.vpc_peering_waiter = Mock() self.instance_service = Mock() self.sg_service = Mock() self.route_table_service = Mock() self.traffic_mirror_service = Mock() self.vpc_service = VPCService(tag_service=self.tag_service, subnet_service=self.subnet_service, instance_service=self.instance_service, vpc_waiter=self.vpc_waiter, vpc_peering_waiter=self.vpc_peering_waiter, sg_service=self.sg_service, route_table_service=self.route_table_service, traffic_mirror_service=self.traffic_mirror_service) def test_get_all_internet_gateways(self): internet_gate = Mock() self.vpc.internet_gateways = Mock() self.vpc.internet_gateways.all = Mock(return_value=[internet_gate]) res = self.vpc_service.get_all_internet_gateways(self.vpc) self.assertEquals(res, [internet_gate]) def test_remove_all_internet_gateways(self): internet_gate = Mock() self.vpc.internet_gateways = Mock() self.vpc.internet_gateways.all = Mock(return_value=[internet_gate]) self.vpc_service.remove_all_internet_gateways(self.vpc) internet_gate.detach_from_vpc.assert_called_with(VpcId=self.vpc.id) self.assertTrue(internet_gate.delete.called) def test_create_and_attach_internet_gateway(self): internet_gate = Mock() internet_gate.id = 'super_id' self.ec2_session.create_internet_gateway = Mock(return_value=internet_gate) internet_gateway_id = self.vpc_service.create_and_attach_internet_gateway(self.ec2_session, self.vpc, self.reservation) self.assertTrue(self.ec2_session.create_internet_gateway.called) self.tag_service.get_default_tags.assert_called_once_with("IGW {0}".format(self.reservation.reservation_id),self.reservation) self.tag_service.set_ec2_resource_tags.assert_called_once_with(resource=internet_gate, tags=self.tag_service.get_default_tags()) self.assertEqual(internet_gateway_id, internet_gate.id) def test_create_vpc_for_reservation(self): vpc = self.vpc_service.create_vpc_for_reservation(self.ec2_session, self.reservation, self.cidr) vpc_name = self.vpc_service.VPC_RESERVATION.format(self.reservation.reservation_id) self.vpc_waiter.wait.assert_called_once_with(vpc=vpc, state=self.vpc_waiter.AVAILABLE) self.assertEqual(self.vpc, vpc) self.ec2_session.create_vpc.assert_called_once_with(CidrBlock=self.cidr) self.tag_service.get_default_tags.assert_called_once_with(vpc_name, self.reservation) self.tag_service.set_ec2_resource_tags.assert_called_once_with(self.vpc, self.tags) def test_find_vpc_for_reservation(self): self.ec2_session.vpcs = Mock() self.ec2_session.vpcs.filter = Mock(return_value=[self.vpc]) vpc = self.vpc_service.find_vpc_for_reservation(self.ec2_session, self.reservation) self.assertEqual(vpc, self.vpc) def test_find_vpc_for_reservation_no_vpc(self): self.ec2_session.vpcs = Mock() self.ec2_session.vpcs.filter = Mock(return_value=[]) vpc = self.vpc_service.find_vpc_for_reservation(self.ec2_session, self.reservation) self.assertIsNone(vpc) def test_find_vpc_for_reservation_too_many(self): self.ec2_session.vpcs = Mock() self.ec2_session.vpcs.filter = Mock(return_value=[1, 2]) self.assertRaises(ValueError, self.vpc_service.find_vpc_for_reservation, self.ec2_session, self.reservation) def test_peer_vpc(self): def change_to_active(vpc_peering_connection): vpc_peering_connection.status['Code'] = VpcPeeringConnectionWaiter.ACTIVE vpc1 = Mock() vpc2 = Mock() peered = Mock() peered.status = {'Code': VpcPeeringConnectionWaiter.PENDING_ACCEPTANCE} peered.accept = Mock(side_effect=change_to_active(peered)) self.ec2_session.create_vpc_peering_connection = Mock(return_value=peered) reservation_model = Mock() res = self.vpc_service.peer_vpcs(self.ec2_session, vpc1, vpc2, reservation_model,Mock()) self.ec2_session.create_vpc_peering_connection.assert_called_once_with(VpcId=vpc1, PeerVpcId=vpc2) self.assertEqual(peered.status['Code'], VpcPeeringConnectionWaiter.ACTIVE) self.assertEqual(res, peered.id) def test_remove_all_peering(self): peering = Mock() peering.status = {'Code': 'ok'} peering1 = Mock() peering1.status = {'Code': 'failed'} peering2 = Mock() peering2.status = {'Code': 'aa'} self.vpc.accepted_vpc_peering_connections = Mock() self.vpc.accepted_vpc_peering_connections.all = Mock(return_value=[peering, peering1, peering2]) res = self.vpc_service.remove_all_peering(self.vpc) self.assertIsNotNone(res) self.assertTrue(peering.delete.called) self.assertFalse(peering1.delete.called) self.assertTrue(peering2.delete.called) def test_remove_all_sgs(self): sg = Mock() self.vpc.security_groups = Mock() self.vpc.security_groups.all = Mock(return_value=[sg]) res = self.vpc_service.remove_all_security_groups(self.vpc, self.reservation.reservation_id ) self.assertIsNotNone(res) self.sg_service.delete_security_group.assert_called_once_with(sg) # When a trying to delete security group(isolated) and it is referenced in another's group rule. # we get resource sg-XXXXXX has a dependent object, so to fix that , isolated group shall be deleted last. def test_remove_all_sgs_isolated_group_removed_last(self): sg = Mock() sg.group_name = 'dummy' isolated_sg = Mock() isolated_sg.group_name = self.sg_service.sandbox_isolated_sg_name(self.reservation.reservation_id) isolated_at_start_sgs = [isolated_sg, sg] isolated_at_end_sgs_calls = [call(sg), call(isolated_sg)] self.vpc.security_groups = Mock() self.vpc.security_groups.all = Mock(return_value=isolated_at_start_sgs) res = self.vpc_service.remove_all_security_groups(self.vpc, self.reservation.reservation_id ) self.assertIsNotNone(res) self.sg_service.delete_security_group.assert_has_calls(isolated_at_end_sgs_calls, any_order=False) def test_remove_subnets(self): subnet = Mock() self.vpc.subnets = Mock() self.vpc.subnets.all = Mock(return_value=[subnet]) res = self.vpc_service.remove_all_subnets(self.vpc) self.assertIsNotNone(res) self.subnet_service.delete_subnet.assert_called_once_with(subnet) def test_delete_all_instances(self): instance = Mock() self.vpc.instances = Mock() self.vpc.instances.all = Mock(return_value=[instance]) res = self.vpc_service.delete_all_instances(self.vpc) self.assertIsNotNone(res) self.instance_service.terminate_instances.assert_called_once_with([instance]) def test_delete_vpc(self): res = self.vpc_service.delete_vpc(self.vpc) self.assertTrue(self.vpc.delete.called) self.assertIsNotNone(res) def test_get_or_create_subnet_for_vpc_1(self): # Scenario(1): Get # Arrange subnet = Mock() self.subnet_service.get_first_or_none_subnet_from_vpc = Mock(return_value=subnet) # Act result = self.vpc_service.get_or_create_subnet_for_vpc(reservation=self.reservation, cidr="1.2.3.4/24", alias="MySubnet", vpc=self.vpc, ec2_client=self.ec2_client, aws_ec2_datamodel=self.aws_ec2_datamodel, logger=self.logger) # Assert self.assertEqual(result, subnet) def test_get_or_create_subnet_for_vpc_2(self): # Scenario(2): Create # Arrange subnet = Mock() self.subnet_service.get_first_or_none_subnet_from_vpc = Mock(return_value=None) self.reservation.reservation_id = "123" self.vpc_service.get_or_pick_availability_zone = Mock(return_value="MyZone") self.subnet_service.create_subnet_for_vpc = Mock(return_value=subnet) # Act result = self.vpc_service.get_or_create_subnet_for_vpc(reservation=self.reservation, cidr="1.2.3.4/24", alias="MySubnet", vpc=self.vpc, ec2_client=self.ec2_client, aws_ec2_datamodel=self.aws_ec2_datamodel, logger=self.logger) # Assert self.assertEqual(result, subnet) self.subnet_service.create_subnet_for_vpc.assert_called_once_with( vpc=self.vpc, cidr="1.2.3.4/24", subnet_name="MySubnet Reservation: 123", availability_zone="MyZone", reservation=self.reservation) def test_get_or_create_private_route_table_1(self): # Scenario(1): Get # Arrange table = Mock() self.route_table_service.get_route_table = Mock(return_value=table) # Act result = self.vpc_service.get_or_create_private_route_table(ec2_session=self.ec2_session, reservation=self.reservation, vpc_id=self.vpc_id) # Assert self.assertEqual(result, table) def test_get_or_create_private_route_table_2(self): # Scenario(2): Create # Arrange table = Mock() self.reservation.reservation_id = "123" self.route_table_service.get_route_table = Mock(return_value=None) self.route_table_service.create_route_table = Mock(return_value=table) # Act result = self.vpc_service.get_or_create_private_route_table(ec2_session=self.ec2_session, reservation=self.reservation, vpc_id=self.vpc_id) # Assert self.assertEqual(result, table) self.route_table_service.create_route_table.assert_called_once_with( self.ec2_session, self.reservation, self.vpc_id, "Private RoutingTable Reservation: 123" ) def test_get_or_throw_private_route_table(self): # Arrange self.route_table_service.get_route_table = Mock(return_value=None) # Act with self.assertRaises(Exception) as error: self.vpc_service.get_or_throw_private_route_table(ec2_session=self.ec2_session, reservation=self.reservation, vpc_id=self.vpc_id) # Assert self.assertEqual(error.exception.message, "Routing table for non-public subnet was not found") def test_get_vpc_cidr(self): # Arrange self.vpc.cidr_block = "1.2.3.4/24" # Act result = self.vpc_service.get_vpc_cidr(ec2_session=self.ec2_session, vpc_id=self.vpc_id) # Assert self.assertEqual(result, "1.2.3.4/24") def test_get_or_pick_availability_zone_1(self): #Scenario(1): from existing subnet # Arrange subnet = Mock() subnet.availability_zone = "z" self.subnet_service.get_first_or_none_subnet_from_vpc = Mock(return_value=subnet) # Act result = self.vpc_service.get_or_pick_availability_zone(ec2_client=self.ec2_client, vpc=self.vpc, aws_ec2_datamodel=self.aws_ec2_datamodel) # Assert self.assertEqual(result, "z") def test_get_or_pick_availability_zone_2(self): # Scenario(2): from available zones list # Arrange self.subnet_service.get_first_or_none_subnet_from_vpc = Mock(return_value=None) self.ec2_client.describe_availability_zones = Mock(return_value={"AvailabilityZones":[{"ZoneName":"z"}]}) # Act result = self.vpc_service.get_or_pick_availability_zone(ec2_client=self.ec2_client, vpc=self.vpc, aws_ec2_datamodel=self.aws_ec2_datamodel) # Assert self.assertEqual(result, "z") def test_get_or_pick_availability_zone_3(self): # Scenario(3): no available zone # Arrange self.subnet_service.get_first_or_none_subnet_from_vpc = Mock(return_value=None) self.ec2_client.describe_availability_zones = Mock(return_value=None) # Act with self.assertRaises(Exception) as error: self.vpc_service.get_or_pick_availability_zone(ec2_client=self.ec2_client, vpc=self.vpc, aws_ec2_datamodel=self.aws_ec2_datamodel) # Assert self.assertEqual(error.exception.message, "No AvailabilityZone is available for this vpc") def test_remove_custom_route_tables(self): # Arrange tables = [Mock(), Mock()] self.vpc.id = "123" self.route_table_service.get_custom_route_tables = Mock(return_value=tables) # Act result = self.vpc_service.remove_custom_route_tables(ec2_session=self.ec2_session, vpc=self.vpc) # Assert self.assertTrue(result) self.route_table_service.delete_table.assert_any_call(tables[0]) self.route_table_service.delete_table.assert_any_call(tables[1]) def test_set_main_route_table_tags(self): # Arrange table = Mock() tags = Mock() self.reservation.reservation_id = "123" self.tag_service.get_default_tags = Mock(return_value=tags) # Act self.vpc_service.set_main_route_table_tags(main_route_table=table, reservation=self.reservation) # Assert self.tag_service.get_default_tags.assert_called_once_with("Main RoutingTable Reservation: 123", self.reservation) self.tag_service.set_ec2_resource_tags.assert_called_once_with(table, tags)
isc
felixfbecker/iterare
src/utils.test.ts
2384
import * as assert from 'assert' import { isIterable, isIterator, toIterator } from './utils' describe('utils', () => { describe('toIterator', () => { it('should return the input is already an Iterator', () => { const iterator = [1, 2, 3][Symbol.iterator]() assert.equal(toIterator(iterator), iterator) }) it('should return an iterator for an Iterable', () => { const iterable = [1, 2, 3] const iterator = toIterator(iterable) assert.equal(iterator.next().value, 1) assert.equal(iterator.next().value, 2) assert.equal(iterator.next().value, 3) assert.equal(iterator.next().done, true) }) it('should throw if the input is neither', () => { assert.throws(() => { toIterator(123 as any) }) }) }) describe('isIterator', () => { it('should return true for an Iterator', () => { const iterator = { next() { /* empty */ }, } assert.equal(isIterator(iterator), true) }) it('should return false for an Iterable', () => { const iterable = [1, 2, 3] assert.equal(isIterator(iterable), false) }) it('should return false for null', () => { assert.equal(isIterator(null), false) }) it('should return false for a scalar', () => { assert.equal(isIterator(true), false) }) it('should return false for an object with a next property', () => { assert.equal(isIterator({ next: 123 }), false) }) }) describe('isIterable', () => { it('should return true for an Iterable', () => { const iterable = [1, 2, 3] assert.equal(isIterable(iterable), true) }) it('should return false for an Iterator', () => { const iterator = { next() { /* empty */ }, } assert.equal(isIterable(iterator), false) }) it('should return false for null', () => { assert.equal(isIterable(null), false) }) it('should return false for a scalar', () => { assert.equal(isIterable(true), false) }) }) })
isc
xdv/ripple-lib-java
ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/crypto/tls/CompressionMethod.java
450
package org.ripple.bouncycastle.crypto.tls; /** * RFC 2246 6.1 */ public class CompressionMethod { public static final short _null = 0; /** * @deprecated use '_null' instead */ public static final short NULL = _null; /* * RFC 3749 2 */ public static final short DEFLATE = 1; /* * Values from 224 decimal (0xE0) through 255 decimal (0xFF) * inclusive are reserved for private use. */ }
isc
textbook/aslack
aslack/slack_bot/handler.py
1989
"""Generic message handling functionality.""" class MessageHandler: """Base class for message handlers. Arguments: *_ (:py:class:`tuple`): Arbitrary positional arguments. """ def __init__(self, *_): self.text = None self._description = None async def __aiter__(self): return self async def __anext__(self): raise StopAsyncIteration def description(self): """A user-friendly description of the handler. Returns: :py:class:`str`: The handler's description. """ if self._description is None: text = '\n'.join(self.__doc__.splitlines()[1:]).strip() lines = [] for line in map(str.strip, text.splitlines()): if line and lines: lines[-1] = ' '.join((lines[-1], line)) elif line: lines.append(line) else: lines.append('') self._description = '\n'.join(lines) return self._description def matches(self, data): """Whether the handler should handle the current message. Args: data: The data representing the current message. Returns: :py:class:`bool`: Whether it should be handled. """ self.text = data.get('text') return True class BotMessageHandler(MessageHandler): """Base class for handlers of messages about the current bot. Arguments: bot (:py:class:`~.SlackBot`): The current bot. Attributes: PHRASE (:py:class:`str`): The phrase to match. """ PHRASE = None def __init__(self, bot): super().__init__() self.bot = bot def matches(self, data): if self.bot.message_is_to_me(data): message = data['text'][len(self.bot.address_as):].strip() if message.startswith(self.PHRASE): return super().matches(data) return False
isc
abel-nieva/abel-nieva.github.io
assets/js/abelnieva.js
2665
/** * abelnieva - The source code of personal website based on Jekyll. * @version v1.0.0 * @link https://abelnieva.com * @author Abel Nieva <abel@abelnieva.com> * @license ISC */ var AN = AN || {}; AN = (function ($) { var _api, dom; _api = {}; dom = { document: $(document), html: $('html'), email: $('#js-email'), links: $('a'), gallery: $('#js-gallery'), galleryBtn: $('#js-gallery').find('li'), siteNavBtn: $('#js-site-nav-btn'), siteNavIcon: $('#js-site-nav-btn').find('.icon'), siteNavList: $('.site-nav__list') }; function init() { buildEmail(); linksWithTargetBlank(); gallery(); siteNavBtn(); } function buildEmail() { var email; email = dom.email.attr('data-email'); email = email.replace(RegExp(' dot ', 'gi'), '.'); email = email.replace(RegExp(' at ', 'gi'), '@'); dom.email.attr('href', 'mailto:' + email); } function linksWithTargetBlank() { dom.links = dom.links.toArray(); dom.links.forEach(function targetBlank(item, index) { var href = item.getAttribute('href'); if (!href.search(/http/g)) { item.setAttribute('target', '_blank'); } }); } function gallery() { dom.galleryBtn = dom.galleryBtn.toArray(); dom.galleryBtn.forEach(function galleryBtn(item, index) { var href = item.getAttribute('data-img'); $(item).click(function onClickGalleryBtn(event) { dom.html.append(getLightbox(href)); $('#js-lightbox').fadeIn('fast', function showLightboxBtn() { dom.html.css('overflow', 'hidden'); }); }); }); } function getLightbox(value) { return '<div id="js-lightbox" style="display:none;" class="lightbox"><button class="lightbox__btn" onclick="AN.onClickLightboxBtn()">' + '<span class="icon icon--cross"></span></button><div class="lightbox__item"><img src="' + value + '"/></div></div>'; } function siteNavBtn() { dom.siteNavBtn.click(function onClickSiteNavBtn(event) { dom.siteNavIcon.toggleClass('icon--cross'); dom.siteNavList.toggleClass('show'); $('html').toggleClass('overflowHidden'); }); $('html, body').on('touchmove', function(event) { if($('html').hasClass('overflowHidden')) { event.preventDefault(); } }); } _api.onClickLightboxBtn = function(value) { $('html').css('overflow', 'visible'); $('#js-lightbox').fadeOut('fast', function removeLightboxBtn() { this.remove(); }); }; init(); return _api; })(jQuery);
isc
beatrichartz/salary-stats
src/lib/index.ts
56
export * from './models'; export * from './statistics';
isc
hybridgroup/alljoyn
alljoyn/alljoyn_core/router/posix/DaemonTransport.cc
11958
/** * @file * UnixTransport is an implementation of Transport that listens * on an AF_UNIX socket. */ /****************************************************************************** * Copyright (c) 2009-2012, 2014, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <errno.h> #include <qcc/platform.h> #include <qcc/Socket.h> #include <qcc/SocketStream.h> #include <qcc/String.h> #include <qcc/StringUtil.h> #include <qcc/Util.h> #include <alljoyn/BusAttachment.h> #include "BusInternal.h" #include "ConfigDB.h" #include "RemoteEndpoint.h" #include "Router.h" #include "DaemonTransport.h" #ifdef ENABLE_POLICYDB #include "PolicyDB.h" #endif #define QCC_MODULE "ALLJOYN" using namespace std; using namespace qcc; namespace ajn { const char* DaemonTransport::TransportName = "unix"; class _DaemonEndpoint; typedef qcc::ManagedObj<_DaemonEndpoint> DaemonEndpoint; /* * An endpoint class to handle the details of authenticating a connection in * the Unix Domain Sockets way. */ class _DaemonEndpoint : public _RemoteEndpoint { public: _DaemonEndpoint(BusAttachment& bus, bool incoming, const qcc::String connectSpec, SocketFd sock) : _RemoteEndpoint(bus, incoming, connectSpec, &stream, DaemonTransport::TransportName), userId(-1), groupId(-1), processId(-1), stream(sock) { } ~_DaemonEndpoint() { } /** * Set the user id of the endpoint. * * @param userId User ID number. */ void SetUserId(uint32_t userId) { this->userId = userId; } /** * Set the group id of the endpoint. * * @param groupId Group ID number. */ void SetGroupId(uint32_t groupId) { this->groupId = groupId; } /** * Set the process id of the endpoint. * * @param processId Process ID number. */ void SetProcessId(uint32_t processId) { this->processId = processId; } /** * Return the user id of the endpoint. * * @return User ID number. */ uint32_t GetUserId() const { return userId; } /** * Return the group id of the endpoint. * * @return Group ID number. */ uint32_t GetGroupId() const { return groupId; } /** * Return the process id of the endpoint. * * @return Process ID number. */ uint32_t GetProcessId() const { return processId; } /** * Indicates if the endpoint supports reporting UNIX style user, group, and process IDs. * * @return 'true' if UNIX IDs supported, 'false' if not supported. */ bool SupportsUnixIDs() const { return true; } private: uint32_t userId; uint32_t groupId; uint32_t processId; SocketStream stream; }; static const int CRED_TIMEOUT = 5000; /**< Times out credentials exchange to avoid denial of service attack */ static QStatus GetSocketCreds(SocketFd sockFd, uid_t* uid, gid_t* gid, pid_t* pid) { QStatus status = ER_OK; #if defined(QCC_OS_DARWIN) *pid = 0; int ret = getpeereid(sockFd, uid, gid); if (ret == -1) { status = ER_OS_ERROR; qcc::Close(sockFd); } #else int enableCred = 1; int ret = setsockopt(sockFd, SOL_SOCKET, SO_PASSCRED, &enableCred, sizeof(enableCred)); if (ret == -1) { status = ER_OS_ERROR; qcc::Close(sockFd); } if (status == ER_OK) { qcc::String authName; ssize_t ret; char nulbuf = 255; struct cmsghdr* cmsg; struct iovec iov[] = { { &nulbuf, sizeof(nulbuf) } }; struct msghdr msg; char cbuf[CMSG_SPACE(sizeof(struct ucred))]; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_iov = iov; msg.msg_iovlen = ArraySize(iov); msg.msg_flags = 0; msg.msg_control = cbuf; msg.msg_controllen = CMSG_LEN(sizeof(struct ucred)); while (true) { ret = recvmsg(sockFd, &msg, 0); if (ret == -1) { if (errno == EWOULDBLOCK) { qcc::Event event(sockFd, qcc::Event::IO_READ, false); status = Event::Wait(event, CRED_TIMEOUT); if (status != ER_OK) { QCC_LogError(status, ("Credentials exhange timeout")); break; } } else { break; } } else { break; } } if ((ret != 1) && (nulbuf != 0)) { qcc::Close(sockFd); status = ER_READ_ERROR; } if (status == ER_OK) { for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if ((cmsg->cmsg_level == SOL_SOCKET) && (cmsg->cmsg_type == SCM_CREDENTIALS)) { struct ucred* cred = reinterpret_cast<struct ucred*>(CMSG_DATA(cmsg)); *uid = cred->uid; *gid = cred->gid; *pid = cred->pid; QCC_DbgHLPrintf(("Received UID: %u GID: %u PID %u", cred->uid, cred->gid, cred->pid)); } } } } #endif return status; } void* DaemonTransport::Run(void* arg) { SocketFd listenFd = (SocketFd)(ptrdiff_t)arg; QStatus status = ER_OK; Event listenEvent(listenFd, Event::IO_READ, false); while (!IsStopping()) { status = Event::Wait(listenEvent); if (status != ER_OK) { if (status != ER_STOPPING_THREAD) { QCC_LogError(status, ("Event::Wait failed")); } break; } SocketFd newSock; status = Accept(listenFd, newSock); uid_t uid = -1; // Initialize to suppress compiler warnings. gid_t gid = -1; pid_t pid = -1; if (status == ER_OK) { status = GetSocketCreds(newSock, &uid, &gid, &pid); } #ifdef ENABLE_POLICYDB PolicyDB policyDB = ConfigDB::GetConfigDB()->GetPolicyDB(); if (status == ER_OK && !policyDB->OKToConnect(uid, gid)) { Close(newSock); status = ER_BUS_POLICY_VIOLATION; } #endif if (status == ER_OK) { qcc::String authName; qcc::String redirection; static const bool truthiness = true; DaemonEndpoint conn = DaemonEndpoint(bus, truthiness, DaemonTransport::TransportName, newSock); conn->SetUserId(uid); conn->SetGroupId(gid); conn->SetProcessId(pid); /* Initialized the features for this endpoint */ conn->GetFeatures().isBusToBus = false; conn->GetFeatures().allowRemote = false; conn->GetFeatures().handlePassing = true; endpointListLock.Lock(MUTEX_CONTEXT); endpointList.push_back(RemoteEndpoint::cast(conn)); endpointListLock.Unlock(MUTEX_CONTEXT); status = conn->Establish("EXTERNAL", authName, redirection); if (status == ER_OK) { conn->SetListener(this); status = conn->Start(); } if (status != ER_OK) { QCC_LogError(status, ("Error starting RemoteEndpoint")); endpointListLock.Lock(MUTEX_CONTEXT); list<RemoteEndpoint>::iterator ei = find(endpointList.begin(), endpointList.end(), RemoteEndpoint::cast(conn)); if (ei != endpointList.end()) { endpointList.erase(ei); } endpointListLock.Unlock(MUTEX_CONTEXT); } } else if (ER_WOULDBLOCK == status || ER_READ_ERROR == status) { status = ER_OK; } if (status != ER_OK) { QCC_LogError(status, ("Error accepting new connection. Ignoring...")); } } qcc::Close(listenFd); QCC_DbgPrintf(("DaemonTransport::Run is exiting status=%s\n", QCC_StatusText(status))); return (void*) status; } QStatus DaemonTransport::NormalizeTransportSpec(const char* inSpec, qcc::String& outSpec, map<qcc::String, qcc::String>& argMap) const { QStatus status = ParseArguments(DaemonTransport::TransportName, inSpec, argMap); qcc::String path = Trim(argMap["path"]); qcc::String abstract = Trim(argMap["abstract"]); if (status == ER_OK) { outSpec = "unix:"; if (!path.empty()) { outSpec.append("path="); outSpec.append(path); argMap["_spec"] = path; } else if (!abstract.empty()) { outSpec.append("abstract="); outSpec.append(abstract); argMap["_spec"] = qcc::String("@") + abstract; } else { status = ER_BUS_BAD_TRANSPORT_ARGS; } } return status; } static QStatus ListenFd(map<qcc::String, qcc::String>& serverArgs, SocketFd& listenFd) { QStatus status = Socket(QCC_AF_UNIX, QCC_SOCK_STREAM, listenFd); if (status != ER_OK) { QCC_LogError(status, ("DaemonTransport::ListenFd(): Socket() failed")); return status; } /* Calculate bindAddr */ qcc::String bindAddr; if (status == ER_OK) { if (!serverArgs["path"].empty()) { bindAddr = serverArgs["path"]; } else if (!serverArgs["abstract"].empty()) { bindAddr = qcc::String("@") + serverArgs["abstract"]; } else { status = ER_BUS_BAD_TRANSPORT_ARGS; QCC_LogError(status, ("DaemonTransport::ListenFd(): Invalid listen spec for unix transport")); return status; } } /* * Bind the socket to the listen address and start listening for incoming * connections on it. */ status = Bind(listenFd, bindAddr.c_str()); if (status != ER_OK) { QCC_LogError(status, ("DaemonTransport::ListenFd(): Bind() failed")); } else { status = qcc::Listen(listenFd, 0); if (status == ER_OK) { QCC_DbgPrintf(("DaemonTransport::ListenFd(): Listening on %s", bindAddr.c_str())); } else { QCC_LogError(status, ("DaemonTransport::ListenFd(): Listen failed")); } } return status; } QStatus DaemonTransport::StartListen(const char* listenSpec) { if (stopping == true) { return ER_BUS_TRANSPORT_NOT_STARTED; } if (IsRunning()) { return ER_BUS_ALREADY_LISTENING; } /* Normalize the listen spec. */ QStatus status; qcc::String normSpec; map<qcc::String, qcc::String> serverArgs; status = NormalizeTransportSpec(listenSpec, normSpec, serverArgs); if (status != ER_OK) { QCC_LogError(status, ("DaemonTransport::StartListen(): Invalid Unix listen spec \"%s\"", listenSpec)); return status; } SocketFd listenFd = -1; status = ListenFd(serverArgs, listenFd); if (status == ER_OK) { status = Thread::Start((void*)(intptr_t)listenFd); } if ((listenFd != -1) && (status != ER_OK)) { qcc::Close(listenFd); } return status; } QStatus DaemonTransport::StopListen(const char* listenSpec) { return Thread::Stop(); } } // namespace ajn
isc
axmatthew/react
system/src/routes/Enquiry/containers/EditEnquiryViewContainer/index.js
958
import React, { Component } from 'react'; import { connect } from 'react-redux'; import enquiryModule from '../../../../modules/enquiries'; import EditEnquiryView from '../../components/EditEnquiryView'; import { baseMapStateToProps } from '../../../../common/container-helpers'; class EditEnquiryViewContainer extends Component { static propTypes = Object.assign({}, EditEnquiryView.propTypes, { params: React.PropTypes.object.isRequired, fetch: React.PropTypes.func.isRequired }); componentDidMount() { this.props.fetch(this.props.params._id); } render() { return React.createElement( EditEnquiryView, Object.assign({}, this.props, { params: undefined, fetch: undefined }) ); } } export default connect(baseMapStateToProps.bind(null, enquiryModule.entityUrl, 'editView'), { fetch: enquiryModule.fetch, // Transfer to presentation component update: enquiryModule.update })(EditEnquiryViewContainer);
isc
FactomProject/btcd
wire/shahash.go
3353
// Copyright (c) 2013-2015 Conformal Systems LLC. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package wire import ( "bytes" "encoding/hex" "encoding/json" "fmt" ) // Size of array used to store sha hashes. See ShaHash. const HashSize = 32 // MaxHashStringSize is the maximum length of a ShaHash hash string. const MaxHashStringSize = HashSize * 2 // ErrHashStrSize describes an error that indicates the caller specified a hash // string that has too many characters. var ErrHashStrSize = fmt.Errorf("max hash string length is %v bytes", MaxHashStringSize) // ShaHash is used in several of the bitcoin messages and common structures. It // typically represents the double sha256 of data. type ShaHash [HashSize]byte // To make it consistent with Factom Hash ------------------- func (hash ShaHash) String() string { //for i := 0; i < HashSize/2; i++ { //hash[i], hash[HashSize-1-i] = hash[HashSize-1-i], hash[i] //} return hex.EncodeToString(hash[:]) } // Bytes returns the bytes which represent the hash as a byte slice. func (hash *ShaHash) Bytes() []byte { newHash := make([]byte, HashSize) copy(newHash, hash[:]) return newHash } // SetBytes sets the bytes which represent the hash. An error is returned if // the number of bytes passed in is not HashSize. func (hash *ShaHash) SetBytes(newHash []byte) error { nhlen := len(newHash) if nhlen != HashSize { return fmt.Errorf("invalid sha length of %v, want %v", nhlen, HashSize) } copy(hash[:], newHash[0:HashSize]) return nil } // IsEqual returns true if target is the same as hash. func (hash *ShaHash) IsEqual(target *ShaHash) bool { return bytes.Equal(hash[:], target[:]) } // NewShaHash returns a new ShaHash from a byte slice. An error is returned if // the number of bytes passed in is not HashSize. func NewShaHash(newHash []byte) (*ShaHash, error) { var sh ShaHash err := sh.SetBytes(newHash) if err != nil { return nil, err } return &sh, err } // NewShaHashFromStr creates a ShaHash from a hash string. The string should be // the hexadecimal string of a byte-reversed hash, but any missing characters // result in zero padding at the end of the ShaHash. func NewShaHashFromStr(hash string) (*ShaHash, error) { // Return error if hash string is too long. if len(hash) > MaxHashStringSize { return nil, ErrHashStrSize } // Hex decoder expects the hash to be a multiple of two. if len(hash)%2 != 0 { hash = "0" + hash } // Convert string hash to bytes. buf, err := hex.DecodeString(hash) if err != nil { return nil, err } // Un-reverse the decoded bytes, copying into in leading bytes of a // ShaHash. There is no need to explicitly pad the result as any // missing (when len(buf) < HashSize) bytes from the decoded hex string // will remain zeros at the end of the ShaHash. var ret ShaHash blen := len(buf) mid := blen / 2 if blen%2 != 0 { mid++ } blen-- for i, b := range buf[:mid] { ret[i], ret[blen-i] = buf[blen-i], b } return &ret, nil } func NewShaHashFromStruct(DataStruct interface{}) (*ShaHash, error) { jsonbytes, err := json.Marshal(DataStruct) if err != nil { fmt.Printf("NewShaHash Json Marshal Error: %s\n", err) return nil, nil } fmt.Println("NewShaHashFromStruct =", jsonbytes) return NewShaHash(DoubleSha256(jsonbytes)) }
isc
Kryten0807/cacofonix
src/components/form/CheckboxGroup.js
8973
// npm dependencies // import React from 'react'; import PropTypes from 'prop-types'; import update from 'react-addons-update'; import uniqueId from 'lodash/uniqueId'; import isArray from 'lodash/isArray'; import isEqual from 'lodash/isEqual'; import classnames from 'classnames'; /** * The CheckboxGroup component */ class CheckboxGroup extends React.Component { /** * Construct the component instance * @param {Object} props The component properties */ constructor(props) { super(props); // declare a variable for the component value // let value = []; // do we have a value prop? if so, make sure it's either an array, or // convert it to an array // if (this.props.value) { value = isArray(this.props.value) ? this.props.value : [this.props.value]; } // calculate a unique ID for the component if one is not provided // this.id = this.props.id || uniqueId('form-checkboxgroup-'); // intialize the validation message for the component // this.validationMessage = this.props.validationMessage || `At least one item in ${this.props.description} must be selected`; // initialize the component state // this.state = { value, hasBeenClicked: false, }; // bind `this` to the onClick handler // this.onClick = this.onClick.bind(this); } /** * Handle the "component is mounting" event */ componentWillMount() { // determine if it's valid // const isValid = !this.props.required || this.state.value.length; // call the `onChildValidationEvent` handler once with // `hasValidated`=false, just to ensure that the parent knows about this // child // if (this.context.onChildValidationEvent) { this.context.onChildValidationEvent( this.id, false, isValid ? null : this.validationMessage ); } } /** * Handle the receipt of new properties * @param {Object} newProps The new properties for the component */ componentWillReceiveProps(newProps) { // save the initial value, so we can check for changes later // const initialValue = this.state.value; // remove any items from the value that do not appear in the new options // this.setState((state) => update(state, { value: { $set: state.value.filter((val) => newProps.options.findIndex((opt) => opt.value === `${val}`) !== -1 ) } }), () => { // then check to see if the value has changed and, if so, call the // `onChange` handler with the new values // if (!isEqual(this.state.value, initialValue) && this.props.onChange) { this.props.onChange(this.state.value); } }); } /** * Handle a click or change event for one of the input elements * @param {String} value The value for the input element that was clicked */ onClick(value) { // determine if the item clicked is currently in the list of checked // items // const idx = this.state.value.findIndex((val) => val === value); // declare a variable to hold the update details // let delta = null; // do we have this item in the list of checked items already? // if (idx === -1) { // no. add the item to the array // delta = { hasBeenClicked: { $set: true }, value: { $push: [value] } }; } else { // yes. remove the item from the array // delta = { hasBeenClicked: { $set: true }, value: { $splice: [[idx, 1]] } }; } // update the state... // this.setState((state) => update(state, delta), () => { // then call the `onChange` handler (if any) // if (this.props.onChange) { this.props.onChange(this.state.value); } // determine if the value is valid // const isValid = !this.props.required || this.state.value.length; // call the "child has validated" handler // if (this.context.onChildValidationEvent) { this.context.onChildValidationEvent( this.id, true, isValid ? null : this.validationMessage ); } }); } /** * Render the component * @return {React.Element} The React element describing the component */ render() { // build the list of classes for the outermost div // const classes = classnames('form-group', { 'has-error': this.props.required && this.state.hasBeenClicked && !this.state.value.length, }); // render a label for the component, if a label has been provided // const label = this.props.label ? ( <label className={classnames('control-label', 'pull-left', { [`col-xs-${this.context.labelColumns}`]: this.context.labelColumns, })} > {this.props.label} {this.props.required ? <sup>&nbsp;<i className="required fa fa-star" /></sup> : '' } </label> ) : null; // render the help block if the component has failed validation // const helpBlock = this.props.required && this.state.hasBeenClicked && !this.state.value.length ? <span className="help-block" style={{ clear: 'both' }}>{this.validationMessage}</span> : ''; // render the input elements for the component // const inputs = ( <div className={classnames('form-checkboxgroup-inputs', { [`col-xs-${12 - this.context.labelColumns}`]: this.context.labelColumns, })} > {this.props.options.map((opt) => <div key={uniqueId('form-checkboxgroup-option-')} className="checkbox pull-left" style={{ marginRight: '2em' }} > <label> <input type="checkbox" value={opt.value} checked={ this.state.value.findIndex((val) => val === opt.value ) !== -1 } onChange={() => this.onClick(opt.value)} /> <span>{opt.name}</span> </label> </div> )} {helpBlock} </div> ); // render the whole component and return it // return ( <div className={classes}> {label} {inputs} </div> ); } } /** * The property types for the component * @type {Object} */ CheckboxGroup.propTypes = { /** * A flag to indicated whether this component is required (ie. at least one * checkbox must be checked) */ required: PropTypes.bool, /** The ID for the component */ id: PropTypes.string, /** The label for the checkbox group */ label: PropTypes.string, /** * The description of the component for use in validation error messages * (ie., "at least one item in <description> must be checked") */ description: PropTypes.string, /** A custom validation error message for the component */ validationMessage: PropTypes.string, /** The `onChange` handler for the component */ onChange: PropTypes.func, /** The value of the component */ value: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.arrayOf(PropTypes.number), PropTypes.string, PropTypes.number, ]), /** The options for the checkbox group */ options: PropTypes.arrayOf(PropTypes.object), }; /** * The context types for the component * @type {Object} */ CheckboxGroup.contextTypes = { onChildValidationEvent: PropTypes.func, labelColumns: PropTypes.number, }; // export the component // export default CheckboxGroup;
isc
danielpinna/sgi-back
src/main/java/br/com/gestaoigrejas/sgi/dto/TaskDTO.java
1143
package br.com.gestaoigrejas.sgi.dto; import java.util.Date; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import org.dozer.DozerBeanMapper; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import br.com.gestaoigrejas.sgi.enums.Status; import br.com.gestaoigrejas.sgi.model.Task; import lombok.Getter; import lombok.Setter; @Getter @Setter @XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class TaskDTO { private Long id; private String name; private String description; private Date startDate; private String startDateSTR; private Date endDate; private String endDateSTR; private Long completionPercentage; private ProjectDTO project; private List<AttachmentDTO> attachments; private String observation; private Status status; private Date registration; private Date lastUpdate; private CollaboratorDTO responsibleChange; public static Task fromDTO(TaskDTO taskDTO){ return new DozerBeanMapper().map(taskDTO, Task.class); } public static TaskDTO toDTO(Task task){ return new DozerBeanMapper().map(task, TaskDTO.class); } }
isc
ariddell/httpstan
httpstan/lib/stan/lib/stan_math/test/unit/math/prim/scal/err/check_2F1_converges_test.cpp
2247
#include <stan/math/prim/scal.hpp> #include <gtest/gtest.h> using stan::math::check_2F1_converges; TEST(passesOnConvergentArgs,Check2F1Converges) { const char* function = "check_2F1_converges"; double a1 = 1.0; double a2 = 1.0; double b1 = 5.0; double z = 0.3; // in radius of convergence for z, other args don't matter EXPECT_NO_THROW(check_2F1_converges(function, a1, a2, b1, z)); a1 = 1.0; a2 = 1.0; b1 = 5.0; z = 1.0; // still in radius of convergence, ok EXPECT_NO_THROW(check_2F1_converges(function, a1, a2, b1, z)); a1 = 1.0; a2 = 1.0; b1 = 1.0; // now in radius of convergences, but b1 is too small. z = 1.0; EXPECT_THROW(check_2F1_converges(function, a1, a2, b1, z), std::domain_error); a1 = 10.0; a2 = 1.0; b1 = 10.0; // now in radius of convergences, but b1 is too small. z = 1.0; EXPECT_THROW(check_2F1_converges(function, a1, a2, b1, z), std::domain_error); a1 = 1.0; a2 = 1.0; b1 = 5.0; z = 1.3; // outside of radius of convergence for current implementation. EXPECT_THROW(check_2F1_converges(function, a1, a2, b1, z), std::domain_error); a1 = 1.0; a2 = 1.0; b1 = 1.0; z = 0.99999999999; // b1 is small, but z < 1 so we're ok. EXPECT_NO_THROW(check_2F1_converges(function, a1, a2, b1, z)); a1 = 1.0; a2 = 1.0; b1 = 1.0; z = -0.999999999999; // checking negative z, this is fine EXPECT_NO_THROW(check_2F1_converges(function, a1, a2, b1, z)); a1 = 1.0; a2 = 1.0; b1 = 1.0; z = std::numeric_limits<double>::infinity(); // limits of range? EXPECT_THROW(check_2F1_converges(function, a1, a2, b1, z), std::domain_error); EXPECT_THROW(check_2F1_converges(function, a1, a2, b1, z), std::domain_error); a1 = 1.0; a2 = 1.0; b1 = 1.0; z = -1.0 * std::numeric_limits<double>::infinity(); // limits of range? EXPECT_THROW(check_2F1_converges(function, a1, a2, b1, z), std::domain_error); EXPECT_THROW(check_2F1_converges(function, a1, a2, b1, z), std::domain_error); a1 = 1.0; a2 = 1.0; b1 = std::numeric_limits<double>::infinity(); // should be ok, underflow to zero (?) z = 0.5; EXPECT_NO_THROW(check_2F1_converges(function, a1, a2, b1, z)); EXPECT_NO_THROW(check_2F1_converges(function, a1, a2, b1, z)); }
isc
fredmorcos/attic
snippets/c++/libsigcpp/main.cc
393
#include <sigc++/sigc++.h> #include <iostream> #include <string> #include "test.h" void signal_emitted (std::string x); int main (int argc, char *argv[]) { test t1; t1.changeMe(); t1.signal_proxy().connect(sigc::ptr_fun(signal_emitted)); t1.changeMe(); return 0; } void signal_emitted (std::string x) { std::cout << "Signal was emitted" << std::endl; std::cout << x << std::endl; }
isc
dbunker/Flask-Tread
examples/blog/app/app_setup.py
1026
import flask from flask.ext.migrate import Migrate import argparse import os def get_config(): parser = argparse.ArgumentParser() parser.add_argument('env', choices=['prod', 'qa', 'test', 'dev', 'env']) args = parser.parse_args() if args.env == 'prod': curconfig = 'config.ProdConfig' elif args.env == 'qa': curconfig = 'config.QAConfig' elif args.env == 'test': curconfig = 'config.TestConfig' elif args.env == 'dev': curconfig = 'config.DevConfig' elif args.env == 'env': curconfig = os.getenv('FLASK_ENV_OBJ') else: raise Exception('Invalid Config') if curconfig == None: raise Exception('Config cannot be null') return curconfig # only use for migrate if __name__ == '__main__': curconfig = get_config() import mainapp mainapp.configure(curconfig) from mainapp import app from mainapp import db migrate = Migrate(app, db) with app.app_context(): flask.ext.migrate.upgrade()
isc
dirga123/clr
openui5/sap/m/semantic/SortSelect-dbg.js
1244
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['sap/m/semantic/SemanticSelect'], function(SemanticSelect) { "use strict"; /** * Constructor for a new SortSelect. * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Custom initial settings for the new control * * @class * A SortSelect button has default semantic-specific properties and is * eligible for aggregation content of a {@link sap.m.semantic.SemanticPage}. * * @extends sap.m.semantic.SemanticSelect * @implements sap.m.semantic.ISort * * @author SAP SE * @version 1.36.5 * * @constructor * @public * @since 1.30.0 * @alias sap.m.semantic.SortSelect * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var SortSelect = SemanticSelect.extend("sap.m.semantic.SortSelect", /** @lends sap.m.semantic.SortSelect.prototype */ { metadata: { library : "sap.m", interfaces : [ "sap.m.semantic.ISort" ] } }); return SortSelect; }, /* bExport= */ true);
isc
nychtml5/www
test/twitter-spec.js
551
'use strict'; var chai = require('chai'); //var should = chai.should(); chai.use(require('sinon-chai')); //var sinon = require('sinon'); // TODO unformatted tweets for getTweets/getMentions //var formattedTweets = require('./fixtures/tweets-formatted'); //var twitter = require('../lib/twitter'); describe('twitter', function() { describe('#getTweets', function() { }); describe('#getMentions', function() { }); describe('#get', function() { it('should return an array of sorted tweets and mentions', function() { }); }); });
isc
kbevers/kvadratnet
kvadratnet/knet.py
4561
""" Command line utils for kvadratnet. """ import os import sys import shutil from collections import Counter import click import kvadratnet as kn @click.group() def cli(): """ CLI for kvadratnet """ @cli.command() @click.argument( "files", nargs=-1, required=True, type=click.Path("r"), ) @click.option( "--prefix", default="", help="Text before kvadratnet cell identifier, e.g. prefix_1km_6666_444.tif", ) @click.option( "--postfix", default="", help="Text after kvadratnet cell identifier, e.g. 1km_6666_444_postfix.tif", ) @click.option( "--verbose", "-v", is_flag=True, help="Be verbose", ) def rename(files, prefix, postfix, verbose): """ Batch rename files with kvadranet-names in them, e.g. add a prefix before the cell identifier. If a pre- or postfix is not specified, everything but the kvadratnet identifier is stripped from the filename FILES is a list of files to be renamed. Can be a globbing expression, e.g. 'dtm/*.tif'. """ for f in files: (folder, filename) = os.path.split(f) (base, ext) = os.path.splitext(filename) try: tilename = kn.tile_name(base) except ValueError: print("{}: No kvadratnet tile name found. Skipping.".format(f)) continue new_filename = prefix + tilename + postfix + ext dst = os.path.join(folder, new_filename) if verbose: print("Renaming {src} to {dst}".format(src=base + ext, dst=new_filename)) os.rename(f, dst) @cli.command() @click.argument( "units", required=True, ) @click.argument( "files", nargs=-1, type=click.Path("r"), ) @click.option( "--verbose", "-v", is_flag=True, help="Be verbose", ) def organize(units, files, verbose): """ Organize files into subfolders according to supplied list of tile units. FILES is a list of files thatrepresents files to be organized. Can be a globbing expression, e.g. 'dtm/*.tif'. UNITS is a list of units representing folders that files will be re-organized into. Allowed units are 100m, 250m, 1km, 10kmm 50km, and 100km. The list has to be quoted string, e.g. "100km 10km". """ # are input units known? for unit in units.split(): if not unit in kn.UNITS: raise ValueError("Unknown unit in units list ({})".format(unit)) for f in files: (_, filename) = os.path.split(f) (base, ext) = os.path.splitext(filename) try: tilename = kn.tile_name(base) except ValueError: print("{}: No kvadratnet tile name found. Skipping.".format(f)) continue sub_dirs = [] for unit in reversed(kn.UNITS): if not unit in units: continue try: sub_dirs.append(kn.parent_tile(tilename, unit)) except ValueError: print("ERROR: {0} is smaller than {1}".format(unit, tilename)) sys.exit(1) folder = os.path.sep.join(sub_dirs) try: os.makedirs(folder) except OSError: pass dst = os.path.join(folder, filename) if verbose: print( "Moving {filename} into {folder}".format( filename=filename, folder=folder ) ) shutil.move(f, dst) @cli.command() @click.argument( "files", nargs=-1, required=True, type=click.Path("r"), ) @click.option( "--unique", is_flag=True, help="Only show unique parents", ) @click.option( "--count", is_flag=True, help="Show number of childs for each parent", ) def parents(files, unique, count): """ Create a list of parent tiles from a list of inputs child tiles. FILES is a list of files that represent child files. Can be globbing expression, e.g. dtm/*.tif. """ counter = Counter() parent_list = [] for filename in files: try: tilename = kn.tile_name(filename.rstrip()) except ValueError: continue parent = kn.parent_tile(tilename) parent_list.append(parent) counter[parent] += 1 if unique: for key, value in counter.items(): if count: print("{:<20} {}".format(key, value)) else: print(key) else: for parent in parent_list: if count: print("{:<20} {}".format(parent, counter[parent])) else: print(parent)
isc
dijonkitchen/phase-0
week-4/count-between/my_solution.rb
861
# Count Between # I worked on this challenge by myself. # count_between is a method with three arguments: # 1. An array of integers # 2. An integer lower bound # 3. An integer upper bound # # It returns the number of integers in the array between the lower and upper bounds, # including (potentially) those bounds. # # If +array+ is empty the method should return 0 # Your Solution Below def count_between(list_of_integers, lower_bound, upper_bound) # Your code goes here! count = 0 if list_of_integers == [] return count elsif lower_bound == upper_bound return list_of_integers.length elsif upper_bound < lower_bound return count else for i in 0...list_of_integers.length if list_of_integers[i] >= lower_bound && list_of_integers[i] <= upper_bound count += 1 end end return count end end
isc
lxe/cprf
test/diff.js
1291
var fs = require('fs'); var path = require('path'); var parallel = require('run-parallel'); module.exports = diff; var statParams = [ 'dev', 'mode', 'nlink', 'uid', 'gid', 'rdev', 'size' ]; function diff (src, dest, t, done) { parallel([ fs.lstat.bind(fs, dest), fs.lstat.bind(fs, src) ], function (err, results) { if (err) return done(err); statParams.forEach(function (param) { t.equal( results[0][param], results[1][param], path.basename(src) + ' stat.' + param); }); // Files if (results[0].isFile()) { return parallel([ fs.readFile.bind(fs, dest), fs.readFile.bind(fs, src), ], function (err, data) { if (err) return done(err); t.deepEqual( data[0], data[1], path.basename(src) + ' contents'); return done(null); }); } // Directories if (results[0].isDirectory()) { return fs.readdir(src, function (err, files) { if (err) return done(err); parallel(files.map(function (file) { return diff.bind(null, path.join(src, file), path.join(dest, file), t); }), done); }); } // Everything else done(null); }); };
isc
kohkimakimoto/workerphp
src/Kohkimakimoto/Worker/Stats/StatsReporter.php
807
<?php namespace Kohkimakimoto\Worker\Stats; class StatsReporter { protected $on = false; protected $interval; protected $bootTime; public function on($interval = 300) { $this->on = true; $this->interval = $interval; } public function isOn() { return $this->on; } public function getInterval() { return $this->interval; } public function setBootTime($bootTime) { $this->bootTime = $bootTime; } public function getBootTime() { return $this->bootTime; } public function getUptime($date = null) { if (!$date) { $date = new \DateTime(); } $uptime = $date->getTimestamp() - $this->bootTime->getTimestamp(); return $uptime; } }
mit
louisgv/verdandi
modules/ibm/dialog.js
362
let watson = require('watson-developer-cloud'); let secret = require('../credential') .auth.nlc; let dialog = watson.dialog({ username: secret.username, password: secret.password, version: 'v1' }); dialog.getDialogs({}, function (err, dialogs) { if (err) console.log('error:', err); else console.log(JSON.stringify(dialogs, null, 2)); });
mit
VictorBac/site1
src/site1/BlogBundle/Entity/ArticleRepository.php
2991
<?php namespace site1\BlogBundle\Entity; use Doctrine\ORM\EntityRepository; /** * ArticleRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ArticleRepository extends EntityRepository { public function getArticles() { $qb = $this->createQueryBuilder('a') ->leftJoin('a.categories', 'cat') ->addSelect('cat') ->leftJoin('a.image', 'i') ->addSelect('i') ->orderBy('a.date', 'DESC'); return $qb->getQuery()->getResult(); } public function getSelectList() { $qb = $this->creatQueryBuilder('a') ->where('a.publication = 1'); return $qb; } public function getArticleAvecCommentaire($id) { $qb = $this->createQueryBuilder('a') ->where('a.id = :id') ->setParameter('id', $id) ->leftJoin('a.commentaires', 'c') ->addSelect('c'); $resultat = $qb->getQuery()->getOneOrNullResult(); return $resultat; } public function getDerniers($nbr) { $qb = $this->createQueryBuilder('a'); $qb->orderBy('a.date', 'DESC')->setMaxResults( $nbr ); $resultat = $qb->getQuery()->getResult(); return $resultat; } public function myFindAll() { $queryBuilder = $this->createQueryBuilder('a'); // On a fini de construire notre requête // On récupère la Query à partir du QueryBuilder $query = $queryBuilder->getQuery(); // On récupère les résultats à partir de la Query $resultats = $query->getResult(); // On retourne ces résultats return $resultats; } public function myFindOne($id) { // On passe par le QueryBuilder vide de l'EntityManager pour l'exemple $qb = $this->_em->createQueryBuilder(); $qb->select('a') ->from($this->_entityName, 'a') ->where('a.id = :id') ->setParameter('id', $id); return $qb->getQuery()->getResult(); } public function myFind() { $qb = $this->createQueryBuilder('a'); // On peut ajouter ce qu'on veut avant $qb->where('a.auteur = :auteur') ->setParameter('auteur', 'winzou'); // On applique notre condition $qb = $this->whereCurrentYear($qb); // On peut ajouter ce qu'on veut après $qb->orderBy('a.date', 'DESC'); return $qb->getQuery() ->getResult(); } public function whereCurrentYear(\Doctrine\ORM\QueryBuilder $qb) { $qb->andWhere('a.date BETWEEN :debut AND :fin') ->setParameter('debut', new \Datetime(date('Y').'-01-01')) // Date entre le 1er janvier de cette année ->setParameter('fin', new \Datetime(date('Y').'-12-31')); // Et le 31 décembre de cette année return $qb; } }
mit
faaslang/faaslang
tests/files/cases/function_invalid_acl_boolean.js
267
/** * Function with an invalid ACL value * @acl * * user_username faas_tester invalid * user_username faas_tester2 deny * user_username faas_tester3 deny * @returns {string} */ module.exports = (callback) => { return callback(null, 'invalid acl entry'); };
mit
joncinque/aggregate-class-calendar
imports/api/coursescraper.js
6334
import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { EventEmitter } from 'events'; import phantomjs from 'phantomjs-prebuilt'; import { parsePage, makeParsePageEventEmitter } from './parsecourse.js'; import { Courses } from './courses.js'; import { dumpCourseTable } from './chromegetcourse.js'; function logCourse(course) { logger.info("{ name: '" + course.name + "'"); logger.info(" , start: " + course.start.format('DD-MM-YYYY HH:mm')); logger.info(" , end: " + course.end.format('DD-MM-YYYY HH:mm')); logger.info(" , room: '" + course.room + "'"); logger.info(" , studio: '" + course.studio + "'"); logger.info(" , teacher: '" + course.teacher + "'"); logger.info(" , url: '" + course.url + "'"); logger.info(" , locale: '" + course.locale + "'"); logger.info(" , style: '" + course.style + "'"); logger.info(" , postcode: '" + course.postcode + "'"); logger.info("}"); } function addJSONCourseToDB(course) { course.start = new Date(course.start); course.end = new Date(course.end); Meteor.call('courses.insert', course); } function addCoursesToDB(courses) { courses.forEach(course => { course.start = course.start.toDate(); course.end = course.end.toDate(); }); courses.forEach(course => { Meteor.call('courses.insert', course); }); } function makeDBCallback(studio) { return (courses) => { logger.info('Finished for studio: ' + studio.name); return addCoursesToDB(courses); } } function makeArrayCallback(studio) { return (courses) => { logger.info('Finished for studio: ' + studio.name); courses.forEach(course => { course.start = course.start.toDate(); course.end = course.end.toDate(); }); return courses; } } function transformToJS(courseArray) { courseArray.forEach(course => { course.start = course.start.toDate(); course.end = course.end.toDate(); }); return courseArray; } function getCoursesAsync(studio, callback) { if (studio.provider === 'MBO') { const htmlFile = Math.abs(studio.studioid) + '.html'; return new Promise((resolve, reject)=>{ return phantomjs.run(Assets.absoluteFilePath('getcourse.js'), studio.provider, studio.studioid, studio.redirectPage) .then(program => { return parsePage(htmlFile, studio, callback); }) .then(data => { resolve(data); }); }); } else { logger.error('Cannot process studio without provider: ' + studio); } } function getCoursesChrome(studio, callback) { const htmlFile = Math.abs(studio.studioid) + '.html'; return dumpCourseTable( studio.provider, studio.studioid, studio.redirectPage ).once('finish-dumping', makeParsePageEventEmitter(studio, callback)); } Meteor.methods({ 'coursescraper.getAllCoursesPhantom'() { if (Meteor.isServer) { let studioScrapePromises = []; let studioInfo = JSON.parse(Assets.getText('studios.json')); for (let index in studioInfo) { let studio = studioInfo[index]; studioScrapePromises.push( getCoursesAsync( studio, Meteor.bindEnvironment(makeDBCallback(studio)))); } return Promise.all(studioScrapePromises).then(()=>{ logger.info("Scraping all done"); }); } else { return Promise.resolve([]); } }, async 'coursescraper.getAllCoursesSyncPhantom' () { if (Meteor.isServer) { let studioInfo = JSON.parse(Assets.getText('studios.json')); let boundAddCourses = Meteor.bindEnvironment(addCoursesToDB); for (let index in studioInfo) { let studio = studioInfo[index]; let courses = await getCoursesAsync(studio); boundAddCourses(courses); logger.info('Finished for studio: ' + studio.name); } logger.info('Scraping all done'); } return Promise.resolve([]); }, 'coursescraper.getAllCoursesChrome' () { let ee = new EventEmitter(); if (Meteor.isServer) { let studioInfo = JSON.parse(Assets.getText('studios.json')); let boundAddCourses = Meteor.bindEnvironment(addCoursesToDB); ee.on('finish-studio', (index)=>{ if (index < studioInfo.length) { let studio = studioInfo[index]; getCoursesChrome(studio ).once('finish-scraping', (data)=>{ boundAddCourses(data); logger.info('Finished for studio [' + studio.name + ']'); ee.emit('finish-studio', ++index); }).once('error', (data)=>{ ee.emit('finish-studio', ++index); }); } else { ee.emit('finish-all-scraping'); logger.info('Scraping all done'); } }); ee.emit('finish-studio', 0); } return ee; }, async 'coursescraper.addCoursesFromFile' (jsonFile) { check(jsonFile, String); if (Meteor.isServer) { let courses = JSON.parse(Assets.getText(jsonFile)); courses.forEach(addJSONCourseToDB); } return Promise.resolve([]); }, 'coursescraper.getCoursesPhantom'(studioid) { check(studioid, Number); if (Meteor.isServer) { let studioInfo = JSON.parse(Assets.getText('studios.json')); for (let index in studioInfo) { let studio = studioInfo[index]; if (studio.studioid === studioid) { return getCoursesAsync( studio, Meteor.bindEnvironment(makeDBCallback(studio))); } } } else { return Promise.resolve([]); } }, 'coursescraper.getCoursesChrome'(studioid) { check(studioid, Number); let ee = new EventEmitter(); if (Meteor.isServer) { let studioInfo = JSON.parse(Assets.getText('studios.json')); let boundAddCourses = Meteor.bindEnvironment(addCoursesToDB); for (let index in studioInfo) { let studio = studioInfo[index]; if (studio.studioid === studioid) { getCoursesChrome(studio ).once('finish-scraping', (data)=>{ boundAddCourses(data); logger.info('Finished for studio [' + studio.name + ']'); ee.emit('finish-all-scraping'); }); } } } return ee; }, });
mit
idreeskhan/activite-scala
src/com/khan/app/activite/MainActivity.scala
334
package com.khan.app.activite import android.app.Activity import android.os.Bundle class MainActivity extends Activity { /** * Called when the activity is first created. */ override def onCreate(savedInstanceState: Bundle) { super.onCreate(savedInstanceState) setContentView(R.layout.main) } }
mit
the-zebulan/CodeWars
tests/kyu_7_tests/test_jaden_casing_strings.py
311
import unittest from katas.kyu_7.jaden_casing_strings import toJadenCase class JadenCaseTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(toJadenCase( 'How can mirrors be real if our eyes aren\'t real' ), 'How Can Mirrors Be Real If Our Eyes Aren\'t Real')
mit
rlugojr/melonJS
src/state/state.js
20082
/* * MelonJS Game Engine * Copyright (C) 2011 - 2017, Olivier Biot, Jason Oster, Aaron McLeod * http://www.melonjs.org * * Screens objects & State machine * */ (function () { /** * A class skeleton for "Screen" Object <br> * every "screen" object (title screen, credits, ingame, etc...) to be managed <br> * through the state manager must inherit from this base class. * @class * @extends me.Object * @memberOf me * @constructor * @see me.state */ me.ScreenObject = me.Object.extend( /** @scope me.ScreenObject.prototype */ { /** @ignore */ init: function () {}, /** * Object reset function * @ignore */ reset : function () { // reset the game manager me.game.reset(); // call the onReset Function this.onResetEvent.apply(this, arguments); }, /** * destroy function * @ignore */ destroy : function () { // notify the object this.onDestroyEvent.apply(this, arguments); }, /** * onResetEvent function<br> * called by the state manager when reseting the object<br> * this is typically where you will load a level, etc... * to be extended * @name onResetEvent * @memberOf me.ScreenObject * @function * @param {} [arguments...] optional arguments passed when switching state * @see me.state#change */ onResetEvent : function () { // to be extended }, /** * onDestroyEvent function<br> * called by the state manager before switching to another state<br> * @name onDestroyEvent * @memberOf me.ScreenObject * @function */ onDestroyEvent : function () { // to be extended } }); // based on the requestAnimationFrame polyfill by Erik Möller (function () { var lastTime = 0; var frameDuration = 1000 / 60; // get unprefixed rAF and cAF, if present var requestAnimationFrame = me.agent.prefixed("requestAnimationFrame"); var cancelAnimationFrame = me.agent.prefixed("cancelAnimationFrame") || me.agent.prefixed("cancelRequestAnimationFrame"); if (!requestAnimationFrame || !cancelAnimationFrame) { requestAnimationFrame = function (callback) { var currTime = window.performance.now(); var timeToCall = Math.max(0, frameDuration - (currTime - lastTime)); var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; cancelAnimationFrame = function (id) { window.clearTimeout(id); }; } // put back in global namespace window.requestAnimationFrame = requestAnimationFrame; window.cancelAnimationFrame = cancelAnimationFrame; }()); /** * a State Manager (state machine)<p> * There is no constructor function for me.state. * @namespace me.state * @memberOf me */ me.state = (function () { // hold public stuff in our singleton var api = {}; /*------------------------------------------- PRIVATE STUFF --------------------------------------------*/ // current state var _state = -1; // requestAnimeFrame Id var _animFrameId = -1; // whether the game state is "paused" var _isPaused = false; // list of screenObject var _screenObject = {}; // fading transition parameters between screen var _fade = { color : "", duration : 0 }; // callback when state switch is done /** @ignore */ var _onSwitchComplete = null; // just to keep track of possible extra arguments var _extraArgs = null; // store the elapsed time during pause/stop period var _pauseTime = 0; /** * @ignore */ function _startRunLoop() { // ensure nothing is running first and in valid state if ((_animFrameId === -1) && (_state !== -1)) { // reset the timer me.timer.reset(); // start the main loop _animFrameId = window.requestAnimationFrame(_renderFrame); } } /** * Resume the game loop after a pause. * @ignore */ function _resumeRunLoop() { // ensure game is actually paused and in valid state if (_isPaused && (_state !== -1)) { // reset the timer me.timer.reset(); _isPaused = false; } } /** * Pause the loop for most screen objects. * @ignore */ function _pauseRunLoop() { // Set the paused boolean to stop updates on (most) entities _isPaused = true; } /** * this is only called when using requestAnimFrame stuff * @param {Number} time current timestamp in milliseconds * @ignore */ function _renderFrame(time) { // update all game objects me.game.update(time); // render all game objects me.game.draw(); // schedule the next frame update if (_animFrameId !== -1) { _animFrameId = window.requestAnimationFrame(_renderFrame); } } /** * stop the SO main loop * @ignore */ function _stopRunLoop() { // cancel any previous animationRequestFrame window.cancelAnimationFrame(_animFrameId); _animFrameId = -1; } /** * start the SO main loop * @ignore */ function _switchState(state) { // clear previous interval if any _stopRunLoop(); // call the screen object destroy method if (_screenObject[_state]) { // just notify the object _screenObject[_state].screen.destroy(); } if (_screenObject[state]) { // set the global variable _state = state; // call the reset function with _extraArgs as arguments _screenObject[_state].screen.reset.apply(_screenObject[_state].screen, _extraArgs); // and start the main loop of the // new requested state _startRunLoop(); // execute callback if defined if (_onSwitchComplete) { _onSwitchComplete(); } // force repaint me.game.repaint(); } } /* * PUBLIC STUFF */ /** * default state ID for Loading Screen * @constant * @name LOADING * @memberOf me.state */ api.LOADING = 0; /** * default state ID for Menu Screen * @constant * @name MENU * @memberOf me.state */ api.MENU = 1; /** * default state ID for "Ready" Screen * @constant * @name READY * @memberOf me.state */ api.READY = 2; /** * default state ID for Play Screen * @constant * @name PLAY * @memberOf me.state */ api.PLAY = 3; /** * default state ID for Game Over Screen * @constant * @name GAMEOVER * @memberOf me.state */ api.GAMEOVER = 4; /** * default state ID for Game End Screen * @constant * @name GAME_END * @memberOf me.state */ api.GAME_END = 5; /** * default state ID for High Score Screen * @constant * @name SCORE * @memberOf me.state */ api.SCORE = 6; /** * default state ID for Credits Screen * @constant * @name CREDITS * @memberOf me.state */ api.CREDITS = 7; /** * default state ID for Settings Screen * @constant * @name SETTINGS * @memberOf me.state */ api.SETTINGS = 8; /** * default state ID for user defined constants<br> * @constant * @name USER * @memberOf me.state * @example * var STATE_INFO = me.state.USER + 0; * var STATE_WARN = me.state.USER + 1; * var STATE_ERROR = me.state.USER + 2; * var STATE_CUTSCENE = me.state.USER + 3; */ api.USER = 100; /** * onPause callback * @function * @name onPause * @memberOf me.state */ api.onPause = null; /** * onResume callback * @function * @name onResume * @memberOf me.state */ api.onResume = null; /** * onStop callback * @function * @name onStop * @memberOf me.state */ api.onStop = null; /** * onRestart callback * @function * @name onRestart * @memberOf me.state */ api.onRestart = null; /** * @ignore */ api.init = function () { // set the embedded loading screen api.set(api.LOADING, new me.DefaultLoadingScreen()); }; /** * Stop the current screen object. * @name stop * @memberOf me.state * @public * @function * @param {Boolean} pauseTrack pause current track on screen stop. */ api.stop = function (music) { // only stop when we are not loading stuff if ((_state !== api.LOADING) && api.isRunning()) { // stop the main loop _stopRunLoop(); // current music stop if (music === true) { me.audio.pauseTrack(); } // store time when stopped _pauseTime = window.performance.now(); // publish the stop notification me.event.publish(me.event.STATE_STOP); // any callback defined ? if (typeof(api.onStop) === "function") { api.onStop(); } } }; /** * pause the current screen object * @name pause * @memberOf me.state * @public * @function * @param {Boolean} pauseTrack pause current track on screen pause */ api.pause = function (music) { // only pause when we are not loading stuff if ((_state !== api.LOADING) && !api.isPaused()) { // stop the main loop _pauseRunLoop(); // current music stop if (music === true) { me.audio.pauseTrack(); } // store time when paused _pauseTime = window.performance.now(); // publish the pause event me.event.publish(me.event.STATE_PAUSE); // any callback defined ? if (typeof(api.onPause) === "function") { api.onPause(); } } }; /** * Restart the screen object from a full stop. * @name restart * @memberOf me.state * @public * @function * @param {Boolean} resumeTrack resume current track on screen resume */ api.restart = function (music) { if (!api.isRunning()) { // restart the main loop _startRunLoop(); // current music stop if (music === true) { me.audio.resumeTrack(); } // calculate the elpased time _pauseTime = window.performance.now() - _pauseTime; // force repaint me.game.repaint(); // publish the restart notification me.event.publish(me.event.STATE_RESTART, [ _pauseTime ]); // any callback defined ? if (typeof(api.onRestart) === "function") { api.onRestart(); } } }; /** * resume the screen object * @name resume * @memberOf me.state * @public * @function * @param {Boolean} resumeTrack resume current track on screen resume */ api.resume = function (music) { if (api.isPaused()) { // resume the main loop _resumeRunLoop(); // current music stop if (music === true) { me.audio.resumeTrack(); } // calculate the elpased time _pauseTime = window.performance.now() - _pauseTime; // publish the resume event me.event.publish(me.event.STATE_RESUME, [ _pauseTime ]); // any callback defined ? if (typeof(api.onResume) === "function") { api.onResume(); } } }; /** * return the running state of the state manager * @name isRunning * @memberOf me.state * @public * @function * @return {Boolean} true if a "process is running" */ api.isRunning = function () { return _animFrameId !== -1; }; /** * Return the pause state of the state manager * @name isPaused * @memberOf me.state * @public * @function * @return {Boolean} true if the game is paused */ api.isPaused = function () { return _isPaused; }; /** * associate the specified state with a screen object * @name set * @memberOf me.state * @public * @function * @param {Number} state State ID (see constants) * @param {me.ScreenObject} so Instantiated ScreenObject to associate * with state ID * @example * var MenuButton = me.GUI_Object.extend({ * "onClick" : function () { * // Change to the PLAY state when the button is clicked * me.state.change(me.state.PLAY); * return true; * } * }); * * var MenuScreen = me.ScreenObject.extend({ * onResetEvent: function() { * // Load background image * me.game.world.addChild( * new me.ImageLayer(0, 0, { * image : "bg", * z: 0 // z-index * } * ); * * // Add a button * me.game.world.addChild( * new MenuButton(350, 200, { "image" : "start" }), * 1 // z-index * ); * * // Play music * me.audio.playTrack("menu"); * }, * * "onDestroyEvent" : function () { * // Stop music * me.audio.stopTrack(); * } * }); * * me.state.set(me.state.MENU, new MenuScreen()); */ api.set = function (state, so) { if (!(so instanceof me.ScreenObject)) { throw new me.Error(so + " is not an instance of me.ScreenObject"); } _screenObject[state] = {}; _screenObject[state].screen = so; _screenObject[state].transition = true; }; /** * return a reference to the current screen object<br> * useful to call a object specific method * @name current * @memberOf me.state * @public * @function * @return {me.ScreenObject} */ api.current = function () { return _screenObject[_state].screen; }; /** * specify a global transition effect * @name transition * @memberOf me.state * @public * @function * @param {String} effect (only "fade" is supported for now) * @param {me.Color|String} color a CSS color value * @param {Number} [duration=1000] expressed in milliseconds */ api.transition = function (effect, color, duration) { if (effect === "fade") { _fade.color = color; _fade.duration = duration; } }; /** * enable/disable transition for a specific state (by default enabled for all) * @name setTransition * @memberOf me.state * @public * @function * @param {Number} state State ID (see constants) * @param {Boolean} enable */ api.setTransition = function (state, enable) { _screenObject[state].transition = enable; }; /** * change the game/app state * @name change * @memberOf me.state * @public * @function * @param {Number} state State ID (see constants) * @param {} [arguments...] extra arguments to be passed to the reset functions * @example * // The onResetEvent method on the play screen will receive two args: * // "level_1" and the number 3 * me.state.change(me.state.PLAY, "level_1", 3); */ api.change = function (state) { // Protect against undefined ScreenObject if (typeof(_screenObject[state]) === "undefined") { throw new me.Error("Undefined ScreenObject for state '" + state + "'"); } if (api.isCurrent(state)) { // do nothing if already the current state return; } _extraArgs = null; if (arguments.length > 1) { // store extra arguments if any _extraArgs = Array.prototype.slice.call(arguments, 1); } // if fading effect if (_fade.duration && _screenObject[state].transition) { /** @ignore */ _onSwitchComplete = function () { me.game.viewport.fadeOut(_fade.color, _fade.duration); }; me.game.viewport.fadeIn( _fade.color, _fade.duration, function () { _switchState.defer(this, state); } ); } // else just switch without any effects else { // wait for the last frame to be // "finished" before switching _switchState.defer(this, state); } }; /** * return true if the specified state is the current one * @name isCurrent * @memberOf me.state * @public * @function * @param {Number} state State ID (see constants) */ api.isCurrent = function (state) { return _state === state; }; // return our object return api; })(); })();
mit
santiaago/ml
data/data.go
1943
//Package data reads, extracts and cleans data. package data import "encoding/csv" // Reader is the interface that wraps the basic read method. // Read returns a 2 Dimensional array of floats. // Use it to extract and clean data that you can then pass to a machine learning // model. type Reader interface { Read() (Container, error) } // Extractor is the interface that wraps the basic extract method. // Extract returns anything and an error. // Use it to extract data that you can then pass to a machine learning // model. type Extractor interface { Extract(r *csv.Reader) (interface{}, error) } type Writer interface { Write(filename string, predictions []float64) error } // Container holds the data and features information. type Container struct { Data [][]float64 // array that holds the information to learn or train. Features []int // array of indexes with the features to use in the Data array. Predict int // index of the data array that tells how to classify. } // Filter returns a 2D array of floats filtered with the params passed in. // It appends the defined Predict column 'Y' coordinate at the end of each row. // Like so: // x1 x2 x3 // x1 x2 x3 func (c Container) Filter(keep []int) (filtered [][]float64) { for i := 0; i < len(c.Data); i++ { var row []float64 for j := 0; j < len(keep); j++ { row = append(row, c.Data[i][keep[j]]) } filtered = append(filtered, row) } return } // Filter returns a 2D array of floats filtered with the params passed in. // It appends the defined Predict column 'Y' coordinate at the end of each row. // Like so: // x1 x2 x3 y // x1 x2 x3 y func (c Container) FilterWithPredict(keep []int) (filtered [][]float64) { for i := 0; i < len(c.Data); i++ { var row []float64 for j := 0; j < len(keep); j++ { row = append(row, c.Data[i][keep[j]]) } row = append(row, c.Data[i][c.Predict]) filtered = append(filtered, row) } return }
mit
hirsch88/ng2-seed
src/app/modules/+todo/todo.spec.ts
504
import { beforeEachProviders, inject, it } from '@angular/core/testing'; // Load the implementations that should be tested import { Todo } from './todo.ts'; describe('TodoComponent', () => { // provide our implementations or mocks to the dependency injector beforeEachProviders(() => [ Todo ]); it('should have 5 todos initially', inject([Todo], (todo: Todo) => { todo.ngOnInit(); expect(todo.todos).toBeDefined; expect(todo.todos.length).toEqual(5); })); });
mit
aletzo/publier
src/Mydevnullnet/Bundle/PublierBundle/Entity/Site.php
2033
<?php namespace Mydevnullnet\Bundle\PublierBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Mydevnullnet\Bundle\PublierBundle\Entity\Site */ class Site { /** * @var integer $id */ private $id; /** * @var string $name */ private $name; /** * @var string $description */ private $description; /** * @var string $domain */ private $domain; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Site */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set description * * @param string $description * @return Site */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set domain * * @param string $domain * @return Site */ public function setDomain($domain) { $this->domain = $domain; return $this; } /** * Get domain * * @return string */ public function getDomain() { return $this->domain; } /** * @var boolean $useSlugs */ private $useSlugs; /** * Set useSlugs * * @param boolean $useSlugs * @return Site */ public function setUseSlugs($useSlugs) { $this->useSlugs = $useSlugs; return $this; } /** * Get useSlugs * * @return boolean */ public function getUseSlugs() { return $this->useSlugs; } }
mit
soh335/go-dnssd
error.go
2324
package dnssd /* #include "dns_sd.h" */ import "C" import ( "errors" ) func createErr(e C.DNSServiceErrorType) error { switch e { case DNSServiceErr_NoError: return nil case DNSServiceErr_Unknown: return errors.New("unknown") case DNSServiceErr_NoSuchName: return errors.New("no such name") case DNSServiceErr_NoMemory: return errors.New("no memory") case DNSServiceErr_BadParam: return errors.New("bad param") case DNSServiceErr_BadReference: return errors.New("bad reference") case DNSServiceErr_BadState: return errors.New("bad state") case DNSServiceErr_BadFlags: return errors.New("bad flags") case DNSServiceErr_Unsupported: return errors.New("unsupported") case DNSServiceErr_NotInitialized: return errors.New("not initialized") case DNSServiceErr_AlreadyRegistered: return errors.New("already registerd") case DNSServiceErr_NameConflict: return errors.New("name conflict") case DNSServiceErr_Invalid: return errors.New("invalid") case DNSServiceErr_Firewall: return errors.New("firewall") case DNSServiceErr_Incompatible: return errors.New("incompatible") case DNSServiceErr_BadInterfaceIndex: return errors.New("bad interface index") case DNSServiceErr_Refused: return errors.New("refused") case DNSServiceErr_NoSuchRecord: return errors.New("no such record") case DNSServiceErr_NoAuth: return errors.New("no auth") case DNSServiceErr_NoSuchKey: return errors.New("no such key") case DNSServiceErr_NATTraversal: return errors.New("NAT traversal") case DNSServiceErr_DoubleNAT: return errors.New("double NAT") case DNSServiceErr_BadTime: return errors.New("bad time") case DNSServiceErr_BadSig: return errors.New("bad sig") case DNSServiceErr_BadKey: return errors.New("bad key") case DNSServiceErr_Transient: return errors.New("transient") case DNSServiceErr_ServiceNotRunning: return errors.New("service not running") case DNSServiceErr_NATPortMappingUnsupported: return errors.New("NAT port mapping unsported") case DNSServiceErr_NATPortMappingDisabled: return errors.New("NAT port mapping disabled") case DNSServiceErr_NoRouter: return errors.New("no router") case DNSServiceErr_PollingMode: return errors.New("polling mode") case DNSServiceErr_Timeout: return errors.New("timeout") default: return nil } }
mit
jkapelner/foxyforms-client
lib/browser/http-client.js
3586
// ---------------------------------------------------------- // A short snippet for detecting versions of IE in JavaScript // without resorting to user-agent sniffing // ---------------------------------------------------------- // If you're not in IE (or IE version is less than 5) then: // ie === undefined // If you're in IE (>=5) then you can determine which version: // ie === 7; // IE7 // Thus, to detect IE: // if (ie) {} // And to detect the version: // ie === 6 // IE6 // ie > 7 // IE8, IE9 ... // ie < 9 // Anything less than IE9 // ---------------------------------------------------------- // UPDATE: Now using Live NodeList idea from @jdalton var ie = (function(){ var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : undef; }()); var xhrHttp = (function () { if (typeof window === 'undefined') { throw new Error('no window object present'); } else if (window.XMLHttpRequest) { return window.XMLHttpRequest; } else if (window.ActiveXObject) { var axs = [ 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0', 'Microsoft.XMLHTTP' ]; for (var i = 0; i < axs.length; i++) { try { var ax = new(window.ActiveXObject)(axs[i]); return function () { if (ax) { var ax_ = ax; ax = null; return ax_; } else { return new(window.ActiveXObject)(axs[i]); } }; } catch (e) {} } throw new Error('ajax not supported in this browser') } else { throw new Error('ajax not supported in this browser'); } })(); exports.request = function(options, postData, callback) { try { if (typeof options !== 'object') { callback('options object is required'); return; } var method = options.method ? options.method : 'GET'; var url = options.scheme + '://' + options.host + ':' + options.port.toString() + options.path; var client; if (ie < 8) { //IE7 and below callback('Internet Explorer ' + ie.toString() + ' is not supported'); } else if ((ie === 8) || (ie === 9)) { //IE8 and IE9 use XDomainRequest var xdr = new XDomainRequest(); if (xdr) { xdr.onerror = function(){ callback('XDomainRequest error'); }; xdr.ontimeout = function(){ callback('XDomainRequest timed out'); }; xdr.onload = function(){ callback(null, xdr.responseText); }; xdr.timeout = 10000; xdr.open(method, url); xdr.send(postData); } else { callback('XDomainRequest undefined'); } } else { //all modern browsers client = new xhrHttp(); client.open(method, url, true); if (options.headers) { for (var key in options.headers) { client.setRequestHeader(key, options.headers[key]); } } client.send(postData); client.onreadystatechange=function() { if (client.readyState==4) { if (client.status==200) { callback(null, client.responseText); } else { //server error callback("XMLHttpRequest error status: " + client.status); } } }; } } catch (err) { callback(err.message); } };
mit
axismaps/EasyMySQL
content/js/lang/es.js
871
var fdLocale = { fullMonths:["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"], monthAbbrs:["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"], fullDays:["Lunes", "Martes", "Mi\u00E9rcoles", "Jueves", "Viernes", "S\u00E1bado", "Domingo"], dayAbbrs:["Lun", "Mar", "Mi\u00E9", "Jue", "Vie", "S\u00E1b", "Dom"], titles:["Mes Anterior", "Mes Siguiente", "A\u00F1o Anterior", "A\u00F1o Siguiente", "Hoy", "Mostar Calendario", "sem", "Semana[[%0%]] de [[%1%]]", "Semana", "Seleccione una Fecha", "Haga clic y arrastre para mover", "Mostrar \u0022[[%0%]]\u0022 primero", "Ir al d\u00EDa de hoy", "Deshabilitar Fecha"]}; try { if("datePickerController" in window) { datePickerController.loadLanguage(); }; } catch(err) {};
mit
duejay/ngProtractor
Gruntfile.js
12258
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // ini: grunt.file.readJSON('config.ini'), uglify: { dist: { files: { 'app/compressed/scripts.min.js': [ 'app/js/*.js' //'!app/js/scripts.min.js', //'!app/js/scripts.min.js.map', ] }, options: { banner: '/* compressed -- <%= grunt.template.today("yyyy-mm-dd h:MM:ss TT") %> */\n', sourceMap: 'app/compressed/scripts.min.js.map', mangle: false, } } }, karma: { unit: { configFile: 'test/karma.conf.js', background: false, coverageDir: 'reports' }, continuous: { configFile: 'test/karma.conf.js', singleRun: true, browsers: ['PhantomJS'] } }, sass: { dist: { files: { 'app/css/app.min.css' : 'app/sass/app.scss' }, options: { style: 'compressed', sourcemap: true, } } }, watch: { options: { livereload: true }, js: { files: [ 'app/js/*.js' //'!app/js/scripts.min.js', //'!app/js/scripts.min.js.map', ] }, js: { files: ['app/partials/*.html'] }, css: { files: ['app/sass/*.scss'], tasks: ['sass'], }, scripts: { files: ['app/js/*.js'], tasks: ['jshint', 'uglify'], options: { spawn: false, }, } /*karma: { files: ['app/js/*.js', 'test/unit/*.js'], tasks: ['karma:unit:run'] }*/ }, protractor: { options: { configFile: "test/protractor-conf.js", // Default config file keepAlive: true, // If false, the grunt process stops when the test fails. noColor: false, // If true, protractor will not use colors in its output. //debug: true, args: { chromeDriver: 'binaries/chromedriver', verbose: true } }, your_target: { options: { //debug: true, //configFile: "e2e.conf.js", // Target-specific config file args: { chromeDriver: 'binaries/chromedriver', verbose: true } // Target-specific arguments } }, }, jshint: { options: { "bitwise" : true, // Prohibit bitwise operators (&, |, ^, etc.). "curly" : true, // Require {} for every new block or scope. "eqeqeq" : true, // Require triple equals i.e. `===`. "forin" : true, // Tolerate `for in` loops without `hasOwnPrototype`. "immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );` "latedef" : true, // Prohibit variable use before definition. "newcap" : true, // Require capitalization of all constructor functions e.g. `new F()`. "noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`. "noempty" : true, // Prohibit use of empty blocks. "nonew" : true, // Prohibit use of constructors for side-effects. "plusplus" : false, // Prohibit use of `++` & `--`. "regexp" : true, // Prohibit `.` and `[^...]` in regular expressions. "undef" : true, // Require all non-global variables be declared before they are used. "strict" : false, // Require `use strict` pragma in every file. "trailing" : true, // Prohibit trailing whitespaces. // == Relaxing Options ================================================ // // These options allow you to suppress certain types of warnings. Use // them only if you are absolutely positive that you know what you are // doing. "asi" : false, // Tolerate Automatic Semicolon Insertion (no semicolons). "boss" : false, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments. "debug" : false, // Allow debugger statements e.g. browser breakpoints. "eqnull" : false, // Tolerate use of `== null`. "es5" : false, // Allow EcmaScript 5 syntax. "esnext" : false, // Allow ES.next specific features such as `const` and `let`. "evil" : false, // Tolerate use of `eval`. "expr" : false, // Tolerate `ExpressionStatement` as Programs. "funcscope" : false, // Tolerate declarations of variables inside of control structures while accessing them later from the outside. "globalstrict" : false, // Allow global "use strict" (also enables 'strict'). "iterator" : false, // Allow usage of __iterator__ property. "lastsemic" : false, // Tolerat missing semicolons when the it is omitted for the last statement in a one-line block. "laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons. "laxcomma" : false, // Suppress warnings about comma-first coding style. "loopfunc" : false, // Allow functions to be defined within loops. "multistr" : false, // Tolerate multi-line strings. "onecase" : false, // Tolerate switches with just one case. "proto" : false, // Tolerate __proto__ property. This property is deprecated. "regexdash" : false, // Tolerate unescaped last dash i.e. `[-...]`. "scripturl" : false, // Tolerate script-targeted URLs. "smarttabs" : false, // Tolerate mixed tabs and spaces when the latter are used for alignmnent only. "shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`. "sub" : false, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`. "supernew" : false, // Tolerate `new function () { ... };` and `new Object;`. "validthis" : false, // Tolerate strict violations when the code is running in strict mode and you use this in a non-constructor function. // == Environments ==================================================== // // These options pre-define global variables that are exposed by // popular JavaScript libraries and runtime environments—such as // browser or node.js. "browser" : true, // Standard browser globals e.g. `window`, `document`. "couch" : false, // Enable globals exposed by CouchDB. "devel" : false, // Allow development statements e.g. `console.log();`. "dojo" : false, // Enable globals exposed by Dojo Toolkit. "jquery" : false, // Enable globals exposed by jQuery JavaScript library. "mootools" : false, // Enable globals exposed by MooTools JavaScript framework. "node" : false, // Enable globals available when code is running inside of the NodeJS runtime environment. "nonstandard" : false, // Define non-standard but widely adopted globals such as escape and unescape. "prototypejs" : false, // Enable globals exposed by Prototype JavaScript framework. "rhino" : false, // Enable globals available when your code is running inside of the Rhino runtime environment. "wsh" : false, // Enable globals available when your code is running as a script for the Windows Script Host. // == JSLint Legacy =================================================== // // These options are legacy from JSLint. Aside from bug fixes they will // not be improved in any way and might be removed at any point. "nomen" : false, // Prohibit use of initial or trailing underbars in names. "onevar" : false, // Allow only one `var` statement per function. "passfail" : false, // Stop on first error. "white" : false, globals: { jQuery: true, angular: true, wc2014App: true }, }, uses_defaults: ['app/js/*.js'], with_overrides: { options: { curly: false, undef: true, }, files: { //src: ['build/*.js'] }, } }, open: { dev : { path: 'http://localhost/angularTestrun/test/units.html', app: 'Google Chrome' }, build : { path : 'http://google.com/', app: 'Firefox' }, file : { path : '/etc/hosts' }, custom: { path : function () { return grunt.option('path'); } } }, githooks: { all: { 'pre-commit': 'jshint karma:continuous' } }, compress: { main: { options: { archive: 'builds/build-<%= pkg.projectName %>-<%= grunt.template.today("yyyy-mm-dd h:MM:ss TT") %>.zip' }, files: [ {src: ['app/**'], dest: 'build /'}, // includes files in path and its subdirs {expand: true, cwd: 'path/', src: ['**'], dest: 'internal_folder3/'}, // makes all src relative to cwd {flatten: true, src: ['path/**'], dest: 'internal_folder4/', filter: 'isFile'} // flattens results to a single level ] } }, secret: grunt.file.readJSON('secret.json'), ssh_deploy: { staging: { options: { host: '<%= secret.host %>', username: '<%= secret.username %>', password: '<%= secret.password %>', port: '50683', deploy_path: '/var/domains/staging.wikixplore.com/www', local_path: 'app', //current_symlink: 'current', debug: true } }, production: { options: { host: '<%= secret.host %>', username: '<%= secret.username %>', password: '<%= secret.password %>', port: '50683', deploy_path: '/var/domains/staging.wikixplore.com/www', local_path: 'app' //current_symlink: 'current' } } }, env : { options : { //Shared Options Hash }, dev : { NODE_ENV : 'development', DEST : 'builds/dev' }, build : { NODE_ENV : 'production', DEST : 'builds/production' } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-protractor-runner'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-open'); grunt.loadNpmTasks('grunt-contrib-compress'); grunt.loadNpmTasks('grunt-ssh-deploy'); grunt.loadNpmTasks('grunt-githooks'); grunt.loadNpmTasks('grunt-env'); grunt.registerTask('default', ['watch']); grunt.registerTask('jshinting', ['jshint']); grunt.registerTask('dev', ['env:dev', 'build']); grunt.registerTask('releasetest', ['jshint', 'karma:continuous']); grunt.registerTask('upload', 'tasks to check for succesfull execution before uploading', function() { grunt.task.requires('jshinting'); grunt.task.requires('karma:continuous'); grunt.task.requires('protractor'); grunt.log.writeln('All critical tests are OK, ready for deployment'); grunt.task.run('[compress]'); //grunt.task.run(['ssh_deploy:production']); }); grunt.registerTask('deploy', 'All tasks before uploading process starts', ['jshinting', 'karma:continuous', 'protractor', 'upload']); };
mit
square/errbit
spec/models/notice_spec.rb
3795
require 'spec_helper' describe Notice do context 'validations' do it 'requires a backtrace' do notice = Factory.build(:notice, :backtrace => nil) notice.should_not be_valid notice.errors[:backtrace].should include("can't be blank") end it 'requires the server_environment' do notice = Factory.build(:notice, :server_environment => nil) notice.should_not be_valid notice.errors[:server_environment].should include("can't be blank") end it 'requires the notifier' do notice = Factory.build(:notice, :notifier => nil) notice.should_not be_valid notice.errors[:notifier].should include("can't be blank") end end context '#from_xml' do before do @xml = Rails.root.join('spec','fixtures','hoptoad_test_notice.xml').read @app = Factory(:app, :api_key => 'APIKEY') Digest::MD5.stub(:hexdigest).and_return('fingerprintdigest') end it 'finds the correct app' do @notice = Notice.from_xml(@xml) @notice.err.app.should == @app end it 'finds the correct err for the notice' do Err.should_receive(:for).with({ :app => @app, :klass => 'HoptoadTestingException', :component => 'application', :action => 'verify', :environment => 'development', :fingerprint => 'fingerprintdigest' }).and_return(err = Factory(:err)) err.notices.stub(:create!) @notice = Notice.from_xml(@xml) end it 'marks the err as unresolve if it was previously resolved' do Err.should_receive(:for).with({ :app => @app, :klass => 'HoptoadTestingException', :component => 'application', :action => 'verify', :environment => 'development', :fingerprint => 'fingerprintdigest' }).and_return(err = Factory(:err, :resolved => true)) err.should be_resolved @notice = Notice.from_xml(@xml) @notice.err.should == err @notice.err.should_not be_resolved end it 'should create a new notice' do @notice = Notice.from_xml(@xml) @notice.should be_persisted end it 'assigns an err to the notice' do @notice = Notice.from_xml(@xml) @notice.err.should be_a(Err) end it 'captures the err message' do @notice = Notice.from_xml(@xml) @notice.message.should == 'HoptoadTestingException: Testing hoptoad via "rake hoptoad:test". If you can see this, it works.' end it 'captures the backtrace' do @notice = Notice.from_xml(@xml) @notice.backtrace.size.should == 73 @notice.backtrace.last['file'].should == '[GEM_ROOT]/bin/rake' end it 'captures the server_environment' do @notice = Notice.from_xml(@xml) @notice.server_environment['environment-name'].should == 'development' end it 'captures the request' do @notice = Notice.from_xml(@xml) @notice.request['url'].should == 'http://example.org/verify' @notice.request['params']['controller'].should == 'application' end it 'captures the notifier' do @notice = Notice.from_xml(@xml) @notice.notifier['name'].should == 'Hoptoad Notifier' end end describe "email notifications" do before do @app = Factory(:app_with_watcher) @err = Factory(:err, :app => @app) end Errbit::Config.email_at_notices.each do |threshold| it "sends an email notification after #{threshold} notice(s)" do @err.notices.stub(:count).and_return(threshold) Mailer.should_receive(:err_notification). and_return(mock('email', :deliver => true)) Factory(:notice, :err => @err) end end end end
mit
lvanni/reputation
src/edu/lognet/reputation/model/user/IConsumer.java
1617
package edu.lognet.reputation.model.user; import java.util.List; import java.util.Map; import edu.lognet.reputation.model.experience.Credibility; import edu.lognet.reputation.model.experience.Experience; import edu.lognet.reputation.model.service.Service; import edu.lognet.reputation.model.user.User.collusionGroup; /** * Represent a Consumer in the simulator * @author Laurent Vanni, Thao Nguyen * */ public interface IConsumer { /** * Choose a provider in a providerList according to his reputation * @param <ReputedProvider> * @param providers * @param choosingStrategy * @return */ public IProvider chooseProvider(List<ReputedProvider> reputedProviderList, Service service, int dataLostPercent, int choosingStrategy); /** * Get the last experience of the consumer related to a provider in a given service * @param provider * @param service * @return Experience */ public Experience getConsumerExp(IProvider provider, Service service); /** * Set the experience of the consumer related to a provider in a given service * @param provider * @param service * @param experience */ public void setConsumerExp(IProvider provider, Service service, Experience experience); /** * Get the credibility of a Rater in a given service (for a given consumer) * @param raters * @return */ public Map<IRater, Credibility> getCredibilityOfRater(Service service); /** * * @return */ public User.raterType getRaterType(); /** * * @return */ public double getRatingTol(); /** * * @return */ public collusionGroup getCollusionCode(); }
mit
igalt/tomOMM
modules/makeathons/client/components/sidenav.client.component.js
2445
(function() { 'use strict'; var app = angular.module('makeathons'); app.component('sidenavComponent', { bindings: { makeathon: '=', menuitems: '=' }, templateUrl: 'modules/makeathons/client/views/sidenav.client.view.html', controller: sidenavComponent, controllerAs: 'vm' }); sidenavComponent.$inject = ['$scope','$state', 'MakeathonsUtils']; function sidenavComponent ($scope, $state, MakeathonsUtils) { var vm = this; sideMenuInit(); vm.isAllow = MakeathonsUtils.isAllow(vm.makeathon); vm.currentState = getStateData(); vm.goToState = goToState; vm.isStateActive = isStateActive; vm.isChecklistCompleted = isChecklistCompleted; vm.nodeName = nodeName; function sideMenuInit() { vm.sideMenu = vm.menuitems[0].sideMenu; vm.opts = vm.menuitems[0].sideMenuOpts; } function nodeName(node){ return node.params; } function isChecklistCompleted(node){ if (node.state === 'manage.checklist' && node.params){ return vm.makeathon.checklists[node.params].completed; } } function isStateActive(node){ switch(node.state) { case 'manage.checklist': return (node.params === $state.params.checklistName); case 'manage.wiki': return (node.params === $state.params.wikiPage); case $state.current.name: return true; default: return false; } } function getStateData(){ return vm.sideMenu.filter(function(node){ return node.state === $state.current.name; })[0]; } function goToState($event, node){ var elm = $event.currentTarget.getElementsByTagName('i')[0]; var stateParams = { makeathonId: $state.params.makeathonId }; switch(node.state) { case 'manage.checklist': stateParams.checklistName = node.params; break; case 'manage.wiki': stateParams.wikiPage = node.params; break; default: break; } if (elm.classList.contains('glyphicon-plus-sign') || elm.classList.contains('glyphicon-minus-sign')){ $(elm).toggleClass('glyphicon-plus-sign glyphicon-minus-sign'); } document.body.style.cursor='wait'; $scope.$on('$stateChangeSuccess', function() { document.body.style.cursor='default'; }); $state.go(node.state, stateParams); } } })();
mit
csecutsc/GmailBot
app.py
5900
# The MIT License (MIT) # # Copyright (c) 2016 Computer Science Enrichment Club # # 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. import gspread import yaml from oauth2client.service_account import ServiceAccountCredentials class SpreadSheetTracker(object): """ Handles getting user data and uploading to a google spreadsheet. Uses the google sheets api to access and upload data. Attributes: details: map, maps variables to sensitive information. torn_api_key: string, api key provided by torn. google_creds_path: string, path to the credentials i.e. "*.json". google_sheets_key: string, code given to a google spreadsheet. wks: worksheet object, object representing the online spreadsheet. userbase: map, maps an email(str) to a the following collection: {'first_name':str, 'last_name':str, 'problems_solved': {'score':int, **} where ** are the list of problems they have solved, as specified in the details.yaml. current_users: int, number of current users that should be in the database. """ def __init__(self): """Initializes basic contents required to access the service.""" with open("details.yaml", 'r') as yaml_file: self.details = yaml.load(yaml_file) self.google_creds_path = str(self.details['google_creds_path']) self.google_sheets_key = str(self.details['google_sheets_key']) self.problem_ids = [i.split(',') for i in self.details['problem_ids']] self.wks = None self.googleSpreadSheetSetup() self.userbase = self.details['userbase'] self.current_users = self.countNumberOfUsers() if(len(self.userbase) < self.current_users or current_users == self.wks.row_count): self.updateUserbase() def googleSpreadSheetSetup(self): """Authenticates user into google services and accesses spreadsheet. Returns: None Raises: gspread.SpreadsheetNotFound """ scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name(self.google_creds_path, scope) gc = gspread.authorize(credentials) self.wks = gc.open_by_key(self.google_sheets_key).sheet1 def updateUserbase(self): """ Updates the local database with the entries on the spreadsheet. Queries the spreadsheet for each user's first name, last name, and email address. Note, that this process will take a long time. Returns: None Raises: None """ end_of_sheet = False # In this case, we will start from the newest users not added in our # currrent database. for i in range(len(self.userbase)+2, self.current_users+1): if end_of_sheet: break first_name = '' last_name = '' email = '' for j in 'ABC': if self.wks.acell(j+str(i)).value == '': end_of_sheet = True else: # Mapping first three entries in spreadsheet to the # corresponding entries we need. if j == 'A': first_name = self.wks.acell(j+str(i)).value if j == 'B': last_name = self.wks.acell(j+str(i)).value if j == 'C': email = self.wks.acell(j+str(i)).value self.userbase[email] = (first_name, last_name, {}) # Now we'll be updating the yaml file so we don't have to redo this # slow procedure. self.details['userbase'] = self.userbase with open('details.yaml', 'w') as outfile: outfile.write(yaml.dump(self.details, default_flow_style=False)) def countNumberOfUsers(self): """Finds the number of users in the google spreadsheet. Returns: an int that is, number of users in the google spreadsheet. If there are no current users in the spread sheet, this returns the maximum number of elements in the spreadsheet, i.e. 100 """ # We use binary search since this is the monotomic increasing sequence # and accessing the api is pretty slow. Takes on average 10 guesses. lo = 2 mid = 0 hi = self.wks.row_count-1 while(lo < hi): mid = lo + (hi - lo + 1)//2 if(self.wks.acell('A'+str(mid)).value != ''): lo = mid else: hi = mid-1 # No users in the spreadsheet if self.wks.acell('A'+str(lo)).value == '': return self.wks.row_count return lo if __name__ == '__main__': sst = SpreadSheetTracker()
mit
relayr/rabbitmq-scala-client
src/main/scala/io/relayr/amqp/connection/ConnectionWrapper.scala
1990
package io.relayr.amqp.connection import com.rabbitmq.client._ import io.relayr.amqp.Event.{ ChannelEvent, ConnectionEvent } import io.relayr.amqp._ import io.relayr.amqp.connection.Listeners._ import scala.concurrent.blocking import scala.language.postfixOps private[amqp] class ConnectionWrapper(conn: Connection, eventConsumer: Event ⇒ Unit, channelFactory: ChannelFactory) extends ConnectionHolder { conn.addShutdownListener(shutdownListener(cause ⇒ eventConsumer(ConnectionEvent.ConnectionShutdown) )) private def createChannel(conn: Connection, qos: Option[Int]): Channel = blocking { val channel = conn.createChannel() // NOTE there may be other parameters possible to set up on the connection at the start qos.foreach(channel.basicQos) eventConsumer(ChannelEvent.ChannelOpened(channel.getChannelNumber, qos)) channel.addReturnListener(new ReturnListener { override def handleReturn(replyCode: Int, replyText: String, exchange: String, routingKey: String, properties: AMQP.BasicProperties, body: Array[Byte]): Unit = eventConsumer(ChannelEvent.MessageReturned(replyCode, replyText, exchange, routingKey, Message.Raw(body, properties))) }) channel.addShutdownListener(shutdownListener(cause ⇒ eventConsumer(ChannelEvent.ChannelShutdown) )) channel } /** * Create a new channel multiplexed over this connection. * @note Blocks on creation of the underlying channel */ override def newChannel(qos: Int): ChannelOwner = newChannel(Some(qos)) override def newChannel(): ChannelOwner = newChannel(None) /** * Create a new channel multiplexed over this connection. * @note Blocks on creation of the underlying channel */ def newChannel(qos: Option[Int] = None): ChannelOwner = this.synchronized { channelFactory(createChannel(conn, qos), eventConsumer) } /** Close the connection. */ override def close(): Unit = this.synchronized { blocking { conn.close() } } }
mit
pagedynamo-cms/PagedynamoAdminBundle
DataFixtures/ORM/LoadMenuData.php
3865
<?php namespace Pagedynamo\AdminBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Pagedynamo\AdminBundle\Entity\Menu; use Pagedynamo\AdminBundle\Entity\User; class LoadMenuData implements FixtureInterface { /** * {@inheritDoc} */ public function load(ObjectManager $manager) { $pages = new Menu(); $pages->setName('Seiten'); $pages->setPosition(0); $pages->setIsDeleteable(false); $pages->setTranslatableLocale('de'); $manager->persist($pages); $newsMenu = new Menu(); $newsMenu->setParent($pages); $newsMenu->setName('News'); $newsMenu->setPosition(2); $newsMenu->setIsDeleteable(false); $newsMenu->setTranslatableLocale('de'); $newsMenu->setRoute('pd_admin_news'); $manager->persist($newsMenu); $content = new Menu(); $content->setName('Content-Seiten'); $content->setParent($pages); $content->setPosition(1); $content->setIsDeleteable(false); $content->setTranslatableLocale('de'); $content->setRoute('pd_admin_page'); $manager->persist($content); $content = new Menu(); $content->setName('Frontend-Menüs'); $content->setParent($pages); $content->setPosition(3); $content->setIsDeleteable(false); $content->setTranslatableLocale('de'); $content->setRoute('pd_admin_frontendmenu'); $manager->persist($content); $filemenu = new Menu(); $filemenu->setName('Dateiverwaltung'); $filemenu->setPosition(1); $filemenu->setIsDeleteable(false); $filemenu->setTranslatableLocale('de'); $manager->persist($filemenu); $mediamenu = new Menu(); $mediamenu->setName('Medien'); $mediamenu->setParent($filemenu); $mediamenu->setIsDeleteable(false); $mediamenu->setTranslatableLocale('de'); $mediamenu->setRoute('pd_admin_file'); $manager->persist($mediamenu); $foldermenu = new Menu(); $foldermenu->setName('Ordner'); $foldermenu->setParent($filemenu); $foldermenu->setIsDeleteable(false); $foldermenu->setTranslatableLocale('de'); $foldermenu->setRoute('pd_admin_folder'); $manager->persist($foldermenu); $systemmenu = new Menu(); $systemmenu->setName('System'); $systemmenu->setPosition(2); $systemmenu->setIsDeleteable(false); $systemmenu->setTranslatableLocale('de'); $manager->persist($systemmenu); $userMenu = new Menu(); $userMenu->setParent($systemmenu); $userMenu->setName('Benutzer'); $userMenu->setIsDeleteable(false); $userMenu->setTranslatableLocale('de'); $userMenu->setRoute('pd_admin_user'); $manager->persist($userMenu); $menuMenu = new Menu(); $menuMenu->setParent($systemmenu); $menuMenu->setName('Menü'); $menuMenu->setIsDeleteable(false); $menuMenu->setTranslatableLocale('de'); $menuMenu->setRoute('pd_admin_menu'); $manager->persist($menuMenu); $menuMenu = new Menu(); $menuMenu->setParent($systemmenu); $menuMenu->setName('Sprachen'); $menuMenu->setIsDeleteable(false); $menuMenu->setTranslatableLocale('de'); $menuMenu->setRoute('pd_admin_sitelanguage'); $manager->persist($menuMenu); $menuMenu = new Menu(); $menuMenu->setParent($systemmenu); $menuMenu->setName('Seiten-Module'); $menuMenu->setIsDeleteable(false); $menuMenu->setTranslatableLocale('de'); $menuMenu->setRoute('pd_admin_pageblocktype'); $manager->persist($menuMenu); $manager->flush(); } }
mit
spittet/futoro-test3
src/db/index.js
95
// @flow import * as capsules from './capsules'; export default { ...capsules }
mit
Khairulrabbi/htmis
resources/views/accesses/index.blade.php
3024
@extends('layouts.admin') @section('content') <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Data Tables <small>advanced tables</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li><a href="#">Tables</a></li> <li class="active">Data tables</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Data Table With Access List</h3> </div><!-- /.box-header --> <div class="box-body"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>Action Name</th> <th>Name</th> <th>Control Name</th> <th>Delete</th> </tr> </thead> <tbody> @foreach($accesses as $access) <tr> <td class="table-text"><div><a href={{'access/'}}{{ $access->id}}{{'/edit'}}> {{ $access->action_name }}</a></div></td> <td class="table-text"><div>{{ $access->name }}</div></td> <td class="table-text"><div>{{ $access->controller_name }}</div></td> <td> {!! Form::open(['url'=>'access/'.$access->id, 'files'=>true, 'onsubmit'=>'return ConfirmDelete()']) !!} {{ csrf_field() }} {{ method_field('DELETE')}} {!! Form::submit('DELETE',array('class'=>'btn btn-danger')) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> {{ $accesses->render() }} </div><!-- /.box-body --> </div><!-- /.box --> </div><!-- /.col --> </div><!-- /.row --> </section><!-- /.content --> </div><!-- /.content-wrapper --> <!-- Control Sidebar --> <div class="control-sidebar-bg"></div> <script type="text/javascript"> function ConfirmDelete() { var x = confirm('Are you sure to delete'); if(x) return true; else return false; } </script> @endsection
mit
saenridanra/inet-dns-extension
doc/doxy/search/classes_4.js
497
var searchData= [ ['gateiterator',['GateIterator',['/home/saen/Programme.local/omnetpp-4.6//doc/api/classcModule_1_1GateIterator.html',1,'cModule']]], ['generatorservice',['GeneratorService',['../d8/ddd/structMDNSNetworkConfigurator_1_1GeneratorService.html',1,'MDNSNetworkConfigurator']]], ['generictraffgen',['GenericTraffGen',['../d1/d97/classGenericTraffGen.html',1,'']]], ['grid',['Grid',['/home/saen/Programme.local/omnetpp-4.6//doc/api/structcKSplit_1_1Grid.html',1,'cKSplit']]] ];
mit
DJCrossman/word-freq
WordFrequency/WordFrequency/main.cpp
1026
/** Program: main.cpp Programmer: David Crossman, 200296439 Date: 01/19/2014 */ #include <iostream> #include <iomanip> #include <locale> #include <string> using namespace std; #include "wordTree.h" void readFile (WordTree *wordTree); void display (TNode *node); int main () { WordTree wordTree; readFile(&wordTree); display(wordTree.getHead()); return 0; } void readFile (WordTree *wordTree) { string data; //loop until the end of file while (!cin.eof() && cin.good()) { cin >> data; //make all the characters lowercase for (unsigned int i = 0; i <= (int) data.size(); i++) data[i] = tolower(data[i]); //insert data in the tree alphabetical if ( isalpha(data[0]) && islower(data[0]) ) wordTree->insert(data); //break; - For some reason will not exit loop at the end of file } }; void display (TNode *node) { if (node != NULL) { display(node->left); cout << node->word << " = " << node->count << endl; display(node->right); } };
mit
hackerspace-ntnu/website
userprofile/migrations/0004_auto_20171115_1627.py
473
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2017-11-15 16:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('userprofile', '0003_auto_20171114_2105'), ] operations = [ migrations.AlterField( model_name='skill', name='icon', field=models.ImageField(blank=True, upload_to='skillicons'), ), ]
mit
crystalwm/Angular_demo
AngularjsTutorial_cn/angular2_examples/tour-of-heroes/systemjs.config.js
1736
(function (global) { var map = { 'app': 'app/app', '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 'rxjs': 'node_modules/rxjs' }; var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }, 'appmultimain':{ defaultExtension: 'js' }, 'appmultiheroes': { main: 'main.js', defaultExtension: 'js' }, 'appheroservice': { main: 'main.js', defaultExtension: 'js' }, 'appheroroute': { main: 'main.js', defaultExtension: 'js' }, }; var ngPackageNames = [ 'common', 'compiler', 'core', 'forms', 'http', 'platform-browser', 'platform-browser-dynamic', 'router', 'router-deprecated', 'upgrade' ]; function packIndex(pkgName) { packages['@angular/' + pkgName] = { main: 'index.js', defaultExtension: 'js' } } function packUmd(pkgName) { packages['@angular/' + pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' } } var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; ngPackageNames.forEach(setPackageConfig); var config = { map: map, packages: packages }; System.config(config); })(this);
mit
idelpivnitskiy/JBattleCity
src/main/java/ua/pp/condor/jbattlecity/area/Constants.java
162
package ua.pp.condor.jbattlecity.area; public class Constants { public static final int TANK_STEP = 10; public static final int MAX_ENEMY_ID = 127; }
mit
mayswind/C3D.NET
C3D.DataViewer/Controls/EventsControl.cs
838
using System; using System.Windows.Forms; namespace C3D.DataViewer.Controls { public partial class EventsControl : UserControl { public EventsControl(C3DFile file) { InitializeComponent(); this.LoadData(file); } private void LoadData(C3DFile file) { if (file == null) { return; } C3DHeaderEvent[] events = file.Header.GetAllHeaderEvents(); if (events != null && events.Length > 0) { for (Int32 i = 0; i < events.Length; i++) { this.lvItems.Items.Add(new ListViewItem(new String[] { events[i].EventName, events[i].EventTime.ToString(), events[i].IsDisplay.ToString() })); } } } } }
mit
4dn-dcic/fourfront
src/encoded/static/components/browse/components/SelectedFilesController.js
13222
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import memoize from 'memoize-one'; import _ from 'underscore'; import { object, console, analytics, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import { expFxn } from './../../util'; // Memoized helper functions for getting counts of files performantly-er. // These are used often by other components which consume/display selected file counts. /** Used and memoized in views which have multiple sets of selectedFiles */ export function uniqueFileCount(files) { if (!files || (typeof files !== 'object' && !Array.isArray(files))) { logger.error("files not in proper form (object/array) or is non-existent", files); return 0; } if (typeof files === 'object') { return _.uniq(_.pluck(_.values(files), 'accession')).length; } else { //array return _.uniq(_.pluck(files, 'accession')).length; } } export function fileCountWithDuplicates(files){ if (!files || (typeof files !== 'object' && !Array.isArray(files))) { logger.error("files not in proper form (object/array) or is non-existent", files); return 0; } if (typeof files === 'object') { return _.keys(files).length; } else { //array return files.length; } } /** * IN PROGRESS -- TODO: Decide if we should store "selectedFiles" or "unselectedFiles" (re: 'All files in facet selection are selected by default') * * @export * @class SelectedFilesController * @extends {React.Component} */ export class SelectedFilesController extends React.PureComponent { /** Utility function to extract out the relevant props passed in by `SelectedFilesController` out of a props object. */ static pick(props){ return _.pick(props, 'selectedFiles', 'selectFile', 'unselectFile', 'resetSelectedFiles', 'incrementalExpandLimit', 'incrementalExpandStep'); } static listToObject(selectedFilesList){ return _.object(_.map( // Ensure all files have an `@id` / view permissions. // Lack of view permissions is OK for when file visible in table as lack of permission // is shown (without checkbox). _.filter(selectedFilesList, object.itemUtil.atId), function(fileItem){ return [ expFxn.fileToAccessionTriple(fileItem, true, true), fileItem ]; } )); } static parseInitiallySelectedFiles(initiallySelectedFiles){ if (initiallySelectedFiles === null){ return {}; } if (!Array.isArray(initiallySelectedFiles) && initiallySelectedFiles && typeof initiallySelectedFiles === 'object'){ // Assume we got a well-formatted selectedFiles object. This is probably only case for tests, e.g. RawFilesStackedTable-test.js. // This means keys must be in form of stringified accession triples, e.g. `"EXPSETACCESSION~EXPACCESSION~FILEACCESSION"` // Lets validate that -- _.forEach(_.keys(initiallySelectedFiles), function(key){ const parts = key.split('~'); if (parts.length !== 3){ logger.error('If supply an object as initiallySelectedFiles, it must have stringified accession triples as keys.'); throw new Error('If supply an object as initiallySelectedFiles, it must have stringified accession triples as keys.'); } }); return _.clone(initiallySelectedFiles); } if (Array.isArray(initiallySelectedFiles)){ return SelectedFilesController.listToObject(initiallySelectedFiles); } logger.error(initiallySelectedFiles); throw new Error('Received unexpected props.initiallySelectedFiles -'); } static defaultProps = { 'initiallySelectedFiles' : null, 'resetSelectedFilesCheck' : function(nextProps, pastProps){ if (typeof nextProps.href === 'string') { if (nextProps.href !== pastProps.href) return true; } if (nextProps.context && pastProps.context && nextProps.context !== pastProps.context) { if (Array.isArray(pastProps.context['@graph']) && !Array.isArray(nextProps.context['@graph'])) return true; //if (Array.isArray(pastProps.context['@graph']) && Array.isArray(nextProps.context['@graph'])) { // var pastGraph = pastProps.context['@graph']; // var newGraph = nextProps.context['@graph']; //} } return false; }, 'analyticsAddFilesToCart' : false }; constructor(props){ super(props); this.selectFile = this.selectFile.bind(this); this.unselectFile = this.unselectFile.bind(this); this.resetSelectedFiles = this.resetSelectedFiles.bind(this); const selectedFiles = SelectedFilesController.parseInitiallySelectedFiles(props.initiallySelectedFiles); this.state = { selectedFiles }; } componentDidMount(){ const { analyticsAddFilesToCart = false } = this.props; if (!analyticsAddFilesToCart) { return; } const { selectedFiles, context } = this.state; const existingFileList = _.keys(selectedFiles).map(function(accessionTripleString){ return selectedFiles[accessionTripleString]; }); if (existingFileList.length > 0) { setTimeout(function(){ const extData = { list: analytics.hrefToListName(window && window.location.href) }; analytics.productsAddToCart(existingFileList, extData); analytics.event( "SelectedFilesController", "Select Files", { eventLabel: extData.list, eventValue: existingFileList.length, currentFilters: analytics.getStringifiedCurrentFilters((context && context.filters) || null) } ); }, 250); } } componentDidUpdate(pastProps){ if (this.props.resetSelectedFilesCheck(this.props, pastProps)){ this.resetSelectedFiles(); } } selectFile(accessionTriple, fileItem = null){ const { context, analyticsAddFilesToCart = false } = this.props; function error(){ logger.error("Supplied accessionTriple is not a string or array of strings/arrays:", accessionTriple); throw new Error("Supplied accessionTriple is not a string or array of strings/arrays:", accessionTriple); } const newlyAddedFileItems = []; this.setState(({ selectedFiles })=>{ var newSelectedFiles = _.extend({}, selectedFiles); function add(id, fileItemCurr = null){ if (typeof newSelectedFiles[id] !== 'undefined'){ logger.error("File already selected!", id); } else { newSelectedFiles[id] = fileItemCurr || true; if (fileItemCurr){ newlyAddedFileItems.push(fileItemCurr); } } } if (Array.isArray(accessionTriple)){ _.forEach(accessionTriple, function(id){ if (typeof id === 'string'){ add(id); } else if (Array.isArray(id)){ add(id[0], id[1]); } else error(); }); } else if (typeof accessionTriple === 'string') { add(accessionTriple, fileItem); } else error(); return { 'selectedFiles' : newSelectedFiles }; }, ()=>{ if (!analyticsAddFilesToCart){ return; } const extData = { list: analytics.hrefToListName(window && window.location.href) }; analytics.productsAddToCart(newlyAddedFileItems, extData); analytics.event( "SelectedFilesController", "Select Files", { eventLabel: extData.list, eventValue: newlyAddedFileItems.length, currentFilters: analytics.getStringifiedCurrentFilters((context && context.filters) || null) } ); }); } unselectFile(accessionTriple){ const { context, analyticsAddFilesToCart = false } = this.props; function error(){ logger.error("Supplied accessionTriple is not a string or array of strings/arrays:", accessionTriple); throw new Error("Supplied accessionTriple is not a string or array of strings/arrays:", accessionTriple); } const newlyRemovedFileItems = []; this.setState(({ selectedFiles })=>{ var newSelectedFiles = _.extend({}, selectedFiles); function remove(id) { if (typeof newSelectedFiles[id] === 'undefined'){ console.log(id, newSelectedFiles); logger.error("File not in set!", id); } else { const fileItemCurr = newSelectedFiles[id]; if (fileItemCurr){ newlyRemovedFileItems.push(fileItemCurr); } delete newSelectedFiles[id]; } } if (Array.isArray(accessionTriple)){ _.forEach(accessionTriple, function(id){ if (typeof id === 'string'){ remove(id); } else error(); }); } else if (typeof accessionTriple === 'string') { remove(accessionTriple); } else error(); return { 'selectedFiles' : newSelectedFiles }; }, ()=>{ if (!analyticsAddFilesToCart){ return; } const extData = { list: analytics.hrefToListName(window && window.location.href) }; analytics.productsRemoveFromCart(newlyRemovedFileItems, extData); analytics.event( "SelectedFilesController", "Unselect Files", { eventLabel: extData.list, eventValue: newlyRemovedFileItems.length, currentFilters: analytics.getStringifiedCurrentFilters((context && context.filters) || null) } ); }); } /** @todo: Maybe change to remove all files (not reset to initial) */ resetSelectedFiles(){ const { context, initiallySelectedFiles, analyticsAddFilesToCart = false } = this.props; const { selectedFiles: existingSelectedFiles } = this.state; const existingFileList = _.keys(existingSelectedFiles).map(function(accessionTripleString){ return existingSelectedFiles[accessionTripleString]; }); const selectedFiles = SelectedFilesController.parseInitiallySelectedFiles(initiallySelectedFiles); this.setState({ selectedFiles },()=>{ if (!analyticsAddFilesToCart || existingFileList.length === 0){ return; } const extData = { list: analytics.hrefToListName(window && window.location.href) }; analytics.productsRemoveFromCart(existingFileList, extData); analytics.event( "SelectedFilesController", "Unselect All Files", { eventLabel: extData.list, eventValue: existingFileList.length, currentFilters: analytics.getStringifiedCurrentFilters((context && context.filters) || null) } ); }); } render(){ const { children } = this.props; const { selectedFiles } = this.state; const propsToPass = _.extend(_.omit(this.props, 'children'), { 'selectedFiles' : selectedFiles, 'selectFile' : this.selectFile, 'unselectFile' : this.unselectFile, 'resetSelectedFiles' : this.resetSelectedFiles }); if (Array.isArray(children)){ return React.Children.map(children, function(child){ if (!React.isValidElement(child)){ logger.error('SelectedFilesController expects props.children[] to be valid React component instances.'); throw new Error('SelectedFilesController expects props.children[] to be valid React component instances.'); } return React.cloneElement(child, propsToPass); }); } else { if (!React.isValidElement(children)){ logger.error('SelectedFilesController expects props.children to be a valid React component instance.'); throw new Error('SelectedFilesController expects props.children to be a valid React component instance.'); } return React.cloneElement(children, propsToPass); } } }
mit
Sobieck00/BOH-Bulldog-Scholarship-Application-Management
BohFoundation.Utilities/Context/Implementation/DeadlineUtilities.cs
1439
using System; using System.Configuration; using BohFoundation.Utilities.Context.Interfaces; using BohFoundation.Utilities.Utilities.Interfaces; namespace BohFoundation.Utilities.Context.Implementation { public class DeadlineUtilities : IDeadlineUtilities { private readonly IClaimsInformationGetters _claimsInformationGetters; private readonly IGetTime _getTime; public DeadlineUtilities(IClaimsInformationGetters claimsInformationGetters, IGetTime getTime) { _claimsInformationGetters = claimsInformationGetters; _getTime = getTime; } public bool IsAfterDeadline() { return _getTime.GetUtcNow() > GetApplicantsDeadlineInUtc(); } public DateTime GetApplicantsDeadlineInUtc() { var config = ConfigurationManager.AppSettings; var month = int.Parse(config.GetValues("deadlineMonth")[0]); var day = int.Parse(config.GetValues("deadlineDay")[0]); var hour = int.Parse(config.GetValues("deadlineHour")[0]); var timezonestring = config.GetValues("deadlineTimeZone")[0]; var year = _claimsInformationGetters.GetApplicantsGraduatingYear(); var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timezonestring); return TimeZoneInfo.ConvertTimeToUtc(new DateTime(year, month, day, hour, 0, 0), timeZone); } } }
mit
MarkerMetro/MarkerMetro.Unity.WinIntegration
SharedSource/Facebook/FB.cs
21085
#if NETFX_CORE using MarkerMetro.Unity.WinLegacy.Security.Cryptography; using System.Threading.Tasks; using System.Globalization; #endif using Facebook; using System; using System.Collections.Generic; using MarkerMetro.Unity.WinIntegration; #if NETFX_CORE using Windows.Storage; using MarkerMetro.Unity.WinIntegration.Storage; #endif namespace MarkerMetro.Unity.WinIntegration.Facebook { public class MissingPlatformException : Exception { public MissingPlatformException() : base("Platform components have not been set") { } } public static class FB { #if NETFX_CORE private static FacebookClient _client; private static IWebInterface _web; private static HideUnityDelegate _onHideUnity; private static string _redirectUrl = "http://www.facebook.com/connect/login_success.html"; private const string TOKEN_KEY = "ATK"; private const string EXPIRY_DATE = "EXP"; private const string EXPIRY_DATE_BIN = "EXPB"; private const string FBID_KEY = "FBID"; private const string FBNAME_KEY = "FBNAME"; #endif public static string UserId { get; private set; } public static string UserName { get; set; } public static bool IsLoggedIn { get { return !string.IsNullOrEmpty(AccessToken); } } public static string AppId { get; private set; } public static string AccessToken { get; private set; } public static DateTime Expires { get; private set; } // check whether facebook is initialized public static bool IsInitialized { get { #if NETFX_CORE return _client != null; #else throw new PlatformNotSupportedException(""); #endif } } public static void Logout() { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || !IsLoggedIn) return; var uri = _client.GetLogoutUrl(new { access_token = AccessToken, next = _redirectUrl, display = "popup" }); _web.ClearCookies(); InvalidateData(); _web.Navigate(uri, false, (url, state) => { _web.Finish(); }, (url, error, state) => _web.Finish()); #else throw new PlatformNotSupportedException(""); #endif } public static void Login(string permissions, FacebookDelegate callback) { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || IsLoggedIn) { // Already in use if (callback != null) { callback(new FBResult() { Error = "Already in use" }); } return; } var uri = _client.GetLoginUrl(new { redirect_uri = _redirectUrl, scope = permissions, display = "popup", response_type = "token" }); _web.ClearCookies(); _web.Navigate(uri, true, onError: LoginNavigationError, state: callback, startedCallback: LoginNavigationStarted); if (_onHideUnity != null) { _onHideUnity(true); } #else throw new PlatformNotSupportedException(""); #endif } #if NETFX_CORE private static void LoginNavigationError(Uri url, int error, object state) { //Debug.LogError("Nav error: " + error); if (state is FacebookDelegate) ((FacebookDelegate)state)(new FBResult() { Error = error.ToString() }); _web.Finish(); if (_onHideUnity != null) _onHideUnity(false); } private static void LoginNavigationStarted(Uri url, object state) { FacebookOAuthResult result; // Check if we're waiting for user input or if login is complete if (_client.TryParseOAuthCallbackUrl(url, out result)) { // Login complete if (result.IsSuccess) { AccessToken = result.AccessToken; Expires = result.Expires; _client.AccessToken = AccessToken; Settings.Set(TOKEN_KEY, EncryptionProvider.Encrypt(AccessToken, AppId)); Settings.Set(EXPIRY_DATE_BIN, Expires.ToBinary()); } _web.Finish(); if (_onHideUnity != null) { _onHideUnity(false); } API("/me?fields=id,name", HttpMethod.GET, fbResult => { if (IsLoggedIn) { UserId = fbResult.Json["id"] as string; UserName = fbResult.Json["name"] as string; Settings.Set(FBID_KEY, UserId); Settings.Set(FBNAME_KEY, UserName); } if (state is FacebookDelegate) { JsonObject jResult = new JsonObject(); jResult.Add(new KeyValuePair<string, object>("authToken", AccessToken)); jResult.Add(new KeyValuePair<string, object>("authTokenExpiry", Expires.ToString())); ((FacebookDelegate)state)(new FBResult() { Json = jResult, Text = jResult.ToString() }); } }); } } #endif public static void Init( InitDelegate onInitComplete, string appId, HideUnityDelegate onHideUnity, string redirectUrl = null) { #if NETFX_CORE if (_client != null) { if (onInitComplete != null) onInitComplete(); return; } if (_web == null) throw new MissingPlatformException(); if (string.IsNullOrEmpty(appId)) throw new ArgumentException("Invalid Facebook App ID"); if (!string.IsNullOrEmpty(redirectUrl)) _redirectUrl = redirectUrl; _client = new FacebookClient(); _client.GetCompleted += HandleGetCompleted; AppId = _client.AppId = appId; _onHideUnity = onHideUnity; if (Settings.HasKey(TOKEN_KEY)) { AccessToken = EncryptionProvider.Decrypt(Settings.GetString(TOKEN_KEY), AppId); if (Settings.HasKey(EXPIRY_DATE)) { string expDate = EncryptionProvider.Decrypt(Settings.GetString(EXPIRY_DATE), AppId); Expires = DateTime.Parse(expDate, CultureInfo.InvariantCulture); } else { long expDate = Settings.GetLong(EXPIRY_DATE_BIN); Expires = DateTime.FromBinary(expDate); } _client.AccessToken = AccessToken; UserId = Settings.GetString(FBID_KEY); UserName = Settings.GetString(FBNAME_KEY); // verifies if the token has expired: if (DateTime.Compare(DateTime.UtcNow, Expires) > 0) InvalidateData(); //var task = TestAccessToken(); //task.Wait(); } if (onInitComplete != null) onInitComplete(); #else throw new PlatformNotSupportedException(""); #endif } public static void ChangeRedirect(string redirectUrl) { #if NETFX_CORE if (!string.IsNullOrEmpty(redirectUrl) && !_web.IsActive) _redirectUrl = redirectUrl; #endif } #if NETFX_CORE /// <summary> /// Test if the access token is still valid by making a simple API call /// </summary> /// <returns>The async task</returns> private static async Task TestAccessToken() { try { await _client.GetTaskAsync("/me?fields=id,name"); } catch (FacebookApiException) { // If any exception then auto login has been an issue. Set everything to null so the game // thinks the user is logged out and they can restart the login procedure InvalidateData(); } } private static void InvalidateData() { AccessToken = null; Expires = default(DateTime); UserId = null; UserName = null; _client.AccessToken = null; Settings.DeleteKey(TOKEN_KEY); Settings.DeleteKey(FBID_KEY); Settings.DeleteKey(FBNAME_KEY); Settings.DeleteKey(EXPIRY_DATE); Settings.DeleteKey(EXPIRY_DATE_BIN); } private static void HandleGetCompleted(object sender, FacebookApiEventArgs e) { var callback = e.UserState as FacebookDelegate; if (callback != null) { var result = new FBResult(); if (e.Cancelled) result.Error = "Cancelled"; else if (e.Error != null) result.Error = e.Error.Message; else { var obj = e.GetResultData(); result.Text = obj.ToString(); result.Json = obj as JsonObject; } Dispatcher.InvokeOnAppThread(() => { callback(result); }); } } #endif public static void API( string endpoint, HttpMethod method, FacebookDelegate callback, object parameters = null) { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (!IsLoggedIn) { // Already in use if (callback != null) callback(new FBResult() { Error = "Not logged in" }); return; } Task.Run(async () => { FBResult fbResult = null; try { object apiCall; if (method == HttpMethod.GET) { apiCall = await _client.GetTaskAsync(endpoint, parameters); } else if (method == HttpMethod.POST) { apiCall = await _client.PostTaskAsync(endpoint, parameters); } else { apiCall = await _client.DeleteTaskAsync(endpoint); } if (apiCall != null) { fbResult = new FBResult(); fbResult.Text = apiCall.ToString(); fbResult.Json = apiCall as JsonObject; } } catch (Exception ex) { fbResult = new FBResult(); fbResult.Error = ex.Message; } if (callback != null) { Dispatcher.InvokeOnAppThread(() => { callback(fbResult); }); } }); #else throw new PlatformNotSupportedException(""); #endif } public static void SetPlatformInterface(IWebInterface web) { #if NETFX_CORE _web = web; #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// Show Request Dialog. /// to, title, data, filters, excludeIds and maxRecipients are not currently supported at this time. /// </summary> public static void AppRequest( string message, string[] to = null, string filters = "", string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null ) { #if NETFX_CORE /// /// @note: [vaughan.sanders 15.8.14] We are overriding the Unity FB.AppRequest here to send a more /// general web style request as WP8 does not support the actual request functionality. /// Currently we ignore all but the message and callback params /// if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || !IsLoggedIn) { // Already in use if (callback != null) callback(new FBResult() { Error = "Already in use / Not Logged In" }); return; } if (_onHideUnity != null) _onHideUnity(true); Uri uri = new Uri("https://www.facebook.com/dialog/apprequests?app_id=" + AppId + "&message=" + message + "&display=popup&redirect_uri=" + _redirectUrl, UriKind.RelativeOrAbsolute); _web.Navigate(uri, true, finishedCallback: (url, state) => { if (url.ToString().StartsWith(_redirectUrl)) { // parsing query string to get request id and facebook ids of the people the request has been sent to // or error code and error messages FBResult fbResult = new FBResult(); fbResult.Json = new JsonObject(); string[] queries = url.Query.Split('&'); if (queries.Length > 0) { string request = string.Empty; List<string> toList = new List<string>(); foreach (string query in queries) { string[] keyValue = query.Split('='); if (keyValue.Length == 2) { if (keyValue[0].Contains("request")) request = keyValue[1]; else if (keyValue[0].Contains("to")) toList.Add(keyValue[1]); else if (keyValue[0].Contains("error_code")) fbResult.Error = keyValue[1]; else if (keyValue[0].Contains("error_message")) fbResult.Text = keyValue[1].Replace('+', ' '); } } if (!string.IsNullOrWhiteSpace(request)) { fbResult.Json.Add(new KeyValuePair<string, object>("request", request)); fbResult.Json.Add(new KeyValuePair<string, object>("to", toList)); } } // If there's no error, assign the success text if (string.IsNullOrWhiteSpace(fbResult.Text)) fbResult.Text = "Success"; _web.Finish(); if (_onHideUnity != null) _onHideUnity(false); if (callback != null) callback(fbResult); } }, onError: LoginNavigationError, state: callback); // throw not supported exception when user passed in parameters not supported currently if (!string.IsNullOrWhiteSpace(filters) || excludeIds != null || maxRecipients != null || to != null || !string.IsNullOrWhiteSpace(data) || !string.IsNullOrWhiteSpace(title)) throw new NotSupportedException("to, title, data, filters, excludeIds and maxRecipients are not currently supported at this time."); #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// Show the Feed Dialog. /// mediaSource, actionName, actionLink, reference and properties are not currently supported at this time. /// </summary> public static void Feed( string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string mediaSource = "", string actionName = "", string actionLink = "", string reference = "", Dictionary<string, string[]> properties = null, FacebookDelegate callback = null) { #if NETFX_CORE if (_web == null) throw new MissingPlatformException(); if (_web.IsActive || !IsLoggedIn) { // Already in use if (callback != null) callback(new FBResult() { Error = "Already in use / Not Logged In" }); return; } if (_onHideUnity != null) _onHideUnity(true); Uri uri = new Uri("https://www.facebook.com/dialog/feed?app_id=" + AppId + "&to=" + toId + "&link=" + link + "&name=" + linkName + "&caption=" + linkCaption + "&description=" + linkDescription + "&picture=" + picture + "&display=popup&redirect_uri=" + _redirectUrl, UriKind.RelativeOrAbsolute); _web.Navigate(uri, true, finishedCallback: (url, state) => { if (url.ToString().StartsWith(_redirectUrl)) { // parsing query string to get request id and facebook ids of the people the request has been sent to // or error code and error messages FBResult fbResult = new FBResult(); fbResult.Json = new JsonObject(); string[] queries = url.Query.Split('&'); if (queries.Length > 0) { string postId = string.Empty; List<string> toList = new List<string>(); foreach (string query in queries) { string[] keyValue = query.Split('='); if (keyValue.Length == 2) { if (keyValue[0].Contains("post_id")) postId = keyValue[1]; else if (keyValue[0].Contains("error_code")) fbResult.Error = keyValue[1]; else if (keyValue[0].Contains("error_msg")) fbResult.Text = keyValue[1].Replace('+', ' '); } } if (!string.IsNullOrWhiteSpace(postId)) { fbResult.Json.Add(new KeyValuePair<string, object>("post_id", postId)); } } // If there's no error, assign the success text if (string.IsNullOrWhiteSpace(fbResult.Text)) fbResult.Text = "Success"; _web.Finish(); if (_onHideUnity != null) _onHideUnity(false); if (callback != null) callback(fbResult); } }, onError: LoginNavigationError, state: callback); // throw not supported exception when user passed in parameters not supported currently if (!string.IsNullOrWhiteSpace(mediaSource) || !string.IsNullOrWhiteSpace(actionName) || !string.IsNullOrWhiteSpace(actionLink) || !string.IsNullOrWhiteSpace(reference) || properties != null) throw new NotSupportedException("mediaSource, actionName, actionLink, reference and properties are not currently supported at this time."); #else throw new PlatformNotSupportedException(""); #endif } } }
mit
yanaiela/easyEmbed
easyEmbed/easyEmbed.py
3380
# The interface file from embeddings import * class Embeddings(object): w2v = Word2Vec() glove = GloVe() w2vf = Word2VecF() # add more here... def download(emb_type, directory='~/.embeddings'): """ Downloads the required pre-trained Embedding :param emb_type: One of the supported Embedding classes (Word2Vec, GloVe etc..) :param directory: The directory where the file will be downloaded default dir: ~/.embeddings :return: the full path of the downloaded file """ if directory[-1] != SEP: directory += SEP if not (os.path.exists(directory) and os.path.isdir(directory)): print 'directory does not exist.. create one' os.makedirs(directory) f_emb = directory + emb_type.file if not os.path.exists(f_emb): print 'downloading the required file: ' + emb_type.name emb_type.download(directory) else: print 'file already exist..' return f_emb def persist_vocab_subset(emb_type, emb_file, word_set, missing_embed=lambda: np.random.rand(1, 300), normalize=False): """ Extracting the required vocabulary from the word embeddings. :param emb_type: One of the supported Embedding classes (Word2Vec, GloVe etc..) :param emb_file: The embedding file which was downloaded (should be the decompressed file) :param word_set: a list of string - all relevant words for the development stage this list can be empty, which will result keeping all of the embeddings :param missing_embed: a function which fills up an embedding vector when such is missing. default one is a random vector (1,300) taken from a uniform distribution over [0,1). It should return a numpy 1 dimension array with same dimension as the rest embeddings :return: vocab - dictionary mapping between word to the embeds index embeds - the new (diminished) word embeddings voc_path - the file path where the vocabulary dictionary was saved emb_path - the file path where the embedding matrix was saved """ emb_dir = SEP.join(emb_file.split(SEP)[:-1]) if (os.path.exists(emb_dir + '/' + emb_type.name + '_' + emb_type.REDUCED_VOC) and os.path.exists(emb_dir + '/' + emb_type.name + '_' + emb_type.REDUCED_EMB)): raise IOError('reduced files already exist, please delete them first') if not os.path.exists(emb_file): print emb_file raise ValueError('embedding file does not exist, please download the file first') vocab, embeds = emb_type.get_vectors(emb_file, word_set, missing_embed, normalize) voc_path, emb_path = emb_type.persist_reduced(vocab, embeds, emb_dir) return vocab, embeds, voc_path, emb_path def read_vocab_subset(emb_type, voc_path, emb_path): """ Reading and retrieving the reduced embeddings from persisted files :param emb_type: :param voc_path: path to the vocabulary dictionary :param emb_path: path to the embedding file :return: the vocabulary dictionary (maps between word and id) and the embedding mat """ if not (os.path.exists(voc_path) and os.path.exists(emb_path)): raise IOError('vocabulary / embedding binaries files doesn\'t exists') vocab, embeds = emb_type.load_reduced(voc_path, emb_path) return vocab, embeds
mit
edloidas/rollrobot
src/query/deprecated.js
367
const { deprecated } = require('../text'); /* Matches deprecated commands `sroll` or `droll` commands: `/sroll` - command for chat `/sroll@rollrobot` - command in group chat (named command) */ const regexp = /^\/(sroll|droll)(@rollrobot)?(\s[\s\S]*)*$/; const reply = () => deprecated; const title = 'Deprecated'; module.exports = { regexp, reply, title };
mit
anudeepsharma/azure-sdk-for-java
azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalImpl.java
2960
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.graphrbac.implementation; import com.microsoft.azure.Page; import com.microsoft.azure.management.apigeneration.LangDefinition; import com.microsoft.azure.management.graphrbac.ServicePrincipal; import com.microsoft.azure.management.resources.fluentcore.model.implementation.CreatableUpdatableImpl; import rx.Observable; import rx.functions.Func1; import java.util.List; /** * Implementation for ServicePrincipal and its parent interfaces. */ @LangDefinition(ContainerName = "/Microsoft.Azure.Management.Fluent.Graph.RBAC") class ServicePrincipalImpl extends CreatableUpdatableImpl<ServicePrincipal, ServicePrincipalInner, ServicePrincipalImpl> implements ServicePrincipal, ServicePrincipal.Definition, ServicePrincipal.Update { private ServicePrincipalsInner client; private ServicePrincipalCreateParametersInner createParameters; ServicePrincipalImpl(String appId, ServicePrincipalsInner client) { super(appId, new ServicePrincipalInner()); this.client = client; this.createParameters = new ServicePrincipalCreateParametersInner().withAppId(appId); } ServicePrincipalImpl(ServicePrincipalInner innerObject, ServicePrincipalsInner client) { super(innerObject.appId(), innerObject); this.client = client; this.createParameters = new ServicePrincipalCreateParametersInner(); } @Override public String objectId() { return inner().objectId(); } @Override public String objectType() { return inner().objectType(); } @Override public String displayName() { return inner().displayName(); } @Override public String appId() { return inner().appId(); } @Override public List<String> servicePrincipalNames() { return inner().servicePrincipalNames(); } @Override public ServicePrincipalImpl withAccountEnabled(boolean enabled) { createParameters.withAccountEnabled(enabled); return this; } @Override protected Observable<ServicePrincipalInner> getInnerAsync() { return client.listAsync(String.format("servicePrincipalNames/any(c:c eq '%s')", name())).map(new Func1<Page<ServicePrincipalInner>, ServicePrincipalInner>() { @Override public ServicePrincipalInner call(Page<ServicePrincipalInner> servicePrincipalInnerPage) { return servicePrincipalInnerPage.items().get(0); } }); } @Override public Observable<ServicePrincipal> createResourceAsync() { throw new UnsupportedOperationException("not implemented yet"); } @Override public boolean isInCreateMode() { return false; } }
mit
AnthonyHeikkinen/java-training
java-i-labwork/Laboration5/PolylinjeTest.java
576
class PolylinjeTest { public static void main (String[] args) { Punkt[] pArr = new Punkt[4]; pArr[0] = new Punkt ("A", 1, 2); pArr[1] = new Punkt ("B", 3, 1); pArr[2] = new Punkt ("C", 5, 7); pArr[3] = new Punkt ("D", 6, 5); Polylinje pl = new Polylinje (pArr); Punkt p = new Punkt ("B1", 4, 3 ); System.out.println ( pl ); System.out.println (pl.langd()); pl.laggTillFramfor( p, "a"); System.out.println (" Efter tillagd "); System.out.println (pl); pl.taBort("b1"); System.out.println ( "Efter borttagning" ); System.out.println (pl); } }
mit
ClickHandlerIO/dagger-gwt
src/main/java/dagger/mapkeys/LongKey.java
925
/* * Copyright (C) 2015 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.mapkeys; import dagger.MapKey; import java.lang.annotation.Documented; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; /** A {@link MapKey} annotation for maps with {@code long} keys. */ @Documented @Target(METHOD) @MapKey public @interface LongKey { long value(); }
mit
cklmercer/vue-events
src/index.js
3223
function plugin(Vue) { // Exit if the plugin has already been installed. if (plugin.installed) return // Create a `vm` to serve as our global event bus. const events = new Vue({ methods: { /** * Emit the given event. * * @param {string|object} event * @param {...*} args */ emit(event, ...args) { this.$emit(event, ...args) }, /** * Emit the given event. * * @param {string|object} event * @param {...*} args */ fire(event, ...args) { this.emit(event, ...args) }, /** * Listen for the given event. * * @param {string} event * @param {function} callback */ on(event, callback) { this.$on(event, callback) }, /** * Listen for the given event. * * @param {string} event * @param {function} callback */ listen(event, callback) { this.on(event, callback) }, /** * Listen for the given event once. * * @param {string} event * @param {function} callback */ once(event, callback) { this.$once(event, callback) }, /** * Remove one or more event listeners. * * @param {string} event * @param {function} callback */ off(event, callback) { this.$off(event, callback) }, /** * Remove one or more event listeners. * * @param {string} event * @param {function} callback */ remove(event, callback) { this.off(event, callback) } } }) // Extend `Vue.prototype` to include our global event bus. Object.defineProperty(Vue.prototype, '$events', { get() { return events } }) // Register a mixin that adds an `events` option to Vue 2.0 components. Vue.mixin({ // Hook into the Vue 2.0 `beforeCreate` life-cycle event. beforeCreate() { // Exit if there's no `events` option. if (typeof this.$options.events !== 'object') return // Cache of events to bound functions for automatic unsubscriptions var eventMap = {} // Loop through each event. for (var key in this.$options.events) { // Assign event type and bound function to map eventMap[key] = this.$options.events[key].bind(this) } // Listen for the `hook:beforeMount` Vue 2.0 life-cycle event. this.$once('hook:beforeMount', () => { // Loop through each event. for (var key in eventMap) { // Register a listener for the event. events.$on(key, eventMap[key]) } }) // Listen for the `hook:beforeDestroy` Vue 2.0 life-cycle event. this.$once('hook:beforeDestroy', () => { // Loop through each event. for (var key in eventMap) { // Register a listener for the event. events.$off(key, eventMap[key]) } // Release cache eventMap = null }) } }) } // Check for `window.Vue` if (typeof window !== 'undefined' && window.Vue) { // Install plugin automatically. window.Vue.use(plugin) } export default plugin
mit
iiet/iiet-git
spec/services/merge_requests/close_service_spec.rb
2984
# frozen_string_literal: true require 'spec_helper' describe MergeRequests::CloseService do let(:user) { create(:user) } let(:user2) { create(:user) } let(:guest) { create(:user) } let(:merge_request) { create(:merge_request, assignees: [user2], author: create(:user)) } let(:project) { merge_request.project } let!(:todo) { create(:todo, :assigned, user: user, project: project, target: merge_request, author: user2) } before do project.add_maintainer(user) project.add_developer(user2) project.add_guest(guest) end describe '#execute' do it_behaves_like 'cache counters invalidator' context 'valid params' do let(:service) { described_class.new(project, user, {}) } before do allow(service).to receive(:execute_hooks) perform_enqueued_jobs do @merge_request = service.execute(merge_request) end end it { expect(@merge_request).to be_valid } it { expect(@merge_request).to be_closed } it 'executes hooks with close action' do expect(service).to have_received(:execute_hooks) .with(@merge_request, 'close') end it 'sends email to user2 about assign of new merge_request' do email = ActionMailer::Base.deliveries.last expect(email.to.first).to eq(user2.email) expect(email.subject).to include(merge_request.title) end it 'creates system note about merge_request reassign' do note = @merge_request.notes.last expect(note.note).to include 'closed' end it 'marks todos as done' do expect(todo.reload).to be_done end end it 'updates metrics' do metrics = merge_request.metrics metrics_service = double(MergeRequestMetricsService) allow(MergeRequestMetricsService) .to receive(:new) .with(metrics) .and_return(metrics_service) expect(metrics_service).to receive(:close) described_class.new(project, user, {}).execute(merge_request) end it 'refreshes the number of open merge requests for a valid MR', :use_clean_rails_memory_store_caching do service = described_class.new(project, user, {}) expect { service.execute(merge_request) } .to change { project.open_merge_requests_count }.from(1).to(0) end it 'clean up environments for the merge request' do expect_next_instance_of(Ci::StopEnvironmentsService) do |service| expect(service).to receive(:execute_for_merge_request).with(merge_request) end described_class.new(project, user).execute(merge_request) end context 'current user is not authorized to close merge request' do before do perform_enqueued_jobs do @merge_request = described_class.new(project, guest).execute(merge_request) end end it 'does not close the merge request' do expect(@merge_request).to be_open end end end end
mit
CodeToSurvive1/reliable-master
web/controllers/home.js
349
'use strict'; function *getContext() { let context = {}; context.session = this.session; let page = {}; context.csrf = this.csrf; page.name = 'home'; context.page = page; return context; } function *dispatch() { const context = yield getContext.call(this); this.body = this.render('home', context); } module.exports = dispatch;
mit
karim/adila
database/src/main/java/adila/db/batman_lg2df100l.java
214
// This file is automatically generated. package adila.db; /* * LG Optimus Vu * * DEVICE: batman * MODEL: LG-F100L */ final class batman_lg2df100l { public static final String DATA = "LG|Optimus Vu|"; }
mit
docwhite/appleseed
src/appleseed/renderer/modeling/material/materialfactoryregistrar.cpp
3248
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "materialfactoryregistrar.h" // appleseed.renderer headers. #include "renderer/modeling/material/genericmaterial.h" #include "renderer/modeling/material/material.h" #ifdef APPLESEED_WITH_OSL #include "renderer/modeling/material/oslmaterial.h" #endif #ifdef APPLESEED_WITH_DISNEY_MATERIAL #include "renderer/modeling/material/disneymaterial.h" #endif // appleseed.foundation headers. #include "foundation/utility/foreach.h" #include "foundation/utility/registrar.h" // Standard headers. #include <cassert> #include <string> using namespace foundation; using namespace std; namespace renderer { APPLESEED_DEFINE_ARRAY(MaterialFactoryArray); struct MaterialFactoryRegistrar::Impl { Registrar<IMaterialFactory> m_registrar; }; MaterialFactoryRegistrar::MaterialFactoryRegistrar() : impl(new Impl()) { register_factory(auto_ptr<FactoryType>(new GenericMaterialFactory())); #ifdef APPLESEED_WITH_OSL register_factory(auto_ptr<FactoryType>(new OSLMaterialFactory())); #endif #ifdef APPLESEED_WITH_DISNEY_MATERIAL register_factory(auto_ptr<FactoryType>(new DisneyMaterialFactory())); #endif } MaterialFactoryRegistrar::~MaterialFactoryRegistrar() { delete impl; } void MaterialFactoryRegistrar::register_factory(auto_ptr<FactoryType> factory) { const string model = factory->get_model(); impl->m_registrar.insert(model, factory); } MaterialFactoryArray MaterialFactoryRegistrar::get_factories() const { FactoryArrayType factories; for (const_each<Registrar<FactoryType>::Items> i = impl->m_registrar.items(); i; ++i) factories.push_back(i->second); return factories; } const MaterialFactoryRegistrar::FactoryType* MaterialFactoryRegistrar::lookup(const char* name) const { assert(name); return impl->m_registrar.lookup(name); } } // namespace renderer
mit
dancannon/PHP-WowApi
lib/WowApi/Request/AbstractRequest.php
6188
<?php namespace WowApi\Request; use WowApi\Client; use WowApi\Exception\ApiException; use WowApi\Exception\RequestException; use WowApi\Exception\NotFoundException; use WowApi\Cache\CacheInterface; use WowApi\ParameterBag; use WowApi\Utilities; abstract class AbstractRequest implements RequestInterface { /** * @var null|\WowApi\Request\HeaderBag */ public $headers = null; /** * @var null|\WowApi\Client */ protected $client = null; public function __construct() { $this->headers = new HeaderBag(array( 'Expect' => '', 'Accept-Charset' => 'UTF-8', 'Accept-Encoding' => 'compress, gzip', 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'User-Agent' => 'PHP WowApi (http://github.com/dancannon/PHP-WowApi)', )); } public function setClient(Client $client) { $this->client = $client; } public function get($path, array $parameters = array()) { return $this->api($path, 'GET', $parameters); } public function post($path, array $parameters = array()) { return $this->api($path, 'POST', $parameters); } public function put($path, array $parameters = array()) { return $this->api($path, 'PUT', $parameters); } public function delete($path, array $parameters = array()) { return $this->api($path, 'DELETE', $parameters); } public function api($path, $method = 'GET', array $parameters = array()) { //Set the path to the full path before checking the cache $path = $this->getFullPath($path); //Make request if($method === 'GET') { $url = $this->getUrl($path, $parameters); } else { $url = $this->getUrl($path); } $this->signRequest($path, $method); return $this->send($url, $method, $parameters); } public function send($url, $method='GET', array $parameters=array()) { // Check the cache if($cache = $this->isCached($url, $parameters)) { if ($cache && isset($cache['cachedAt']) && (time() - $cache['cachedAt']) < $this->client->options->get('ttl')) { $response['modified'] = false; return $cache; } if (isset($cache) && isset($cache['lastModified'])) { $this->headers->set('If-Modified-Since', date(DATE_RFC1123, $cache['lastModified'])); } } $response = $this->makeRequest($url, $method, $parameters); $httpCode = $response['headers']['http_code']; if (isset($cache) && $httpCode === 304) { $cache['modified'] = false; return $cache; } else { $response = json_decode($response['response'], true); // Check for errors if($httpCode === 404) { if ($response !== false && isset($response['reason'])) { throw new NotFoundException($response['reason']); } else { throw new NotFoundException("Page not found."); } } elseif ($httpCode !== 200 || !$response) { if ($response !== false && isset($response['reason'])) { throw new ApiException($response['reason'], $httpCode); } else { throw new ApiException("Unknown error.", $httpCode); } } } $this->cache($url, $parameters, $response); $response['modified'] = true; return $response; } protected function isCached($path, $parameters) { $cache = $this->client->getCache()->getCachedResponse($path, $parameters); if (($cache !== false)) { $cache = json_decode($cache, true); if($cache) { return $cache; } } return false; } protected function cache($path, $parameters, $response) { if(isset($response['lastModified'])) { $response['lastModified'] = round($response['lastModified']/1000); } $response['cachedAt'] = time(); $cache = json_encode($response); $this->client->getCache()->setCachedResponse($path, $parameters, $cache); } protected function signRequest($path, $method) { // Attempt to authenticate application $publicKey = $this->client->options->get('publicKey'); $privateKey = $this->client->options->get('privateKey'); if ($publicKey !== null && $privateKey !== null) { $date = gmdate(DATE_RFC1123); //Signed requests don't like certain some characters, but urldecode changes too many $badCharacters = array('%21', '%26', '%27', '%28', '%29', '%3A', '%40'); $goodCharacters = array('!', '&', '\'', '(', ')', ':', '@'); $path = str_replace($badCharacters, $goodCharacters, $path); $stringToSign = "$method\n" . $date . "\n".$path."\n"; $signature = base64_encode(hash_hmac('sha1',$stringToSign, $privateKey, true)); $this->headers->set("Authorization", "BNET" . " " . $publicKey . ":" . $signature); $this->headers->set("Date", $date); } } protected function getFullPath($path) { $replacements[':path'] = trim($path, '/'); return strtr($this->client->options->get('fullPath'), $replacements); } protected function getUrl($path, $queryParams=array()) { $replacements = array(); $replacements[':protocol'] = $this->client->options->get('protocol'); $replacements[':region'] = $this->client->options->get('region'); $replacements[':fullPath'] = $path; $url = strtr($this->client->options->get('url'), $replacements); //Add locale to query parameters $queryParams['locale'] = $this->client->options->get('locale'); if(!empty($queryParams)) { $url .= Utilities::build_http_query($queryParams); } return $url; } }
mit
code-master5/CP-Personal
lintcode/12_min_stack.cpp
715
class MinStack { stack <int> stk, minStk; public: MinStack() { // do intialization if necessary } /* * @param number: An integer * @return: nothing */ void push(int number) { stk.push(number); if (minStk.empty() || ( number <= minStk.top())) { minStk.push(number); } } /* * @return: An integer */ int pop() { // write your code here int number = stk.top(); stk.pop(); if (number == minStk.top()) minStk.pop(); return number; } /* * @return: An integer */ int min() { // write your code here return minStk.top(); } };
mit
maxxyPhp/fifagoal
public/assets/js/datepicker/bootstrap-datepicker.js
46866
/* ========================================================= * bootstrap-datepicker.js * Repo: https://github.com/eternicode/bootstrap-datepicker/ * Demo: http://eternicode.github.io/bootstrap-datepicker/ * Docs: http://bootstrap-datepicker.readthedocs.org/ * Forked from http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Started by Stefan Petre; improvements by Andrew Rowls + contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ (function($, undefined){ var $window = $(window); function UTCDate(){ return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday(){ var today = new Date(); return UTCDate(today.getFullYear(), today.getMonth(), today.getDate()); } function alias(method){ return function(){ return this[method].apply(this, arguments); }; } var DateArray = (function(){ var extras = { get: function(i){ return this.slice(i)[0]; }, contains: function(d){ // Array.indexOf is not cross-browser; // $.inArray doesn't work with Dates var val = d && d.valueOf(); for (var i=0, l=this.length; i < l; i++) if (this[i].valueOf() === val) return i; return -1; }, remove: function(i){ this.splice(i,1); }, replace: function(new_array){ if (!new_array) return; if (!$.isArray(new_array)) new_array = [new_array]; this.clear(); this.push.apply(this, new_array); }, clear: function(){ this.splice(0); }, copy: function(){ var a = new DateArray(); a.replace(this); return a; } }; return function(){ var a = []; a.push.apply(a, arguments); $.extend(a, extras); return a; }; })(); // Picker object var Datepicker = function(element, options){ this.dates = new DateArray(); this.viewDate = UTCToday(); this.focusDate = null; this._process_options(options); this.element = $(element); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on, .input-group-addon, .btn') : false; this.hasInput = this.component && this.element.find('input').length; if (this.component && this.component.length === 0) this.component = false; this.picker = $(DPGlobal.template); this._buildEvents(); this._attachEvents(); if (this.isInline){ this.picker.addClass('datepicker-inline').appendTo(this.element); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.o.rtl){ this.picker.addClass('datepicker-rtl'); } this.viewMode = this.o.startView; if (this.o.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function(i, val){ return parseInt(val) + 1; }); this._allow_update = false; this.setStartDate(this._o.startDate); this.setEndDate(this._o.endDate); this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled); this.fillDow(); this.fillMonths(); this._allow_update = true; this.update(); this.showMode(); if (this.isInline){ this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _process_options: function(opts){ // Store raw options for reference this._o = $.extend({}, this._o, opts); // Processed options var o = this.o = $.extend({}, this._o); // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" var lang = o.language; if (!dates[lang]){ lang = lang.split('-')[0]; if (!dates[lang]) lang = defaults.language; } o.language = lang; switch (o.startView){ case 2: case 'decade': o.startView = 2; break; case 1: case 'year': o.startView = 1; break; default: o.startView = 0; } switch (o.minViewMode){ case 1: case 'months': o.minViewMode = 1; break; case 2: case 'years': o.minViewMode = 2; break; default: o.minViewMode = 0; } o.startView = Math.max(o.startView, o.minViewMode); // true, false, or Number > 0 if (o.multidate !== true){ o.multidate = Number(o.multidate) || false; if (o.multidate !== false) o.multidate = Math.max(0, o.multidate); else o.multidate = 1; } o.multidateSeparator = String(o.multidateSeparator); o.weekStart %= 7; o.weekEnd = ((o.weekStart + 6) % 7); var format = DPGlobal.parseFormat(o.format); if (o.startDate !== -Infinity){ if (!!o.startDate){ if (o.startDate instanceof Date) o.startDate = this._local_to_utc(this._zero_time(o.startDate)); else o.startDate = DPGlobal.parseDate(o.startDate, format, o.language); } else { o.startDate = -Infinity; } } if (o.endDate !== Infinity){ if (!!o.endDate){ if (o.endDate instanceof Date) o.endDate = this._local_to_utc(this._zero_time(o.endDate)); else o.endDate = DPGlobal.parseDate(o.endDate, format, o.language); } else { o.endDate = Infinity; } } o.daysOfWeekDisabled = o.daysOfWeekDisabled||[]; if (!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/); o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function(d){ return parseInt(d, 10); }); var plc = String(o.orientation).toLowerCase().split(/\s+/g), _plc = o.orientation.toLowerCase(); plc = $.grep(plc, function(word){ return (/^auto|left|right|top|bottom$/).test(word); }); o.orientation = {x: 'auto', y: 'auto'}; if (!_plc || _plc === 'auto') ; // no action else if (plc.length === 1){ switch (plc[0]){ case 'top': case 'bottom': o.orientation.y = plc[0]; break; case 'left': case 'right': o.orientation.x = plc[0]; break; } } else { _plc = $.grep(plc, function(word){ return (/^left|right$/).test(word); }); o.orientation.x = _plc[0] || 'auto'; _plc = $.grep(plc, function(word){ return (/^top|bottom$/).test(word); }); o.orientation.y = _plc[0] || 'auto'; } }, _events: [], _secondaryEvents: [], _applyEvents: function(evs){ for (var i=0, el, ch, ev; i < evs.length; i++){ el = evs[i][0]; if (evs[i].length === 2){ ch = undefined; ev = evs[i][1]; } else if (evs[i].length === 3){ ch = evs[i][1]; ev = evs[i][2]; } el.on(ev, ch); } }, _unapplyEvents: function(evs){ for (var i=0, el, ev, ch; i < evs.length; i++){ el = evs[i][0]; if (evs[i].length === 2){ ch = undefined; ev = evs[i][1]; } else if (evs[i].length === 3){ ch = evs[i][1]; ev = evs[i][2]; } el.off(ev, ch); } }, _buildEvents: function(){ if (this.isInput){ // single input this._events = [ [this.element, { focus: $.proxy(this.show, this), keyup: $.proxy(function(e){ if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1) this.update(); }, this), keydown: $.proxy(this.keydown, this) }] ]; } else if (this.component && this.hasInput){ // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(function(e){ if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1) this.update(); }, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')){ // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } this._events.push( // Component: listen for blur on element descendants [this.element, '*', { blur: $.proxy(function(e){ this._focused_from = e.target; }, this) }], // Input: listen for blur on element [this.element, { blur: $.proxy(function(e){ this._focused_from = e.target; }, this) }] ); this._secondaryEvents = [ [this.picker, { click: $.proxy(this.click, this) }], [$(window), { resize: $.proxy(this.place, this) }], [$(document), { 'mousedown touchstart': $.proxy(function(e){ // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || this.element.find(e.target).length || this.picker.is(e.target) || this.picker.find(e.target).length )){ this.hide(); } }, this) }] ]; }, _attachEvents: function(){ this._detachEvents(); this._applyEvents(this._events); }, _detachEvents: function(){ this._unapplyEvents(this._events); }, _attachSecondaryEvents: function(){ this._detachSecondaryEvents(); this._applyEvents(this._secondaryEvents); }, _detachSecondaryEvents: function(){ this._unapplyEvents(this._secondaryEvents); }, _trigger: function(event, altdate){ var date = altdate || this.dates.get(-1), local_date = this._utc_to_local(date); this.element.trigger({ type: event, date: local_date, dates: $.map(this.dates, this._utc_to_local), format: $.proxy(function(ix, format){ if (arguments.length === 0){ ix = this.dates.length - 1; format = this.o.format; } else if (typeof ix === 'string'){ format = ix; ix = this.dates.length - 1; } format = format || this.o.format; var date = this.dates.get(ix); return DPGlobal.formatDate(date, format, this.o.language); }, this) }); }, show: function(){ if (!this.isInline) this.picker.appendTo('body'); this.picker.show(); this.place(); this._attachSecondaryEvents(); this._trigger('show'); }, hide: function(){ if (this.isInline) return; if (!this.picker.is(':visible')) return; this.focusDate = null; this.picker.hide().detach(); this._detachSecondaryEvents(); this.viewMode = this.o.startView; this.showMode(); if ( this.o.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this._trigger('hide'); }, remove: function(){ this.hide(); this._detachEvents(); this._detachSecondaryEvents(); this.picker.remove(); delete this.element.data().datepicker; if (!this.isInput){ delete this.element.data().date; } }, _utc_to_local: function(utc){ return utc && new Date(utc.getTime() + (utc.getTimezoneOffset()*60000)); }, _local_to_utc: function(local){ return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000)); }, _zero_time: function(local){ return local && new Date(local.getFullYear(), local.getMonth(), local.getDate()); }, _zero_utc_time: function(utc){ return utc && new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate())); }, getDates: function(){ return $.map(this.dates, this._utc_to_local); }, getUTCDates: function(){ return $.map(this.dates, function(d){ return new Date(d); }); }, getDate: function(){ return this._utc_to_local(this.getUTCDate()); }, getUTCDate: function(){ return new Date(this.dates.get(-1)); }, setDates: function(){ var args = $.isArray(arguments[0]) ? arguments[0] : arguments; this.update.apply(this, args); this._trigger('changeDate'); this.setValue(); }, setUTCDates: function(){ var args = $.isArray(arguments[0]) ? arguments[0] : arguments; this.update.apply(this, $.map(args, this._utc_to_local)); this._trigger('changeDate'); this.setValue(); }, setDate: alias('setDates'), setUTCDate: alias('setUTCDates'), setValue: function(){ var formatted = this.getFormattedDate(); if (!this.isInput){ if (this.component){ this.element.find('input').val(formatted).change(); } } else { this.element.val(formatted).change(); } }, getFormattedDate: function(format){ if (format === undefined) format = this.o.format; var lang = this.o.language; return $.map(this.dates, function(d){ return DPGlobal.formatDate(d, format, lang); }).join(this.o.multidateSeparator); }, setStartDate: function(startDate){ this._process_options({startDate: startDate}); this.update(); this.updateNavArrows(); }, setEndDate: function(endDate){ this._process_options({endDate: endDate}); this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function(daysOfWeekDisabled){ this._process_options({daysOfWeekDisabled: daysOfWeekDisabled}); this.update(); this.updateNavArrows(); }, place: function(){ if (this.isInline) return; var calendarWidth = this.picker.outerWidth(), calendarHeight = this.picker.outerHeight(), visualPadding = 10, windowWidth = $window.width(), windowHeight = $window.height(), scrollTop = $window.scrollTop(); var zIndex = parseInt(this.element.parents().filter(function(){ return $(this).css('z-index') !== 'auto'; }).first().css('z-index'))+10; var offset = this.component ? this.component.parent().offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false); var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false); var left = offset.left, top = offset.top; this.picker.removeClass( 'datepicker-orient-top datepicker-orient-bottom '+ 'datepicker-orient-right datepicker-orient-left' ); if (this.o.orientation.x !== 'auto'){ this.picker.addClass('datepicker-orient-' + this.o.orientation.x); if (this.o.orientation.x === 'right') left -= calendarWidth - width; } // auto x orientation is best-placement: if it crosses a window // edge, fudge it sideways else { // Default to left this.picker.addClass('datepicker-orient-left'); if (offset.left < 0) left -= offset.left - visualPadding; else if (offset.left + calendarWidth > windowWidth) left = windowWidth - calendarWidth - visualPadding; } // auto y orientation is best-situation: top or bottom, no fudging, // decision based on which shows more of the calendar var yorient = this.o.orientation.y, top_overflow, bottom_overflow; if (yorient === 'auto'){ top_overflow = -scrollTop + offset.top - calendarHeight; bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight); if (Math.max(top_overflow, bottom_overflow) === bottom_overflow) yorient = 'top'; else yorient = 'bottom'; } this.picker.addClass('datepicker-orient-' + yorient); if (yorient === 'top') top += height; else top -= calendarHeight + parseInt(this.picker.css('padding-top')); this.picker.css({ top: top, left: left, zIndex: zIndex }); }, _allow_update: true, update: function(){ if (!this._allow_update) return; var oldDates = this.dates.copy(), dates = [], fromArgs = false; if (arguments.length){ $.each(arguments, $.proxy(function(i, date){ if (date instanceof Date) date = this._local_to_utc(date); dates.push(date); }, this)); fromArgs = true; } else { dates = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); if (dates && this.o.multidate) dates = dates.split(this.o.multidateSeparator); else dates = [dates]; delete this.element.data().date; } dates = $.map(dates, $.proxy(function(date){ return DPGlobal.parseDate(date, this.o.format, this.o.language); }, this)); dates = $.grep(dates, $.proxy(function(date){ return ( date < this.o.startDate || date > this.o.endDate || !date ); }, this), true); this.dates.replace(dates); if (this.dates.length) this.viewDate = new Date(this.dates.get(-1)); else if (this.viewDate < this.o.startDate) this.viewDate = new Date(this.o.startDate); else if (this.viewDate > this.o.endDate) this.viewDate = new Date(this.o.endDate); if (fromArgs){ // setting date by clicking this.setValue(); } else if (dates.length){ // setting date by typing if (String(oldDates) !== String(this.dates)) this._trigger('changeDate'); } if (!this.dates.length && oldDates.length) this._trigger('clearDate'); this.fill(); }, fillDow: function(){ var dowCnt = this.o.weekStart, html = '<tr>'; if (this.o.calendarWeeks){ var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.o.weekStart + 7){ html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function(){ var html = '', i = 0; while (i < 12){ html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>'; } this.picker.find('.datepicker-months td').html(html); }, setRange: function(range){ if (!range || !range.length) delete this.range; else this.range = $.map(range, function(d){ return d.valueOf(); }); this.fill(); }, getClassNames: function(date){ var cls = [], year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), today = new Date(); if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)){ cls.push('old'); } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)){ cls.push('new'); } if (this.focusDate && date.valueOf() === this.focusDate.valueOf()) cls.push('focused'); // Compare internal UTC date with local today, not UTC today if (this.o.todayHighlight && date.getUTCFullYear() === today.getFullYear() && date.getUTCMonth() === today.getMonth() && date.getUTCDate() === today.getDate()){ cls.push('today'); } if (this.dates.contains(date) !== -1) cls.push('active'); if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate || $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1){ cls.push('disabled'); } if (this.range){ if (date > this.range[0] && date < this.range[this.range.length-1]){ cls.push('range'); } if ($.inArray(date.valueOf(), this.range) !== -1){ cls.push('selected'); } } return cls; }, fill: function(){ var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity, startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity, endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity, endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity, todaytxt = dates[this.o.language].today || dates['en'].today || '', cleartxt = dates[this.o.language].clear || dates['en'].clear || '', tooltip; this.picker.find('.datepicker-days thead th.datepicker-switch') .text(dates[this.o.language].months[month]+' '+year); this.picker.find('tfoot th.today') .text(todaytxt) .toggle(this.o.todayBtn !== false); this.picker.find('tfoot th.clear') .text(cleartxt) .toggle(this.o.clearBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month-1, 28), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while (prevMonth.valueOf() < nextMonth){ if (prevMonth.getUTCDay() === this.o.weekStart){ html.push('<tr>'); if (this.o.calendarWeeks){ // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">'+ calWeek +'</td>'); } } clsName = this.getClassNames(prevMonth); clsName.push('day'); if (this.o.beforeShowDay !== $.noop){ var before = this.o.beforeShowDay(this._utc_to_local(prevMonth)); if (before === undefined) before = {}; else if (typeof(before) === 'boolean') before = {enabled: before}; else if (typeof(before) === 'string') before = {classes: before}; if (before.enabled === false) clsName.push('disabled'); if (before.classes) clsName = clsName.concat(before.classes.split(/\s+/)); if (before.tooltip) tooltip = before.tooltip; } clsName = $.unique(clsName); html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() === this.o.weekEnd){ html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate()+1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); $.each(this.dates, function(i, d){ if (d.getUTCFullYear() === year) months.eq(d.getUTCMonth()).addClass('active'); }); if (year < startYear || year > endYear){ months.addClass('disabled'); } if (year === startYear){ months.slice(0, startMonth).addClass('disabled'); } if (year === endYear){ months.slice(endMonth+1).addClass('disabled'); } html = ''; year = parseInt(year/10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; var years = $.map(this.dates, function(d){ return d.getUTCFullYear(); }), classes; for (var i = -1; i < 11; i++){ classes = ['year']; if (i === -1) classes.push('old'); else if (i === 10) classes.push('new'); if ($.inArray(year, years) !== -1) classes.push('active'); if (year < startYear || year > endYear) classes.push('disabled'); html += '<span class="' + classes.join(' ') + '">'+year+'</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function(){ if (!this._allow_update) return; var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode){ case 0: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()){ this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()){ this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: case 2: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()){ this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()){ this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, click: function(e){ e.preventDefault(); var target = $(e.target).closest('span, td, th'), year, month, day; if (target.length === 1){ switch (target[0].nodeName.toLowerCase()){ case 'th': switch (target[0].className){ case 'datepicker-switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1); switch (this.viewMode){ case 0: this.viewDate = this.moveMonth(this.viewDate, dir); this._trigger('changeMonth', this.viewDate); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); if (this.viewMode === 1) this._trigger('changeYear', this.viewDate); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.o.todayBtn === 'linked' ? null : 'view'; this._setDate(date, which); break; case 'clear': var element; if (this.isInput) element = this.element; else if (this.component) element = this.element.find('input'); if (element) element.val("").change(); this.update(); this._trigger('changeDate'); if (this.o.autoclose) this.hide(); break; } break; case 'span': if (!target.is('.disabled')){ this.viewDate.setUTCDate(1); if (target.is('.month')){ day = 1; month = target.parent().find('span').index(target); year = this.viewDate.getUTCFullYear(); this.viewDate.setUTCMonth(month); this._trigger('changeMonth', this.viewDate); if (this.o.minViewMode === 1){ this._setDate(UTCDate(year, month, day)); } } else { day = 1; month = 0; year = parseInt(target.text(), 10)||0; this.viewDate.setUTCFullYear(year); this._trigger('changeYear', this.viewDate); if (this.o.minViewMode === 2){ this._setDate(UTCDate(year, month, day)); } } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')){ day = parseInt(target.text(), 10)||1; year = this.viewDate.getUTCFullYear(); month = this.viewDate.getUTCMonth(); if (target.is('.old')){ if (month === 0){ month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')){ if (month === 11){ month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day)); } break; } } if (this.picker.is(':visible') && this._focused_from){ $(this._focused_from).focus(); } delete this._focused_from; }, _toggle_multidate: function(date){ var ix = this.dates.contains(date); if (!date){ this.dates.clear(); } else if (ix !== -1){ this.dates.remove(ix); } else { this.dates.push(date); } if (typeof this.o.multidate === 'number') while (this.dates.length > this.o.multidate) this.dates.remove(0); }, _setDate: function(date, which){ if (!which || which === 'date') this._toggle_multidate(date && new Date(date)); if (!which || which === 'view') this.viewDate = date && new Date(date); this.fill(); this.setValue(); this._trigger('changeDate'); var element; if (this.isInput){ element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element){ element.change(); } if (this.o.autoclose && (!which || which === 'date')){ this.hide(); } }, moveMonth: function(date, dir){ if (!date) return undefined; if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag === 1){ test = dir === -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function(){ return new_date.getUTCMonth() === month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function(){ return new_date.getUTCMonth() !== new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i=0; i < mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function(){ return new_month !== new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()){ new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function(date, dir){ return this.moveMonth(date, dir*12); }, dateWithinRange: function(date){ return date >= this.o.startDate && date <= this.o.endDate; }, keydown: function(e){ if (this.picker.is(':not(:visible)')){ if (e.keyCode === 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, newDate, newViewDate, focusDate = this.focusDate || this.viewDate; switch (e.keyCode){ case 27: // escape if (this.focusDate){ this.focusDate = null; this.viewDate = this.dates.get(-1) || this.viewDate; this.fill(); } else this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.o.keyboardNavigation) break; dir = e.keyCode === 37 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir); newViewDate = this.moveYear(focusDate, dir); this._trigger('changeYear', this.viewDate); } else if (e.shiftKey){ newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir); newViewDate = this.moveMonth(focusDate, dir); this._trigger('changeMonth', this.viewDate); } else { newDate = new Date(this.dates.get(-1) || UTCToday()); newDate.setUTCDate(newDate.getUTCDate() + dir); newViewDate = new Date(focusDate); newViewDate.setUTCDate(focusDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)){ this.focusDate = this.viewDate = newViewDate; this.setValue(); this.fill(); e.preventDefault(); } break; case 38: // up case 40: // down if (!this.o.keyboardNavigation) break; dir = e.keyCode === 38 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir); newViewDate = this.moveYear(focusDate, dir); this._trigger('changeYear', this.viewDate); } else if (e.shiftKey){ newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir); newViewDate = this.moveMonth(focusDate, dir); this._trigger('changeMonth', this.viewDate); } else { newDate = new Date(this.dates.get(-1) || UTCToday()); newDate.setUTCDate(newDate.getUTCDate() + dir * 7); newViewDate = new Date(focusDate); newViewDate.setUTCDate(focusDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)){ this.focusDate = this.viewDate = newViewDate; this.setValue(); this.fill(); e.preventDefault(); } break; case 32: // spacebar // Spacebar is used in manually typing dates in some formats. // As such, its behavior should not be hijacked. break; case 13: // enter focusDate = this.focusDate || this.dates.get(-1) || this.viewDate; this._toggle_multidate(focusDate); dateChanged = true; this.focusDate = null; this.viewDate = this.dates.get(-1) || this.viewDate; this.setValue(); this.fill(); if (this.picker.is(':visible')){ e.preventDefault(); if (this.o.autoclose) this.hide(); } break; case 9: // tab this.focusDate = null; this.viewDate = this.dates.get(-1) || this.viewDate; this.fill(); this.hide(); break; } if (dateChanged){ if (this.dates.length) this._trigger('changeDate'); else this._trigger('clearDate'); var element; if (this.isInput){ element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element){ element.change(); } } }, showMode: function(dir){ if (dir){ this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir)); } this.picker .find('>div') .hide() .filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName) .css('display', 'block'); this.updateNavArrows(); } }; var DateRangePicker = function(element, options){ this.element = $(element); this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; }); delete options.inputs; $(this.inputs) .datepicker(options) .bind('changeDate', $.proxy(this.dateUpdated, this)); this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); }); this.updateDates(); }; DateRangePicker.prototype = { updateDates: function(){ this.dates = $.map(this.pickers, function(i){ return i.getUTCDate(); }); this.updateRanges(); }, updateRanges: function(){ var range = $.map(this.dates, function(d){ return d.valueOf(); }); $.each(this.pickers, function(i, p){ p.setRange(range); }); }, dateUpdated: function(e){ // `this.updating` is a workaround for preventing infinite recursion // between `changeDate` triggering and `setUTCDate` calling. Until // there is a better mechanism. if (this.updating) return; this.updating = true; var dp = $(e.target).data('datepicker'), new_date = dp.getUTCDate(), i = $.inArray(e.target, this.inputs), l = this.inputs.length; if (i === -1) return; $.each(this.pickers, function(i, p){ if (!p.getUTCDate()) p.setUTCDate(new_date); }); if (new_date < this.dates[i]){ // Date being moved earlier/left while (i >= 0 && new_date < this.dates[i]){ this.pickers[i--].setUTCDate(new_date); } } else if (new_date > this.dates[i]){ // Date being moved later/right while (i < l && new_date > this.dates[i]){ this.pickers[i++].setUTCDate(new_date); } } this.updateDates(); delete this.updating; }, remove: function(){ $.map(this.pickers, function(p){ p.remove(); }); delete this.element.data().datepicker; } }; function opts_from_el(el, prefix){ // Derive options from element data-attrs var data = $(el).data(), out = {}, inkey, replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'); prefix = new RegExp('^' + prefix.toLowerCase()); function re_lower(_,a){ return a.toLowerCase(); } for (var key in data) if (prefix.test(key)){ inkey = key.replace(replace, re_lower); out[inkey] = data[key]; } return out; } function opts_from_locale(lang){ // Derive options from locale plugins var out = {}; // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" if (!dates[lang]){ lang = lang.split('-')[0]; if (!dates[lang]) return; } var d = dates[lang]; $.each(locale_opts, function(i,k){ if (k in d) out[k] = d[k]; }); return out; } var old = $.fn.datepicker; $.fn.datepicker = function(option){ var args = Array.apply(null, arguments); args.shift(); var internal_return; this.each(function(){ var $this = $(this), data = $this.data('datepicker'), options = typeof option === 'object' && option; if (!data){ var elopts = opts_from_el(this, 'date'), // Preliminary otions xopts = $.extend({}, defaults, elopts, options), locopts = opts_from_locale(xopts.language), // Options priority: js args, data-attrs, locales, defaults opts = $.extend({}, defaults, locopts, elopts, options); if ($this.is('.input-daterange') || opts.inputs){ var ropts = { inputs: opts.inputs || $this.find('input').toArray() }; $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts)))); } else { $this.data('datepicker', (data = new Datepicker(this, opts))); } } if (typeof option === 'string' && typeof data[option] === 'function'){ internal_return = data[option].apply(data, args); if (internal_return !== undefined) return false; } }); if (internal_return !== undefined) return internal_return; else return this; }; var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, multidate: false, multidateSeparator: ',', orientation: "auto", rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; var locale_opts = $.fn.datepicker.locale_opts = [ 'format', 'rtl', 'weekStart' ]; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"], daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"], daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"], months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"], monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"], today: "Aujourd'hui", clear: "Effacer", weekStart: 1, format: "dd/mm/yyyy" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function(year){ return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function(year, month){ return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function(format){ // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, parseDate: function(date, format, language){ if (!date) return undefined; if (date instanceof Date) return date; if (typeof format === 'string') format = DPGlobal.parseFormat(format); var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir, i; if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)){ date = new Date(); for (i=0; i < parts.length; i++){ part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch (part[2]){ case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } parts = date && date.match(this.nonpunctuation) || []; date = new Date(); var parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function(d,v){ return d.setUTCFullYear(v); }, yy: function(d,v){ return d.setUTCFullYear(2000+v); }, m: function(d,v){ if (isNaN(d)) return d; v -= 1; while (v < 0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() !== v) d.setUTCDate(d.getUTCDate()-1); return d; }, d: function(d,v){ return d.setUTCDate(v); } }, val, filtered; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length !== fparts.length){ fparts = $(fparts).filter(function(i,p){ return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder function match_part(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m === p; } if (parts.length === fparts.length){ var cnt; for (i=0, cnt = fparts.length; i < cnt; i++){ val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)){ switch (part){ case 'MM': filtered = $(dates[language].months).filter(match_part); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(match_part); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } var _date, s; for (i=0; i < setters_order.length; i++){ s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])){ _date = new Date(date); setters_map[s](_date, parsed[s]); if (!isNaN(_date)) date = _date; } } } return date; }, formatDate: function(date, format, language){ if (!date) return ''; if (typeof format === 'string') format = DPGlobal.parseFormat(format); var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; date = []; var seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i <= cnt; i++){ if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>'+ '<tr>'+ '<th class="prev">&laquo;</th>'+ '<th colspan="5" class="datepicker-switch"></th>'+ '<th class="next">&raquo;</th>'+ '</tr>'+ '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot>'+ '<tr>'+ '<th colspan="7" class="today"></th>'+ '</tr>'+ '<tr>'+ '<th colspan="7" class="clear"></th>'+ '</tr>'+ '</tfoot>' }; DPGlobal.template = '<div class="datepicker">'+ '<div class="datepicker-days">'+ '<table class=" table-condensed">'+ DPGlobal.headTemplate+ '<tbody></tbody>'+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-months">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-years">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; /* DATEPICKER NO CONFLICT * =================== */ $.fn.datepicker.noConflict = function(){ $.fn.datepicker = old; return this; }; /* DATEPICKER DATA-API * ================== */ $(document).on( 'focus.datepicker.data-api click.datepicker.data-api', '[data-provide="datepicker"]', function(e){ var $this = $(this); if ($this.data('datepicker')) return; e.preventDefault(); // component click requires us to explicitly show it $this.datepicker('show'); } ); $(function(){ $('[data-provide="datepicker-inline"]').datepicker(); }); }(window.jQuery));
mit
thepiprogrammer/PyNewsApp
web_to_file.py
358
import json from urllib.request import urlopen url = "https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=631086356f124f4d82bd059ea5fccc88" response = urlopen(url) data = json.loads(response.read()) with open("jsondata.txt", 'w') as outfile: outfile.write(json.dumps(data, sort_keys=True, indent=4)) print(data['articles'][7]['author'])
mit
trybeans/Beans-Woo
front/snow/init.php
140
<?php namespace BeansWoo\Front\Snow; include_once('block.php'); class Main { public static function init(){ Block::init(); } }
mit