repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lsimkins/laravel-zend-bundle
library/Zend/Controller/Plugin/ErrorHandler.php
9088
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Controller * @subpackage Plugins * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_Controller_Plugin_Abstract */ // require_once 'Zend/Controller/Plugin/Abstract.php'; /** * Handle exceptions that bubble up based on missing controllers, actions, or * application errors, and forward to an error handler. * * @uses Zend_Controller_Plugin_Abstract * @category Zend * @package Zend_Controller * @subpackage Plugins * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: ErrorHandler.php 24241 2011-07-14 08:09:41Z bate $ */ class Zend_Controller_Plugin_ErrorHandler extends Zend_Controller_Plugin_Abstract { /** * Const - No controller exception; controller does not exist */ const EXCEPTION_NO_CONTROLLER = 'EXCEPTION_NO_CONTROLLER'; /** * Const - No action exception; controller exists, but action does not */ const EXCEPTION_NO_ACTION = 'EXCEPTION_NO_ACTION'; /** * Const - No route exception; no routing was possible */ const EXCEPTION_NO_ROUTE = 'EXCEPTION_NO_ROUTE'; /** * Const - Other Exception; exceptions thrown by application controllers */ const EXCEPTION_OTHER = 'EXCEPTION_OTHER'; /** * Module to use for errors; defaults to default module in dispatcher * @var string */ protected $_errorModule; /** * Controller to use for errors; defaults to 'error' * @var string */ protected $_errorController = 'error'; /** * Action to use for errors; defaults to 'error' * @var string */ protected $_errorAction = 'error'; /** * Flag; are we already inside the error handler loop? * @var bool */ protected $_isInsideErrorHandlerLoop = false; /** * Exception count logged at first invocation of plugin * @var int */ protected $_exceptionCountAtFirstEncounter = 0; /** * Constructor * * Options may include: * - module * - controller * - action * * @param Array $options * @return void */ public function __construct(Array $options = array()) { $this->setErrorHandler($options); } /** * setErrorHandler() - setup the error handling options * * @param array $options * @return Zend_Controller_Plugin_ErrorHandler */ public function setErrorHandler(Array $options = array()) { if (isset($options['module'])) { $this->setErrorHandlerModule($options['module']); } if (isset($options['controller'])) { $this->setErrorHandlerController($options['controller']); } if (isset($options['action'])) { $this->setErrorHandlerAction($options['action']); } return $this; } /** * Set the module name for the error handler * * @param string $module * @return Zend_Controller_Plugin_ErrorHandler */ public function setErrorHandlerModule($module) { $this->_errorModule = (string) $module; return $this; } /** * Retrieve the current error handler module * * @return string */ public function getErrorHandlerModule() { if (null === $this->_errorModule) { $this->_errorModule = Zend_Controller_Front::getInstance()->getDispatcher()->getDefaultModule(); } return $this->_errorModule; } /** * Set the controller name for the error handler * * @param string $controller * @return Zend_Controller_Plugin_ErrorHandler */ public function setErrorHandlerController($controller) { $this->_errorController = (string) $controller; return $this; } /** * Retrieve the current error handler controller * * @return string */ public function getErrorHandlerController() { return $this->_errorController; } /** * Set the action name for the error handler * * @param string $action * @return Zend_Controller_Plugin_ErrorHandler */ public function setErrorHandlerAction($action) { $this->_errorAction = (string) $action; return $this; } /** * Retrieve the current error handler action * * @return string */ public function getErrorHandlerAction() { return $this->_errorAction; } /** * Route shutdown hook -- Ccheck for router exceptions * * @param Zend_Controller_Request_Abstract $request */ public function routeShutdown(Zend_Controller_Request_Abstract $request) { $this->_handleError($request); } /** * Pre dispatch hook -- check for exceptions and dispatch error handler if * necessary * * @param Zend_Controller_Request_Abstract $request */ public function preDispatch(Zend_Controller_Request_Abstract $request) { $this->_handleError($request); } /** * Post dispatch hook -- check for exceptions and dispatch error handler if * necessary * * @param Zend_Controller_Request_Abstract $request */ public function postDispatch(Zend_Controller_Request_Abstract $request) { $this->_handleError($request); } /** * Handle errors and exceptions * * If the 'noErrorHandler' front controller flag has been set, * returns early. * * @param Zend_Controller_Request_Abstract $request * @return void */ protected function _handleError(Zend_Controller_Request_Abstract $request) { $frontController = Zend_Controller_Front::getInstance(); if ($frontController->getParam('noErrorHandler')) { return; } $response = $this->getResponse(); if ($this->_isInsideErrorHandlerLoop) { $exceptions = $response->getException(); if (count($exceptions) > $this->_exceptionCountAtFirstEncounter) { // Exception thrown by error handler; tell the front controller to throw it $frontController->throwExceptions(true); throw array_pop($exceptions); } } // check for an exception AND allow the error handler controller the option to forward if (($response->isException()) && (!$this->_isInsideErrorHandlerLoop)) { $this->_isInsideErrorHandlerLoop = true; // Get exception information $error = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); $exceptions = $response->getException(); $exception = $exceptions[0]; $exceptionType = get_class($exception); $error->exception = $exception; switch ($exceptionType) { case 'Zend_Controller_Router_Exception': if (404 == $exception->getCode()) { $error->type = self::EXCEPTION_NO_ROUTE; } else { $error->type = self::EXCEPTION_OTHER; } break; case 'Zend_Controller_Dispatcher_Exception': $error->type = self::EXCEPTION_NO_CONTROLLER; break; case 'Zend_Controller_Action_Exception': if (404 == $exception->getCode()) { $error->type = self::EXCEPTION_NO_ACTION; } else { $error->type = self::EXCEPTION_OTHER; } break; default: $error->type = self::EXCEPTION_OTHER; break; } // Keep a copy of the original request $error->request = clone $request; // get a count of the number of exceptions encountered $this->_exceptionCountAtFirstEncounter = count($exceptions); // Forward to the error handler $request->setParam('error_handler', $error) ->setModuleName($this->getErrorHandlerModule()) ->setControllerName($this->getErrorHandlerController()) ->setActionName($this->getErrorHandlerAction()) ->setDispatched(false); } } }
bsd-3-clause
uq-eresearch/gbr-cat
CRESIS/AJAX_APP/src/main/webapp/cresis/js/source/widgets/tree/TreeEditor.js
4615
/* * Ext JS Library 2.0.2 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.tree.TreeEditor * @extends Ext.Editor * Provides editor functionality for inline tree node editing. Any valid {@link Ext.form.Field} can be used * as the editor field. * @constructor * @param {TreePanel} tree * @param {Object} config Either a prebuilt {@link Ext.form.Field} instance or a Field config object */ Ext.tree.TreeEditor = function(tree, config){ config = config || {}; var field = config.events ? config : new Ext.form.TextField(config); Ext.tree.TreeEditor.superclass.constructor.call(this, field); this.tree = tree; if(!tree.rendered){ tree.on('render', this.initEditor, this); }else{ this.initEditor(tree); } }; Ext.extend(Ext.tree.TreeEditor, Ext.Editor, { /** * @cfg {String} alignment * The position to align to (see {@link Ext.Element#alignTo} for more details, defaults to "l-l"). */ alignment: "l-l", // inherit autoSize: false, /** * @cfg {Boolean} hideEl * True to hide the bound element while the editor is displayed (defaults to false) */ hideEl : false, /** * @cfg {String} cls * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor") */ cls: "x-small-editor x-tree-editor", /** * @cfg {Boolean} shim * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false) */ shim:false, // inherit shadow:"frame", /** * @cfg {Number} maxWidth * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed * the containing tree element's size, it will be automatically limited for you to the container width, taking * scroll and client offsets into account prior to each edit. */ maxWidth: 250, /** * @cfg {Number} editDelay The number of milliseconds between clicks to register a double-click that will trigger * editing on the current node (defaults to 350). If two clicks occur on the same node within this time span, * the editor for the node will display, otherwise it will be processed as a regular click. */ editDelay : 350, initEditor : function(tree){ tree.on('beforeclick', this.beforeNodeClick, this); tree.on('dblclick', this.onNodeDblClick, this); this.on('complete', this.updateNode, this); this.on('beforestartedit', this.fitToTree, this); this.on('startedit', this.bindScroll, this, {delay:10}); this.on('specialkey', this.onSpecialKey, this); }, // private fitToTree : function(ed, el){ var td = this.tree.getTreeEl().dom, nd = el.dom; if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible td.scrollLeft = nd.offsetLeft; } var w = Math.min( this.maxWidth, (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5); this.setSize(w, ''); }, // private triggerEdit : function(node, defer){ this.completeEdit(); if(node.attributes.editable !== false){ this.editNode = node; this.autoEditTimer = this.startEdit.defer(this.editDelay, this, [node.ui.textNode, node.text]); return false; } }, // private bindScroll : function(){ this.tree.getTreeEl().on('scroll', this.cancelEdit, this); }, // private beforeNodeClick : function(node, e){ clearTimeout(this.autoEditTimer); if(this.tree.getSelectionModel().isSelected(node)){ e.stopEvent(); return this.triggerEdit(node); } }, onNodeDblClick : function(node, e){ clearTimeout(this.autoEditTimer); }, // private updateNode : function(ed, value){ this.tree.getTreeEl().un('scroll', this.cancelEdit, this); this.editNode.setText(value); }, // private onHide : function(){ Ext.tree.TreeEditor.superclass.onHide.call(this); if(this.editNode){ this.editNode.ui.focus.defer(50, this.editNode.ui); } }, // private onSpecialKey : function(field, e){ var k = e.getKey(); if(k == e.ESC){ e.stopEvent(); this.cancelEdit(); }else if(k == e.ENTER && !e.hasModifier()){ e.stopEvent(); this.completeEdit(); } } });
bsd-3-clause
mixman/djangodev
django/db/models/fields/files.py
15966
import datetime import os from django import forms from django.db.models.fields import Field from django.core.files.base import File from django.core.files.storage import default_storage from django.core.files.images import ImageFile from django.db.models import signals from django.utils.encoding import force_unicode, smart_str from django.utils.translation import ugettext_lazy as _ class FieldFile(File): def __init__(self, instance, field, name): super(FieldFile, self).__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be simple strings. # By overriding the == operator, it can remain backwards compatibility. if hasattr(other, 'name'): return self.name == other.name return self.name == other def __ne__(self, other): return not self.__eq__(other) def __hash__(self): # Required because we defined a custom __eq__. return hash(self.name) # The standard File contains most of the necessary properties, but # FieldFiles can be instantiated without a name, so that needs to # be checked for here. def _require_file(self): if not self: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) def _get_file(self): self._require_file() if not hasattr(self, '_file') or self._file is None: self._file = self.storage.open(self.name, 'rb') return self._file def _set_file(self, file): self._file = file def _del_file(self): del self._file file = property(_get_file, _set_file, _del_file) def _get_path(self): self._require_file() return self.storage.path(self.name) path = property(_get_path) def _get_url(self): self._require_file() return self.storage.url(self.name) url = property(_get_url) def _get_size(self): self._require_file() if not self._committed: return self.file.size return self.storage.size(self.name) size = property(_get_size) def open(self, mode='rb'): self._require_file() self.file.open(mode) # open() doesn't alter the file's contents, but it does reset the pointer open.alters_data = True # In addition to the standard File API, FieldFiles have extra methods # to further manipulate the underlying file, as well as update the # associated model instance. def save(self, name, content, save=True): name = self.field.generate_filename(self.instance, name) self.name = self.storage.save(name, content) setattr(self.instance, self.field.name, self.name) # Update the filesize cache self._size = content.size self._committed = True # Save the object because it has changed, unless save is False if save: self.instance.save() save.alters_data = True def delete(self, save=True): # Only close the file if it's already open, which we know by the # presence of self._file if hasattr(self, '_file'): self.close() del self.file self.storage.delete(self.name) self.name = None setattr(self.instance, self.field.name, self.name) # Delete the filesize cache if hasattr(self, '_size'): del self._size self._committed = False if save: self.instance.save() delete.alters_data = True def _get_closed(self): file = getattr(self, '_file', None) return file is None or file.closed closed = property(_get_closed) def close(self): file = getattr(self, '_file', None) if file is not None: file.close() def __getstate__(self): # FieldFile needs access to its associated model field and an instance # it's attached to in order to work properly, but the only necessary # data to be pickled is the file's name itself. Everything else will # be restored later, by FileDescriptor below. return {'name': self.name, 'closed': False, '_committed': True, '_file': None} class FileDescriptor(object): """ The descriptor for the file attribute on the model instance. Returns a FieldFile when accessed so you can do stuff like:: >>> instance.file.size Assigns a file object on assignment so you can do:: >>> instance.file = File(...) """ def __init__(self, field): self.field = field def __get__(self, instance=None, owner=None): if instance is None: raise AttributeError( "The '%s' attribute can only be accessed from %s instances." % (self.field.name, owner.__name__)) # This is slightly complicated, so worth an explanation. # instance.file`needs to ultimately return some instance of `File`, # probably a subclass. Additionally, this returned object needs to have # the FieldFile API so that users can easily do things like # instance.file.path and have that delegated to the file storage engine. # Easy enough if we're strict about assignment in __set__, but if you # peek below you can see that we're not. So depending on the current # value of the field we have to dynamically construct some sort of # "thing" to return. # The instance dict contains whatever was originally assigned # in __set__. file = instance.__dict__[self.field.name] # If this value is a string (instance.file = "path/to/file") or None # then we simply wrap it with the appropriate attribute class according # to the file field. [This is FieldFile for FileFields and # ImageFieldFile for ImageFields; it's also conceivable that user # subclasses might also want to subclass the attribute class]. This # object understands how to convert a path to a file, and also how to # handle None. if isinstance(file, basestring) or file is None: attr = self.field.attr_class(instance, self.field, file) instance.__dict__[self.field.name] = attr # Other types of files may be assigned as well, but they need to have # the FieldFile interface added to the. Thus, we wrap any other type of # File inside a FieldFile (well, the field's attr_class, which is # usually FieldFile). elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.name] = file_copy # Finally, because of the (some would say boneheaded) way pickle works, # the underlying FieldFile might not actually itself have an associated # file. So we need to reset the details of the FieldFile in those cases. elif isinstance(file, FieldFile) and not hasattr(file, 'field'): file.instance = instance file.field = self.field file.storage = self.field.storage # That was fun, wasn't it? return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor description = _("File path") def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs): for arg in ('primary_key', 'unique'): if arg in kwargs: raise TypeError("'%s' is not a valid argument for %s." % (arg, self.__class__)) self.storage = storage or default_storage self.upload_to = upload_to if callable(upload_to): self.generate_filename = upload_to kwargs['max_length'] = kwargs.get('max_length', 100) super(FileField, self).__init__(verbose_name, name, **kwargs) def get_internal_type(self): return "FileField" def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'name'): value = value.name return super(FileField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): "Returns field's value prepared for saving into a database." # Need to convert File objects provided via a form to unicode for database insertion if value is None: return None return unicode(value) def pre_save(self, model_instance, add): "Returns field's value just before saving." file = super(FileField, self).pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model file.save(file.name, file, save=False) return file def contribute_to_class(self, cls, name): super(FileField, self).contribute_to_class(cls, name) setattr(cls, self.name, self.descriptor_class(self)) def get_directory_name(self): return os.path.normpath(force_unicode(datetime.datetime.now().strftime(smart_str(self.upload_to)))) def get_filename(self, filename): return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename))) def generate_filename(self, instance, filename): return os.path.join(self.get_directory_name(), self.get_filename(filename)) def save_form_data(self, instance, data): # Important: None means "no change", other false value means "clear" # This subtle distinction (rather than a more explicit marker) is # needed because we need to consume values that are also sane for a # regular (non Model-) Form to find in its cleaned_data dictionary. if data is not None: # This value will be converted to unicode and stored in the # database, so leaving False as-is is not acceptable. if not data: data = '' setattr(instance, self.name, data) def formfield(self, **kwargs): defaults = {'form_class': forms.FileField, 'max_length': self.max_length} # If a file has been provided previously, then the form doesn't require # that a new file is provided this time. # The code to mark the form field as not required is used by # form_for_instance, but can probably be removed once form_for_instance # is gone. ModelForm uses a different method to check for an existing file. if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) return super(FileField, self).formfield(**defaults) class ImageFileDescriptor(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) super(ImageFileDescriptor, self).__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11084), only update dimensions if # the field had a value before this assignment. Since the default # value for FileField subclasses is an instance of field.attr_class, # previous_file will only be None when we are called from # Model.__init__(). The ImageField.update_dimension_fields method # hooked up to the post_init signal handles the Model.__init__() cases. # Assignment happening outside of Model.__init__() will trigger the # update right here. if previous_file is not None: self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, '_dimensions_cache'): del self._dimensions_cache super(ImageFieldFile, self).delete(save) class ImageField(FileField): attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = _("File path") def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field super(ImageField, self).__init__(verbose_name, name, **kwargs) def contribute_to_class(self, cls, name): super(ImageField, self).contribute_to_class(cls, name) # Attach update_dimension_fields so that dimension fields declared # after their corresponding image field don't stay cleared by # Model.__init__, see bug #11196. signals.post_init.connect(self.update_dimension_fields, sender=cls) def update_dimension_fields(self, instance, force=False, *args, **kwargs): """ Updates field's width and height fields, if defined. This method is hooked up to model's post_init signal to update dimensions after instantiating a model instance. However, dimensions won't be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object from the database. Dimensions can be forced to update with force=True, which is how ImageFileDescriptor.__set__ calls this method. """ # Nothing to update if the field doesn't have have dimension fields. has_dimension_fields = self.width_field or self.height_field if not has_dimension_fields: return # getattr will call the ImageFileDescriptor's __get__ method, which # coerces the assigned value into an instance of self.attr_class # (ImageFieldFile in this case). file = getattr(instance, self.attname) # Nothing to update if we have no file and not being forced to update. if not file and not force: return dimension_fields_filled = not( (self.width_field and not getattr(instance, self.width_field)) or (self.height_field and not getattr(instance, self.height_field)) ) # When both dimension fields have values, we are most likely loading # data from the database or updating an image field that already had # an image stored. In the first case, we don't want to update the # dimension fields because we are already getting their values from the # database. In the second case, we do want to update the dimensions # fields and will skip this return because force will be True since we # were called from ImageFileDescriptor.__set__. if dimension_fields_filled and not force: return # file should be an instance of ImageFieldFile or should be None. if file: width = file.width height = file.height else: # No file, so clear dimensions fields. width = None height = None # Update the width and height fields. if self.width_field: setattr(instance, self.width_field, width) if self.height_field: setattr(instance, self.height_field, height) def formfield(self, **kwargs): defaults = {'form_class': forms.ImageField} defaults.update(kwargs) return super(ImageField, self).formfield(**defaults)
bsd-3-clause
psi4/DatenQM
qcfractal/storage_sockets/models/sql_base.py
5236
from qcelemental.util import msgpackext_dumps, msgpackext_loads from sqlalchemy import and_, inspect from sqlalchemy.dialects.postgresql import BYTEA from sqlalchemy.ext.associationproxy import ASSOCIATION_PROXY from sqlalchemy.ext.declarative import as_declarative from sqlalchemy.ext.hybrid import HYBRID_PROPERTY from sqlalchemy.orm import object_session from sqlalchemy.types import TypeDecorator # from sqlalchemy.ext.orderinglist import ordering_list # from sqlalchemy.ext.associationproxy import association_proxy # from sqlalchemy.dialects.postgresql import aggregate_order_by class MsgpackExt(TypeDecorator): """Converts JSON-like data to msgpack with full NumPy Array support.""" impl = BYTEA def process_bind_param(self, value, dialect): if value is None: return value else: return msgpackext_dumps(value) def process_result_value(self, value, dialect): if value is None: return value else: return msgpackext_loads(value) @as_declarative() class Base: """Base declarative class of all ORM models""" db_related_fields = ["result_type", "base_result_id", "_trajectory", "collection_type", "lname"] def to_dict(self, exclude=None): tobe_deleted_keys = [] if exclude: tobe_deleted_keys.extend(exclude) dict_obj = [x for x in self._all_col_names() if x not in self.db_related_fields and x not in tobe_deleted_keys] # Add the attributes to the final results ret = {k: getattr(self, k) for k in dict_obj} if "extra" in ret: ret.update(ret["extra"]) del ret["extra"] # transform ids from int into str id_fields = self._get_fieldnames_with_DB_ids_() for key in id_fields: if key in ret.keys() and ret[key] is not None: if isinstance(ret[key], (list, tuple)): ret[key] = [str(i) for i in ret[key]] else: ret[key] = str(ret[key]) return ret @classmethod def _get_fieldnames_with_DB_ids_(cls): class_inspector = inspect(cls) id_fields = [] for key, col in class_inspector.columns.items(): # if PK, FK, or column property (TODO: work around for column property) if col.primary_key or len(col.foreign_keys) > 0 or key != col.key: id_fields.append(key) return id_fields @classmethod def _get_col_types(cls): # Must use private attributes so that they are not shared by subclasses if hasattr(cls, "__columns") and hasattr(cls, "__hybrids") and hasattr(cls, "__relationships"): return cls.__columns, cls.__hybrids, cls.__relationships mapper = inspect(cls) cls.__columns = [] cls.__hybrids = [] cls.__relationships = {} for k, v in mapper.relationships.items(): cls.__relationships[k] = {} cls.__relationships[k]["join_class"] = v.argument cls.__relationships[k]["remote_side_column"] = list(v.remote_side)[0] for k, c in mapper.all_orm_descriptors.items(): if k == "__mapper__": continue if c.extension_type == ASSOCIATION_PROXY: continue if c.extension_type == HYBRID_PROPERTY: cls.__hybrids.append(k) elif k not in mapper.relationships: cls.__columns.append(k) return cls.__columns, cls.__hybrids, cls.__relationships @classmethod def _all_col_names(cls): all_cols, hybrid, _ = cls._get_col_types() return all_cols + hybrid def _update_many_to_many(self, table, parent_id_name, child_id_name, parent_id_val, new_list, old_list=None): """Perfomr upsert on a many to many association table Does NOT commit changes, parent should optimize when it needs to commit raises exception if ids don't exist in the DB """ session = object_session(self) old_set = {x for x in old_list} if old_list else set() new_set = {x for x in new_list} if new_list else set() # Update many-to-many relations # Remove old relations and apply the new ones if old_set != new_set: to_add = new_set - old_set to_del = old_set - new_set if to_del: session.execute( table.delete().where( and_(table.c[parent_id_name] == parent_id_val, table.c[child_id_name].in_(to_del)) ) ) if to_add: session.execute( table.insert().values([{parent_id_name: parent_id_val, child_id_name: my_id} for my_id in to_add]) ) def __str__(self): if hasattr(self, "id"): return str(self.id) return super.__str__(self) # @validates('created_on', 'modified_on') # def validate_date(self, key, date): # """For SQLite, translate str to dates manually""" # if date is not None and isinstance(date, str): # date = dateutil.parser.parse(date) # return date
bsd-3-clause
bingoyang/scala-otp
controlflow/src/test/scala/scala/actors/controlflow/AsyncFunctionSuite.scala
1860
package scala.actors.controlflow import org.testng.annotations.{Test, BeforeMethod} import org.scalatest.testng.TestNGSuite import org.scalatest.prop.Checkers import org.scalacheck.Arbitrary import org.scalacheck.Arbitrary._ import org.scalacheck.Gen import org.scalacheck.Prop._ import org.scalatest._ import scala.actors.controlflow._ import scala.actors.controlflow.ControlFlow._ import scala.actors.controlflow.ControlFlowTestHelper._ /** * Tests for control flow. * * @author <a href="http://www.richdougherty.com/">Rich Dougherty</a> */ class AsyncFunctionSuite extends TestNGSuite with Checkers { val addOne: AsyncFunction1[Int, Int] = { (x: Int, fc: FC[Int]) => fc.ret(x + 1) } val double: AsyncFunction1[Int, Int] = { x: Int => x * 2 }.toAsyncFunction val two: AsyncFunction0[Int] = Return(2).toAsyncFunction @Test def testAsyncFunction1 = asyncTest(10000) { println("testAsyncFunction1") assert(addOne.toFunction.apply(2) == 3) assert(double.toFunction.apply(2) == 4) assert((addOne andThen double).toFunction.apply(2) == 6) assert((double andThen addOne).toFunction.apply(2) == 5) assert((addOne compose double).toFunction.apply(2) == 5) assert((double compose addOne).toFunction.apply(2) == 6) } @Test def testAsyncFunction0 = asyncTest(10000) { println("testAsyncFunction0") assert(two.toFunction.apply == 2) assert((two andThen addOne).toFunction.apply == 3) assert((two andThen double).toFunction.apply == 4) assert((two andThen addOne andThen double).toFunction.apply == 6) assert((two andThen addOne andThen double).toFunction.apply == 6) assert((two andThen double andThen addOne).toFunction.apply == 5) assert((two andThen (addOne compose double)).toFunction.apply == 5) assert((two andThen (double compose addOne)).toFunction.apply == 6) } }
bsd-3-clause
platformdotnet/Platform.VirtualFileSystem
src/Platform.VirtualFileSystem/Providers/Local/LocalFile.cs
12174
using System; using System.IO; using System.Linq; using System.Threading; namespace Platform.VirtualFileSystem.Providers.Local { /// <summary> /// Implementation of <see cref="IFile"/> for <see cref="LocalFileSystem"/>s. /// </summary> public class LocalFile : AbstractFile, INativePathService { private readonly FileInfo fileInfo; public override bool SupportsActivityEvents { get { return true; } } public LocalFile(LocalFileSystem fileSystem, LocalNodeAddress address) : base(address, fileSystem) { this.FileSystem = fileSystem; this.fileInfo = new FileInfo(address.AbsoluteNativePath); } public override INode DoCreate(bool createParent) { if (createParent) { this.ParentDirectory.Refresh(); if (!this.ParentDirectory.Exists) { this.ParentDirectory.Create(true); } try { this.fileInfo.Create().Close(); } catch (DirectoryNotFoundException) { } this.ParentDirectory.Create(true); try { this.fileInfo.Create().Close(); } catch (DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(this.Address); } catch (FileNotFoundException) { throw new FileNodeNotFoundException(this.Address); } Refresh(); } else { try { this.fileInfo.Create().Close(); } catch (DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(this.Address); } catch (FileNotFoundException) { throw new FileNodeNotFoundException(this.Address); } } return this; } protected override INode DoDelete() { try { Native.GetInstance().DeleteFileContent(this.fileInfo.FullName, null); Refresh(); } catch (FileNotFoundException) { throw new FileNodeNotFoundException(Address); } catch (DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(Address); } return this; } protected override INode DoCopyTo(INode target, bool overwrite) { return CopyTo(target, overwrite, false); } private INode CopyTo(INode target, bool overwrite, bool deleteOriginal) { string targetLocalPath = null; if (target.NodeType.IsLikeDirectory) { target = target.ResolveFile(this.Address.Name); } try { var service = (INativePathService)target.GetService(typeof(INativePathService)); targetLocalPath = service.GetNativePath(); } catch (NotSupportedException) { } var thisLocalPath = ((LocalNodeAddress)this.Address).AbsoluteNativePath; if (targetLocalPath == null || !Path.GetPathRoot(thisLocalPath).EqualsIgnoreCase(Path.GetPathRoot(targetLocalPath))) { if (deleteOriginal) { base.DoMoveTo(target, overwrite); } else { base.DoCopyTo(target, overwrite); } } else { target.Refresh(); if (overwrite && target.Exists) { try { target.Delete(); } catch (FileNodeNotFoundException) { } } try { if (deleteOriginal) { try { File.Move(thisLocalPath, targetLocalPath); } catch (System.IO.DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(this.Address); } catch (System.IO.FileNotFoundException) { throw new FileNodeNotFoundException(this.Address); } } else { try { File.Copy(thisLocalPath, targetLocalPath); } catch (System.IO.DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(this.Address); } catch (System.IO.FileNotFoundException) { throw new FileNodeNotFoundException(this.Address); } } return this; } catch (IOException) { if (overwrite && target.Exists) { try { target.Delete(); } catch (FileNotFoundException) { } } else { throw; } } if (deleteOriginal) { try { File.Move(thisLocalPath, targetLocalPath); } catch (System.IO.DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(this.Address); } catch (System.IO.FileNotFoundException) { throw new FileNodeNotFoundException(this.Address); } } else { try { File.Copy(thisLocalPath, targetLocalPath); } catch (System.IO.DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(this.Address); } catch (System.IO.FileNotFoundException) { throw new FileNodeNotFoundException(this.Address); } } } return this; } protected override INode DoMoveTo(INode target, bool overwrite) { return CopyTo(target, overwrite, true); } private class LocalFileMovingService : AbstractRunnableService { private readonly LocalFile localFile; private readonly LocalFile destinationFile; private readonly bool overwrite; public override IMeter Progress { get { return this.progress; } } private readonly MutableMeter progress = new MutableMeter(0, 1, 0, "files"); public LocalFileMovingService(LocalFile localFile, LocalFile destinationFile, bool overwrite) { this.localFile = localFile; this.destinationFile = destinationFile; this.overwrite = overwrite; } public override void DoRun() { this.progress.SetCurrentValue(0); this.localFile.DoMoveTo(this.destinationFile, this.overwrite); this.progress.SetCurrentValue(1); } } public override IService GetService(ServiceType serviceType) { var typedServiceType = serviceType as NodeMovingServiceType; if (typedServiceType != null) { if (typedServiceType.Destination is LocalFile) { if (typedServiceType.Destination.Address.RootUri.Equals(this.Address.RootUri)) { return new LocalFileMovingService(this, (LocalFile)typedServiceType.Destination, typedServiceType.Overwrite); } } } else if (serviceType.Is(typeof(INativePathService))) { return this; } return base.GetService(serviceType); } protected override Stream DoOpenStream(string contentName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) { try { if (string.IsNullOrEmpty(contentName) || contentName == Native.GetInstance().DefaultContentName) { return new FileStream(this.fileInfo.FullName, fileMode, fileAccess, fileShare); } else { return Native.GetInstance().OpenAlternateContentStream ( this.fileInfo.FullName, contentName, fileMode, fileAccess, fileShare ); } } catch (FileNotFoundException) { throw new FileNodeNotFoundException(Address); } } protected override Stream DoGetInputStream(string contentName, out string encoding, FileMode mode, FileShare sharing) { encoding = null; try { if (string.IsNullOrEmpty(contentName) || contentName == Native.GetInstance().DefaultContentName) { for (var i = 0; i < 10; i++) { try { return new FileStream(this.fileInfo.FullName, mode, FileAccess.Read, sharing); } catch (DirectoryNotFoundException) { throw; } catch (FileNotFoundException) { throw; } catch (IOException) { if (i == 9) { throw; } Thread.Sleep(500); } } throw new IOException(); } else { return Native.GetInstance().OpenAlternateContentStream ( this.fileInfo.FullName, contentName, mode, FileAccess.Read, sharing ); } } catch (FileNotFoundException) { throw new FileNodeNotFoundException(Address); } catch (DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(Address); } } protected override Stream DoGetOutputStream(string contentName, string encoding, FileMode mode, FileShare sharing) { try { if (string.IsNullOrEmpty(contentName) || contentName == Native.GetInstance().DefaultContentName) { return new FileStream(this.fileInfo.FullName, mode, FileAccess.Write, sharing); } else { return Native.GetInstance().OpenAlternateContentStream ( this.fileInfo.FullName, contentName, mode, FileAccess.Write, sharing ); } } catch (FileNotFoundException) { throw new FileNodeNotFoundException(Address); } catch (DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(Address); } } protected override INodeAttributes CreateAttributes() { return new AutoRefreshingFileAttributes(new LocalFileAttributes(this, this.fileInfo), -1); } protected override bool SupportsAlternateContent() { return true; } string INativePathService.GetNativePath() { return ((LocalNodeAddress)this.Address).AbsoluteNativePath; } string INativePathService.GetNativeShortPath() { return Native.GetInstance().GetShortPath(((LocalNodeAddress)this.Address).AbsoluteNativePath); } public override string DefaultContentName { get { return Native.GetInstance().DefaultContentName; } } public override System.Collections.Generic.IEnumerable<string> GetContentNames() { return Native.GetInstance().GetContentInfos(((LocalNodeAddress)this.Address).AbsoluteNativePath).Select(contentInfo => contentInfo.Name); } protected override void DeleteContent(string contentName) { if (contentName == null) { contentName = Native.GetInstance().DefaultContentName; } try { Native.GetInstance().DeleteFileContent(((LocalNodeAddress)this.Address).AbsoluteNativePath, contentName); } catch (FileNotFoundException) { throw new FileNodeNotFoundException(Address); } catch (DirectoryNotFoundException) { throw new DirectoryNodeNotFoundException(Address); } } protected override INode DoRenameTo(string name, bool overwrite) { name = StringUriUtils.RemoveQuery(name); var destPath = Path.Combine(this.fileInfo.DirectoryName, name); for (var i = 0; i < 5; i++) { try { if (overwrite) { File.Delete(destPath); } // // Don't use FileInfo.MoveTo as it changes the existing FileInfo // use the new path. // File.Move(this.fileInfo.FullName, destPath); this.fileInfo.Refresh(); break; } catch (IOException) { if (i == 4) { throw; } Thread.Sleep(500); } } return this; } protected override IFile DoCreateHardLink(IFile targetFile, bool overwrite) { string target; var path = this.fileInfo.FullName; try { var service = (INativePathService)targetFile.GetService(typeof(INativePathService)); target = service.GetNativePath(); } catch (NotSupportedException) { throw new NotSupportedException(); } targetFile.Refresh(); if (this.Exists && !overwrite) { throw new IOException("Hardlink already exists"); } else { ActionUtils.ToRetryAction<object> ( delegate { if (this.Exists) { this.Delete(); } try { Native.GetInstance().CreateHardLink(path, target); } catch (TooManyLinksException) { throw new TooManyLinksException(this, targetFile); } }, TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(0.25) )(null); } return this; } } }
bsd-3-clause
samuel/kokki
kokki/cookbooks/nagios3/recipes/default.py
3935
from kokki import Package, Service, File, Template env.include_recipe("apache2") Package("nagios3") Service("nagios3", supports_status = True, supports_restart = True, supports_reload = True) # NRPE plugin Package("nagios-nrpe-plugin") ## File("/etc/nagios3/cgi.cfg", owner = "root", group = "root", mode = 0644, content = Template("nagios3/cgi.cfg.j2"), notifies = [("restart", env.resources["Service"]["nagios3"])]) if env.system.ec2: File("/etc/nagios3/conf.d/host-gateway_nagios3.cfg", action = "delete", notifies = [("restart", env.resources["Service"]["nagios3"])]) File("/etc/nagios3/conf.d/extinfo_nagios2.cfg", action = "delete", notifies = [("restart", env.resources["Service"]["nagios3"])]) # nagios3 hostgroups File("/etc/nagios3/conf.d/hostgroups_nagios2.cfg", action = "delete", notifies = [("restart", env.resources["Service"]["nagios3"])]) File("nagio3-hostgroups", path = "/etc/nagios3/conf.d/hostgroups.cfg", owner = "root", group = "root", mode = 0644, content = Template("nagios3/hostgroups.cfg.j2"), notifies = [("restart", env.resources["Service"]["nagios3"])]) # nagios3 contacts File("/etc/nagios3/conf.d/contacts_nagios2.cfg", action = "delete", notifies = [("restart", env.resources["Service"]["nagios3"])]) File("nagio3-contacts", path = "/etc/nagios3/conf.d/contacts.cfg", owner = "root", group = "root", mode = 0644, content = Template("nagios3/contacts.cfg.j2"), notifies = [("restart", env.resources["Service"]["nagios3"])]) env.cookbooks.nagios3.Contact("root", alias = "Root", service_notification_period = "24x7", host_notification_period = "24x7", service_notification_options = "w,u,c,r", host_notification_options = "d,r", service_notification_commands = "notify-service-by-email", host_notification_commands = "notify-host-by-email", email = "root@localhost") # nagios3 services File("/etc/nagios3/conf.d/services_nagios2.cfg", action = "delete", notifies = [("restart", env.resources["Service"]["nagios3"])]) env.cookbooks.nagios3.Service("HTTP", hostgroup_name = "http-servers", check_command = "check_http", use = "generic-service", notification_interval = 0) env.cookbooks.nagios3.Service("SSH", hostgroup_name = "ssh-servers", check_command = "check_ssh", use = "generic-service", notification_interval = 0) env.cookbooks.nagios3.Service("PING", hostgroup_name = "ping-servers", check_command = "check_ping!100.0,20%!500.0,60%", use = "generic-service", notification_interval = 0) # nagios3 hosts File("/etc/nagios3/conf.d/localhost_nagios2.cfg", action = "delete", notifies = [("restart", env.resources["Service"]["nagios3"])]) File("nagios3-hosts", path = "/etc/nagios3/conf.d/hosts.cfg", owner = "root", group = "root", mode = 0644, content = Template("nagios3/hosts.cfg.j2"), notifies = [("restart", env.resources["Service"]["nagios3"])]) env.cookbooks.nagios3.Host("localhost", address = "127.0.0.1", groups = ["ssh-servers"]) env.cookbooks.nagios3.Service("Disk Space", host_name = "localhost", check_command = "check_all_disks!20%!10%") env.cookbooks.nagios3.Service("Total Processes", host_name = "localhost", check_command = "check_procs!250!400") env.cookbooks.nagios3.Service("Current Load", host_name = "localhost", check_command = "check_load!5.0!4.0!3.0!10.0!6.0!4.0") ## File("/etc/apache2/conf.d/nagios3.conf", action = "delete", notifies = [("restart", env.resources["Service"]["apache2"])]) File("/etc/apache2/sites-available/nagios3", owner = "www-data", group = "www-data", mode = 0644, content = Template("nagios3/apache2-site.j2"), notifies = [("restart", env.resources["Service"]["apache2"])]) env.cookbooks.apache2.site("nagios3")
bsd-3-clause
kelle/astropy
astropy/io/ascii/tests/test_ipac_definitions.py
4170
# Licensed under a 3-clause BSD style license - see LICENSE.rst # TEST_UNICODE_LITERALS import pytest from ..ui import read from ..ipac import Ipac, IpacFormatError, IpacFormatErrorDBMS from ....tests.helper import catch_warnings from ... import ascii from ....table import Table from ..core import masked from ....extern.six.moves import cStringIO as StringIO DATA = ''' | a | b | | char | char | ABBBBBBABBBBBBBA ''' def test_ipac_default(): # default should be ignore table = read(DATA, Reader=Ipac) assert table['a'][0] == 'BBBBBB' assert table['b'][0] == 'BBBBBBB' def test_ipac_ignore(): table = read(DATA, Reader=Ipac, definition='ignore') assert table['a'][0] == 'BBBBBB' assert table['b'][0] == 'BBBBBBB' def test_ipac_left(): table = read(DATA, Reader=Ipac, definition='left') assert table['a'][0] == 'BBBBBBA' assert table['b'][0] == 'BBBBBBBA' def test_ipac_right(): table = read(DATA, Reader=Ipac, definition='right') assert table['a'][0] == 'ABBBBBB' assert table['b'][0] == 'ABBBBBBB' def test_too_long_colname_default(): table = Table([[3]], names=['a1234567890123456789012345678901234567890']) out = StringIO() with pytest.raises(IpacFormatError): ascii.write(table, out, Writer=Ipac) def test_too_long_colname_strict(): table = Table([[3]], names=['a1234567890123456']) out = StringIO() with pytest.raises(IpacFormatErrorDBMS): ascii.write(table, out, Writer=Ipac, DBMS=True) def test_too_long_colname_notstrict(): table = Table([[3]], names=['a1234567890123456789012345678901234567890']) out = StringIO() with pytest.raises(IpacFormatError): ascii.write(table, out, Writer=Ipac, DBMS=False) @pytest.mark.parametrize(("strict_", "Err"), [(True, IpacFormatErrorDBMS), (False, IpacFormatError)]) def test_non_alfnum_colname(strict_, Err): table = Table([[3]], names=['a123456789 01234']) out = StringIO() with pytest.raises(Err): ascii.write(table, out, Writer=Ipac, DBMS=strict_) def test_colname_starswithnumber_strict(): table = Table([[3]], names=['a123456789 01234']) out = StringIO() with pytest.raises(IpacFormatErrorDBMS): ascii.write(table, out, Writer=Ipac, DBMS=True) def test_double_colname_strict(): table = Table([[3], [1]], names=['DEC', 'dec']) out = StringIO() with pytest.raises(IpacFormatErrorDBMS): ascii.write(table, out, Writer=Ipac, DBMS=True) @pytest.mark.parametrize('colname', ['x', 'y', 'z', 'X', 'Y', 'Z']) def test_reserved_colname_strict(colname): table = Table([['reg']], names=[colname]) out = StringIO() with pytest.raises(IpacFormatErrorDBMS): ascii.write(table, out, Writer=Ipac, DBMS=True) def test_too_long_comment(): with catch_warnings(UserWarning) as w: table = Table([[3]]) table.meta['comments'] = ['a' * 79] out = StringIO() ascii.write(table, out, Writer=Ipac) w = w[0] assert 'Comment string > 78 characters was automatically wrapped.' == str(w.message) expected_out = """\ \\ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\ a |col0| |long| | | |null| 3 """ assert out.getvalue().strip().splitlines() == expected_out.splitlines() def test_out_with_nonstring_null(): '''Test a (non-string) fill value. Even for an unmasked tables, the fill_value should show up in the table header. ''' table = Table([[3]], masked=True) out = StringIO() ascii.write(table, out, Writer=Ipac, fill_values=[(masked, -99999)]) expected_out = """\ | col0| | long| | | |-99999| 3 """ assert out.getvalue().strip().splitlines() == expected_out.splitlines() def test_include_exclude_names(): table = Table([[1], [2], [3]], names=('A', 'B', 'C')) out = StringIO() ascii.write(table, out, Writer=Ipac, include_names=('A', 'B'), exclude_names=('A',)) # column B should be the only included column in output expected_out = """\ | B| |long| | | |null| 2 """ assert out.getvalue().strip().splitlines() == expected_out.splitlines()
bsd-3-clause
tomap/YUICompressor.NET
Code/Yahoo.Yui.Compressor.Tests/TestHelpers/BuildEngine.cs
1692
using System.Text; using Microsoft.Build.Framework; using NUnit.Framework; namespace Yahoo.Yui.Compressor.Tests.TestHelpers { public static class BuildEngine { public static bool ContainsError(IBuildEngine engine, string error) { return CheckForError(engine, error, true); } public static bool DoesNotContainError(IBuildEngine engine, string error) { return CheckForError(engine, error, false); } private static bool CheckForError(IBuildEngine engine, string error, bool exists) { var buildEngine = engine as BuildEngineStub; if (buildEngine == null) { Assert.Fail("Not a BuildEngineStub, cannot test with this"); } if (buildEngine.Errors != null && buildEngine.Errors.Count > 0) { foreach (var anError in buildEngine.Errors) { if (anError.StartsWith(error)) { return exists; } } } if (!exists) { return true; } var sb = new StringBuilder(); sb.AppendLine(error + " not found. Actual errors: "); foreach (var anError in buildEngine.Errors) { sb.AppendLine(anError); } Assert.Fail(sb.ToString()); // ReSharper disable HeuristicUnreachableCode return !exists; // ReSharper restore HeuristicUnreachableCode } } }
bsd-3-clause
hlzz/dotfiles
graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/words/xish/xmlstream.py
8787
# -*- test-case-name: twisted.words.test.test_xmlstream -*- # # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ XML Stream processing. An XML Stream is defined as a connection over which two XML documents are exchanged during the lifetime of the connection, one for each direction. The unit of interaction is a direct child element of the root element (stanza). The most prominent use of XML Streams is Jabber, but this module is generically usable. See Twisted Words for Jabber specific protocol support. Maintainer: Ralph Meijer """ from twisted.python import failure from twisted.internet import protocol from twisted.words.xish import domish, utility STREAM_CONNECTED_EVENT = intern("//event/stream/connected") STREAM_START_EVENT = intern("//event/stream/start") STREAM_END_EVENT = intern("//event/stream/end") STREAM_ERROR_EVENT = intern("//event/stream/error") class XmlStream(protocol.Protocol, utility.EventDispatcher): """ Generic Streaming XML protocol handler. This protocol handler will parse incoming data as XML and dispatch events accordingly. Incoming stanzas can be handled by registering observers using XPath-like expressions that are matched against each stanza. See L{utility.EventDispatcher} for details. """ def __init__(self): utility.EventDispatcher.__init__(self) self.stream = None self.rawDataOutFn = None self.rawDataInFn = None def _initializeStream(self): """ Sets up XML Parser. """ self.stream = domish.elementStream() self.stream.DocumentStartEvent = self.onDocumentStart self.stream.ElementEvent = self.onElement self.stream.DocumentEndEvent = self.onDocumentEnd ### -------------------------------------------------------------- ### ### Protocol events ### ### -------------------------------------------------------------- def connectionMade(self): """ Called when a connection is made. Sets up the XML parser and dispatches the L{STREAM_CONNECTED_EVENT} event indicating the connection has been established. """ self._initializeStream() self.dispatch(self, STREAM_CONNECTED_EVENT) def dataReceived(self, data): """ Called whenever data is received. Passes the data to the XML parser. This can result in calls to the DOM handlers. If a parse error occurs, the L{STREAM_ERROR_EVENT} event is called to allow for cleanup actions, followed by dropping the connection. """ try: if self.rawDataInFn: self.rawDataInFn(data) self.stream.parse(data) except domish.ParserError: self.dispatch(failure.Failure(), STREAM_ERROR_EVENT) self.transport.loseConnection() def connectionLost(self, reason): """ Called when the connection is shut down. Dispatches the L{STREAM_END_EVENT}. """ self.dispatch(reason, STREAM_END_EVENT) self.stream = None ### -------------------------------------------------------------- ### ### DOM events ### ### -------------------------------------------------------------- def onDocumentStart(self, rootElement): """ Called whenever the start tag of a root element has been received. Dispatches the L{STREAM_START_EVENT}. """ self.dispatch(self, STREAM_START_EVENT) def onElement(self, element): """ Called whenever a direct child element of the root element has been received. Dispatches the received element. """ self.dispatch(element) def onDocumentEnd(self): """ Called whenever the end tag of the root element has been received. Closes the connection. This causes C{connectionLost} being called. """ self.transport.loseConnection() def setDispatchFn(self, fn): """ Set another function to handle elements. """ self.stream.ElementEvent = fn def resetDispatchFn(self): """ Set the default function (C{onElement}) to handle elements. """ self.stream.ElementEvent = self.onElement def send(self, obj): """ Send data over the stream. Sends the given C{obj} over the connection. C{obj} may be instances of L{domish.Element}, C{unicode} and C{str}. The first two will be properly serialized and/or encoded. C{str} objects must be in UTF-8 encoding. Note: because it is easy to make mistakes in maintaining a properly encoded C{str} object, it is advised to use C{unicode} objects everywhere when dealing with XML Streams. @param obj: Object to be sent over the stream. @type obj: L{domish.Element}, L{domish} or C{str} """ if domish.IElement.providedBy(obj): obj = obj.toXml() if isinstance(obj, unicode): obj = obj.encode('utf-8') if self.rawDataOutFn: self.rawDataOutFn(obj) self.transport.write(obj) class BootstrapMixin(object): """ XmlStream factory mixin to install bootstrap event observers. This mixin is for factories providing L{IProtocolFactory<twisted.internet.interfaces.IProtocolFactory>} to make sure bootstrap event observers are set up on protocols, before incoming data is processed. Such protocols typically derive from L{utility.EventDispatcher}, like L{XmlStream}. You can set up bootstrap event observers using C{addBootstrap}. The C{event} and C{fn} parameters correspond with the C{event} and C{observerfn} arguments to L{utility.EventDispatcher.addObserver}. @since: 8.2. @ivar bootstraps: The list of registered bootstrap event observers. @type bootstrap: C{list} """ def __init__(self): self.bootstraps = [] def installBootstraps(self, dispatcher): """ Install registered bootstrap observers. @param dispatcher: Event dispatcher to add the observers to. @type dispatcher: L{utility.EventDispatcher} """ for event, fn in self.bootstraps: dispatcher.addObserver(event, fn) def addBootstrap(self, event, fn): """ Add a bootstrap event handler. @param event: The event to register an observer for. @type event: C{str} or L{xpath.XPathQuery} @param fn: The observer callable to be registered. """ self.bootstraps.append((event, fn)) def removeBootstrap(self, event, fn): """ Remove a bootstrap event handler. @param event: The event the observer is registered for. @type event: C{str} or L{xpath.XPathQuery} @param fn: The registered observer callable. """ self.bootstraps.remove((event, fn)) class XmlStreamFactoryMixin(BootstrapMixin): """ XmlStream factory mixin that takes care of event handlers. All positional and keyword arguments passed to create this factory are passed on as-is to the protocol. @ivar args: Positional arguments passed to the protocol upon instantiation. @type args: C{tuple}. @ivar kwargs: Keyword arguments passed to the protocol upon instantiation. @type kwargs: C{dict}. """ def __init__(self, *args, **kwargs): BootstrapMixin.__init__(self) self.args = args self.kwargs = kwargs def buildProtocol(self, addr): """ Create an instance of XmlStream. The returned instance will have bootstrap event observers registered and will proceed to handle input on an incoming connection. """ xs = self.protocol(*self.args, **self.kwargs) xs.factory = self self.installBootstraps(xs) return xs class XmlStreamFactory(XmlStreamFactoryMixin, protocol.ReconnectingClientFactory): """ Factory for XmlStream protocol objects as a reconnection client. """ protocol = XmlStream def buildProtocol(self, addr): """ Create a protocol instance. Overrides L{XmlStreamFactoryMixin.buildProtocol} to work with a L{ReconnectingClientFactory}. As this is called upon having an connection established, we are resetting the delay for reconnection attempts when the connection is lost again. """ self.resetDelay() return XmlStreamFactoryMixin.buildProtocol(self, addr)
bsd-3-clause
RdeWilde/yii2
framework/yii/web/User.php
17129
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\web; use Yii; use yii\base\Component; use yii\base\InvalidConfigException; /** * User is the class for the "user" application component that manages the user authentication status. * * In particular, [[User::isGuest]] returns a value indicating whether the current user is a guest or not. * Through methods [[login()]] and [[logout()]], you can change the user authentication status. * * User works with a class implementing the [[Identity]] interface. This class implements * the actual user authentication logic and is often backed by a user database table. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class User extends Component { const EVENT_BEFORE_LOGIN = 'beforeLogin'; const EVENT_AFTER_LOGIN = 'afterLogin'; const EVENT_BEFORE_LOGOUT = 'beforeLogout'; const EVENT_AFTER_LOGOUT = 'afterLogout'; /** * @var string the class name of the [[identity]] object. */ public $identityClass; /** * @var boolean whether to enable cookie-based login. Defaults to false. */ public $enableAutoLogin = false; /** * @var string|array the URL for login when [[loginRequired()]] is called. * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL. * The first element of the array should be the route to the login action, and the rest of * the name-value pairs are GET parameters used to construct the login URL. For example, * * ~~~ * array('site/login', 'ref' => 1) * ~~~ * * If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called. */ public $loginUrl = array('site/login'); /** * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true. * @see Cookie */ public $identityCookie = array('name' => '_identity', 'httpOnly' => true); /** * @var integer the number of seconds in which the user will be logged out automatically if he * remains inactive. If this property is not set, the user will be logged out after * the current session expires (c.f. [[Session::timeout]]). */ public $authTimeout; /** * @var boolean whether to automatically renew the identity cookie each time a page is requested. * This property is effective only when [[enableAutoLogin]] is true. * When this is false, the identity cookie will expire after the specified duration since the user * is initially logged in. When this is true, the identity cookie will expire after the specified duration * since the user visits the site the last time. * @see enableAutoLogin */ public $autoRenewCookie = true; /** * @var string the session variable name used to store the value of [[id]]. */ public $idVar = '__id'; /** * @var string the session variable name used to store the value of expiration timestamp of the authenticated state. * This is used when [[authTimeout]] is set. */ public $authTimeoutVar = '__expire'; /** * @var string the session variable name used to store the value of [[returnUrl]]. */ public $returnUrlVar = '__returnUrl'; private $_access = array(); /** * Initializes the application component. */ public function init() { parent::init(); if ($this->identityClass === null) { throw new InvalidConfigException('User::identityClass must be set.'); } if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) { throw new InvalidConfigException('User::identityCookie must contain the "name" element.'); } Yii::$app->getSession()->open(); $this->renewAuthStatus(); if ($this->enableAutoLogin) { if ($this->getIsGuest()) { $this->loginByCookie(); } elseif ($this->autoRenewCookie) { $this->renewIdentityCookie(); } } } private $_identity = false; /** * Returns the identity object associated with the currently logged user. * @return Identity the identity object associated with the currently logged user. * Null is returned if the user is not logged in (not authenticated). * @see login * @see logout */ public function getIdentity() { if ($this->_identity === false) { $id = $this->getId(); if ($id === null) { $this->_identity = null; } else { /** @var $class Identity */ $class = Yii::import($this->identityClass); $this->_identity = $class::findIdentity($id); } } return $this->_identity; } /** * Sets the identity object. * This method should be mainly be used by the User component or its child class * to maintain the identity object. * * You should normally update the user identity via methods [[login()]], [[logout()]] * or [[switchIdentity()]]. * * @param Identity $identity the identity object associated with the currently logged user. */ public function setIdentity($identity) { $this->_identity = $identity; } /** * Logs in a user. * * This method stores the necessary session information to keep track * of the user identity information. If `$duration` is greater than 0 * and [[enableAutoLogin]] is true, it will also send out an identity * cookie to support cookie-based login. * * @param Identity $identity the user identity (which should already be authenticated) * @param integer $duration number of seconds that the user can remain in logged-in status. * Defaults to 0, meaning login till the user closes the browser or the session is manually destroyed. * If greater than 0 and [[enableAutoLogin]] is true, cookie-based login will be supported. * @return boolean whether the user is logged in */ public function login($identity, $duration = 0) { if ($this->beforeLogin($identity, false)) { $this->switchIdentity($identity, $duration); $this->afterLogin($identity, false); } return !$this->getIsGuest(); } /** * Logs in a user by cookie. * * This method attempts to log in a user using the ID and authKey information * provided by the given cookie. */ protected function loginByCookie() { $name = $this->identityCookie['name']; $value = Yii::$app->getRequest()->getCookies()->getValue($name); if ($value !== null) { $data = json_decode($value, true); if (count($data) === 3 && isset($data[0], $data[1], $data[2])) { list ($id, $authKey, $duration) = $data; /** @var $class Identity */ $class = $this->identityClass; $identity = $class::findIdentity($id); if ($identity !== null && $identity->validateAuthKey($authKey)) { if ($this->beforeLogin($identity, true)) { $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0); $this->afterLogin($identity, true); } } elseif ($identity !== null) { Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__); } } } } /** * Logs out the current user. * This will remove authentication-related session data. * If `$destroySession` is true, all session data will be removed. * @param boolean $destroySession whether to destroy the whole session. Defaults to true. */ public function logout($destroySession = true) { $identity = $this->getIdentity(); if ($identity !== null && $this->beforeLogout($identity)) { $this->switchIdentity(null); if ($destroySession) { Yii::$app->getSession()->destroy(); } $this->afterLogout($identity); } } /** * Returns a value indicating whether the user is a guest (not authenticated). * @return boolean whether the current user is a guest. */ public function getIsGuest() { return $this->getIdentity() === null; } /** * Returns a value that uniquely represents the user. * @return string|integer the unique identifier for the user. If null, it means the user is a guest. */ public function getId() { return Yii::$app->getSession()->get($this->idVar); } /** * Returns the URL that the user should be redirected to after successful login. * This property is usually used by the login action. If the login is successful, * the action should read this property and use it to redirect the user browser. * @param string|array $defaultUrl the default return URL in case it was not set previously. * If this is null, it means [[Application::homeUrl]] will be redirected to. * Please refer to [[\yii\helpers\Html::url()]] on acceptable URL formats. * @return string the URL that the user should be redirected to after login. * @see loginRequired */ public function getReturnUrl($defaultUrl = null) { $url = Yii::$app->getSession()->get($this->returnUrlVar, $defaultUrl); return $url === null ? Yii::$app->getHomeUrl() : $url; } /** * @param string|array $url the URL that the user should be redirected to after login. * Please refer to [[\yii\helpers\Html::url()]] on acceptable URL formats. */ public function setReturnUrl($url) { Yii::$app->getSession()->set($this->returnUrlVar, $url); } /** * Redirects the user browser to the login page. * Before the redirection, the current URL (if it's not an AJAX url) will be * kept as [[returnUrl]] so that the user browser may be redirected back * to the current page after successful login. Make sure you set [[loginUrl]] * so that the user browser can be redirected to the specified login URL after * calling this method. * After calling this method, the current request processing will be terminated. */ public function loginRequired() { $request = Yii::$app->getRequest(); if (!$request->getIsAjax()) { $this->setReturnUrl($request->getUrl()); } if ($this->loginUrl !== null) { $response = Yii::$app->getResponse(); $response->redirect($this->loginUrl)->send(); exit(); } else { throw new HttpException(403, Yii::t('yii', 'Login Required')); } } /** * This method is called before logging in a user. * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event. * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param Identity $identity the user identity information * @param boolean $cookieBased whether the login is cookie-based * @return boolean whether the user should continue to be logged in */ protected function beforeLogin($identity, $cookieBased) { $event = new UserEvent(array( 'identity' => $identity, 'cookieBased' => $cookieBased, )); $this->trigger(self::EVENT_BEFORE_LOGIN, $event); return $event->isValid; } /** * This method is called after the user is successfully logged in. * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event. * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param Identity $identity the user identity information * @param boolean $cookieBased whether the login is cookie-based */ protected function afterLogin($identity, $cookieBased) { $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent(array( 'identity' => $identity, 'cookieBased' => $cookieBased, ))); } /** * This method is invoked when calling [[logout()]] to log out a user. * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event. * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param Identity $identity the user identity information * @return boolean whether the user should continue to be logged out */ protected function beforeLogout($identity) { $event = new UserEvent(array( 'identity' => $identity, )); $this->trigger(self::EVENT_BEFORE_LOGOUT, $event); return $event->isValid; } /** * This method is invoked right after a user is logged out via [[logout()]]. * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event. * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param Identity $identity the user identity information */ protected function afterLogout($identity) { $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent(array( 'identity' => $identity, ))); } /** * Renews the identity cookie. * This method will set the expiration time of the identity cookie to be the current time * plus the originally specified cookie duration. */ protected function renewIdentityCookie() { $name = $this->identityCookie['name']; $value = Yii::$app->getRequest()->getCookies()->getValue($name); if ($value !== null) { $data = json_decode($value, true); if (is_array($data) && isset($data[2])) { $cookie = new Cookie($this->identityCookie); $cookie->value = $value; $cookie->expire = time() + (int)$data[2]; Yii::$app->getResponse()->getCookies()->add($cookie); } } } /** * Sends an identity cookie. * This method is used when [[enableAutoLogin]] is true. * It saves [[id]], [[Identity::getAuthKey()|auth key]], and the duration of cookie-based login * information in the cookie. * @param Identity $identity * @param integer $duration number of seconds that the user can remain in logged-in status. * @see loginByCookie */ protected function sendIdentityCookie($identity, $duration) { $cookie = new Cookie($this->identityCookie); $cookie->value = json_encode(array( $identity->getId(), $identity->getAuthKey(), $duration, )); $cookie->expire = time() + $duration; Yii::$app->getResponse()->getCookies()->add($cookie); } /** * Switches to a new identity for the current user. * * This method will save necessary session information to keep track of the user authentication status. * If `$duration` is provided, it will also send out appropriate identity cookie * to support cookie-based login. * * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]] * when the current user needs to be associated with the corresponding identity information. * * @param Identity $identity the identity information to be associated with the current user. * If null, it means switching to be a guest. * @param integer $duration number of seconds that the user can remain in logged-in status. * This parameter is used only when `$identity` is not null. */ public function switchIdentity($identity, $duration = 0) { $session = Yii::$app->getSession(); if (YII_ENV !== 'test') { $session->regenerateID(true); } $this->setIdentity($identity); $session->remove($this->idVar); $session->remove($this->authTimeoutVar); if ($identity instanceof Identity) { $session->set($this->idVar, $identity->getId()); if ($this->authTimeout !== null) { $session->set($this->authTimeoutVar, time() + $this->authTimeout); } if ($duration > 0 && $this->enableAutoLogin) { $this->sendIdentityCookie($identity, $duration); } } elseif ($this->enableAutoLogin) { Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie)); } } /** * Updates the authentication status according to [[authTimeout]]. * This method is called during [[init()]]. * It will update the user's authentication status if it has not outdated yet. * Otherwise, it will logout the user. */ protected function renewAuthStatus() { if ($this->authTimeout !== null && !$this->getIsGuest()) { $expire = Yii::$app->getSession()->get($this->authTimeoutVar); if ($expire !== null && $expire < time()) { $this->logout(false); } else { Yii::$app->getSession()->set($this->authTimeoutVar, time() + $this->authTimeout); } } } /** * Performs access check for this user. * @param string $operation the name of the operation that need access check. * @param array $params name-value pairs that would be passed to business rules associated * with the tasks and roles assigned to the user. A param with name 'userId' is added to * this array, which holds the value of [[id]] when [[DbAuthManager]] or * [[PhpAuthManager]] is used. * @param boolean $allowCaching whether to allow caching the result of access check. * When this parameter is true (default), if the access check of an operation was performed * before, its result will be directly returned when calling this method to check the same * operation. If this parameter is false, this method will always call * [[AuthManager::checkAccess()]] to obtain the up-to-date access result. Note that this * caching is effective only within the same request and only works when `$params = array()`. * @return boolean whether the operations can be performed by this user. */ public function checkAccess($operation, $params = array(), $allowCaching = true) { $auth = Yii::$app->getAuthManager(); if ($auth === null) { return false; } if ($allowCaching && empty($params) && isset($this->_access[$operation])) { return $this->_access[$operation]; } $access = $auth->checkAccess($this->getId(), $operation, $params); if ($allowCaching && empty($params)) { $this->_access[$operation] = $access; } return $access; } }
bsd-3-clause
delkyd/Oracle-Cloud
PaaS-SaaS_DataSync/DataSync/Pharmacy/Pharmacy/src/com/oracle/pts/pharmacy/wsclient/PharmacyWSService.java
2857
package com.oracle.pts.pharmacy.wsclient; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceFeature; // !DO NOT EDIT THIS FILE! // This source file is generated by Oracle tools // Contents may be subject to change // For reporting problems, use the following // Version = Oracle WebServices (11.1.1.0.0, build 130224.1947.04102) @WebServiceClient(wsdlLocation="http://localhost:7101/Pharmacy/PharmacyWSPort?WSDL", targetNamespace="http://pharmacy.webservice.pts.oracle.com/", name="PharmacyWSService") public class PharmacyWSService extends Service { private static URL wsdlLocationURL; private static Logger logger; static { try { logger = Logger.getLogger("com.oracle.pts.pharmacy.wsclient.PharmacyWSService"); URL baseUrl = PharmacyWSService.class.getResource("."); if (baseUrl == null) { wsdlLocationURL = PharmacyWSService.class.getResource("http://localhost:7101/Pharmacy/PharmacyWSPort?WSDL"); if (wsdlLocationURL == null) { baseUrl = new File(".").toURL(); wsdlLocationURL = new URL(baseUrl, "http://localhost:7101/Pharmacy/PharmacyWSPort?WSDL"); } } else { if (!baseUrl.getPath().endsWith("/")) { baseUrl = new URL(baseUrl, baseUrl.getPath() + "/"); } wsdlLocationURL = new URL(baseUrl, "http://localhost:7101/Pharmacy/PharmacyWSPort?WSDL"); } } catch (MalformedURLException e) { logger.log(Level.ALL, "Failed to create wsdlLocationURL using http://localhost:7101/Pharmacy/PharmacyWSPort?WSDL", e); } } public PharmacyWSService() { super(wsdlLocationURL, new QName("http://pharmacy.webservice.pts.oracle.com/", "PharmacyWSService")); } public PharmacyWSService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } @WebEndpoint(name="PharmacyWSPort") public PharmacyWS getPharmacyWSPort() { return (PharmacyWS) super.getPort(new QName("http://pharmacy.webservice.pts.oracle.com/", "PharmacyWSPort"), PharmacyWS.class); } @WebEndpoint(name="PharmacyWSPort") public PharmacyWS getPharmacyWSPort(WebServiceFeature... features) { return (PharmacyWS) super.getPort(new QName("http://pharmacy.webservice.pts.oracle.com/", "PharmacyWSPort"), PharmacyWS.class, features); } }
bsd-3-clause
motobreath/UC-Merced-Template-V2
module/Admin/src/Admin/Controller/UsersController.php
2495
<?php namespace Admin\Controller; use Zend\Mvc\Controller\AbstractActionController; use Admin\Form; class UsersController extends AbstractActionController { /** * User Mapper (Table Gateway UserTable) * @var \Application\Model\UserTable */ private $userMapper; /** * Role Mapper (Table Gateway RoleTable) * @var \Application\Model\RoleTable */ private $roleMapper; public function indexAction(){ $this->getServiceLocator()->get('ViewHelperManager')->get('InlineScript')->appendFile('/js/admin.js'); $form = new Form\AdminUsers(); $form->setInputFilter( new Form\Validation\AdminFilter( $this->getServiceLocator() ) ); $request = $this->getRequest(); if( $request->isPost() ){ $form->setData( $request->getPost() ); if( $form->isValid() ){ $user = new \Application\Model\User(); $user->exchangeArray( $form->getData() ); $user->name = $user->ucmnetid; $userID = $this->getUserMapper()->save($user); $role = new \Application\Model\Role(); $role->exchangeArray(array( 'id' => 0, 'userID' => $userID, 'role' => 'admin' )); $this->getRoleMapper()->save($role); $this->flashMessenger()->addSuccessMessage("<strong>Success!</strong> Administrator was added. Add another?"); return $this->redirect()->toUrl('/admin/users'); } } return array( 'form' => $form, 'admins'=>$this->getUserMapper()->getAdmins(), 'successMessages'=>$this->flashMessenger()->getSuccessMessages() ); } /** * Ajax call */ public function modifyadminAction(){ $adminID = $this->params()->fromPost('admin'); $this->getUserMapper()->delete($adminID); return $this->getRoleMapper()->deleteUser($adminID); } public function getRoleMapper() { if( $this->roleMapper == null ){ $this->roleMapper = $this->getServiceLocator()->get('Application\Model\RoleMapper'); } return $this->roleMapper; } public function getUserMapper() { if( $this->userMapper == null ){ $this->userMapper = $this->getServiceLocator()->get('Application\Model\UserMapper'); } return $this->userMapper; } }
bsd-3-clause
ric2b/Vivaldi-browser
chromium/content/browser/background_sync/background_sync_metrics_unittest.cc
5570
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/metrics/histogram_tester.h" #include "testing/gtest/include/gtest/gtest.h" #include "content/browser/background_sync/background_sync_metrics.h" #include "third_party/blink/public/mojom/background_sync/background_sync.mojom.h" namespace content { using blink::mojom::BackgroundSyncType; class BackgroundSyncMetricsTest : public ::testing::Test { public: BackgroundSyncMetricsTest() = default; ~BackgroundSyncMetricsTest() override = default; protected: base::HistogramTester histogram_tester_; DISALLOW_COPY_AND_ASSIGN(BackgroundSyncMetricsTest); }; TEST_F(BackgroundSyncMetricsTest, RecordEventStarted) { BackgroundSyncMetrics::RecordEventStarted(BackgroundSyncType::ONE_SHOT, /* started_in_foreground= */ false); histogram_tester_.ExpectBucketCount( "BackgroundSync.Event.OneShotStartedInForeground", false, 1); BackgroundSyncMetrics::RecordEventStarted(BackgroundSyncType::PERIODIC, /* started_in_foreground= */ true); histogram_tester_.ExpectBucketCount( "BackgroundSync.Event.PeriodicStartedInForeground", true, 1); } TEST_F(BackgroundSyncMetricsTest, RecordRegistrationComplete) { BackgroundSyncMetrics::RecordRegistrationComplete( /* event_succeeded= */ true, /* num_attempts_required= */ 3); histogram_tester_.ExpectBucketCount( "BackgroundSync.Registration.OneShot.EventSucceededAtCompletion", true, 1); histogram_tester_.ExpectBucketCount( "BackgroundSync.Registration.OneShot.NumAttemptsForSuccessfulEvent", 3, 1); } TEST_F(BackgroundSyncMetricsTest, RecordEventResult) { BackgroundSyncMetrics::RecordEventResult(BackgroundSyncType::ONE_SHOT, /* event_succeeded= */ true, /* finished_in_foreground= */ true); histogram_tester_.ExpectBucketCount( "BackgroundSync.Event.OneShotResultPattern", BackgroundSyncMetrics::ResultPattern::RESULT_PATTERN_SUCCESS_FOREGROUND, 1); BackgroundSyncMetrics::RecordEventResult(BackgroundSyncType::PERIODIC, /* event_succeeded= */ false, /* finished_in_foreground= */ false); histogram_tester_.ExpectBucketCount( "BackgroundSync.Event.PeriodicResultPattern", BackgroundSyncMetrics::ResultPattern::RESULT_PATTERN_FAILED_BACKGROUND, 1); } TEST_F(BackgroundSyncMetricsTest, RecordBatchSyncEventComplete) { BackgroundSyncMetrics::RecordBatchSyncEventComplete( BackgroundSyncType::ONE_SHOT, base::TimeDelta::FromSeconds(1), /* from_wakeup_task= */ false, /* number_of_batched_sync_events= */ 1); histogram_tester_.ExpectUniqueSample( "BackgroundSync.Event.Time", base::TimeDelta::FromSeconds(1).InMilliseconds(), 1); BackgroundSyncMetrics::RecordBatchSyncEventComplete( BackgroundSyncType::PERIODIC, base::TimeDelta::FromMinutes(1), /* from_wakeup_task= */ false, /* number_of_batched_sync_events= */ 10); histogram_tester_.ExpectUniqueSample( "PeriodicBackgroundSync.Event.Time", base::TimeDelta::FromMinutes(1).InMilliseconds(), 1); } TEST_F(BackgroundSyncMetricsTest, CountRegisterSuccess) { BackgroundSyncMetrics::CountRegisterSuccess( BackgroundSyncType::ONE_SHOT, /* min_interval_ms= */ -1, BackgroundSyncMetrics::REGISTRATION_COULD_FIRE, /* registration_is_duplicate= */ BackgroundSyncMetrics::REGISTRATION_IS_NOT_DUPLICATE); histogram_tester_.ExpectUniqueSample( "BackgroundSync.Registration.OneShot.CouldFire", 1, 1); histogram_tester_.ExpectUniqueSample("BackgroundSync.Registration.OneShot", BACKGROUND_SYNC_STATUS_OK, 1); histogram_tester_.ExpectUniqueSample( "BackgroundSync.Registration.OneShot.IsDuplicate", 0, 1); BackgroundSyncMetrics::CountRegisterSuccess( BackgroundSyncType::PERIODIC, /* min_interval_ms= */ 1000, BackgroundSyncMetrics::REGISTRATION_COULD_FIRE, /* registration_is_duplicate= */ BackgroundSyncMetrics::REGISTRATION_IS_DUPLICATE); histogram_tester_.ExpectUniqueSample( "BackgroundSync.Registration.Periodic.MinInterval", 1, 1); histogram_tester_.ExpectUniqueSample("BackgroundSync.Registration.Periodic", BACKGROUND_SYNC_STATUS_OK, 1); histogram_tester_.ExpectUniqueSample( "BackgroundSync.Registration.Periodic.IsDuplicate", 1, 1); } TEST_F(BackgroundSyncMetricsTest, CountUnregisterPeriodicSync) { BackgroundSyncMetrics::CountUnregisterPeriodicSync(BACKGROUND_SYNC_STATUS_OK); histogram_tester_.ExpectUniqueSample("BackgroundSync.Unregistration.Periodic", BACKGROUND_SYNC_STATUS_OK, 1); } TEST_F(BackgroundSyncMetricsTest, EventsFiredFromWakeupTask) { BackgroundSyncMetrics::RecordEventsFiredFromWakeupTask( BackgroundSyncType::ONE_SHOT, /* events_fired= */ false); histogram_tester_.ExpectBucketCount( "BackgroundSync.WakeupTaskFiredEvents.OneShot", false, 1); BackgroundSyncMetrics::RecordEventsFiredFromWakeupTask( BackgroundSyncType::PERIODIC, /* events_fired= */ true); histogram_tester_.ExpectBucketCount( "BackgroundSync.WakeupTaskFiredEvents.Periodic", true, 1); } } // namespace content
bsd-3-clause
phcorp/doctrineviz
env/AppKernel.php
831
<?php use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\HttpKernel\Kernel; class AppKernel extends Kernel { public function registerBundles() { $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Janalis\Doctrineviz\DoctrinevizBundle(), ]; if (in_array($this->getEnvironment(), ['dev', 'test'], true)) { $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml'); } }
bsd-3-clause
chromium2014/src
chrome/browser/sync_file_system/drive_backend/remote_to_local_syncer_unittest.cc
17698
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/drive_backend/remote_to_local_syncer.h" #include <map> #include "base/bind.h" #include "base/callback.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/run_loop.h" #include "base/thread_task_runner_handle.h" #include "chrome/browser/drive/drive_uploader.h" #include "chrome/browser/drive/fake_drive_service.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_test_util.h" #include "chrome/browser/sync_file_system/drive_backend/fake_drive_service_helper.h" #include "chrome/browser/sync_file_system/drive_backend/list_changes_task.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_context.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_initializer.h" #include "chrome/browser/sync_file_system/drive_backend/sync_task_manager.h" #include "chrome/browser/sync_file_system/drive_backend/sync_task_token.h" #include "chrome/browser/sync_file_system/fake_remote_change_processor.h" #include "chrome/browser/sync_file_system/sync_file_system_test_util.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/test/test_browser_thread_bundle.h" #include "google_apis/drive/gdata_errorcode.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/src/helpers/memenv/memenv.h" #include "third_party/leveldatabase/src/include/leveldb/env.h" namespace sync_file_system { namespace drive_backend { namespace { fileapi::FileSystemURL URL(const GURL& origin, const std::string& path) { return CreateSyncableFileSystemURL( origin, base::FilePath::FromUTF8Unsafe(path)); } } // namespace class RemoteToLocalSyncerTest : public testing::Test { public: typedef FakeRemoteChangeProcessor::URLToFileChangesMap URLToFileChangesMap; RemoteToLocalSyncerTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {} virtual ~RemoteToLocalSyncerTest() {} virtual void SetUp() OVERRIDE { ASSERT_TRUE(database_dir_.CreateUniqueTempDir()); in_memory_env_.reset(leveldb::NewMemEnv(leveldb::Env::Default())); scoped_ptr<drive::FakeDriveService> fake_drive_service(new drive::FakeDriveService); scoped_ptr<drive::DriveUploaderInterface> drive_uploader(new drive::DriveUploader( fake_drive_service.get(), base::ThreadTaskRunnerHandle::Get().get())); fake_drive_helper_.reset( new FakeDriveServiceHelper(fake_drive_service.get(), drive_uploader.get(), kSyncRootFolderTitle)); remote_change_processor_.reset(new FakeRemoteChangeProcessor); context_.reset(new SyncEngineContext( fake_drive_service.PassAs<drive::DriveServiceInterface>(), drive_uploader.Pass(), NULL, base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get())); context_->SetRemoteChangeProcessor(remote_change_processor_.get()); RegisterSyncableFileSystem(); sync_task_manager_.reset(new SyncTaskManager( base::WeakPtr<SyncTaskManager::Client>(), 10 /* max_parallel_task */, base::ThreadTaskRunnerHandle::Get())); sync_task_manager_->Initialize(SYNC_STATUS_OK); } virtual void TearDown() OVERRIDE { sync_task_manager_.reset(); RevokeSyncableFileSystem(); fake_drive_helper_.reset(); context_.reset(); base::RunLoop().RunUntilIdle(); } void InitializeMetadataDatabase() { SyncEngineInitializer* initializer = new SyncEngineInitializer(context_.get(), database_dir_.path(), in_memory_env_.get()); SyncStatusCode status = SYNC_STATUS_UNKNOWN; sync_task_manager_->ScheduleSyncTask( FROM_HERE, scoped_ptr<SyncTask>(initializer), SyncTaskManager::PRIORITY_MED, base::Bind(&RemoteToLocalSyncerTest::DidInitializeMetadataDatabase, base::Unretained(this), initializer, &status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SYNC_STATUS_OK, status); } void DidInitializeMetadataDatabase(SyncEngineInitializer* initializer, SyncStatusCode* status_out, SyncStatusCode status) { *status_out = status; context_->SetMetadataDatabase(initializer->PassMetadataDatabase()); } void RegisterApp(const std::string& app_id, const std::string& app_root_folder_id) { SyncStatusCode status = SYNC_STATUS_FAILED; context_->GetMetadataDatabase()->RegisterApp(app_id, app_root_folder_id, CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SYNC_STATUS_OK, status); } MetadataDatabase* GetMetadataDatabase() { return context_->GetMetadataDatabase(); } protected: std::string CreateSyncRoot() { std::string sync_root_folder_id; EXPECT_EQ(google_apis::HTTP_CREATED, fake_drive_helper_->AddOrphanedFolder( kSyncRootFolderTitle, &sync_root_folder_id)); return sync_root_folder_id; } std::string CreateRemoteFolder(const std::string& parent_folder_id, const std::string& title) { std::string folder_id; EXPECT_EQ(google_apis::HTTP_CREATED, fake_drive_helper_->AddFolder( parent_folder_id, title, &folder_id)); return folder_id; } std::string CreateRemoteFile(const std::string& parent_folder_id, const std::string& title, const std::string& content) { std::string file_id; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->AddFile( parent_folder_id, title, content, &file_id)); return file_id; } void DeleteRemoteFile(const std::string& file_id) { EXPECT_EQ(google_apis::HTTP_NO_CONTENT, fake_drive_helper_->DeleteResource(file_id)); } void CreateLocalFolder(const fileapi::FileSystemURL& url) { remote_change_processor_->UpdateLocalFileMetadata( url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY)); } void CreateLocalFile(const fileapi::FileSystemURL& url) { remote_change_processor_->UpdateLocalFileMetadata( url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE)); } SyncStatusCode RunSyncer() { SyncStatusCode status = SYNC_STATUS_UNKNOWN; scoped_ptr<RemoteToLocalSyncer> syncer(new RemoteToLocalSyncer(context_.get())); syncer->RunPreflight(SyncTaskToken::CreateForTesting( CreateResultReceiver(&status))); base::RunLoop().RunUntilIdle(); return status; } void RunSyncerUntilIdle() { SyncStatusCode status = SYNC_STATUS_UNKNOWN; while (status != SYNC_STATUS_NO_CHANGE_TO_SYNC) status = RunSyncer(); } SyncStatusCode ListChanges() { SyncStatusCode status = SYNC_STATUS_UNKNOWN; sync_task_manager_->ScheduleSyncTask( FROM_HERE, scoped_ptr<SyncTask>(new ListChangesTask(context_.get())), SyncTaskManager::PRIORITY_MED, CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); return status; } void AppendExpectedChange(const fileapi::FileSystemURL& url, FileChange::ChangeType change_type, SyncFileType file_type) { expected_changes_[url].push_back(FileChange(change_type, file_type)); } void VerifyConsistency() { remote_change_processor_->VerifyConsistency(expected_changes_); } private: content::TestBrowserThreadBundle thread_bundle_; base::ScopedTempDir database_dir_; scoped_ptr<leveldb::Env> in_memory_env_; scoped_ptr<SyncEngineContext> context_; scoped_ptr<FakeDriveServiceHelper> fake_drive_helper_; scoped_ptr<FakeRemoteChangeProcessor> remote_change_processor_; scoped_ptr<SyncTaskManager> sync_task_manager_; URLToFileChangesMap expected_changes_; DISALLOW_COPY_AND_ASSIGN(RemoteToLocalSyncerTest); }; TEST_F(RemoteToLocalSyncerTest, AddNewFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); const std::string folder1 = CreateRemoteFolder(app_root, "folder1"); const std::string file1 = CreateRemoteFile(app_root, "file1", "data1"); const std::string folder2 = CreateRemoteFolder(folder1, "folder2"); const std::string file2 = CreateRemoteFile(folder1, "file2", "data2"); RunSyncerUntilIdle(); // Create expected changes. // TODO(nhiroki): Clean up creating URL part. AppendExpectedChange(URL(kOrigin, "folder1"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); AppendExpectedChange(URL(kOrigin, "file1"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); AppendExpectedChange(URL(kOrigin, "folder1/folder2"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); AppendExpectedChange(URL(kOrigin, "folder1/file2"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); VerifyConsistency(); EXPECT_FALSE(GetMetadataDatabase()->HasDirtyTracker()); } TEST_F(RemoteToLocalSyncerTest, DeleteFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); const std::string folder = CreateRemoteFolder(app_root, "folder"); const std::string file = CreateRemoteFile(app_root, "file", "data"); AppendExpectedChange(URL(kOrigin, "folder"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); AppendExpectedChange(URL(kOrigin, "file"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); RunSyncerUntilIdle(); VerifyConsistency(); DeleteRemoteFile(folder); DeleteRemoteFile(file); AppendExpectedChange(URL(kOrigin, "folder"), FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_UNKNOWN); AppendExpectedChange(URL(kOrigin, "file"), FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_UNKNOWN); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); EXPECT_FALSE(GetMetadataDatabase()->HasDirtyTracker()); } TEST_F(RemoteToLocalSyncerTest, DeleteNestedFiles) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); const std::string folder1 = CreateRemoteFolder(app_root, "folder1"); const std::string file1 = CreateRemoteFile(app_root, "file1", "data1"); const std::string folder2 = CreateRemoteFolder(folder1, "folder2"); const std::string file2 = CreateRemoteFile(folder1, "file2", "data2"); AppendExpectedChange(URL(kOrigin, "folder1"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); AppendExpectedChange(URL(kOrigin, "file1"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); AppendExpectedChange(URL(kOrigin, "folder1/folder2"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); AppendExpectedChange(URL(kOrigin, "folder1/file2"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); RunSyncerUntilIdle(); VerifyConsistency(); DeleteRemoteFile(folder1); AppendExpectedChange(URL(kOrigin, "folder1"), FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_UNKNOWN); // Changes for descendant files ("folder2" and "file2") should be ignored. EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); EXPECT_FALSE(GetMetadataDatabase()->HasDirtyTracker()); } TEST_F(RemoteToLocalSyncerTest, Conflict_CreateFileOnFolder) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateLocalFolder(URL(kOrigin, "folder")); CreateRemoteFile(app_root, "folder", "data"); // Folder-File conflict happens. File creation should be ignored. EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); // Tracker for the remote file should be lowered. EXPECT_FALSE(GetMetadataDatabase()->GetNormalPriorityDirtyTracker(NULL)); EXPECT_TRUE(GetMetadataDatabase()->HasLowPriorityDirtyTracker()); } TEST_F(RemoteToLocalSyncerTest, Conflict_CreateFolderOnFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); RunSyncerUntilIdle(); VerifyConsistency(); CreateLocalFile(URL(kOrigin, "file")); CreateRemoteFolder(app_root, "file"); // File-Folder conflict happens. Folder should override the existing file. AppendExpectedChange(URL(kOrigin, "file"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); EXPECT_FALSE(GetMetadataDatabase()->HasDirtyTracker()); } TEST_F(RemoteToLocalSyncerTest, Conflict_CreateFolderOnFolder) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateLocalFolder(URL(kOrigin, "folder")); CreateRemoteFolder(app_root, "folder"); // Folder-Folder conflict happens. Folder creation should be ignored. EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); EXPECT_FALSE(GetMetadataDatabase()->HasDirtyTracker()); } TEST_F(RemoteToLocalSyncerTest, Conflict_CreateFileOnFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateLocalFile(URL(kOrigin, "file")); CreateRemoteFile(app_root, "file", "data"); // File-File conflict happens. File creation should be ignored. EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); // Tracker for the remote file should be lowered. EXPECT_FALSE(GetMetadataDatabase()->GetNormalPriorityDirtyTracker(NULL)); EXPECT_TRUE(GetMetadataDatabase()->HasLowPriorityDirtyTracker()); } TEST_F(RemoteToLocalSyncerTest, Conflict_CreateNestedFolderOnFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); RunSyncerUntilIdle(); VerifyConsistency(); const std::string folder = CreateRemoteFolder(app_root, "folder"); CreateLocalFile(URL(kOrigin, "/folder")); CreateRemoteFile(folder, "file", "data"); // File-Folder conflict happens. Folder should override the existing file. AppendExpectedChange(URL(kOrigin, "/folder"), FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); } TEST_F(RemoteToLocalSyncerTest, AppRootDeletion) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); RunSyncerUntilIdle(); VerifyConsistency(); DeleteRemoteFile(app_root); AppendExpectedChange(URL(kOrigin, "/"), FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_UNKNOWN); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); RunSyncerUntilIdle(); VerifyConsistency(); // SyncEngine will re-register the app and resurrect the app root later. } } // namespace drive_backend } // namespace sync_file_system
bsd-3-clause
omco/geode
geode/mesh/module.cpp
521
//##################################################################### // Module mesh //##################################################################### #include <geode/python/wrap.h> using namespace geode; void wrap_mesh() { GEODE_WRAP(ids) GEODE_WRAP(polygon_mesh) GEODE_WRAP(segment_soup) GEODE_WRAP(triangle_mesh) GEODE_WRAP(triangle_subdivision) GEODE_WRAP(halfedge_mesh) GEODE_WRAP(corner_mesh) GEODE_WRAP(mesh_io) GEODE_WRAP(lower_hull) GEODE_WRAP(decimate) GEODE_WRAP(improve_mesh) }
bsd-3-clause
pombredanne/pythran
pythran/tests/euler/euler35.py
1138
#runas solve(1000000) # pythran export solve(int) def solve(a): """ The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ sieve = [True] * a sieve[0] = sieve[1] = False def mark(sieve, x): for i in range(x+x, len(sieve), x): sieve[i] = False for x in range(2, int(len(sieve) ** 0.5) + 1): mark(sieve, x) def circular(n): digits = [] while n > 0: digits.insert(0, str(n % 10)) n = n // 10 for d in range(1, len(digits)): yield int(''.join(digits[d:] + digits[0:d])) count = 0 for n, p in enumerate(sieve): if p: iscircularprime = 1 for m in circular(n): if not sieve[m]: iscircularprime = 0 break if iscircularprime: count = count + 1 return count
bsd-3-clause
tomhughes/node-mapnik
test/image_view.test.js
10324
"use strict"; var mapnik = require('../'); var assert = require('assert'); var fs = require('fs'); describe('mapnik.ImageView ', function() { it('should throw with invalid usage', function() { // no 'new' keyword assert.throws(function() { mapnik.ImageView(1, 1); }); assert.throws(function() { new mapnik.ImageView(); }); }); it('should be initialized properly', function() { var im = new mapnik.Image(256, 256); var view = im.view(0, 0, 256, 256); assert.equal(view.isSolidSync(), true); var pixel = view.getPixel(0, 0, {get_color:true}); assert.equal(pixel.r, 0); assert.equal(pixel.g, 0); assert.equal(pixel.b, 0); assert.equal(pixel.a, 0); im = new mapnik.Image(256, 256); im.fill(new mapnik.Color(2, 2, 2, 2)); view = im.view(0, 0, 256, 256); assert.equal(view.isSolidSync(), true); pixel = view.getPixel(0, 0, {get_color:true}); assert.equal(pixel.r, 2); assert.equal(pixel.g, 2); assert.equal(pixel.b, 2); assert.equal(pixel.a, 2); assert.equal(view.getPixel(99999999, 9999999), undefined); }); it('isSolid for view should return blue with view being offset', function(done) { var im = new mapnik.Image(256, 256); im.fill(new mapnik.Color('blue')); im.setPixel(0,0,new mapnik.Color('green')); var view = im.view(1, 1, 255, 255); assert.equal(view.isSolid(), true); assert.equal(view.isSolidSync(), true); view.isSolid(function(err,solid,pixel) { assert.equal(solid, true); assert.equal(pixel, 4294901760); done(); }); }); it('isSolid async works if true', function(done) { var im = new mapnik.Image(256, 256); var view = im.view(0, 0, 256, 256); assert.equal(view.isSolidSync(), true); view.isSolid(function(err,solid,pixel) { assert.equal(solid, true); assert.equal(pixel, 0); done(); }); }); it('isSolid async works if true and white', function(done) { var im = new mapnik.Image(256, 256); var color = new mapnik.Color('white'); im.fill(color); var view = im.view(0, 0, 256, 256); assert.equal(view.isSolidSync(), true); view.isSolid(function(err,solid,pixel) { assert.equal(solid, true); assert.equal(pixel, 4294967295); done(); }); }); it('isSolid async works if false', function(done) { var im = new mapnik.Image.open('./test/support/a.png'); var view = im.view(0, 0, im.width(), im.height()); assert.equal(view.isSolid(), false); assert.throws(function() { view.isSolid(null); }); assert.equal(view.isSolidSync(), false); view.isSolid(function(err,solid,pixel) { assert.equal(solid, false); assert.equal(pixel, undefined); done(); }); }); it('isSolid should fail with bad parameters', function(done) { var im = new mapnik.Image(0,0); var view = im.view(0,0,0,0); assert.throws(function() { view.isSolidSync(); }); view.isSolid(function(err,solid,pixel) { assert.throws(function() { if (err) throw err; }); done(); }); }); it('getPixel should fail with bad parameters', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.rgba8}); im.fill(1); var view = im.view(0,0,4,4); assert.throws(function() { view.getPixel(); }); assert.throws(function() { view.getPixel(1); }); assert.throws(function() { view.getPixel(1,'2'); }); assert.throws(function() { view.getPixel('1',2); }); assert.throws(function() { view.getPixel(1,2, null); }); assert.throws(function() { view.getPixel(1,2, {get_color:1}); }); }); it('getPixel supports rgba8', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.rgba8}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray8', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray8}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray8s', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray8s}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray16', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray16}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray16s', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray16s}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray32', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray32}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray32s', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray32s}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray32f', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray32f}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray64', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray64}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray64s', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray64s}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('getPixel supports gray64f', function() { var im = new mapnik.Image(4,4,{type: mapnik.imageType.gray64f}); im.fill(1); var view = im.view(0,0,4,4); assert.equal(view.getPixel(0,0), 1); }); it('should throw with invalid encoding', function(done) { var im = new mapnik.Image(256, 256); var view = im.view(0,0,256,256); assert.throws(function() { view.encodeSync('foo'); }); assert.throws(function() { view.encodeSync(1); }); assert.throws(function() { view.encodeSync('png', null); }); assert.throws(function() { view.encodeSync('png', {palette:null}); }); assert.throws(function() { view.encodeSync('png', {palette:{}}); }); assert.throws(function() { view.encode('png', {palette:{}}, function(err, result) {}); }); assert.throws(function() { view.encode('png', {palette:null}, function(err, result) {}); }); assert.throws(function() { view.encode('png', null, function(err, result) {}); }); assert.throws(function() { view.encode(1, {}, function(err, result) {}); }); assert.throws(function() { view.encode('png', {}, null); }); view.encode('foo', {}, function(err, result) { assert.throws(function() { if (err) throw err; }); done(); }); }); it('should encode with a pallete', function(done) { var im = new mapnik.Image(256, 256); var view = im.view(0,0,256,256); var pal = new mapnik.Palette(new Buffer('\xff\x09\x93\xFF\x01\x02\x03\x04','ascii')); assert.ok(view.encodeSync('png', {palette:pal})); view.encode('png', {palette:pal}, function(err, result) { if (err) throw err; assert.ok(result); done(); }); }); it('should be able to save an ImageView', function(done) { var im = new mapnik.Image(256, 256); var view = im.view(0,0,256,256); var pal = new mapnik.Palette(new Buffer('\xff\x09\x93\xFF\x01\x02\x03\x04','ascii')); var expected = './test/tmp/mapnik-image-view-saved.png'; view.save(expected); assert.ok(fs.existsSync(expected)); done(); }); it('should throw with invalid formats', function() { var im = new mapnik.Image(256, 256); var view = im.view(0,0,256,256); assert.throws(function() { view.save('foo','foo'); }); assert.throws(function() { view.save(); }); assert.throws(function() { view.save('file.png', null); }); assert.throws(function() { view.save('foo'); }); assert.throws(function() { view.save('foo','foo'); }); assert.throws(function() { view.save(); }); assert.throws(function() { view.save('file.png', null); }); assert.throws(function() { view.save('foo'); }); assert.throws(function() { view.saveSync(); }); assert.throws(function() { view.saveSync('foo','foo'); }); assert.throws(function() { view.saveSync('file.png', null); }); assert.throws(function() { view.saveSync('foo'); }); assert.throws(function() { view.save(function(err) {}); }); assert.throws(function() { view.save('file.png', null, function(err) {}); }); assert.throws(function() { view.save('foo', function(err) {}); }); }); if (mapnik.supports.webp) { it('should support webp encoding', function(done) { var im = new mapnik.Image(256,256); im.fill(new mapnik.Color('green')); im.encode('webp',function(err,buf1) { // jshint ignore:line if (err) throw err; var v = im.view(0,0,256,256); v.encode('webp', function(err,buf2) { // jshint ignore:line if (err) throw err; // disabled because this is not stable across mapnik versions or webp versions //assert.equal(buf1.length,buf2.length); done(); }); }); }); } });
bsd-3-clause
NCIP/webgenome
java/core/junit/org/rti/webgenome/util/CommandLineTableFormatterTester.java
1162
/*L * Copyright RTI International * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/webgenome/LICENSE.txt for details. */ /* $Source: /share/content/gforge/webcgh/webgenome/java/core/junit/org/rti/webgenome/util/CommandLineTableFormatterTester.java,v $ $Revision: 1.1 $ $Date: 2007-03-29 17:03:30 $ */ package org.rti.webgenome.util; import org.apache.log4j.Logger; import org.rti.webgenome.util.CommandLineTableFormatter; import junit.framework.TestCase; /** * Test case for class <code>CommandLineTableFormatter</code> */ public class CommandLineTableFormatterTester extends TestCase { private static final Logger LOGGER = Logger.getLogger(CommandLineTableFormatterTester.class); /** * * */ public void test1() { CommandLineTableFormatter formatter = new CommandLineTableFormatter(3); formatter.addRow(new String[]{"1", "22", "333"}); formatter.addRow(new String[]{"22", "1", "1"}); formatter.addRow(new String[]{"1", "1", "22"}); formatter.setPadding(5); String table = formatter.getTable(); LOGGER.info("\n" + table); assertEquals(table.length(), 53); } }
bsd-3-clause
smthmlk/phoneypdf
pdf/filters/PDFFilters.py
27110
# Some code has been reused and modified from the original by Mathieu Fenniak: # Parameters management in Flate and LZW algorithms, asciiHexDecode and ascii85Decode # # Copyright (c) 2006, Mathieu Fenniak # All rights reserved. # # 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. # * The name of the author may not 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. # # peepdf is a tool to analyse and modify PDF files # http://peepdf.eternal-todo.com # By Jose Miguel Esparza <jesparza AT eternal-todo.com> # # Copyright (C) 2011 Jose Miguel Esparza # # This file is part of peepdf. # # peepdf is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # peepdf is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with peepdf. If not, see <http://www.gnu.org/licenses/>. # ''' Module to manage encoding/decoding in PDF files ''' import sys, zlib, lzw, struct from PDFUtils import getNumsFromBytes, getBytesFromBits, getBitsFromNum from ccitt import CCITTFax def decodeStream(stream, filter, parameters = {}): ''' Decode the given stream @param stream: Stream to be decoded (string) @param filter: Filter to apply to decode the stream @param parameters: List of PDFObjects containing the parameters for the filter @return: A tuple (status,statusContent), where statusContent is the decoded stream in case status = 0 or an error in case status = -1 ''' if filter == '/ASCIIHexDecode' or filter == 'AHx': ret = asciiHexDecode(stream) elif filter == '/ASCII85Decode' or filter == 'A85': ret = ascii85Decode(stream) elif filter == '/LZWDecode' or filter == 'LZW': ret = lzwDecode(stream, parameters) elif filter == '/FlateDecode' or filter == 'Fl': ret = flateDecode(stream, parameters) elif filter == '/RunLengthDecode' or filter == 'RL': ret = runLengthDecode(stream) elif filter == '/CCITTFaxDecode' or filter == 'CCF': ret = ccittFaxDecode(stream, parameters) elif filter == '/JBIG2Decode': ret = jbig2Decode(stream, parameters) elif filter == '/DCTDecode' or filter == 'DCT': ret = dctDecode(stream, parameters) elif filter == '/JPXDecode': ret = jpxDecode(stream) elif filter == '/Crypt': ret = crypt(stream, parameters) return ret def encodeStream(stream, filter, parameters = {}): ''' Encode the given stream @param stream: Stream to be decoded (string) @param filter: Filter to apply to decode the stream @param parameters: List of PDFObjects containing the parameters for the filter @return: A tuple (status,statusContent), where statusContent is the encoded stream in case status = 0 or an error in case status = -1 ''' if filter == '/ASCIIHexDecode': ret = asciiHexEncode(stream) elif filter == '/ASCII85Decode': ret = ascii85Encode(stream) elif filter == '/LZWDecode': ret = lzwEncode(stream, parameters) elif filter == '/FlateDecode': ret = flateEncode(stream, parameters) elif filter == '/RunLengthDecode': ret = runLengthEncode(stream) elif filter == '/CCITTFaxDecode': ret = ccittFaxEncode(stream, parameters) elif filter == '/JBIG2Decode': ret = jbig2Encode(stream, parameters) elif filter == '/DCTDecode': ret = dctEncode(stream, parameters) elif filter == '/JPXDecode': ret = jpxEncode(stream) elif filter == '/Crypt': ret = crypt(stream, parameters) return ret ''' The ascii85Decode code is part of pdfminer (http://pypi.python.org/pypi/pdfminer/) Copyright (c) 2004-2010 Yusuke Shinyama <yusuke at cs dot nyu dot edu> 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. """ In ASCII85 encoding, every four bytes are encoded with five ASCII letters, using 85 different types of characters (as 256**4 < 85**5). When the length of the original bytes is not a multiple of 4, a special rule is used for round up. The Adobe's ASCII85 implementation is slightly different from its original in handling the last characters. The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85 >>> ascii85decode('9jqo^BlbD-BleB1DJ+*+F(f,q') 'Man is distinguished' >>> ascii85decode('E,9)oF*2M7/c~>') 'pleasure.' """ ''' def ascii85Decode(stream): ''' Method to decode streams using ASCII85 @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' n = b = 0 decodedStream = '' try: for c in stream: if '!' <= c and c <= 'u': n += 1 b = b*85+(ord(c)-33) if n == 5: decodedStream += struct.pack('>L',b) n = b = 0 elif c == 'z': assert n == 0 decodedStream += '\0\0\0\0' elif c == '~': if n: for _ in range(5-n): b = b*85+84 decodedStream += struct.pack('>L',b)[:n-1] break except: return (-1,'Unspecified error') return (0,decodedStream) def ascii85Encode(stream): ''' Method to encode streams using ASCII85 (NOT SUPPORTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' return (-1,'Ascii85Encode not supported yet') def asciiHexDecode(stream): ''' Method to decode streams using hexadecimal encoding @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' eod = '>' decodedStream = '' char = '' index = 0 while index < len(stream): c = stream[index] if c == eod: if len(decodedStream) % 2 != 0: char += '0' try: decodedStream += chr(int(char, base=16)) except: return (-1,'Error in hexadecimal conversion') break elif c.isspace(): index += 1 continue char += c if len(char) == 2: try: decodedStream += chr(int(char, base=16)) except: return (-1,'Error in hexadecimal conversion') char = '' index += 1 return (0,decodedStream) def asciiHexEncode(stream): ''' Method to encode streams using hexadecimal encoding @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' try: encodedStream = stream.encode('hex') except: return (-1,'Error in hexadecimal conversion') return (0,encodedStream) def flateDecode(stream, parameters): ''' Method to decode streams using the Flate algorithm @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' try: decodedStream = zlib.decompress(stream) except: return (-1,'Error decompressing string') if parameters == None or parameters == {}: return (0,decodedStream) else: if parameters.has_key('/Predictor'): predictor = parameters['/Predictor'].getRawValue() else: predictor = 1 # Columns = number of samples per row if parameters.has_key('/Columns'): columns = parameters['/Columns'].getRawValue() else: columns = 1 # Colors = number of components per sample if parameters.has_key('/Colors'): colors = parameters['/Colors'].getRawValue() if colors < 1: colors = 1 else: colors = 1 # BitsPerComponent: number of bits per color component if parameters.has_key('/BitsPerComponent'): bits = parameters['/BitsPerComponent'].getRawValue() if bits not in [1,2,4,8,16]: bits = 8 else: bits = 8 if predictor != None and predictor != 1: ret = post_prediction(decodedStream, predictor, columns, colors, bits) return ret else: return (0,decodedStream) def flateEncode(stream, parameters): ''' Method to encode streams using the Flate algorithm @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' if parameters == None or parameters == {}: try: return (0,zlib.compress(stream)) except: return (-1,'Error compressing string') else: if parameters.has_key('/Predictor'): predictor = parameters['/Predictor'].getRawValue() else: predictor = 1 # Columns = number of samples per row if parameters.has_key('/Columns'): columns = parameters['/Columns'].getRawValue() else: columns = 1 # Colors = number of components per sample if parameters.has_key('/Colors'): colors = parameters['/Colors'].getRawValue() if colors < 1: colors = 1 else: colors = 1 # BitsPerComponent: number of bits per color component if parameters.has_key('/BitsPerComponent'): bits = parameters['/BitsPerComponent'].getRawValue() if bits not in [1,2,4,8,16]: bits = 8 else: bits = 8 if predictor != None and predictor != 1: ret = pre_prediction(stream, predictor, columns, colors, bits) if ret[0] == -1: return ret output = ret[1] else: output = stream try: return (0,zlib.compress(output)) except: return (-1,'Error compressing string') def lzwDecode(stream, parameters): ''' Method to decode streams using the LZW algorithm @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' try: decodedStream = lzw.lzwdecode(stream) except: return (-1,'Error decompressing string') if parameters == None or parameters == {}: return (0,decodedStream) else: if parameters.has_key('/Predictor'): predictor = parameters['/Predictor'].getRawValue() else: predictor = 1 # Columns = number of samples per row if parameters.has_key('/Columns'): columns = parameters['/Columns'].getRawValue() else: columns = 1 # Colors = number of components per sample if parameters.has_key('/Colors'): colors = parameters['/Colors'].getRawValue() if colors < 1: colors = 1 else: colors = 1 # BitsPerComponent: number of bits per color component if parameters.has_key('/BitsPerComponent'): bits = parameters['/BitsPerComponent'].getRawValue() if bits not in [1,2,4,8,16]: bits = 8 else: bits = 8 if parameters.has_key('/EarlyChange'): earlyChange = parameters['/EarlyChange'].getRawValue() else: earlyChange = 1 if predictor != None and predictor != 1: ret = post_prediction(decodedStream, predictor, columns, colors, bits) return ret else: return (0,decodedStream) def lzwEncode(stream, parameters): ''' Method to encode streams using the LZW algorithm @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' if parameters == None or parameters == {}: try: generator = lzw.compress(stream) for c in generator: encodedStream += c return (0,encodedStream) except: return (-1,'Error compressing string') else: if parameters.has_key('/Predictor'): predictor = parameters['/Predictor'].getRawValue() else: predictor = 1 # Columns = number of samples per row if parameters.has_key('/Columns'): columns = parameters['/Columns'].getRawValue() else: columns = 1 # Colors = number of components per sample if parameters.has_key('/Colors'): colors = parameters['/Colors'].getRawValue() if colors < 1: colors = 1 else: colors = 1 # BitsPerComponent: number of bits per color component if parameters.has_key('/BitsPerComponent'): bits = parameters['/BitsPerComponent'].getRawValue() if bits not in [1,2,4,8,16]: bits = 8 else: bits = 8 if parameters.has_key('/EarlyChange'): earlyChange = parameters['/EarlyChange'].getRawValue() else: earlyChange = 1 if predictor != None and predictor != 1: ret = pre_prediction(stream, predictor, columns, colors, bits) if ret[0] == -1: return ret output = ret[1] else: output = stream try: generator = lzw.compress(output) for c in generator: encodedStream += c return (0,encodedStream) except: return (-1,'Error decompressing string') def pre_prediction(stream, predictor, columns, colors, bits): ''' Predictor function to make the stream more predictable and improve compression (PDF Specification) @param stream: The stream to be modified @param predictor: The type of predictor to apply @param columns: Number of samples per row @param colors: Number of colors per sample @param bits: Number of bits per color @return: A tuple (status,statusContent), where statusContent is the modified stream in case status = 0 or an error in case status = -1 ''' output = '' #TODO: TIFF and more PNG predictions # PNG prediction if predictor >= 10 and predictor <= 15: # PNG prediction can vary from row to row for row in xrange(len(stream) / columns): rowdata = [ord(x) for x in stream[(row*columns):((row+1)*columns)]] filterByte = predictor - 10 rowdata = [filterByte]+rowdata if filterByte == 0: pass elif filterByte == 1: for i in range(len(rowdata)-1,1,-1): if rowdata[i] < rowdata[i-1]: rowdata[i] = rowdata[i] + 256 - rowdata[i-1] else: rowdata[i] = rowdata[i] - rowdata[i-1] elif filterByte == 2: (-1,'Unsupported predictor') else: return (-1,'Unsupported predictor') output += (''.join([chr(x) for x in rowdata])) return (0,output) else: return (-1,'Unsupported predictor') def post_prediction(decodedStream, predictor, columns, colors, bits): ''' Predictor function to obtain the real stream, removing the prediction (PDF Specification) @param decodedStream: The decoded stream to be modified @param predictor: The type of predictor to apply @param columns: Number of samples per row @param colors: Number of colors per sample @param bits: Number of bits per color @return: A tuple (status,statusContent), where statusContent is the modified decoded stream in case status = 0 or an error in case status = -1 ''' output = '' bytesPerRow = (colors * bits * columns + 7) / 8 # TIFF - 2 # http://www.gnupdf.org/PNG_and_TIFF_Predictors_Filter#TIFF if predictor == 2: numRows = len(decodedStream) / bytesPerRow bitmask = 2 ** bits - 1 outputBitsStream = '' for rowIndex in range(numRows): row = decodedStream[rowIndex*bytesPerRow:rowIndex*bytesPerRow+bytesPerRow] ret,colorNums = getNumsFromBytes(row, bits) if ret == -1: return (ret,colorNums) pixel = [0 for x in range(colors)] for i in range(columns): for j in range(colors): diffPixel = colorNums[i+j] pixel[j] = (pixel[j] + diffPixel) & bitmask ret, outputBits = getBitsFromNum(pixel[j],bits) if ret == -1: return (ret,outputBits) outputBitsStream += outputBits output = getBytesFromBits(outputBitsStream) return output # PNG prediction # http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html # http://www.gnupdf.org/PNG_and_TIFF_Predictors_Filter#TIFF elif predictor >= 10 and predictor <= 15: bytesPerRow += 1 numRows = (len(decodedStream) + bytesPerRow -1) / bytesPerRow numSamplesPerRow = columns + 1 bytesPerSample = (colors * bits + 7) / 8 upRowdata = (0,) * numSamplesPerRow for row in xrange(numRows): rowdata = [ord(x) for x in decodedStream[(row*bytesPerRow):((row+1)*bytesPerRow)]] # PNG prediction can vary from row to row filterByte = rowdata[0] rowdata[0] = 0 if filterByte == 0: # None pass elif filterByte == 1: # Sub - 11 for i in range(1, numSamplesPerRow): if i < bytesPerSample: prevSample = 0 else: prevSample = rowdata[i-bytesPerSample] rowdata[i] = (rowdata[i] + prevSample) % 256 elif filterByte == 2: # Up - 12 for i in range(1, numSamplesPerRow): upSample = upRowdata[i] rowdata[i] = (rowdata[i] + upSample) % 256 elif filterByte == 3: # Average - 13 for i in range(1, numSamplesPerRow): upSample = upRowdata[i] if i < bytesPerSample: prevSample = 0 else: prevSample = rowdata[i-bytesPerSample] rowdata[i] = (rowdata[i] + ((prevSample+upSample)/2)) % 256 elif filterByte == 4: # Paeth - 14 for i in range(1, numSamplesPerRow): upSample = upRowdata[i] if i < bytesPerSample: prevSample = 0 upPrevSample = 0 else: prevSample = rowdata[i-bytesPerSample] upPrevSample = upRowdata[i-bytesPerSample] p = prevSample + upSample - upPrevSample pa = abs(p - prevSample) pb = abs(p - upSample) pc = abs(p - upPrevSample) if pa <= pb and pa <= pc: nearest = prevSample elif pb <= pc: nearest = upSample else: nearest = upPrevSample rowdata[i] = (rowdata[i] + nearest) % 256 else: # Optimum - 15 #return (-1,'Unsupported predictor') pass upRowdata = rowdata output += (''.join([chr(x) for x in rowdata[1:]])) return (0,output) else: return (-1,'Wrong value for predictor') def runLengthDecode(stream): ''' Method to decode streams using the Run-Length algorithm @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' index = 0 try: while index < len(stream): length = ord(stream[index]) if length >= 0 and length < 128: decodedStream += stream[index+1:index+length+2] index += length+2 elif length > 128 and length < 256: decodedStream += stream[index+1] * (257 - length) index += 2 else: break except: return (-1,'Error decoding string') return (0,decodedStream) def runLengthEncode(stream): ''' Method to encode streams using the Run-Length algorithm (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' return (-1,'RunLengthEncode not supported yet') def ccittFaxDecode(stream, parameters): ''' Method to decode streams using the CCITT facsimile standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' if parameters == None or parameters == {}: try: decodedStream = CCITTFax().decode(stream) return (0, decodedStream) except: return (-1,'Error decompressing string') else: # K = A code identifying the encoding scheme used if parameters.has_key('/K'): k = parameters['/K'].getRawValue() if type(k) != int: k = 0 else: if k != 0: # Only supported "Group 3, 1-D" encoding (Pure one-dimensional encoding) return (-1,'CCITT encoding scheme not supported') else: k = 0 # EndOfLine = A flag indicating whether end-of-line bit patterns are required to be present in the encoding. if parameters.has_key('/EndOfLine'): eol = parameters['/EndOfLine'].getRawValue() if eol == 'true': eol = True else: eol = False else: eol = False # EncodedByteAlign = A flag indicating whether the filter expects extra 0 bits before each encoded line so that the line begins on a byte boundary if parameters.has_key('/EncodedByteAlign'): byteAlign = parameters['/EncodedByteAlign'].getRawValue() if byteAlign == 'true': byteAlign = True else: byteAlign = False else: byteAlign = False # Columns = The width of the image in pixels. if parameters.has_key('/Columns'): columns = parameters['/Columns'].getRawValue() if type(columns) != int: columns = 1728 else: columns = 1728 # Rows = The height of the image in scan lines. if parameters.has_key('/Rows'): rows = parameters['/Rows'].getRawValue() if type(rows) != int: rows = 0 else: rows = 0 # EndOfBlock = number of samples per row if parameters.has_key('/EndOfBlock'): eob = parameters['/EndOfBlock'].getRawValue() if eob == 'false': eob = False else: eob = True else: eob = True # BlackIs1 = A flag indicating whether 1 bits are to be interpreted as black pixels and 0 bits as white pixels if parameters.has_key('/BlackIs1'): blackIs1 = parameters['/BlackIs1'].getRawValue() if blackIs1 == 'true': blackIs1 = True else: blackIs1 = False else: blackIs1 = False # DamagedRowsBeforeError = The number of damaged rows of data to be tolerated before an error occurs if parameters.has_key('/DamagedRowsBeforeError'): damagedRowsBeforeError = parameters['/DamagedRowsBeforeError'].getRawValue() else: damagedRowsBeforeError = 0 try: decodedStream = CCITTFax().decode(stream, k, eol, byteAlign, columns, rows, eob, blackIs1, damagedRowsBeforeError) return (0, decodedStream) except: return (-1,'Error decompressing string') def ccittFaxEncode(stream, parameters): ''' Method to encode streams using the CCITT facsimile standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' return (-1,'CcittFaxEncode not supported yet') def crypt(stream, parameters): ''' Method to encrypt streams using a PDF security handler (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encrypted PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' return (-1,'Crypt not supported yet') def decrypt(stream, parameters): ''' Method to decrypt streams using a PDF security handler (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decrypted PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' return (-1,'Decrypt not supported yet') def dctDecode(stream, parameters): ''' Method to decode streams using a DCT technique based on the JPEG standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' return (-1,'DctDecode not supported yet') def dctEncode(stream, parameters): ''' Method to encode streams using a DCT technique based on the JPEG standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' return (-1,'DctEncode not supported yet') def jbig2Decode(stream, parameters): ''' Method to decode streams using the JBIG2 standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' return (-1,'Jbig2Decode not supported yet') def jbig2Encode(stream, parameters): ''' Method to encode streams using the JBIG2 standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' return (-1,'Jbig2Encode not supported yet') def jpxDecode(stream): ''' Method to decode streams using the JPEG2000 standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the decoded PDF stream in case status = 0 or an error in case status = -1 ''' decodedStream = '' return (-1,'JpxDecode not supported yet') def jpxEncode(stream): ''' Method to encode streams using the JPEG2000 standard (NOT IMPLEMENTED YET) @param stream: A PDF stream @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1 ''' encodedStream = '' return (-1,'JpxEncode not supported yet')
bsd-3-clause
Artemish/jodd
jodd-core/src/test/java/jodd/typeconverter/SqlTimestampConverterTest.java
2719
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved. package jodd.typeconverter; import jodd.datetime.JDateTime; import jodd.typeconverter.impl.SqlTimestampConverter; import org.junit.Test; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; import static org.junit.Assert.*; public class SqlTimestampConverterTest { private static long time = new JDateTime(2011, 11, 1, 9, 10, 12, 567).getTimeInMillis(); SqlTimestampConverter sqlTimestampConverter = new SqlTimestampConverter(); @Test public void testNull() { assertNull(sqlTimestampConverter.convert(null)); } @Test public void testCalendar2Timestamp() { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(time); Timestamp timestamp = sqlTimestampConverter.convert(calendar); assertEquals(time, timestamp.getTime()); } @Test public void testDate2Timestamp() { Date date = new Date(time); Timestamp timestamp = sqlTimestampConverter.convert(date); assertEquals(time, timestamp.getTime()); } @Test public void testTimestamp2Timestamp() { Timestamp timestamp2 = new Timestamp(time); Timestamp timestamp = sqlTimestampConverter.convert(timestamp2); assertEquals(time, timestamp.getTime()); } @Test public void testSqlDate2Timestamp() { java.sql.Date date = new java.sql.Date(time); Timestamp timestamp = sqlTimestampConverter.convert(date); assertEquals(time, timestamp.getTime()); } @Test public void testSqlTime2Timestamp() { Time sqltime = new Time(time); Timestamp timestamp = sqlTimestampConverter.convert(sqltime); assertEquals(time, timestamp.getTime()); } @Test public void testJDateTime2Timestamp() { JDateTime jdt = new JDateTime(time); Timestamp timestamp = sqlTimestampConverter.convert(jdt); assertEquals(time, timestamp.getTime()); } @Test public void testConversion() { assertNull(sqlTimestampConverter.convert(null)); assertEquals(Timestamp.valueOf("2011-01-01 00:01:02"), sqlTimestampConverter.convert(Timestamp.valueOf("2011-01-01 00:01:02"))); assertEquals(new Timestamp(60), sqlTimestampConverter.convert(Integer.valueOf(60))); assertEquals(Timestamp.valueOf("2011-01-01 00:01:02"), sqlTimestampConverter.convert("2011-01-01 00:01:02")); assertEquals(Timestamp.valueOf("2011-01-01 00:01:02"), sqlTimestampConverter.convert(" 2011-01-01 00:01:02 ")); try { sqlTimestampConverter.convert("00:01"); fail(); } catch (TypeConversionException ignore) { } try { sqlTimestampConverter.convert("a"); fail(); } catch (TypeConversionException ignore) { } } }
bsd-3-clause
eric-chau/Relational
library/Respect/Relational/Mapper.php
20006
<?php namespace Respect\Relational; use Exception; use PDO; use SplObjectStorage; use InvalidArgumentException; use PDOStatement; use PDOException; use stdClass; use Respect\Data\AbstractMapper; use Respect\Data\Collections\Collection; use Respect\Data\Collections as c; use Respect\Data\CollectionIterator; use ReflectionProperty; use ReflectionClass; /** Maps objects to database operations */ class Mapper extends AbstractMapper implements c\Filterable, c\Mixable, c\Typable { /** * Holds our connector * * @var Db */ protected $db; /** * Namespace to look for entities. * * @var string */ public $entityNamespace = '\\'; /** * Disable or enable entity constructors. * * @var bool */ public $disableEntityConstructor = false; /** * @param mixed $db Db or Pdo */ public function __construct($db) { parent::__construct(); if ($db instanceof PDO) { $this->db = new Db($db); } elseif ($db instanceof Db) { $this->db = $db; } else { throw new InvalidArgumentException( '$db must be an instance of Respect\Relational\Db or PDO.' ); } } /** * Flushes a single instance into the database. This method supports * mixing, so flushing a mixed instance will flush distinct tables on the * database. * * @param object $entity Entity instance to be flushed */ protected function flushSingle($entity) { $coll = $this->tracked[$entity]; $cols = $this->extractColumns($entity, $coll); if ($this->removed->contains($entity)) { $this->rawDelete($cols, $coll, $entity); } elseif ($this->new->contains($entity)) { $this->rawInsert($cols, $coll, $entity); } else { $this->rawUpdate($cols, $coll); } } public function persist($object, Collection $onCollection) { $next = $onCollection->getNext(); if ($this->filterable($onCollection)) { $next->setMapper($this); $next->persist($object); return; } if ($next) { $remote = $this->getStyle()->remoteIdentifier($next->getName()); $next->setMapper($this); $next->persist($this->inferGet($object, $remote)); } foreach ($onCollection->getChildren() as $child) { $remote = $this->getStyle()->remoteIdentifier($child->getName()); $child->persist($this->inferGet($object, $remote)); } return parent::persist($object, $onCollection); } /** * Receives columns from an entity and her collection. Returns the columns * that belong only to the main entity. This method supports mixing, so * extracting mixins will also persist them on their respective * tables. * * @param Collection $collection Target collection * @param array $cols Entity columns * * @return array Columns left for the main collection */ protected function extractAndOperateMixins(Collection $collection, $cols) { if (!$this->mixable($collection)) { return $cols; } foreach ($this->getMixins($collection) as $mix => $spec) { //Extract from $cols only the columns from the mixin $mixCols = array_intersect_key( $cols, array_combine( //create array with keys only $spec, array_fill(0, count($spec), '') ) ); if (isset($cols["{$mix}_id"])) { $mixCols['id'] = $cols["{$mix}_id"]; $cols = array_diff($cols, $mixCols); //Remove mixin columns $this->rawUpdate($mixCols, $this->__get($mix)); } else { $mixCols['id'] = null; $cols = array_diff($cols, $mixCols); //Remove mixin columns $this->rawinsert($mixCols, $this->__get($mix)); } } return $cols; } protected function guessCondition(&$columns, Collection $collection) { $primaryName = $this->getStyle()->identifier($collection->getName()); $condition = array($primaryName => $columns[$primaryName]); unset($columns[$primaryName]); return $condition; } protected function rawDelete( array $condition, Collection $collection, $entity ) { $name = $collection->getName(); $columns = $this->extractColumns($entity, $collection); $condition = $this->guessCondition($columns, $collection); return $this->db ->deleteFrom($name) ->where($condition) ->exec(); } protected function rawUpdate(array $columns, Collection $collection) { $columns = $this->extractAndOperateMixins($collection, $columns); $name = $collection->getName(); $condition = $this->guessCondition($columns, $collection); return $this->db ->update($name) ->set($columns) ->where($condition) ->exec(); } protected function rawInsert( array $columns, Collection $collection, $entity = null ) { $columns = $this->extractAndOperateMixins($collection, $columns); $name = $collection->getName(); $isInserted = $this->db ->insertInto($name, $columns) ->values($columns) ->exec(); if (!is_null($entity)) { $this->checkNewIdentity($entity, $collection); } return $isInserted; } public function flush() { $conn = $this->db->getConnection(); $conn->beginTransaction(); try { foreach ($this->changed as $entity) { $this->flushSingle($entity); } } catch (Exception $e) { $conn->rollback(); throw $e; } $this->reset(); $conn->commit(); } protected function checkNewIdentity($entity, Collection $collection) { $identity = null; try { $identity = $this->db->getConnection()->lastInsertId(); } catch (PDOException $e) { //some drivers may throw an exception here, it is just irrelevant return false; } if (!$identity) { return false; } $primaryName = $this->getStyle()->identifier($collection->getName()); $this->inferSet($entity, $primaryName, $identity); return true; } protected function createStatement( Collection $collection, $withExtra = null ) { $query = $this->generateQuery($collection); if ($withExtra instanceof Sql) { $query->appendQuery($withExtra); } $statement = $this->db->prepare((string) $query, PDO::FETCH_NUM); $statement->execute($query->getParams()); return $statement; } protected function generateQuery(Collection $collection) { $collections = iterator_to_array( CollectionIterator::recursive($collection), true ); $sql = new Sql(); $this->buildSelectStatement($sql, $collections); $this->buildTables($sql, $collections); return $sql; } protected function extractColumns($entity, Collection $collection) { $primaryName = $this->getStyle()->identifier($collection->getName()); $cols = $this->getAllProperties($entity); foreach ($cols as &$c) { if (is_object($c)) { $c = $this->inferGet($c, $primaryName); } } return $cols; } protected function buildSelectStatement(Sql $sql, $collections) { $selectTable = array(); foreach ($collections as $tableSpecifier => $c) { if ($this->mixable($c)) { foreach ($this->getMixins($c) as $mixin => $columns) { foreach ($columns as $col) { $selectTable[] = "{$tableSpecifier}_mix{$mixin}.$col"; } $selectTable[] = "{$tableSpecifier}_mix{$mixin}.". $this->getStyle()->identifier($mixin). " as {$mixin}_id"; } } if ($this->filterable($c)) { $filters = $this->getFilters($c); if ($filters) { $pkName = $tableSpecifier.'.'. $this->getStyle()->identifier($c->getName()); if ($filters == array('*')) { $selectColumns[] = $pkName; } else { $selectColumns = array( $tableSpecifier.'.'. $this->getStyle()->identifier($c->getName()), ); foreach ($filters as $f) { $selectColumns[] = "{$tableSpecifier}.{$f}"; } } if ($c->getNext()) { $selectColumns[] = $tableSpecifier.'.'. $this->getStyle()->remoteIdentifier( $c->getNext()->getName() ); } $selectTable = array_merge($selectTable, $selectColumns); } } else { $selectTable[] = "$tableSpecifier.*"; } } return $sql->select($selectTable); } protected function buildTables(Sql $sql, $collections) { $conditions = $aliases = array(); foreach ($collections as $alias => $collection) { $this->parseCollection( $sql, $collection, $alias, $aliases, $conditions ); } return $sql->where($conditions); } protected function parseConditions(&$conditions, $collection, $alias) { $entity = $collection->getName(); $originalConditions = $collection->getCondition(); $parsedConditions = array(); $aliasedPk = $this->getStyle()->identifier($entity); $aliasedPk = $alias.'.'.$aliasedPk; if (is_scalar($originalConditions)) { $parsedConditions = array($aliasedPk => $originalConditions); } elseif (is_array($originalConditions)) { foreach ($originalConditions as $column => $value) { if (is_numeric($column)) { $parsedConditions[$column] = preg_replace( "/{$entity}[.](\w+)/", "$alias.$1", $value ); } else { $parsedConditions["$alias.$column"] = $value; } } } return $parsedConditions; } protected function parseMixins(Sql $sql, Collection $collection, $entity) { if ($this->mixable($collection)) { foreach ($this->getMixins($collection) as $mix => $spec) { $sql->innerJoin($mix); $sql->as("{$entity}_mix{$mix}"); } } } protected function parseCollection( Sql $sql, Collection $collection, $alias, &$aliases, &$conditions ) { $s = $this->getStyle(); $entity = $collection->getName(); $parent = $collection->getParentName(); $next = $collection->getNextName(); $parentAlias = $parent ? $aliases[$parent] : null; $aliases[$entity] = $alias; $conditions = $this->parseConditions( $conditions, $collection, $alias ) ?: $conditions; //No parent collection means it's the first table in the query if (is_null($parentAlias)) { $sql->from($entity); $this->parseMixins($sql, $collection, $entity); return; } else { if ($collection->isRequired()) { $sql->innerJoin($entity); } else { $sql->leftJoin($entity); } $this->parseMixins($sql, $collection, $entity); if ($alias !== $entity) { $sql->as($alias); } $aliasedPk = $alias.'.'.$s->identifier($entity); $aliasedParentPk = $parentAlias.'.'.$s->identifier($parent); if ($this->hasComposition($entity, $next, $parent)) { $onName = $alias.'.'.$s->remoteIdentifier($parent); $onAlias = $aliasedParentPk; } else { $onName = $parentAlias.'.'.$s->remoteIdentifier($entity); $onAlias = $aliasedPk; } return $sql->on(array($onName => $onAlias)); } } protected function hasComposition($entity, $next, $parent) { $s = $this->getStyle(); return $entity === $s->composed($parent, $next) || $entity === $s->composed($next, $parent); } protected function fetchSingle( Collection $collection, PDOStatement $statement ) { $name = $collection->getName(); $entityName = $name; $row = $statement->fetch(PDO::FETCH_OBJ); if (!$row) { return false; } if ($this->typable($collection)) { $entityName = $this->inferGet($row, $this->getType($collection)); } $entities = new SplObjectStorage(); $entities[$this->transformSingleRow($row, $entityName)] = $collection; return $entities; } protected function getNewEntityByName($entityName) { $entityName = $this->getStyle()->styledName($entityName); $entityClass = $this->entityNamespace.$entityName; $entityClass = class_exists($entityClass) ? $entityClass : '\stdClass'; $entityReflection = new ReflectionClass($entityClass); if (!$this->disableEntityConstructor) { return $entityReflection->newInstanceArgs(); } return $entityReflection->newInstanceWithoutConstructor(); } protected function transformSingleRow($row, $entityName) { $newRow = $this->getNewEntityByName($entityName); foreach ($row as $prop => $value) { $this->inferSet($newRow, $prop, $value); } return $newRow; } protected function inferSet(&$entity, $prop, $value) { try { $mirror = new \ReflectionProperty($entity, $prop); $mirror->setAccessible(true); $mirror->setValue($entity, $value); } catch (\ReflectionException $e) { $entity->{$prop} = $value; } } protected function inferGet(&$object, $prop) { try { $mirror = new \ReflectionProperty($object, $prop); $mirror->setAccessible(true); return $mirror->getValue($object); } catch (\ReflectionException $e) { return; } } protected function fetchMulti( Collection $collection, PDOStatement $statement ) { $entities = array(); $row = $statement->fetch(PDO::FETCH_NUM); if (!$row) { return false; } $this->postHydrate( $entities = $this->createEntities($row, $statement, $collection) ); return $entities; } protected function createEntities( $row, PDOStatement $statement, Collection $collection ) { $entities = new SplObjectStorage(); $entitiesInstances = $this->buildEntitiesInstances( $collection, $entities ); $entityInstance = array_pop($entitiesInstances); //Reversely traverses the columns to avoid conflicting foreign key names foreach (array_reverse($row, true) as $col => $value) { $columnMeta = $statement->getColumnMeta($col); $columnName = $columnMeta['name']; $primaryName = $this->getStyle()->identifier( $entities[$entityInstance]->getName() ); $this->inferSet($entityInstance, $columnName, $value); if ($primaryName == $columnName) { $entityInstance = array_pop($entitiesInstances); } } return $entities; } protected function buildEntitiesInstances( Collection $collection, SplObjectStorage $entities ) { $entitiesInstances = array(); foreach (CollectionIterator::recursive($collection) as $c) { if ($this->filterable($c) && !$this->getFilters($c)) { continue; } $entityInstance = $this->getNewEntityByName($c->getName()); $mixins = array(); if ($this->mixable($c)) { $mixins = $this->getMixins($c); foreach ($mixins as $mix) { $entitiesInstances[] = $entityInstance; } } $entities[$entityInstance] = $c; $entitiesInstances[] = $entityInstance; } return $entitiesInstances; } protected function postHydrate(SplObjectStorage $entities) { $entitiesClone = clone $entities; foreach ($entities as $instance) { foreach ($this->getAllProperties($instance) as $field => $v) { if (!$this->getStyle()->isRemoteIdentifier($field)) { continue; } foreach ($entitiesClone as $sub) { $this->tryHydration($entities, $sub, $field, $v); } $this->inferSet($instance, $field, $v); } } } protected function tryHydration($entities, $sub, $field, &$v) { $tableName = $entities[$sub]->getName(); $primaryName = $this->getStyle()->identifier($tableName); if ($tableName === $this->getStyle()->remoteFromIdentifier($field) && $this->inferGet($sub, $primaryName) === $v) { $v = $sub; } } protected function getSetterStyle($name) { $name = str_replace('_', '', $this->getStyle()->styledProperty($name)); return "set{$name}"; } protected function getAllProperties($object) { $cols = get_object_vars($object); $ref = new \ReflectionClass($object); foreach ($ref->getProperties() as $prop) { if (preg_match('/@Relational\\\isNotColumn/', $prop->getDocComment())) { continue; } $prop->setAccessible(true); $cols[$prop->name] = $prop->getValue($object); } return $cols; } public function getFilters(Collection $collection) { return $collection->getExtra('filters'); } public function getMixins(Collection $collection) { return $collection->getExtra('mixins'); } public function getType(Collection $collection) { return $collection->getExtra('type'); } public function mixable(Collection $collection) { return $collection->have('mixins'); } public function typable(Collection $collection) { return $collection->have('type'); } public function filterable(Collection $collection) { return $collection->have('filters'); } }
bsd-3-clause
Phoenix1708/t2-server-jar-android-0.1
t2-server-jar-android-0.1-hyde/src/main/java/uk/org/taverna/server/client/connection/params/AbstractConnectionParams.java
2915
/* * Copyright (c) 2010, 2011 The University of Manchester, UK. * * All rights reserved. * * 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 names of The University of Manchester 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 uk.org.taverna.server.client.connection.params; import java.util.HashMap; /** * * @author Robert Haines */ public abstract class AbstractConnectionParams implements ConnectionParams { protected final HashMap<String, Object> params; public AbstractConnectionParams() { this.params = new HashMap<String, Object>(); params.put(NULL_CONNECTION, false); } @Override public Object getParameter(String id) { return params.get(id); } @Override public Object removeParameter(String id) { return params.remove(id); } @Override public ConnectionParams setParameter(String id, Object value) { params.put(id, value); return this; } @Override public boolean getBooleanParameter(String id, boolean defaultValue) { Boolean bool = (Boolean) params.get(id); if (bool == null) { bool = defaultValue; } return bool; } @Override public ConnectionParams setBooleanParameter(String id, boolean value) { params.put(id, value); return this; } @Override public boolean isParameterTrue(String id) { return getBooleanParameter(id, false) == true; } @Override public boolean isParameterFalse(String id) { return getBooleanParameter(id, false) == false; } }
bsd-3-clause
qur/gopy
lib/float.go
1182
// Copyright 2011 Julian Phillips. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package py // #include "utils.h" import "C" import ( "fmt" "unsafe" ) type Float struct { AbstractObject NumberProtocol o C.PyFloatObject } // FloatType is the Type object that represents the Float type. var FloatType = (*Type)(unsafe.Pointer(&C.PyFloat_Type)) func floatCheck(obj Object) bool { return C.floatCheck(c(obj)) != 0 } func newFloat(obj *C.PyObject) *Float { return (*Float)(unsafe.Pointer(obj)) } func NewFloat(v float64) (*Float, error) { ret := C.PyFloat_FromDouble(C.double(v)) if ret == nil { return nil, exception() } return newFloat(ret), nil } func NewFloatString(v string) (*Float, error) { s, err := NewString(v) if err != nil { return nil, err } defer s.Decref() ret := C.PyFloat_FromString(c(s), nil) if ret == nil { return nil, exception() } return newFloat(ret), nil } func (f *Float) Float64() float64 { return float64(C.PyFloat_AsDouble(c(f))) } func (f *Float) String() string { if f == nil { return "<nil>" } return fmt.Sprintf("%v", f.Float64()) }
bsd-3-clause
Xyresic/Kaku
app/src/main/java/ca/fuwafuwa/kaku/XmlParsers/KanjiDict2/Kd2DTO/Kd2Radical.java
1036
package ca.fuwafuwa.kaku.XmlParsers.KanjiDict2.Kd2DTO; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import ca.fuwafuwa.kaku.XmlParsers.KanjiDict2.Kd2Consts; /** * Created by 0xbad1d3a5 on 12/1/2016. */ public class Kd2Radical { private static final String XMLTAG = Kd2Consts.RADICAL; private List<Kd2RadValue> rad_value = new ArrayList<>(); public Kd2Radical(XmlPullParser parser) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, XMLTAG); parser.nextToken(); while (!XMLTAG.equals(parser.getName())){ String name = parser.getName() == null ? "" : parser.getName(); switch(name){ case Kd2Consts.RAD_VALUE: rad_value.add(new Kd2RadValue(parser)); } parser.nextToken(); } parser.require(XmlPullParser.END_TAG, null, XMLTAG); } }
bsd-3-clause
development2015/kds
backend/views/slru/sukarelawan/ss2_progwarga.php
1355
<?php use yii\helpers\Html; use yii\grid\GridView; use yii\helpers\Url; use miloschuman\highcharts\Highcharts; /* @var $this yii\web\View */ $this->title = 'Komuniti Development System'; ?> <br><br> <?php foreach ($model11 as $key => $value) { // store data in array $ya[] = (int)$value['ya']; // x axis must integer value $tidak[] = (int)$value['tidak']; // x axis must integer value $state[] = $value['state']; } // store array data to temp variable $xAxis = $state; $yAxisP = $tidak; $yAxisL = $ya; echo Highcharts::widget([ 'scripts' => [ 'modules/exporting', // adds Exporting button/menu to chart ], 'options' => [ 'chart' => [ 'type' => 'column' ], 'title' => ['text' => 'Slru - Sukarelawan Progam Warga Emas'], 'xAxis' => [ 'categories' => $xAxis, ], 'yAxis' => [ 'title' => [ 'text' => 'Jumlah', 'align' => 'high'], 'labels' => ['overflow' => 'justify'] ], 'plotOptions' => [ 'column' => [ 'dataLabels' => [ 'enabled' => true, 'align' => 'center',] ] ], 'series' => [ ['name' => 'Ya', 'data' => $yAxisL], ['name' => 'Tidak', 'data' => $yAxisP] ] ] ]); ?>
bsd-3-clause
vadimtk/chrome4sdp
third_party/WebKit/Source/core/editing/FrameSelectionTest.cpp
7117
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/editing/FrameSelection.h" #include "bindings/core/v8/ExceptionStatePlaceholder.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Text.h" #include "core/frame/FrameView.h" #include "core/html/HTMLBodyElement.h" #include "core/html/HTMLDocument.h" #include "core/testing/DummyPageHolder.h" #include "wtf/OwnPtr.h" #include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" #include "wtf/StdLibExtras.h" #include <gtest/gtest.h> namespace blink { class FrameSelectionTest : public ::testing::Test { protected: void SetUp() override; DummyPageHolder& dummyPageHolder() const { return *m_dummyPageHolder; } HTMLDocument& document() const; void setSelection(const VisibleSelection&); FrameSelection& selection() const; PassRefPtrWillBeRawPtr<Text> appendTextNode(const String& data); int layoutCount() const { return m_dummyPageHolder->frameView().layoutCount(); } private: OwnPtr<DummyPageHolder> m_dummyPageHolder; RawPtrWillBePersistent<HTMLDocument> m_document; RefPtrWillBePersistent<Text> m_textNode; }; void FrameSelectionTest::SetUp() { m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600)); m_document = toHTMLDocument(&m_dummyPageHolder->document()); ASSERT(m_document); } HTMLDocument& FrameSelectionTest::document() const { return *m_document; } void FrameSelectionTest::setSelection(const VisibleSelection& newSelection) { m_dummyPageHolder->frame().selection().setSelection(newSelection); } FrameSelection& FrameSelectionTest::selection() const { return m_dummyPageHolder->frame().selection(); } PassRefPtrWillBeRawPtr<Text> FrameSelectionTest::appendTextNode(const String& data) { RefPtrWillBeRawPtr<Text> text = document().createTextNode(data); document().body()->appendChild(text); return text.release(); } TEST_F(FrameSelectionTest, SetValidSelection) { RefPtrWillBeRawPtr<Text> text = appendTextNode("Hello, World!"); VisibleSelection validSelection(Position(text, 0), Position(text, 5)); EXPECT_FALSE(validSelection.isNone()); setSelection(validSelection); EXPECT_FALSE(selection().isNone()); } TEST_F(FrameSelectionTest, SetInvalidSelection) { // Create a new document without frame by using DOMImplementation. DocumentInit dummy; RefPtrWillBeRawPtr<Document> documentWithoutFrame = Document::create(); RefPtrWillBeRawPtr<Element> body = documentWithoutFrame->createElement(HTMLNames::bodyTag, false); documentWithoutFrame->appendChild(body); RefPtrWillBeRawPtr<Text> anotherText = documentWithoutFrame->createTextNode("Hello, another world"); body->appendChild(anotherText); // Create a new VisibleSelection for the new document without frame and // update FrameSelection with the selection. VisibleSelection invalidSelection; invalidSelection.setWithoutValidation(Position(anotherText, 0), Position(anotherText, 5)); setSelection(invalidSelection); EXPECT_TRUE(selection().isNone()); } TEST_F(FrameSelectionTest, InvalidateCaretRect) { RefPtrWillBeRawPtr<Text> text = appendTextNode("Hello, World!"); document().view()->updateAllLifecyclePhases(); VisibleSelection validSelection(Position(text, 0), Position(text, 0)); setSelection(validSelection); selection().setCaretRectNeedsUpdate(); EXPECT_TRUE(selection().isCaretBoundsDirty()); selection().invalidateCaretRect(); EXPECT_FALSE(selection().isCaretBoundsDirty()); document().body()->removeChild(text); document().updateLayoutIgnorePendingStylesheets(); selection().setCaretRectNeedsUpdate(); EXPECT_TRUE(selection().isCaretBoundsDirty()); selection().invalidateCaretRect(); EXPECT_FALSE(selection().isCaretBoundsDirty()); } TEST_F(FrameSelectionTest, PaintCaretShouldNotLayout) { RefPtrWillBeRawPtr<Text> text = appendTextNode("Hello, World!"); document().view()->updateAllLifecyclePhases(); document().body()->setContentEditable("true", ASSERT_NO_EXCEPTION); document().body()->focus(); EXPECT_TRUE(document().body()->focused()); VisibleSelection validSelection(Position(text, 0), Position(text, 0)); selection().setCaretVisible(true); setSelection(validSelection); EXPECT_TRUE(selection().isCaret()); EXPECT_TRUE(selection().ShouldPaintCaretForTesting()); int startCount = layoutCount(); { // To force layout in next updateLayout calling, widen view. FrameView& frameView = dummyPageHolder().frameView(); IntRect frameRect = frameView.frameRect(); frameRect.setWidth(frameRect.width() + 1); frameRect.setHeight(frameRect.height() + 1); dummyPageHolder().frameView().setFrameRect(frameRect); } selection().paintCaret(nullptr, LayoutPoint(), LayoutRect()); EXPECT_EQ(startCount, layoutCount()); } #define EXPECT_EQ_SELECTED_TEXT(text) \ EXPECT_EQ(text, WebString(selection().selectedText()).utf8()) TEST_F(FrameSelectionTest, SelectWordAroundPosition) { // "Foo Bar Baz," RefPtrWillBeRawPtr<Text> text = appendTextNode("Foo Bar&nbsp;&nbsp;Baz,"); // "Fo|o Bar Baz," EXPECT_TRUE(selection().selectWordAroundPosition(VisiblePosition(Position(text, 2)))); EXPECT_EQ_SELECTED_TEXT("Foo"); // "Foo| Bar Baz," EXPECT_TRUE(selection().selectWordAroundPosition(VisiblePosition(Position(text, 3)))); EXPECT_EQ_SELECTED_TEXT("Foo"); // "Foo Bar | Baz," EXPECT_FALSE(selection().selectWordAroundPosition(VisiblePosition(Position(text, 13)))); // "Foo Bar Baz|," EXPECT_TRUE(selection().selectWordAroundPosition(VisiblePosition(Position(text, 22)))); EXPECT_EQ_SELECTED_TEXT("Baz"); } TEST_F(FrameSelectionTest, MoveRangeSelectionTest) { // "Foo Bar Baz," RefPtrWillBeRawPtr<Text> text = appendTextNode("Foo Bar Baz,"); // Itinitializes with "Foo B|a>r Baz," (| means start and > means end). selection().setSelection(VisibleSelection(Position(text, 5), Position(text, 6))); EXPECT_EQ_SELECTED_TEXT("a"); // "Foo B|ar B>az," with the Character granularity. selection().moveRangeSelection(VisiblePosition(Position(text, 5)), VisiblePosition(Position(text, 9)), CharacterGranularity); EXPECT_EQ_SELECTED_TEXT("ar B"); // "Foo B|ar B>az," with the Word granularity. selection().moveRangeSelection(VisiblePosition(Position(text, 5)), VisiblePosition(Position(text, 9)), WordGranularity); EXPECT_EQ_SELECTED_TEXT("Bar Baz"); // "Fo<o B|ar Baz," with the Character granularity. selection().moveRangeSelection(VisiblePosition(Position(text, 5)), VisiblePosition(Position(text, 2)), CharacterGranularity); EXPECT_EQ_SELECTED_TEXT("o B"); // "Fo<o B|ar Baz," with the Word granularity. selection().moveRangeSelection(VisiblePosition(Position(text, 5)), VisiblePosition(Position(text, 2)), WordGranularity); EXPECT_EQ_SELECTED_TEXT("Foo Bar"); } } // namespace blink
bsd-3-clause
SonicLighter/yii2
console/migrations/m160711_110840_comments.php
932
<?php use yii\db\Migration; class m160711_110840_comments extends Migration { public function up() { $this->createTable('comments',[ 'id' => $this->primaryKey(), 'userId' => $this->integer()->notNull(), 'postId' => $this->integer()->notNull(), 'message' => $this->text()->notNull(), ]); $this->addForeignKey('fk_comments_users', 'comments', 'userId', 'users', 'id'); $this->addForeignKey('fk_comments_posts', 'comments', 'postId', 'posts', 'id'); } public function down() { $this->dropForeignKey('fk_comments_users', 'comments'); $this->dropForeignKey('fk_comments_posts', 'comments'); $this->dropTable('comments'); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ }
bsd-3-clause
luxiaohan/openxal-csns-luxh
apps/bricks/src/xal/app/bricks/TreeUtility.java
1682
// // TreeUtility.java // xal // // Created by Thomas Pelaia on 7/28/06. // Copyright 2006 Oak Ridge National Lab. All rights reserved. // package xal.app.bricks; import xal.extension.bricks.*; import javax.swing.*; import javax.swing.tree.*; import java.util.ArrayList; import java.util.List; /** utility for performing common bricks operations on the tree of bricks */ public class TreeUtility { /** get the selected bean node */ static BeanNode<?> getSelectedBeanNode( final JTree tree ) { final TreePath selectionPath = tree.getSelectionPath(); return getBeanNode( selectionPath ); } /** get the selected bean nodes */ static BeanNode<?>[] getSelectedBeanNodes( final JTree tree ) { final TreePath[] selectionPaths = tree.getSelectionPaths(); if ( selectionPaths == null ) return new BeanNode<?>[0]; final List<BeanNode<?>> nodes = new ArrayList<BeanNode<?>>( selectionPaths.length ); for ( final TreePath treePath : selectionPaths ) { final BeanNode<?> node = getBeanNode( treePath ); if ( node != null ) { nodes.add( node ); } } return nodes.toArray( new BeanNode<?>[ nodes.size() ] ); } /** get the bean node from the tree path */ static BeanNode<?> getBeanNode( final TreePath treePath ) { if ( treePath != null ) { final Object treeNode = treePath.getLastPathComponent(); if ( treeNode instanceof DefaultMutableTreeNode ) { final Object userObject = ((DefaultMutableTreeNode)treeNode).getUserObject(); if ( userObject instanceof BeanNode ) { return (BeanNode<?>)userObject; } else { return null; } } else { return null; } } else { return null; } } }
bsd-3-clause
newscloud/bh
app/protected/components/Pocket.php
5377
<?php /** * php-Pocket * * A PHP library for interfacing with Pocket (getpocket.com) * * @package pocket-api-php * @author Dan Chen * @license MIT License */ class Pocket { /** * The maximum number of seconds to wait for the Pocket API to respond * * @var int */ const CURL_TIMEOUT = 15; /** * The number of seconds to wait while trying to connect to the Pocket API * * @var int */ const CURL_CONNECTTIMEOUT = 5; /** * The User Agent string for the HTTP request * * @var string */ const CURL_USERAGENT = 'php-pocket 0.2'; private $_config = array( 'apiUrl' => 'https://getpocket.com/v3', 'consumerKey' => null, 'accessToken' => null, 'debug' => false ); private static $_statusCodes = array( 400 => 'Invalid request, please make sure you follow the documentation for proper syntax', 401 => 'Problem authenticating the user', 403 => 'User was authenticated, but access denied due to lack of permission or rate limiting', 503 => 'Pocket\'s sync server is down for scheduled maintenance' ); /** * Constructor * * @param array $settings Array of settings with consumerKey being required * - consumerKey : required * - accessToken : optional * - apiUrl : optional * - debug : optional * * @return void */ public function __construct($settings) { foreach ($settings as $setting => $value) { if (!array_key_exists($setting, $this->_config)) { throw new PocketException('Error unknown configuration setting: ' . $setting); } $this->_config[$setting] = $value; } if ($this->_config['consumerKey'] == null) { throw new PocketException('Error: Application Consumer Key not provided'); } } public function setAccessToken($accessToken) { $this->_config['accessToken'] = $accessToken; } public function requestToken($redirectUri, $state = false) { $params = array(); $params['redirect_uri'] = $redirectUri; if ($state != false) { $params['state'] = $state; } $result = $this->_request('/oauth/request', $params); $query = array( 'request_token' => $result['code'], 'redirect_uri' => $redirectUri ); $query['redirect_uri'] = 'https://getpocket.com/auth/authorize?' . http_build_query($query); return $query; } public function convertToken($token) { $params = array(); $params['code'] = $token; $result = $this->_request('/oauth/authorize', $params); return $result; } /** * Retrieve a user’s list of items with optional filters * * @param array $params List of parameters (optional) * @param bool $accessToken The user's access token (optional) * * @return array Response from Pocket * @throws PocketException */ public function retrieve($params = array(), $accessToken = true) { return $this->_request('/get', $params, $accessToken); } /** * Sets the persistent storage handler * * @param array $params List of parameters * @param bool $accessToken The user's access token (optional) * * @return array Response from Pocket * @throws PocketException */ public function add($params = array(), $accessToken = true) { return $this->_request('/add', $params, $accessToken); } /** * Private method that makes the HTTP call to Pocket using cURL * * @return array Response from Pocket * @throws PocketException */ private function _request($method, $params = null, $accessToken = false) { $url = $this->_config['apiUrl'] . $method; if (!$params) { $params = array(); } $params['consumer_key'] = $this->_config['consumerKey']; if ($accessToken === true) { $params['access_token'] = $this->_config['accessToken']; } else if ($accessToken !== false) { $params['access_token'] = $accessToken; } $params = json_encode($params); $c = curl_init(); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_POST, true); curl_setopt($c, CURLOPT_POSTFIELDS, $params); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); curl_setopt($c, CURLOPT_HEADER, $this->_config['debug']); curl_setopt($c, CURLINFO_HEADER_OUT, true); curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'X-Accept: application/json')); curl_setopt($c, CURLOPT_USERAGENT, self::CURL_USERAGENT); curl_setopt($c, CURLOPT_CONNECTTIMEOUT, self::CURL_CONNECTTIMEOUT); curl_setopt($c, CURLOPT_TIMEOUT, self::CURL_TIMEOUT); if ($this->_config['debug'] === true) { curl_setopt($c, CURLINFO_HEADER_OUT, true); } $response = curl_exec($c); $status = curl_getinfo($c, CURLINFO_HTTP_CODE); if ($status != 200) { if (isset(self::$_statusCodes[$status])) { throw new PocketException('Error: ' . self::$_statusCodes[$status], $status); } } if ($this->_config['debug'] === true) { $headerSize = curl_getinfo($c, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $headerSize); $response = substr($response, $headerSize); echo "cURL Header:\n"; print_r(curl_getinfo($c, CURLINFO_HEADER_OUT)); echo "\n\nPOST Body:\n"; print_r($params); echo "\n\nResponse Header:\n"; print_r($header); echo "\n\nResponse Body:\n"; print_r($response); } curl_close($c); $result = json_decode($response, true); if (!$result) { throw new PocketException('Error could not parse response: ' . var_export($response)); } return $result; } } class PocketException extends Exception { // TODO }
bsd-3-clause
fijj/pearl
backend/views/clients/form.php
970
<?php use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ $this->title = $title; $this->params['breadcrumbs'][] = [ 'label' => 'Клиенты', 'url' => Url::to(['clients/index']), ]; if($action == "update"){ $this->params['breadcrumbs'][] = [ 'label' => $clients->firstName, ]; } $this->params['breadcrumbs'][] = $this->title; ?> <? $form = ActiveForm::begin([ 'id' => 'clients-form', ]) ?> <?= $form->field($clients, 'firstName') ?> <?= $form->field($clients, 'secondName') ?> <?= $form->field($clients, 'thirdName') ?> <?= $form->field($clients, 'phone') ?> <?= $form->field($clients, 'phoneHome') ?> <?= $form->field($clients, 'address') ?> <?= $form->field($clients, 'from')->dropDownList($clients->fromArr, ['prompt' => '--Выбрать из списка--']) ?> <?= Html::submitButton('Сохранить', ['class' => 'btn btn-primary pull-right']) ?> <?php ActiveForm::end() ?>
bsd-3-clause
8v060htwyc/whois
whois-update/src/main/java/net/ripe/db/whois/update/keycert/PgpSignedMessageUtil.java
3390
package net.ripe.db.whois.update.keycert; import org.bouncycastle.openpgp.PGPSignature; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * Signed message util, mostly copied from BouncyCastle PGP tests. */ final class PgpSignedMessageUtil { private PgpSignedMessageUtil() { } static int readInputLine(final ByteArrayOutputStream out, final InputStream in) throws IOException { out.reset(); int lookAhead = -1; int ch; while ((ch = in.read()) >= 0) { out.write(ch); if (ch == '\r' || ch == '\n') { lookAhead = readPassedEOL(out, ch, in); break; } } return lookAhead; } static int readInputLine(final ByteArrayOutputStream out, int lookAhead, final InputStream in) throws IOException { int newLookAhead = lookAhead; out.reset(); int ch = lookAhead; do { out.write(ch); if (ch == '\r' || ch == '\n') { newLookAhead = readPassedEOL(out, ch, in); break; } } while ((ch = in.read()) >= 0); if (ch < 0) { newLookAhead = -1; } return newLookAhead; } static int readPassedEOL(final ByteArrayOutputStream out, final int lastCh, final InputStream in) throws IOException { int lookAhead = in.read(); if (lastCh == '\r' && lookAhead == '\n') { out.write(lookAhead); lookAhead = in.read(); } return lookAhead; } static byte[] getLineSeparator() { final String nl = System.getProperty("line.separator"); byte[] nlBytes = new byte[nl.length()]; for (int i = 0; i != nlBytes.length; i++) { nlBytes[i] = (byte) nl.charAt(i); } return nlBytes; } static int getLengthWithoutSeparatorOrTrailingWhitespace(final byte[] line) { int end = line.length - 1; while (end >= 0 && isWhiteSpace(line[end])) { end--; } return end + 1; } static boolean isLineEnding(final byte b) { return b == '\r' || b == '\n'; } static int getLengthWithoutWhiteSpace(final byte[] line) { int end = line.length - 1; while (end >= 0 && isWhiteSpace(line[end])) { end--; } return end + 1; } static boolean isWhiteSpace(byte b) { return isLineEnding(b) || b == '\t' || b == ' '; } static void processLine(final PGPSignature sig, final byte[] line) throws IOException { final int length = getLengthWithoutWhiteSpace(line); if (length > 0) { sig.update(line, 0, length); } } // Convert line endings to the canonical <CR><LF> sequence before the signature can be verified. (Ref. RFC2015). static byte[] canonicalise(final byte[] content) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); for (byte ch : content) { if (ch == '\r') { continue; } if (ch == '\n') { out.write('\r'); out.write('\n'); } else { out.write(ch); } } return out.toByteArray(); } }
bsd-3-clause
bfjelds/iot-utilities-1
IotCoreAppDeployment/IoTCoreSdkProvider/SharedDependenciesProvider.cs
563
// Copyright (c) Microsoft. All rights reserved. using Microsoft.Iot.IotCoreAppProjectExtensibility; using System.Collections.Generic; namespace Microsoft.Iot.IoTCoreSdkProvider { public class SharedDependencyProvider : IDependencyProvider { public Dictionary<string, IDependency> GetSupportedDependencies() { var dependencies = new Dictionary<string, IDependency>(); var cppuwp = new CPlusPlusUwpDependency(); dependencies.Add(cppuwp.Name, cppuwp); return dependencies; } } }
bsd-3-clause
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE415_Double_Free/s02/CWE415_Double_Free__new_delete_int_32.cpp
3234
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE415_Double_Free__new_delete_int_32.cpp Label Definition File: CWE415_Double_Free__new_delete.label.xml Template File: sources-sinks-32.tmpl.cpp */ /* * @description * CWE: 415 Double Free * BadSource: Allocate data using new and Deallocae data using delete * GoodSource: Allocate data using new * Sinks: * GoodSink: do nothing * BadSink : Deallocate data using delete * Flow Variant: 32 Data flow using two pointers to the same value within the same function * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE415_Double_Free__new_delete_int_32 { #ifndef OMITBAD void bad() { int * data; int * *dataPtr1 = &data; int * *dataPtr2 = &data; /* Initialize data */ data = NULL; { int * data = *dataPtr1; data = new int; /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */ delete data; *dataPtr1 = data; } { int * data = *dataPtr2; /* POTENTIAL FLAW: Possibly deleting memory twice */ delete data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { int * data; int * *dataPtr1 = &data; int * *dataPtr2 = &data; /* Initialize data */ data = NULL; { int * data = *dataPtr1; data = new int; /* FIX: Do NOT delete data in the source - the bad sink deletes data */ *dataPtr1 = data; } { int * data = *dataPtr2; /* POTENTIAL FLAW: Possibly deleting memory twice */ delete data; } } /* goodB2G() uses the BadSource with the GoodSink */ static void goodB2G() { int * data; int * *dataPtr1 = &data; int * *dataPtr2 = &data; /* Initialize data */ data = NULL; { int * data = *dataPtr1; data = new int; /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */ delete data; *dataPtr1 = data; } { int * data = *dataPtr2; /* do nothing */ /* FIX: Don't attempt to delete the memory */ ; /* empty statement needed for some flow variants */ } } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE415_Double_Free__new_delete_int_32; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
bsd-3-clause
jason-simmons/sky_engine
shell/platform/android/platform_view_android.cc
14659
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/android/platform_view_android.h" #include <memory> #include <utility> #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/shell/common/shell_io_manager.h" #include "flutter/shell/gpu/gpu_surface_gl_delegate.h" #include "flutter/shell/platform/android/android_context_gl.h" #include "flutter/shell/platform/android/android_external_texture_gl.h" #include "flutter/shell/platform/android/android_surface_gl.h" #include "flutter/shell/platform/android/android_surface_software.h" #include "flutter/shell/platform/android/external_view_embedder/external_view_embedder.h" #include "flutter/shell/platform/android/surface/android_surface.h" #if SHELL_ENABLE_VULKAN #include "flutter/shell/platform/android/android_surface_vulkan.h" #endif // SHELL_ENABLE_VULKAN #include "flutter/shell/platform/android/context/android_context.h" #include "flutter/shell/platform/android/jni/platform_view_android_jni.h" #include "flutter/shell/platform/android/platform_message_response_android.h" #include "flutter/shell/platform/android/vsync_waiter_android.h" namespace flutter { AndroidSurfaceFactoryImpl::AndroidSurfaceFactoryImpl( const std::shared_ptr<AndroidContext>& context, std::shared_ptr<PlatformViewAndroidJNI> jni_facade) : android_context_(context), jni_facade_(jni_facade) {} AndroidSurfaceFactoryImpl::~AndroidSurfaceFactoryImpl() = default; std::unique_ptr<AndroidSurface> AndroidSurfaceFactoryImpl::CreateSurface() { switch (android_context_->RenderingApi()) { case AndroidRenderingAPI::kSoftware: return std::make_unique<AndroidSurfaceSoftware>(android_context_, jni_facade_); case AndroidRenderingAPI::kOpenGLES: return std::make_unique<AndroidSurfaceGL>(android_context_, jni_facade_); case AndroidRenderingAPI::kVulkan: #if SHELL_ENABLE_VULKAN return std::make_unique<AndroidSurfaceVulkan>(android_context_, jni_facade_); #endif // SHELL_ENABLE_VULKAN default: FML_DCHECK(false); return nullptr; } } static std::shared_ptr<flutter::AndroidContext> CreateAndroidContext( bool use_software_rendering, bool create_onscreen_surface) { if (!create_onscreen_surface) { return nullptr; } if (use_software_rendering) { return std::make_shared<AndroidContext>(AndroidRenderingAPI::kSoftware); } #if SHELL_ENABLE_VULKAN return std::make_shared<AndroidContext>(AndroidRenderingAPI::kVulkan); #else // SHELL_ENABLE_VULKAN return std::make_unique<AndroidContextGL>( AndroidRenderingAPI::kOpenGLES, fml::MakeRefCounted<AndroidEnvironmentGL>()); #endif // SHELL_ENABLE_VULKAN } PlatformViewAndroid::PlatformViewAndroid( PlatformView::Delegate& delegate, flutter::TaskRunners task_runners, std::shared_ptr<PlatformViewAndroidJNI> jni_facade, bool use_software_rendering, bool create_onscreen_surface) : PlatformViewAndroid(delegate, std::move(task_runners), std::move(jni_facade), CreateAndroidContext(use_software_rendering, create_onscreen_surface)) {} PlatformViewAndroid::PlatformViewAndroid( PlatformView::Delegate& delegate, flutter::TaskRunners task_runners, const std::shared_ptr<PlatformViewAndroidJNI>& jni_facade, const std::shared_ptr<flutter::AndroidContext>& android_context) : PlatformView(delegate, std::move(task_runners)), jni_facade_(jni_facade), android_context_(std::move(android_context)), platform_view_android_delegate_(jni_facade) { // TODO(dnfield): always create a pbuffer surface for background use to // resolve https://github.com/flutter/flutter/issues/73675 if (android_context_) { FML_CHECK(android_context_->IsValid()) << "Could not create surface from invalid Android context."; surface_factory_ = std::make_shared<AndroidSurfaceFactoryImpl>( android_context_, jni_facade_); android_surface_ = surface_factory_->CreateSurface(); FML_CHECK(android_surface_ && android_surface_->IsValid()) << "Could not create an OpenGL, Vulkan or Software surface to set up " "rendering."; } } PlatformViewAndroid::~PlatformViewAndroid() = default; void PlatformViewAndroid::NotifyCreated( fml::RefPtr<AndroidNativeWindow> native_window) { if (android_surface_) { InstallFirstFrameCallback(); fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get(), native_window = std::move(native_window)]() { surface->SetNativeWindow(native_window); latch.Signal(); }); latch.Wait(); } PlatformView::NotifyCreated(); } void PlatformViewAndroid::NotifySurfaceWindowChanged( fml::RefPtr<AndroidNativeWindow> native_window) { if (android_surface_) { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get(), native_window = std::move(native_window)]() { surface->TeardownOnScreenContext(); surface->SetNativeWindow(native_window); latch.Signal(); }); latch.Wait(); } } void PlatformViewAndroid::NotifyDestroyed() { PlatformView::NotifyDestroyed(); if (android_surface_) { fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), [&latch, surface = android_surface_.get()]() { surface->TeardownOnScreenContext(); latch.Signal(); }); latch.Wait(); } } void PlatformViewAndroid::NotifyChanged(const SkISize& size) { if (!android_surface_) { return; } fml::AutoResetWaitableEvent latch; fml::TaskRunner::RunNowOrPostTask( task_runners_.GetRasterTaskRunner(), // [&latch, surface = android_surface_.get(), size]() { surface->OnScreenSurfaceResize(size); latch.Signal(); }); latch.Wait(); } void PlatformViewAndroid::DispatchPlatformMessage(JNIEnv* env, std::string name, jobject java_message_data, jint java_message_position, jint response_id) { uint8_t* message_data = static_cast<uint8_t*>(env->GetDirectBufferAddress(java_message_data)); std::vector<uint8_t> message = std::vector<uint8_t>(message_data, message_data + java_message_position); fml::RefPtr<flutter::PlatformMessageResponse> response; if (response_id) { response = fml::MakeRefCounted<PlatformMessageResponseAndroid>( response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); } PlatformView::DispatchPlatformMessage( std::make_unique<flutter::PlatformMessage>( std::move(name), std::move(message), std::move(response))); } void PlatformViewAndroid::DispatchEmptyPlatformMessage(JNIEnv* env, std::string name, jint response_id) { fml::RefPtr<flutter::PlatformMessageResponse> response; if (response_id) { response = fml::MakeRefCounted<PlatformMessageResponseAndroid>( response_id, jni_facade_, task_runners_.GetPlatformTaskRunner()); } PlatformView::DispatchPlatformMessage( std::make_unique<flutter::PlatformMessage>(std::move(name), std::move(response))); } void PlatformViewAndroid::InvokePlatformMessageResponseCallback( JNIEnv* env, jint response_id, jobject java_response_data, jint java_response_position) { if (!response_id) return; auto it = pending_responses_.find(response_id); if (it == pending_responses_.end()) return; uint8_t* response_data = static_cast<uint8_t*>(env->GetDirectBufferAddress(java_response_data)); std::vector<uint8_t> response = std::vector<uint8_t>( response_data, response_data + java_response_position); auto message_response = std::move(it->second); pending_responses_.erase(it); message_response->Complete( std::make_unique<fml::DataMapping>(std::move(response))); } void PlatformViewAndroid::InvokePlatformMessageEmptyResponseCallback( JNIEnv* env, jint response_id) { if (!response_id) return; auto it = pending_responses_.find(response_id); if (it == pending_responses_.end()) return; auto message_response = std::move(it->second); pending_responses_.erase(it); message_response->CompleteEmpty(); } // |PlatformView| void PlatformViewAndroid::HandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { int response_id = 0; if (auto response = message->response()) { response_id = next_response_id_++; pending_responses_[response_id] = response; } // This call can re-enter in InvokePlatformMessageXxxResponseCallback. jni_facade_->FlutterViewHandlePlatformMessage(std::move(message), response_id); message = nullptr; } // |PlatformView| void PlatformViewAndroid::OnPreEngineRestart() const { jni_facade_->FlutterViewOnPreEngineRestart(); } void PlatformViewAndroid::DispatchSemanticsAction(JNIEnv* env, jint id, jint action, jobject args, jint args_position) { if (env->IsSameObject(args, NULL)) { std::vector<uint8_t> args_vector; PlatformView::DispatchSemanticsAction( id, static_cast<flutter::SemanticsAction>(action), args_vector); return; } uint8_t* args_data = static_cast<uint8_t*>(env->GetDirectBufferAddress(args)); std::vector<uint8_t> args_vector = std::vector<uint8_t>(args_data, args_data + args_position); PlatformView::DispatchSemanticsAction( id, static_cast<flutter::SemanticsAction>(action), std::move(args_vector)); } // |PlatformView| void PlatformViewAndroid::UpdateSemantics( flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) { platform_view_android_delegate_.UpdateSemantics(update, actions); } void PlatformViewAndroid::RegisterExternalTexture( int64_t texture_id, const fml::jni::JavaObjectWeakGlobalRef& surface_texture) { RegisterTexture(std::make_shared<AndroidExternalTextureGL>( texture_id, surface_texture, std::move(jni_facade_))); } // |PlatformView| std::unique_ptr<VsyncWaiter> PlatformViewAndroid::CreateVSyncWaiter() { return std::make_unique<VsyncWaiterAndroid>(task_runners_); } // |PlatformView| std::unique_ptr<Surface> PlatformViewAndroid::CreateRenderingSurface() { if (!android_surface_) { return nullptr; } return android_surface_->CreateGPUSurface( android_context_->GetMainSkiaContext().get()); } // |PlatformView| std::shared_ptr<ExternalViewEmbedder> PlatformViewAndroid::CreateExternalViewEmbedder() { return std::make_shared<AndroidExternalViewEmbedder>( *android_context_, jni_facade_, surface_factory_); } // |PlatformView| sk_sp<GrDirectContext> PlatformViewAndroid::CreateResourceContext() const { if (!android_surface_) { return nullptr; } sk_sp<GrDirectContext> resource_context; if (android_surface_->ResourceContextMakeCurrent()) { // TODO(chinmaygarde): Currently, this code depends on the fact that only // the OpenGL surface will be able to make a resource context current. If // this changes, this assumption breaks. Handle the same. resource_context = ShellIOManager::CreateCompatibleResourceLoadingContext( GrBackend::kOpenGL_GrBackend, GPUSurfaceGLDelegate::GetDefaultPlatformGLInterface()); } else { FML_DLOG(ERROR) << "Could not make the resource context current."; } return resource_context; } // |PlatformView| void PlatformViewAndroid::ReleaseResourceContext() const { if (android_surface_) { android_surface_->ResourceContextClearCurrent(); } } // |PlatformView| std::unique_ptr<std::vector<std::string>> PlatformViewAndroid::ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data) { return jni_facade_->FlutterViewComputePlatformResolvedLocale( supported_locale_data); } // |PlatformView| void PlatformViewAndroid::RequestDartDeferredLibrary(intptr_t loading_unit_id) { if (jni_facade_->RequestDartDeferredLibrary(loading_unit_id)) { return; } return; // TODO(garyq): Call LoadDartDeferredLibraryFailure() } // |PlatformView| void PlatformViewAndroid::LoadDartDeferredLibrary( intptr_t loading_unit_id, std::unique_ptr<const fml::Mapping> snapshot_data, std::unique_ptr<const fml::Mapping> snapshot_instructions) { delegate_.LoadDartDeferredLibrary(loading_unit_id, std::move(snapshot_data), std::move(snapshot_instructions)); } // |PlatformView| void PlatformViewAndroid::LoadDartDeferredLibraryError( intptr_t loading_unit_id, const std::string error_message, bool transient) { delegate_.LoadDartDeferredLibraryError(loading_unit_id, error_message, transient); } // |PlatformView| void PlatformViewAndroid::UpdateAssetResolverByType( std::unique_ptr<AssetResolver> updated_asset_resolver, AssetResolver::AssetResolverType type) { delegate_.UpdateAssetResolverByType(std::move(updated_asset_resolver), type); } void PlatformViewAndroid::InstallFirstFrameCallback() { // On Platform Task Runner. SetNextFrameCallback( [platform_view = GetWeakPtr(), platform_task_runner = task_runners_.GetPlatformTaskRunner()]() { // On GPU Task Runner. platform_task_runner->PostTask([platform_view]() { // Back on Platform Task Runner. if (platform_view) { reinterpret_cast<PlatformViewAndroid*>(platform_view.get()) ->FireFirstFrameCallback(); } }); }); } void PlatformViewAndroid::FireFirstFrameCallback() { jni_facade_->FlutterViewOnFirstFrame(); } } // namespace flutter
bsd-3-clause
scheib/chromium
ui/views/controls/resize_area_unittest.cc
6860
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/resize_area.h" #include <memory> #include <utility> #include "base/bind.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/test/event_generator.h" #include "ui/views/controls/resize_area_delegate.h" #include "ui/views/test/views_test_base.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_utils.h" #if !defined(OS_MAC) #include "ui/aura/window.h" #endif namespace { // Constants used by the ResizeAreaTest.SuccessfulGestureDrag test to simulate // a gesture drag by |kGestureScrollDistance| resulting from // |kGestureScrollSteps| ui::ET_GESTURE_SCROLL_UPDATE events being delivered. const int kGestureScrollDistance = 100; const int kGestureScrollSteps = 4; const int kDistancePerGestureScrollUpdate = kGestureScrollDistance / kGestureScrollSteps; } // namespace namespace views { // Testing delegate used by ResizeAreaTest. class TestResizeAreaDelegate : public ResizeAreaDelegate { public: TestResizeAreaDelegate(); TestResizeAreaDelegate(const TestResizeAreaDelegate&) = delete; TestResizeAreaDelegate& operator=(const TestResizeAreaDelegate&) = delete; ~TestResizeAreaDelegate() override; // ResizeAreaDelegate: void OnResize(int resize_amount, bool done_resizing) override; int resize_amount() { return resize_amount_; } bool done_resizing() { return done_resizing_; } bool on_resize_called() { return on_resize_called_; } private: int resize_amount_ = 0; bool done_resizing_ = false; bool on_resize_called_ = false; }; TestResizeAreaDelegate::TestResizeAreaDelegate() = default; TestResizeAreaDelegate::~TestResizeAreaDelegate() = default; void TestResizeAreaDelegate::OnResize(int resize_amount, bool done_resizing) { resize_amount_ = resize_amount; done_resizing_ = done_resizing; on_resize_called_ = true; } // Test fixture for testing the ResizeArea class. class ResizeAreaTest : public ViewsTestBase { public: ResizeAreaTest(); ResizeAreaTest(const ResizeAreaTest&) = delete; ResizeAreaTest& operator=(const ResizeAreaTest&) = delete; ~ResizeAreaTest() override; // Callback used by the SuccessfulGestureDrag test. void ProcessGesture(ui::EventType type, const gfx::Vector2dF& delta); protected: // testing::Test: void SetUp() override; void TearDown() override; ui::test::EventGenerator* event_generator() { return event_generator_.get(); } int resize_amount() { return delegate_->resize_amount(); } bool done_resizing() { return delegate_->done_resizing(); } bool on_resize_called() { return delegate_->on_resize_called(); } views::Widget* widget() { return widget_; } private: std::unique_ptr<TestResizeAreaDelegate> delegate_; views::Widget* widget_ = nullptr; std::unique_ptr<ui::test::EventGenerator> event_generator_; // The number of ui::ET_GESTURE_SCROLL_UPDATE events seen by // ProcessGesture(). int gesture_scroll_updates_seen_ = 0; }; ResizeAreaTest::ResizeAreaTest() = default; ResizeAreaTest::~ResizeAreaTest() = default; void ResizeAreaTest::ProcessGesture(ui::EventType type, const gfx::Vector2dF& delta) { if (type == ui::ET_GESTURE_SCROLL_BEGIN) { EXPECT_FALSE(done_resizing()); EXPECT_FALSE(on_resize_called()); } else if (type == ui::ET_GESTURE_SCROLL_UPDATE) { gesture_scroll_updates_seen_++; EXPECT_EQ(kDistancePerGestureScrollUpdate * gesture_scroll_updates_seen_, resize_amount()); EXPECT_FALSE(done_resizing()); EXPECT_TRUE(on_resize_called()); } else if (type == ui::ET_GESTURE_SCROLL_END) { EXPECT_TRUE(done_resizing()); } } void ResizeAreaTest::SetUp() { views::ViewsTestBase::SetUp(); delegate_ = std::make_unique<TestResizeAreaDelegate>(); auto resize_area = std::make_unique<ResizeArea>(delegate_.get()); gfx::Size size(10, 10); resize_area->SetBounds(0, 0, size.width(), size.height()); views::Widget::InitParams init_params( CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS)); init_params.bounds = gfx::Rect(size); widget_ = new views::Widget(); widget_->Init(std::move(init_params)); widget_->SetContentsView(std::move(resize_area)); widget_->Show(); event_generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow(widget_)); } void ResizeAreaTest::TearDown() { if (widget_ && !widget_->IsClosed()) widget_->Close(); views::ViewsTestBase::TearDown(); } // TODO(tdanderson): Enable these tests on OSX. See crbug.com/710475. #if !defined(OS_MAC) // Verifies the correct calls have been made to // TestResizeAreaDelegate::OnResize() for a sequence of mouse events // corresponding to a successful resize operation. TEST_F(ResizeAreaTest, SuccessfulMouseDrag) { event_generator()->MoveMouseToCenterOf(widget()->GetNativeView()); event_generator()->PressLeftButton(); const int kFirstDragAmount = -5; event_generator()->MoveMouseBy(kFirstDragAmount, 0); EXPECT_EQ(kFirstDragAmount, resize_amount()); EXPECT_FALSE(done_resizing()); EXPECT_TRUE(on_resize_called()); const int kSecondDragAmount = 17; event_generator()->MoveMouseBy(kSecondDragAmount, 0); EXPECT_EQ(kFirstDragAmount + kSecondDragAmount, resize_amount()); EXPECT_FALSE(done_resizing()); event_generator()->ReleaseLeftButton(); EXPECT_EQ(kFirstDragAmount + kSecondDragAmount, resize_amount()); EXPECT_TRUE(done_resizing()); } // Verifies that no resize is performed when attempting to resize using the // right mouse button. TEST_F(ResizeAreaTest, FailedMouseDrag) { event_generator()->MoveMouseToCenterOf(widget()->GetNativeView()); event_generator()->PressRightButton(); const int kDragAmount = 18; event_generator()->MoveMouseBy(kDragAmount, 0); EXPECT_EQ(0, resize_amount()); } // Verifies the correct calls have been made to // TestResizeAreaDelegate::OnResize() for a sequence of gesture events // corresponding to a successful resize operation. TEST_F(ResizeAreaTest, SuccessfulGestureDrag) { gfx::Point start = widget()->GetNativeView()->bounds().CenterPoint(); event_generator()->GestureScrollSequenceWithCallback( start, gfx::Point(start.x() + kGestureScrollDistance, start.y()), base::Milliseconds(200), kGestureScrollSteps, base::BindRepeating(&ResizeAreaTest::ProcessGesture, base::Unretained(this))); } // Verifies that no resize is performed on a gesture tap. TEST_F(ResizeAreaTest, NoDragOnGestureTap) { event_generator()->GestureTapAt( widget()->GetNativeView()->bounds().CenterPoint()); EXPECT_EQ(0, resize_amount()); } #endif // !defined(OS_MAC) } // namespace views
bsd-3-clause
chromium2014/src
components/data_reduction_proxy/browser/data_reduction_proxy_usage_stats_unittest.cc
3071
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/data_reduction_proxy/browser/data_reduction_proxy_usage_stats.h" #include "base/memory/scoped_ptr.h" #include "net/base/request_priority.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_status.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::MessageLoop; using base::MessageLoopProxy; using data_reduction_proxy::DataReductionProxyParams; using net::TestDelegate; using net::TestURLRequestContext; using net::URLRequest; using net::URLRequestStatus; using testing::Return; namespace { class DataReductionProxyParamsMock : public DataReductionProxyParams { public: DataReductionProxyParamsMock() : DataReductionProxyParams(0) {} virtual ~DataReductionProxyParamsMock() {} MOCK_METHOD1(IsDataReductionProxyEligible, bool(const net::URLRequest*)); MOCK_CONST_METHOD2(WasDataReductionProxyUsed, bool(const net::URLRequest*, std::pair<GURL, GURL>* proxy_servers)); private: DISALLOW_COPY_AND_ASSIGN(DataReductionProxyParamsMock); }; } // namespace namespace data_reduction_proxy { class DataReductionProxyUsageStatsTest : public testing::Test { public: DataReductionProxyUsageStatsTest() : loop_proxy_(MessageLoopProxy::current().get()), context_(true), mock_url_request_(GURL(), net::IDLE, &delegate_, &context_) { context_.Init(); } // Required for MessageLoopProxy::current(). base::MessageLoopForUI loop_; MessageLoopProxy* loop_proxy_; protected: TestURLRequestContext context_; TestDelegate delegate_; DataReductionProxyParamsMock mock_params_; URLRequest mock_url_request_; }; TEST_F(DataReductionProxyUsageStatsTest, isDataReductionProxyUnreachable) { struct TestCase { bool is_proxy_eligible; bool was_proxy_used; bool is_unreachable; }; const TestCase test_cases[] = { { false, false, false }, { true, true, false }, { true, false, true } }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) { TestCase test_case = test_cases[i]; EXPECT_CALL(mock_params_, IsDataReductionProxyEligible(&mock_url_request_)) .WillRepeatedly(Return(test_case.is_proxy_eligible)); EXPECT_CALL(mock_params_, WasDataReductionProxyUsed(&mock_url_request_, NULL)) .WillRepeatedly(Return(test_case.was_proxy_used)); scoped_ptr<DataReductionProxyUsageStats> usage_stats( new DataReductionProxyUsageStats( &mock_params_, loop_proxy_, loop_proxy_)); usage_stats->OnUrlRequestCompleted(&mock_url_request_, false); MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(test_case.is_unreachable, usage_stats->isDataReductionProxyUnreachable()); } } } // namespace data_reduction_proxy
bsd-3-clause
oogles/djem
djem/pagination.py
1398
from django.conf import settings from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator def get_page(number, object_list, per_page=None, **kwargs): """ Return the specified page, as a Django Page instance, from a Paginator constructed from the given object list and other keyword arguments. Handle InvalidPage exceptions and return logical valid pages instead. The ``per_page`` argument defaults to DJEM_DEFAULT_PAGE_LENGTH, if set. Otherwise, it is a required argument. """ if per_page is None: try: per_page = settings.DJEM_DEFAULT_PAGE_LENGTH except AttributeError: raise TypeError('The "per_page" argument is required unless DJEM_DEFAULT_PAGE_LENGTH is set.') paginator = Paginator(object_list, per_page, **kwargs) try: return paginator.page(number) except PageNotAnInteger: number = 1 except EmptyPage: if number < 1: # Page number too low, return first page number = 1 elif paginator.num_pages: # Page number too high, return last page number = paginator.num_pages else: # Paginator has no pages, still try for the first page. Will return # an empty page unless allow_empty_first_page is False. number = 1 return paginator.page(number)
bsd-3-clause
rosskevin/relay
packages/react-relay/classic/store/__mocks__/RelayGarbageCollector.js
404
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @format */ 'use strict'; module.exports = require.requireActual('RelayGarbageCollector');
bsd-3-clause
ajrichards/notebook
python/notes-np-in1d.py
180
#!/usr/bin/env python import sys import numpy as np a = np.arange(10) b = np.array([3,4,5]) mask1 = np.in1d(a,b) mask2 = np.in1d(b,a) print('mask1',mask1) print('mask2',mask2)
bsd-3-clause
ChromiumWebApps/chromium
chrome/browser/prefs/incognito_mode_prefs_unittest.cc
3264
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_pref_service_syncable.h" #include "testing/gtest/include/gtest/gtest.h" class IncognitoModePrefsTest : public testing::Test { protected: virtual void SetUp() { IncognitoModePrefs::RegisterProfilePrefs(prefs_.registry()); } TestingPrefServiceSyncable prefs_; }; TEST_F(IncognitoModePrefsTest, IntToAvailability) { ASSERT_EQ(0, IncognitoModePrefs::ENABLED); ASSERT_EQ(1, IncognitoModePrefs::DISABLED); ASSERT_EQ(2, IncognitoModePrefs::FORCED); IncognitoModePrefs::Availability incognito; EXPECT_TRUE(IncognitoModePrefs::IntToAvailability(0, &incognito)); EXPECT_EQ(IncognitoModePrefs::ENABLED, incognito); EXPECT_TRUE(IncognitoModePrefs::IntToAvailability(1, &incognito)); EXPECT_EQ(IncognitoModePrefs::DISABLED, incognito); EXPECT_TRUE(IncognitoModePrefs::IntToAvailability(2, &incognito)); EXPECT_EQ(IncognitoModePrefs::FORCED, incognito); EXPECT_FALSE(IncognitoModePrefs::IntToAvailability(10, &incognito)); EXPECT_EQ(IncognitoModePrefs::ENABLED, incognito); EXPECT_FALSE(IncognitoModePrefs::IntToAvailability(-1, &incognito)); EXPECT_EQ(IncognitoModePrefs::ENABLED, incognito); } TEST_F(IncognitoModePrefsTest, GetAvailability) { prefs_.SetUserPref(prefs::kIncognitoModeAvailability, base::Value::CreateIntegerValue( IncognitoModePrefs::ENABLED)); EXPECT_EQ(IncognitoModePrefs::ENABLED, IncognitoModePrefs::GetAvailability(&prefs_)); prefs_.SetUserPref(prefs::kIncognitoModeAvailability, base::Value::CreateIntegerValue( IncognitoModePrefs::DISABLED)); EXPECT_EQ(IncognitoModePrefs::DISABLED, IncognitoModePrefs::GetAvailability(&prefs_)); prefs_.SetUserPref(prefs::kIncognitoModeAvailability, base::Value::CreateIntegerValue( IncognitoModePrefs::FORCED)); EXPECT_EQ(IncognitoModePrefs::FORCED, IncognitoModePrefs::GetAvailability(&prefs_)); } typedef IncognitoModePrefsTest IncognitoModePrefsDeathTest; // Takes too long to execute on Mac. http://crbug.com/101109 #if defined(OS_MACOSX) #define MAYBE_GetAvailabilityBadValue DISABLED_GetAvailabilityBadValue #else #define MAYBE_GetAvailabilityBadValue GetAvailabilityBadValue #endif #if GTEST_HAS_DEATH_TEST TEST_F(IncognitoModePrefsDeathTest, MAYBE_GetAvailabilityBadValue) { prefs_.SetUserPref(prefs::kIncognitoModeAvailability, base::Value::CreateIntegerValue(-1)); #if defined(NDEBUG) && defined(DCHECK_ALWAYS_ON) EXPECT_DEATH({ IncognitoModePrefs::Availability availability = IncognitoModePrefs::GetAvailability(&prefs_); EXPECT_EQ(IncognitoModePrefs::ENABLED, availability); }, ""); #else EXPECT_DEBUG_DEATH({ IncognitoModePrefs::Availability availability = IncognitoModePrefs::GetAvailability(&prefs_); EXPECT_EQ(IncognitoModePrefs::ENABLED, availability); }, ""); #endif } #endif // GTEST_HAS_DEATH_TEST
bsd-3-clause
snowballstem/snowball
go/stemwords/main.go
1237
//go:generate go run generate.go ../algorithms algorithms.go //go:generate gofmt -s -w algorithms.go package main import ( "bufio" "flag" "fmt" "log" "os" snowballRuntime "github.com/snowballstem/snowball/go" ) var language = flag.String("l", "", "language") var input = flag.String("i", "", "input file") var output = flag.String("o", "", "output file") func main() { flag.Parse() if *language == "" { log.Fatal("must specify language") } stemmer, ok := languages[*language] if !ok { log.Fatalf("no language support for %s", *language) } var reader = os.Stdin if *input != "" { var err error reader, err = os.Open(*input) if err != nil { log.Fatal(err) } defer reader.Close() } var writer = os.Stdout if *output != "" { var err error writer, err = os.Create(*output) if err != nil { log.Fatal(err) } defer writer.Close() } var err error scanner := bufio.NewScanner(reader) for scanner.Scan() { word := scanner.Text() env := snowballRuntime.NewEnv(word) stemmer(env) fmt.Fprintf(writer, "%s\n", env.Current()) } if err = scanner.Err(); err != nil { log.Fatal(err) } } type StemFunc func(env *snowballRuntime.Env) bool var languages = make(map[string]StemFunc)
bsd-3-clause
jkowalski/NLog
tests/NLog.UnitTests/Targets/MailTargetTests.cs
16283
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // 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 Jaroslaw Kowalski 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. // #if !SILVERLIGHT && !NET_CF namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Net; using System.Net.Mail; using NUnit.Framework; #if !NUNIT using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif using NLog.Internal; using NLog.Layouts; using NLog.Targets; [TestFixture] public class MailTargetTests : NLogTestBase { [Test] public void SimpleEmailTest() { var mmt = new MockMailTarget { From = "foo@bar.com", To = "bar@foo.com", CC = "me@myserver.com;you@yourserver.com", Bcc = "foo@myserver.com;bar@yourserver.com", Subject = "Hello from NLog", SmtpServer = "server1", SmtpPort = 27, Body = "${level} ${logger} ${message}" }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); Assert.AreEqual(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.AreEqual(1, mock.MessagesSent.Count); Assert.AreEqual("server1", mock.Host); Assert.AreEqual(27, mock.Port); Assert.IsFalse(mock.EnableSsl); Assert.IsNull(mock.Credentials); var msg = mock.MessagesSent[0]; Assert.AreEqual("Hello from NLog", msg.Subject); Assert.AreEqual("foo@bar.com", msg.From.Address); Assert.AreEqual(1, msg.To.Count); Assert.AreEqual("bar@foo.com", msg.To[0].Address); Assert.AreEqual(2, msg.CC.Count); Assert.AreEqual("me@myserver.com", msg.CC[0].Address); Assert.AreEqual("you@yourserver.com", msg.CC[1].Address); Assert.AreEqual(2, msg.Bcc.Count); Assert.AreEqual("foo@myserver.com", msg.Bcc[0].Address); Assert.AreEqual("bar@yourserver.com", msg.Bcc[1].Address); Assert.AreEqual(msg.Body, "Info MyLogger log message 1"); } [Test] public void NtlmEmailTest() { var mmt = new MockMailTarget { From = "foo@bar.com", To = "bar@foo.com", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Ntlm, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); Assert.AreEqual(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.AreEqual(CredentialCache.DefaultNetworkCredentials, mock.Credentials); } [Test] public void BasicAuthEmailTest() { try { var mmt = new MockMailTarget { From = "foo@bar.com", To = "bar@foo.com", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Basic, SmtpUserName = "${mdc:username}", SmtpPassword = "${mdc:password}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); MappedDiagnosticsContext.Set("username", "u1"); MappedDiagnosticsContext.Set("password", "p1"); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); Assert.AreEqual(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; var credential = mock.Credentials as NetworkCredential; Assert.IsNotNull(credential); Assert.AreEqual("u1", credential.UserName); Assert.AreEqual("p1", credential.Password); Assert.AreEqual(string.Empty, credential.Domain); } finally { MappedDiagnosticsContext.Clear(); } } [Test] public void CsvLayoutTest() { var layout = new CsvLayout() { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; var mmt = new MockMailTarget { From = "foo@bar.com", To = "bar@foo.com", SmtpServer = "server1", AddNewLines = true, Layout = layout, }; layout.Initialize(null); mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); Assert.AreEqual(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.AreEqual(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; string expectedBody = "name;level;message\nMyLogger1;Info;log message 1\nMyLogger2;Debug;log message 2\nMyLogger3;Error;log message 3\n"; Assert.AreEqual(expectedBody, msg.Body); } [Test] public void PerMessageServer() { var mmt = new MockMailTarget { From = "foo@bar.com", To = "bar@foo.com", SmtpServer = "${logger}.mydomain.com", Body = "${message}", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.AreEqual(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.AreEqual("MyLogger1.mydomain.com", mock1.Host); Assert.AreEqual(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.AreEqual("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.AreEqual("MyLogger2.mydomain.com", mock2.Host); Assert.AreEqual(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.AreEqual("log message 2\n", msg2.Body); } [Test] public void ErrorHandlingTest() { var mmt = new MockMailTarget { From = "foo@bar.com", To = "bar@foo.com", SmtpServer = "${logger}", Body = "${message}", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); var exceptions2 = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "ERROR", "log message 2").WithContinuation(exceptions2.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); Assert.IsNull(exceptions[1], Convert.ToString(exceptions[1])); Assert.IsNotNull(exceptions2[0]); Assert.AreEqual("Some SMTP error.", exceptions2[0].Message); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.AreEqual(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.AreEqual("MyLogger1", mock1.Host); Assert.AreEqual(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.AreEqual("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.AreEqual("ERROR", mock2.Host); Assert.AreEqual(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.AreEqual("log message 2\n", msg2.Body); } /// <summary> /// Tests that it is possible to user different email address for each log message, /// for example by using ${logger}, ${event-context} or any other layout renderer. /// </summary> [Test] public void PerMessageAddress() { var mmt = new MockMailTarget { From = "foo@bar.com", To = "${logger}@foo.com", Body = "${message}", SmtpServer = "server1.mydomain.com", AddNewLines = true, }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger1", "log message 3").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); // 2 messages are sent, one using MyLogger1.mydomain.com, another using MyLogger2.mydomain.com Assert.AreEqual(2, mmt.CreatedMocks.Count); var mock1 = mmt.CreatedMocks[0]; Assert.AreEqual(1, mock1.MessagesSent.Count); var msg1 = mock1.MessagesSent[0]; Assert.AreEqual("MyLogger1@foo.com", msg1.To[0].Address); Assert.AreEqual("log message 1\nlog message 3\n", msg1.Body); var mock2 = mmt.CreatedMocks[1]; Assert.AreEqual(1, mock2.MessagesSent.Count); var msg2 = mock2.MessagesSent[0]; Assert.AreEqual("MyLogger2@foo.com", msg2.To[0].Address); Assert.AreEqual("log message 2\n", msg2.Body); } [Test] public void CustomHeaderAndFooter() { var mmt = new MockMailTarget { From = "foo@bar.com", To = "bar@foo.com", SmtpServer = "server1", AddNewLines = true, Layout = "${message}", Header = "First event: ${logger}", Footer = "Last event: ${logger}", }; mmt.Initialize(null); var exceptions = new List<Exception>(); mmt.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "MyLogger1", "log message 1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "log message 2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "MyLogger3", "log message 3").WithContinuation(exceptions.Add)); Assert.IsNull(exceptions[0], Convert.ToString(exceptions[0])); Assert.AreEqual(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; Assert.AreEqual(1, mock.MessagesSent.Count); var msg = mock.MessagesSent[0]; string expectedBody = "First event: MyLogger1\nlog message 1\nlog message 2\nlog message 3\nLast event: MyLogger3\n"; Assert.AreEqual(expectedBody, msg.Body); } [Test] public void DefaultSmtpClientTest() { var mailTarget = new MailTarget(); var client = mailTarget.CreateSmtpClient(); Assert.IsInstanceOfType(typeof(MySmtpClient), client); } public class MockSmtpClient : ISmtpClient { public MockSmtpClient() { this.MessagesSent = new List<MailMessage>(); } public string Host { get; set; } public int Port { get; set; } public ICredentialsByHost Credentials { get; set; } public bool EnableSsl { get; set; } public List<MailMessage> MessagesSent { get; private set; } public void Send(MailMessage msg) { this.MessagesSent.Add(msg); if (Host == "ERROR") { throw new InvalidOperationException("Some SMTP error."); } } public void Dispose() { } } public class MockMailTarget : MailTarget { public List<MockSmtpClient> CreatedMocks = new List<MockSmtpClient>(); internal override ISmtpClient CreateSmtpClient() { var mock = new MockSmtpClient(); CreatedMocks.Add(mock); return mock; } } } } #endif
bsd-3-clause
msf-oca-his/dhis-core
dhis-2/dhis-support/dhis-support-hibernate/src/main/java/org/hisp/dhis/hibernate/jsonb/type/JsonBinaryPlainStringType.java
3698
package org.hisp.dhis.hibernate.jsonb.type; /* * Copyright (c) 2004-2017, University of Oslo * All rights reserved. * * 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 the HISP project 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. */ import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.postgresql.util.PGobject; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * User defined type to handle dynamic json structures to be stored in jsonb. * Always deserializes into java Strings. * * @author Ameen Mohamed <ameen@dhis2.org> */ @SuppressWarnings("rawtypes") public class JsonBinaryPlainStringType extends JsonBinaryType { @Override public Class returnedClass() { return String.class; } @Override public Object nullSafeGet( ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner ) throws HibernateException, SQLException { final Object result = rs.getObject( names[0] ); if ( !rs.wasNull() ) { String content = null; if ( result instanceof String ) { content = (String) result; } else if ( result instanceof PGobject ) { content = ((PGobject) result).getValue(); } // Other types currently ignored if ( content != null ) { return content.toString(); } } return null; } @Override public void nullSafeSet( PreparedStatement ps, Object value, int idx, SharedSessionContractImplementor session ) throws HibernateException, SQLException { if ( value == null ) { ps.setObject( idx, null ); return; } PGobject pg = new PGobject(); pg.setType( "jsonb" ); pg.setValue( value.toString() ); ps.setObject( idx, pg ); } @Override public Object deepCopy( Object value ) throws HibernateException { return value == null ? null : value.toString(); } @Override public void setParameterValues( Properties parameters ) { } }
bsd-3-clause
yungsters/relay
packages/relay-runtime/store/__tests__/__generated__/RelayReaderRequiredFieldsTest4Fragment.graphql.js
2089
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<7a6a146b48959f8790b8922bde8d4195>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disable */ 'use strict'; /*:: import type { ReaderFragment } from 'relay-runtime'; import type { FragmentReference } from "relay-runtime"; declare export opaque type RelayReaderRequiredFieldsTest4Fragment$ref: FragmentReference; declare export opaque type RelayReaderRequiredFieldsTest4Fragment$fragmentType: RelayReaderRequiredFieldsTest4Fragment$ref; export type RelayReaderRequiredFieldsTest4Fragment = ?{| +me: {| +lastName: string, |}, +$refType: RelayReaderRequiredFieldsTest4Fragment$ref, |}; export type RelayReaderRequiredFieldsTest4Fragment$data = RelayReaderRequiredFieldsTest4Fragment; export type RelayReaderRequiredFieldsTest4Fragment$key = { +$data?: RelayReaderRequiredFieldsTest4Fragment$data, +$fragmentRefs: RelayReaderRequiredFieldsTest4Fragment$ref, ... }; */ var node/*: ReaderFragment*/ = { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "RelayReaderRequiredFieldsTest4Fragment", "selections": [ { "kind": "RequiredField", "field": { "alias": null, "args": null, "concreteType": "User", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "kind": "RequiredField", "field": { "alias": null, "args": null, "kind": "ScalarField", "name": "lastName", "storageKey": null }, "action": "LOG", "path": "me.lastName" } ], "storageKey": null }, "action": "LOG", "path": "me" } ], "type": "Query", "abstractKey": null }; if (__DEV__) { (node/*: any*/).hash = "d7f205cf08433933dc07eab03eb39cee"; } module.exports = node;
bsd-3-clause
SonicLighter/yii2
frontend/views/posts/index.php
598
<?php /* @var $this yii\web\View */ use yii\helpers\Html; use yii\widgets\LinkPager; use yii\widgets\ListView; use yii\grid\GridView; use yii\bootstrap\ActiveForm; use yii\grid\ActionColumn; $this->title = 'Posts'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-about"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Create Post', ['create'], ['class' => 'btn btn-info']) ?> </p> <?= ListView::widget([ 'dataProvider' => $dataProvider, 'itemView' => 'listview/post', ]); ?> </div>
bsd-3-clause
msf-oca-his/dhis2-core
dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/userkeyjsonvalue/hibernate/HibernateUserKeyJsonValueStore.java
4514
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * 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 the HISP project 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 org.hisp.dhis.userkeyjsonvalue.hibernate; import java.util.List; import java.util.stream.Collectors; import javax.persistence.criteria.CriteriaBuilder; import org.hibernate.SessionFactory; import org.hisp.dhis.common.adapter.BaseIdentifiableObject_; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.security.acl.AclService; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.userkeyjsonvalue.UserKeyJsonValue; import org.hisp.dhis.userkeyjsonvalue.UserKeyJsonValueStore; import org.springframework.context.ApplicationEventPublisher; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; /** * @author Stian Sandvold */ @Repository( "org.hisp.dhis.userkeyjsonvalue.UserKeyJsonValueStore" ) public class HibernateUserKeyJsonValueStore extends HibernateIdentifiableObjectStore<UserKeyJsonValue> implements UserKeyJsonValueStore { public HibernateUserKeyJsonValueStore( SessionFactory sessionFactory, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService ) { super( sessionFactory, jdbcTemplate, publisher, UserKeyJsonValue.class, currentUserService, aclService, true ); } @Override public UserKeyJsonValue getUserKeyJsonValue( User user, String namespace, String key ) { CriteriaBuilder builder = getCriteriaBuilder(); return getSingleResult( builder, newJpaParameters() .addPredicate( root -> builder.equal( root.get( BaseIdentifiableObject_.CREATED_BY ), user ) ) .addPredicate( root -> builder.equal( root.get( "namespace" ), namespace ) ) .addPredicate( root -> builder.equal( root.get( "key" ), key ) ) ); } @Override public List<String> getNamespacesByUser( User user ) { CriteriaBuilder builder = getCriteriaBuilder(); return getList( builder, newJpaParameters() .addPredicate( root -> builder.equal( root.get( BaseIdentifiableObject_.CREATED_BY ), user ) ) ) .stream().map( UserKeyJsonValue::getNamespace ).distinct().collect( Collectors.toList() ); } @Override public List<String> getKeysByUserAndNamespace( User user, String namespace ) { return (getUserKeyJsonValueByUserAndNamespace( user, namespace )).stream().map( UserKeyJsonValue::getKey ) .collect( Collectors.toList() ); } @Override public List<UserKeyJsonValue> getUserKeyJsonValueByUserAndNamespace( User user, String namespace ) { CriteriaBuilder builder = getCriteriaBuilder(); return getList( builder, newJpaParameters() .addPredicate( root -> builder.equal( root.get( BaseIdentifiableObject_.CREATED_BY ), user ) ) .addPredicate( root -> builder.equal( root.get( "namespace" ), namespace ) ) ); } }
bsd-3-clause
majestrate/i2pd
libi2pd/NetDb.hpp
6115
#ifndef NETDB_H__ #define NETDB_H__ // this file is called NetDb.hpp to resolve conflict with libc's netdb.h on case insensitive fs #include <inttypes.h> #include <set> #include <map> #include <list> #include <string> #include <thread> #include <mutex> #include "Base.h" #include "Gzip.h" #include "FS.h" #include "Queue.h" #include "I2NPProtocol.h" #include "RouterInfo.h" #include "LeaseSet.h" #include "Tunnel.h" #include "TunnelPool.h" #include "Reseed.h" #include "NetDbRequests.h" #include "Family.h" namespace i2p { namespace data { const int NETDB_MIN_ROUTERS = 90; const int NETDB_FLOODFILL_EXPIRATION_TIMEOUT = 60*60; // 1 hour, in seconds const int NETDB_INTRODUCEE_EXPIRATION_TIMEOUT = 65*60; const int NETDB_MIN_EXPIRATION_TIMEOUT = 90*60; // 1.5 hours const int NETDB_MAX_EXPIRATION_TIMEOUT = 27*60*60; // 27 hours const int NETDB_PUBLISH_INTERVAL = 60*40; /** function for visiting a leaseset stored in a floodfill */ typedef std::function<void(const IdentHash, std::shared_ptr<LeaseSet>)> LeaseSetVisitor; /** function for visiting a router info we have locally */ typedef std::function<void(std::shared_ptr<const i2p::data::RouterInfo>)> RouterInfoVisitor; /** function for visiting a router info and determining if we want to use it */ typedef std::function<bool(std::shared_ptr<const i2p::data::RouterInfo>)> RouterInfoFilter; class NetDb { public: NetDb (); ~NetDb (); void Start (); void Stop (); bool AddRouterInfo (const uint8_t * buf, int len); bool AddRouterInfo (const IdentHash& ident, const uint8_t * buf, int len); bool AddLeaseSet (const IdentHash& ident, const uint8_t * buf, int len, std::shared_ptr<i2p::tunnel::InboundTunnel> from); std::shared_ptr<RouterInfo> FindRouter (const IdentHash& ident) const; std::shared_ptr<LeaseSet> FindLeaseSet (const IdentHash& destination) const; std::shared_ptr<RouterProfile> FindRouterProfile (const IdentHash& ident) const; void RequestDestination (const IdentHash& destination, RequestedDestination::RequestComplete requestComplete = nullptr); void RequestDestinationFrom (const IdentHash& destination, const IdentHash & from, bool exploritory, RequestedDestination::RequestComplete requestComplete = nullptr); void HandleDatabaseStoreMsg (std::shared_ptr<const I2NPMessage> msg); void HandleDatabaseSearchReplyMsg (std::shared_ptr<const I2NPMessage> msg); void HandleDatabaseLookupMsg (std::shared_ptr<const I2NPMessage> msg); std::shared_ptr<const RouterInfo> GetRandomRouter () const; std::shared_ptr<const RouterInfo> GetRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const; std::shared_ptr<const RouterInfo> GetHighBandwidthRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const; std::shared_ptr<const RouterInfo> GetRandomPeerTestRouter (bool v4only = true) const; std::shared_ptr<const RouterInfo> GetRandomIntroducer () const; std::shared_ptr<const RouterInfo> GetClosestFloodfill (const IdentHash& destination, const std::set<IdentHash>& excluded, bool closeThanUsOnly = false) const; std::vector<IdentHash> GetClosestFloodfills (const IdentHash& destination, size_t num, std::set<IdentHash>& excluded, bool closeThanUsOnly = false) const; std::shared_ptr<const RouterInfo> GetClosestNonFloodfill (const IdentHash& destination, const std::set<IdentHash>& excluded) const; std::shared_ptr<const RouterInfo> GetRandomRouterInFamily(const std::string & fam) const; void SetUnreachable (const IdentHash& ident, bool unreachable); void PostI2NPMsg (std::shared_ptr<const I2NPMessage> msg); /** set hidden mode, aka don't publish our RI to netdb and don't explore */ void SetHidden(bool hide); void Reseed (); Families& GetFamilies () { return m_Families; }; // for web interface int GetNumRouters () const { return m_RouterInfos.size (); }; int GetNumFloodfills () const { return m_Floodfills.size (); }; int GetNumLeaseSets () const { return m_LeaseSets.size (); }; /** visit all lease sets we currently store */ void VisitLeaseSets(LeaseSetVisitor v); /** visit all router infos we have currently on disk, usually insanely expensive, does not access in memory RI */ void VisitStoredRouterInfos(RouterInfoVisitor v); /** visit all router infos we have loaded in memory, cheaper than VisitLocalRouterInfos but locks access while visiting */ void VisitRouterInfos(RouterInfoVisitor v); /** visit N random router that match using filter, then visit them with a visitor, return number of RouterInfos that were visited */ size_t VisitRandomRouterInfos(RouterInfoFilter f, RouterInfoVisitor v, size_t n); void ClearRouterInfos () { m_RouterInfos.clear (); }; private: void Load (); bool LoadRouterInfo (const std::string & path); void SaveUpdated (); void Run (); // exploratory thread void Explore (int numDestinations); void Publish (); void ManageLeaseSets (); void ManageRequests (); void ReseedFromFloodfill(const RouterInfo & ri, int numRouters=40, int numFloodfills=20); template<typename Filter> std::shared_ptr<const RouterInfo> GetRandomRouter (Filter filter) const; private: mutable std::mutex m_LeaseSetsMutex; std::map<IdentHash, std::shared_ptr<LeaseSet> > m_LeaseSets; mutable std::mutex m_RouterInfosMutex; std::map<IdentHash, std::shared_ptr<RouterInfo> > m_RouterInfos; mutable std::mutex m_FloodfillsMutex; std::list<std::shared_ptr<RouterInfo> > m_Floodfills; bool m_IsRunning; uint64_t m_LastLoad; std::thread * m_Thread; i2p::util::Queue<std::shared_ptr<const I2NPMessage> > m_Queue; // of I2NPDatabaseStoreMsg GzipInflator m_Inflator; Reseeder * m_Reseeder; Families m_Families; i2p::fs::HashedStorage m_Storage; friend class NetDbRequests; NetDbRequests m_Requests; /** router info we are bootstrapping from or nullptr if we are not currently doing that*/ std::shared_ptr<RouterInfo> m_FloodfillBootstrap; /** true if in hidden mode */ bool m_HiddenMode; }; extern NetDb netdb; } } #endif
bsd-3-clause
pbrunet/pythran
third_party/nt2/arithmetic/include/functions/scalar/idivfix.hpp
258
#ifndef NT2_ARITHMETIC_INCLUDE_FUNCTIONS_SCALAR_IDIVFIX_HPP_INCLUDED #define NT2_ARITHMETIC_INCLUDE_FUNCTIONS_SCALAR_IDIVFIX_HPP_INCLUDED #include <nt2/arithmetic/functions/idivfix.hpp> #include <boost/simd/arithmetic/functions/generic/idivfix.hpp> #endif
bsd-3-clause
NCIP/caaers
caAERS/software/web/src/test/java/gov/nih/nci/cabig/caaers/web/task/TaskControllerTest.java
1585
/******************************************************************************* * Copyright SemanticBits, Northwestern University and Akaza Research * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caaers/LICENSE.txt for details. ******************************************************************************/ package gov.nih.nci.cabig.caaers.web.task; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.servlet.ModelAndView; public class TaskControllerTest extends TestCase { private TaskController taskController; @Override protected void setUp() throws Exception { super.setUp(); taskController = new TaskController(); } public void testHandleRequestInternal() throws Exception{ ModelAndView mv = taskController.handleRequestInternal(new MockHttpServletRequest(), new MockHttpServletResponse()); assertEquals("main/mainPage", mv.getViewName()); List<TaskGroup> taskGroups = (List<TaskGroup>)mv.getModel().get("taskgroups"); assertEquals(0, taskGroups.size()); List<TaskGroup> newTaskGroups = new ArrayList<TaskGroup>(); newTaskGroups.add(new TaskGroup()); taskController.setTaskGroups(newTaskGroups); mv = taskController.handleRequestInternal(new MockHttpServletRequest(), new MockHttpServletResponse()); taskGroups = (List<TaskGroup>)mv.getModel().get("taskgroups"); assertEquals(1, taskGroups.size()); } }
bsd-3-clause
dram1008/tpk
public_html/1/libraries/plugins/export/ExportCodegen.class.php
12855
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Set of functions used to build NHibernate dumps of tables * * @package PhpMyAdmin-Export * @subpackage CodeGen */ if (!defined('PHPMYADMIN')) { exit; } /* Get the export interface */ require_once 'libraries/plugins/ExportPlugin.class.php'; /* Get the table property class */ require_once 'libraries/plugins/export/TableProperty.class.php'; /** * Handles the export for the CodeGen class * * @package PhpMyAdmin-Export * @subpackage CodeGen */ class ExportCodegen extends ExportPlugin { /** * CodeGen Formats * * @var array */ private $_cgFormats; /** * CodeGen Handlers * * @var array */ private $_cgHandlers; /** * Constructor */ public function __construct() { // initialize the specific export CodeGen variables $this->initSpecificVariables(); $this->setProperties(); } /** * Initialize the local variables that are used for export CodeGen * * @return void */ protected function initSpecificVariables() { $this->_setCgFormats( [ "NHibernate C# DO", "NHibernate XML" ] ); $this->_setCgHandlers( [ "_handleNHibernateCSBody", "_handleNHibernateXMLBody" ] ); } /** * Sets the export CodeGen properties * * @return void */ protected function setProperties() { $props = 'libraries/properties/'; include_once "$props/plugins/ExportPluginProperties.class.php"; include_once "$props/options/groups/OptionsPropertyRootGroup.class.php"; include_once "$props/options/groups/OptionsPropertyMainGroup.class.php"; include_once "$props/options/items/HiddenPropertyItem.class.php"; include_once "$props/options/items/SelectPropertyItem.class.php"; $exportPluginProperties = new ExportPluginProperties(); $exportPluginProperties->setText('CodeGen'); $exportPluginProperties->setExtension('cs'); $exportPluginProperties->setMimeType('text/cs'); $exportPluginProperties->setOptionsText(__('Options')); // create the root group that will be the options field for // $exportPluginProperties // this will be shown as "Format specific options" $exportSpecificOptions = new OptionsPropertyRootGroup(); $exportSpecificOptions->setName("Format Specific Options"); // general options main group $generalOptions = new OptionsPropertyMainGroup(); $generalOptions->setName("general_opts"); // create primary items and add them to the group $leaf = new HiddenPropertyItem(); $leaf->setName("structure_or_data"); $generalOptions->addProperty($leaf); $leaf = new SelectPropertyItem(); $leaf->setName("format"); $leaf->setText(__('Format:')); $leaf->setValues($this->_getCgFormats()); $generalOptions->addProperty($leaf); // add the main group to the root group $exportSpecificOptions->addProperty($generalOptions); // set the options for the export plugin property item $exportPluginProperties->setOptions($exportSpecificOptions); $this->properties = $exportPluginProperties; } /** * This method is called when any PluginManager to which the observer * is attached calls PluginManager::notify() * * @param SplSubject $subject The PluginManager notifying the observer * of an update. * * @return void */ public function update(SplSubject $subject) { } /** * Outputs export header * * @return bool Whether it succeeded */ public function exportHeader() { return true; } /** * Outputs export footer * * @return bool Whether it succeeded */ public function exportFooter() { return true; } /** * Outputs database header * * @param string $db Database name * * @return bool Whether it succeeded */ public function exportDBHeader($db) { return true; } /** * Outputs database footer * * @param string $db Database name * * @return bool Whether it succeeded */ public function exportDBFooter($db) { return true; } /** * Outputs CREATE DATABASE statement * * @param string $db Database name * * @return bool Whether it succeeded */ public function exportDBCreate($db) { return true; } /** * Outputs the content of a table in NHibernate format * * @param string $db database name * @param string $table table name * @param string $crlf the end of line sequence * @param string $error_url the url to go back in case of error * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { $CG_FORMATS = $this->_getCgFormats(); $CG_HANDLERS = $this->_getCgHandlers(); $format = $GLOBALS['codegen_format']; if (isset($CG_FORMATS[ $format ])) { return PMA_exportOutputHandler( $this->$CG_HANDLERS[ $format ]($db, $table, $crlf) ); } return PMA_exportOutputHandler(sprintf("%s is not supported.", $format)); } /** * Used to make identifiers (from table or database names) * * @param string $str name to be converted * @param bool $ucfirst whether to make the first character uppercase * * @return string identifier */ public static function cgMakeIdentifier($str, $ucfirst = true) { // remove unsafe characters $str = preg_replace('/[^\p{L}\p{Nl}_]/u', '', $str); // make sure first character is a letter or _ if (!preg_match('/^\pL/u', $str)) { $str = '_' . $str; } if ($ucfirst) { $str = ucfirst($str); } return $str; } /** * C# Handler * * @param string $db database name * @param string $table table name * @param string $crlf line separator * * @return string containing C# code lines, separated by "\n" */ private function _handleNHibernateCSBody($db, $table, $crlf) { $lines = []; $result = PMA_DBI_query( sprintf( 'DESC %s.%s', PMA_Util::backquote($db), PMA_Util::backquote($table) ) ); if ($result) { $tableProperties = []; while ($row = PMA_DBI_fetch_row($result)) { $tableProperties[] = new TableProperty($row); } PMA_DBI_free_result($result); $lines[] = 'using System;'; $lines[] = 'using System.Collections;'; $lines[] = 'using System.Collections.Generic;'; $lines[] = 'using System.Text;'; $lines[] = 'namespace ' . ExportCodegen::cgMakeIdentifier($db); $lines[] = '{'; $lines[] = ' #region ' . ExportCodegen::cgMakeIdentifier($table); $lines[] = ' public class ' . ExportCodegen::cgMakeIdentifier($table); $lines[] = ' {'; $lines[] = ' #region Member Variables'; foreach ($tableProperties as $tableProperty) { $lines[] = $tableProperty->formatCs( ' protected #dotNetPrimitiveType# _#name#;' ); } $lines[] = ' #endregion'; $lines[] = ' #region Constructors'; $lines[] = ' public ' . ExportCodegen::cgMakeIdentifier($table) . '() { }'; $temp = []; foreach ($tableProperties as $tableProperty) { if (!$tableProperty->isPK()) { $temp[] = $tableProperty->formatCs( '#dotNetPrimitiveType# #name#' ); } } $lines[] = ' public ' . ExportCodegen::cgMakeIdentifier($table) . '(' . implode(', ', $temp) . ')'; $lines[] = ' {'; foreach ($tableProperties as $tableProperty) { if (!$tableProperty->isPK()) { $lines[] = $tableProperty->formatCs( ' this._#name#=#name#;' ); } } $lines[] = ' }'; $lines[] = ' #endregion'; $lines[] = ' #region Public Properties'; foreach ($tableProperties as $tableProperty) { $lines[] = $tableProperty->formatCs( ' public virtual #dotNetPrimitiveType# #ucfirstName#' . "\n" . ' {' . "\n" . ' get {return _#name#;}' . "\n" . ' set {_#name#=value;}' . "\n" . ' }' ); } $lines[] = ' #endregion'; $lines[] = ' }'; $lines[] = ' #endregion'; $lines[] = '}'; } return implode("\n", $lines); } /** * XML Handler * * @param string $db database name * @param string $table table name * @param string $crlf line separator * * @return string containing XML code lines, separated by "\n" */ private function _handleNHibernateXMLBody($db, $table, $crlf) { $lines = []; $lines[] = '<?xml version="1.0" encoding="utf-8" ?' . '>'; $lines[] = '<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" ' . 'namespace="' . ExportCodegen::cgMakeIdentifier($db) . '" ' . 'assembly="' . ExportCodegen::cgMakeIdentifier($db) . '">'; $lines[] = ' <class ' . 'name="' . ExportCodegen::cgMakeIdentifier($table) . '" ' . 'table="' . ExportCodegen::cgMakeIdentifier($table) . '">'; $result = PMA_DBI_query( sprintf( "DESC %s.%s", PMA_Util::backquote($db), PMA_Util::backquote($table) ) ); if ($result) { while ($row = PMA_DBI_fetch_row($result)) { $tableProperty = new TableProperty($row); if ($tableProperty->isPK()) { $lines[] = $tableProperty->formatXml( ' <id name="#ucfirstName#" type="#dotNetObjectType#"' . ' unsaved-value="0">' . "\n" . ' <column name="#name#" sql-type="#type#"' . ' not-null="#notNull#" unique="#unique#"' . ' index="PRIMARY"/>' . "\n" . ' <generator class="native" />' . "\n" . ' </id>' ); } else { $lines[] = $tableProperty->formatXml( ' <property name="#ucfirstName#"' . ' type="#dotNetObjectType#">' . "\n" . ' <column name="#name#" sql-type="#type#"' . ' not-null="#notNull#" #indexName#/>' . "\n" . ' </property>' ); } } PMA_DBI_free_result($result); } $lines[] = ' </class>'; $lines[] = '</hibernate-mapping>'; return implode("\n", $lines); } /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ /** * Getter for CodeGen formats * * @return array */ private function _getCgFormats() { return $this->_cgFormats; } /** * Setter for CodeGen formats * * @param array $CG_FORMATS contains CodeGen Formats * * @return void */ private function _setCgFormats($CG_FORMATS) { $this->_cgFormats = $CG_FORMATS; } /** * Getter for CodeGen handlers * * @return array */ private function _getCgHandlers() { return $this->_cgHandlers; } /** * Setter for CodeGen handlers * * @param array $CG_HANDLERS contains CodeGen handler methods * * @return void */ private function _setCgHandlers($CG_HANDLERS) { $this->_cgHandlers = $CG_HANDLERS; } } ?>
bsd-3-clause
CBIIT/caaers
caAERS/software/AntInstaller/src/org/tp23/antinstaller/renderer/swing/AIShortTextField.java
1898
/* * Copyright 2005 Paul Hinds * * 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 org.tp23.antinstaller.renderer.swing; import java.awt.Dimension; import javax.swing.JTextField; import javax.swing.text.Document; /** * A JTextField with altered prefered size to facilitate fixing the width * but still using a GridBagLayout. This text field is for use inconjunction * with a button for example file chooser. * @author Paul Hinds * @version $Id: AIShortTextField.java,v 1.1 2006/08/19 15:35:36 kumarvi Exp $ */ public class AIShortTextField extends JTextField { public AIShortTextField() { super(); } public AIShortTextField(int columns) { super(columns); } public AIShortTextField(String text) { super(text); } public AIShortTextField(String text, int columns) { super(text, columns); } public AIShortTextField(Document doc, String text, int columns) { super(doc, text, columns); } private Dimension prefSize = new Dimension(SwingOutputFieldRenderer.SHORT_FIELD_WIDTH, SwingOutputFieldRenderer.FIELD_HEIGHT); public Dimension getMinimumSize() { return prefSize; } public Dimension getPreferredSize() { return prefSize; } public void setOverflow(Dimension prefSize) { this.prefSize = prefSize; } public Dimension getMaximumSize() { return prefSize; } }
bsd-3-clause
wuzhc/WZCSHOP
frontend/views/member/index.php
15238
<?php use yii\helpers\Html; $this->title = '会员中心'; $this->params['breadcrumbs'][] = $this->title; ?> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-3"> <!-- Profile Image --> <div class="box box-primary"> <div class="box-body box-profile"> <img class="profile-user-img img-responsive img-circle" src="<?= $member->header_img ?: Yii::$app->urlManager->baseUrl.'/public/common/dist/img/avatar04.png' ?>" height="128" width="128" alt="头像"> <h3 class="profile-username text-center"><?= $member->nickname;?></h3> <p class="text-muted text-center"><?= $member->username;?></p> <ul class="list-group list-group-unbordered"> <li class="list-group-item"> <b style="color: #8c8c8c">我的收藏</b> <a class="pull-right">1,322</a> </li> <li class="list-group-item"> <b style="color: #8c8c8c">购买记录</b> <a class="pull-right">13,287</a> </li> </ul> <a href="#" class="btn btn-primary btn-block"><b>Follow</b></a> </div> <!-- /.box-body --> </div> <!-- /.box --> <!-- About Me Box --> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">其他信息</h3> </div> <!-- /.box-header --> <div class="box-body"> <strong><i class="fa fa-book margin-r-5"></i> Education</strong> <p class="text-muted"> B.S. in Computer Science from the University of Tennessee at Knoxville </p> <hr> <strong><i class="fa fa-map-marker margin-r-5"></i>地址</strong> <p class="text-muted">广东省广州市白云区人和镇太阳岛中心</p> <hr> <strong><i class="fa fa-pencil margin-r-5"></i> Skills</strong> <p> <span class="label label-danger">UI Design</span> <span class="label label-success">Coding</span> <span class="label label-info">Javascript</span> <span class="label label-warning">PHP</span> <span class="label label-primary">Node.js</span> </p> <hr> <strong><i class="fa fa-file-text-o margin-r-5"></i> Notes</strong> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam fermentum enim neque.</p> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> <div class="col-md-9"> <div class="nav-tabs-custom"> <ul class="nav nav-tabs"> <li class="active"><a href="#settings" data-toggle="tab" aria-expanded="false">完善资料</a></li> <li class=""><a href="#activity" data-toggle="tab" aria-expanded="true">我的评论</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="settings"> <form class="form-horizontal"> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">账号</label> <div class="col-sm-10"> <input class="form-control" id="inputName" placeholder="账号" readOnly='true' value="<?= $member->username; ?>"> </div> </div> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">昵称</label> <div class="col-sm-10"> <input class="form-control" id="inputName" placeholder="nickname" value="<?= $member->nickname; ?>"> </div> </div> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">QQ</label> <div class="col-sm-10"> <input class="form-control" id="inputName" placeholder="QQ" value="<?= $member->qq; ?>"> </div> </div> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">手机</label> <div class="col-sm-10"> <input class="form-control" id="inputName" placeholder="手机" value="<?= $member->phone; ?>"> </div> </div> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">邮箱</label> <div class="col-sm-10"> <input class="form-control" id="inputName" placeholder="邮箱" value="<?= $member->email; ?>" type="email"> </div> </div> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">头像</label> <div class="col-sm-10"> <input class="form-control" id="inputName" placeholder="头像" value="<?= $member->header_img; ?>"> </div> </div> <div class="form-group"> <label for="inputEmail" class="col-sm-2 control-label">性别</label> <div class="col-sm-10"> <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>男 <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>女 </div> </div> <div class="form-group"> <label for="inputExperience" class="col-sm-2 control-label">简介</label> <div class="col-sm-10"> <textarea class="form-control" id="inputExperience" placeholder="Experience"></textarea> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox"> I agree to the <a href="#">terms and conditions</a> </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-danger">Submit</button> </div> </div> </form> </div> <!-- /.tab-pane --> <div class="tab-pane" id="activity"> <!-- Post --> <div class="post"> <div class="user-block"> <img class="img-circle img-bordered-sm" src="<?= $member->header_img ?: Yii::$app->urlManager->baseUrl.'/public/common/dist/img/avatar04.png' ?>" alt="user image"> <span class="username"> <a href="#"><?= $member->username;?> <?= $member->nickname ?></a> <a href="#" class="pull-right btn-box-tool"><i class="fa fa-times"></i></a> </span> <span class="description">Shared publicly - 7:30 PM today</span> </div> <!-- /.user-block --> <p> Lorem ipsum represents a long-held tradition for designers, typographers and the like. Some people hate it and argue for its demise, but others ignore the hate as they create awesome tools to help create filler text for everyone from bacon lovers to Charlie Sheen fans. </p> <ul class="list-inline"> <li><a href="#" class="link-black text-sm"><i class="fa fa-share margin-r-5"></i> Share</a></li> <li><a href="#" class="link-black text-sm"><i class="fa fa-thumbs-o-up margin-r-5"></i> Like</a> </li> <li class="pull-right"> <a href="#" class="link-black text-sm"><i class="fa fa-comments-o margin-r-5"></i> Comments (5)</a></li> </ul> <input class="form-control input-sm" placeholder="Type a comment" type="text"> </div> <!-- /.post --> <!-- Post --> <div class="post clearfix"> <div class="user-block"> <img class="img-circle img-bordered-sm" src="../../dist/img/user7-128x128.jpg" alt="User Image"> <span class="username"> <a href="#">Sarah Ross</a> <a href="#" class="pull-right btn-box-tool"><i class="fa fa-times"></i></a> </span> <span class="description">Sent you a message - 3 days ago</span> </div> <!-- /.user-block --> <p> Lorem ipsum represents a long-held tradition for designers, typographers and the like. Some people hate it and argue for its demise, but others ignore the hate as they create awesome tools to help create filler text for everyone from bacon lovers to Charlie Sheen fans. </p> <form class="form-horizontal"> <div class="form-group margin-bottom-none"> <div class="col-sm-9"> <input class="form-control input-sm" placeholder="Response"> </div> <div class="col-sm-3"> <button type="submit" class="btn btn-danger pull-right btn-block btn-sm">Send</button> </div> </div> </form> </div> <!-- /.post --> <!-- Post --> <div class="post"> <div class="user-block"> <img class="img-circle img-bordered-sm" src="../../dist/img/user6-128x128.jpg" alt="User Image"> <span class="username"> <a href="#">Adam Jones</a> <a href="#" class="pull-right btn-box-tool"><i class="fa fa-times"></i></a> </span> <span class="description">Posted 5 photos - 5 days ago</span> </div> <!-- /.user-block --> <div class="row margin-bottom"> <div class="col-sm-6"> <img class="img-responsive" src="../../dist/img/photo1.png" alt="Photo"> </div> <!-- /.col --> <div class="col-sm-6"> <div class="row"> <div class="col-sm-6"> <img class="img-responsive" src="../../dist/img/photo2.png" alt="Photo"> <br> <img class="img-responsive" src="../../dist/img/photo3.jpg" alt="Photo"> </div> <!-- /.col --> <div class="col-sm-6"> <img class="img-responsive" src="../../dist/img/photo4.jpg" alt="Photo"> <br> <img class="img-responsive" src="../../dist/img/photo1.png" alt="Photo"> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.col --> </div> <!-- /.row --> <ul class="list-inline"> <li><a href="#" class="link-black text-sm"><i class="fa fa-share margin-r-5"></i> Share</a></li> <li><a href="#" class="link-black text-sm"><i class="fa fa-thumbs-o-up margin-r-5"></i> Like</a> </li> <li class="pull-right"> <a href="#" class="link-black text-sm"><i class="fa fa-comments-o margin-r-5"></i> Comments (5)</a></li> </ul> <input class="form-control input-sm" placeholder="Type a comment" type="text"> </div> <!-- /.post --> </div> </div> <!-- /.tab-content --> </div> <!-- /.nav-tabs-custom --> </div> <!-- /.col --> </div> <!-- /.row --> <!-- /.content -->
bsd-3-clause
tmc/graphql
executor/doc.go
91
// Package executor produces results from a graphql Operation and Schema. package executor
isc
qinzuoyan/rDSN
src/tools/webstudio/app_package/static/js/dsn/dsn_types.js
5883
// // Autogenerated by Thrift Compiler (@PACKAGE_VERSION@) // // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING // error_code = function(args) { this.code = null; if (args) { if (args.code !== undefined && args.code !== null) { this.code = args.code; } } }; error_code.prototype = {}; error_code.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype == Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype == Thrift.Type.STRING) { this.code = input.readString().value; } else { input.skip(ftype); } break; case 0: input.skip(ftype); break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; error_code.prototype.write = function(output) { output.writeStructBegin('error_code'); if (this.code !== null && this.code !== undefined) { output.writeFieldBegin('code', Thrift.Type.STRING, 1); output.writeString(this.code); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; task_code = function(args) { this.code = null; if (args) { if (args.code !== undefined && args.code !== null) { this.code = args.code; } } }; task_code.prototype = {}; task_code.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype == Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype == Thrift.Type.STRING) { this.code = input.readString().value; } else { input.skip(ftype); } break; case 0: input.skip(ftype); break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; task_code.prototype.write = function(output) { output.writeStructBegin('task_code'); if (this.code !== null && this.code !== undefined) { output.writeFieldBegin('code', Thrift.Type.STRING, 1); output.writeString(this.code); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; gpid = function(args) { this.id = null; if (args) { if (args.id !== undefined && args.id !== null) { this.id = args.id; } } }; gpid.prototype = {}; gpid.prototype.app_id = function() { var idstr = this.id.toString(2); var idstr2 = ''; for (var i = 0; i < 64 - idstr.length; i++) { idstr2 += '0'; }; idstr2 += idstr; return parseInt(idstr2.substring(32), 2); } gpid.prototype.partition_index = function() { var idstr = this.id.toString(2); var idstr2 = ''; for (var i = 0; i < 64 - idstr.length; i++) { idstr2 += '0'; }; idstr2 += idstr; return parseInt(idstr2.substring(0, 32), 2); } gpid.prototype.toString = function() { var idstr = this.id.toString(2); var idstr2 = ''; for (var i = 0; i < 64 - idstr.length; i++) { idstr2 += '0'; }; idstr2 += idstr; return parseInt(idstr2.substring(32), 2) + "." + parseInt(idstr2.substring(0, 32), 2); } gpid.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype == Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype == Thrift.Type.I64) { this.id = input.readI64().value; } else { input.skip(ftype); } break; case 0: input.skip(ftype); break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; gpid.prototype.write = function(output) { output.writeStructBegin('gpid'); if (this.id !== null && this.id !== undefined) { output.writeFieldBegin('id', Thrift.Type.I64, 1); output.writeI64(this.id); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; rpc_address = function(args) { this.host = null; this.port = null; if (args) { if (args.host !== undefined && args.host !== null) { this.host = args.host; } if (args.port !== undefined && args.port !== null) { this.port = args.port; } } }; rpc_address.prototype = {}; rpc_address.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype == Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype == Thrift.Type.STRING) { this.host = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype == Thrift.Type.I32) { this.port = input.readI32().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; rpc_address.prototype.write = function(output) { output.writeStructBegin('rpc_address'); if (this.host !== null && this.host !== undefined) { output.writeFieldBegin('host', Thrift.Type.STRING, 1); output.writeString(this.host); output.writeFieldEnd(); } if (this.port !== null && this.port !== undefined) { output.writeFieldBegin('port', Thrift.Type.I32, 2); output.writeI32(this.port); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; };
mit
chm-tm/nunit-gui
src/nunit-gui/Model/ITestModel.cs
4332
// *********************************************************************** // Copyright (c) 2016 Charlie Poole // // 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. // *********************************************************************** using System.Collections.Generic; using NUnit.Engine; namespace NUnit.Gui.Model { /// <summary> /// Delegates for all events related to the model /// </summary> public delegate void TestEventHandler(TestEventArgs args); public delegate void RunStartingEventHandler(RunStartingEventArgs args); public delegate void TestNodeEventHandler(TestNodeEventArgs args); public delegate void TestResultEventHandler(TestResultEventArgs args); public delegate void TestItemEventHandler(TestItemEventArgs args); public interface ITestModel : IServiceLocator, System.IDisposable { #region Events // Events related to loading and unloading tests. event TestNodeEventHandler TestLoaded; event TestNodeEventHandler TestReloaded; event TestEventHandler TestUnloaded; // Events related to running tests event RunStartingEventHandler RunStarting; event TestNodeEventHandler SuiteStarting; event TestNodeEventHandler TestStarting; event TestResultEventHandler RunFinished; event TestResultEventHandler SuiteFinished; event TestResultEventHandler TestFinished; // Event used to broadcast a change in the selected // item, so that all presenters may be notified. event TestItemEventHandler SelectedItemChanged; #endregion #region Properties CommandLineOptions Options { get; } IRecentFiles RecentFiles { get; } bool IsPackageLoaded { get; } // TestNode hierarchy representing the discovered tests TestNode Tests { get; } // See if tests are available bool HasTests { get; } // See if a test is running bool IsTestRunning { get; } bool HasResults { get; } Settings.SettingsModel Settings { get; } IList<RuntimeFramework> AvailableRuntimes { get; } #endregion #region Methods // Perform initial actions on startup, loading and possibly running tests void OnStartup(); // Create a new empty project using a default name void NewProject(); // Create a new project given a filename void NewProject(string filename); void SaveProject(); // Load a TestPackage void LoadTests(IList<string> files); // Unload current TestPackage void UnloadTests(); // Reload current TestPackage void ReloadTests(); // Reload current TestPackage using specified runtime void ReloadTests(string runtime); // Run all the tests void RunAllTests(); // Run just the specified ITestItem void RunTests(ITestItem testItem); // Cancel the running test void CancelTestRun(); // Get the result for a test if available ResultNode GetResultForTest(TestNode testNode); // Broadcast event when SelectedTestItem changes void NotifySelectedItemChanged(ITestItem testItem); #endregion } }
mit
KonstantinShemyak/cytoscape.js
src/extensions/renderer/canvas/drawing-images.js
3276
'use strict'; var CRp = {}; CRp.safeDrawImage = function( context, img, ix, iy, iw, ih, x, y, w, h ){ var r = this; try { context.drawImage( img, ix, iy, iw, ih, x, y, w, h ); } catch(e){ r.data.canvasNeedsRedraw[r.NODE] = true; r.data.canvasNeedsRedraw[r.DRAG] = true; r.drawingImage = true; r.redraw(); } }; CRp.drawInscribedImage = function(context, img, node) { var r = this; var nodeX = node._private.position.x; var nodeY = node._private.position.y; var style = node._private.style; var fit = style['background-fit'].value; var xPos = style['background-position-x']; var yPos = style['background-position-y']; var repeat = style['background-repeat'].value; var nodeW = node.width(); var nodeH = node.height(); var rs = node._private.rscratch; var clip = style['background-clip'].value; var shouldClip = clip === 'node'; var imgOpacity = style['background-image-opacity'].value; var imgW = img.width || img.cachedW; var imgH = img.height || img.cachedH; // workaround for broken browsers like ie if( null == imgW || null == imgH ){ document.body.appendChild( img ); imgW = img.cachedW = img.width || img.offsetWidth; imgH = img.cachedH = img.height || img.offsetHeight; document.body.removeChild( img ); } var w = imgW; var h = imgH; var bgW = style['background-width']; if( bgW.value !== 'auto' ){ if( bgW.units === '%' ){ w = bgW.value/100 * nodeW; } else { w = bgW.pfValue; } } var bgH = style['background-height']; if( bgH.value !== 'auto' ){ if( bgH.units === '%' ){ h = bgH.value/100 * nodeH; } else { h = bgH.pfValue; } } if( w === 0 || h === 0 ){ return; // no point in drawing empty image (and chrome is broken in this case) } if( fit === 'contain' ){ var scale = Math.min( nodeW/w, nodeH/h ); w *= scale; h *= scale; } else if( fit === 'cover' ){ var scale = Math.max( nodeW/w, nodeH/h ); w *= scale; h *= scale; } var x = (nodeX - nodeW/2); // left if( xPos.units === '%' ){ x += (nodeW - w) * xPos.value/100; } else { x += xPos.pfValue; } var y = (nodeY - nodeH/2); // top if( yPos.units === '%' ){ y += (nodeH - h) * yPos.value/100; } else { y += yPos.pfValue; } if( rs.pathCache ){ x -= nodeX; y -= nodeY; nodeX = 0; nodeY = 0; } var gAlpha = context.globalAlpha; context.globalAlpha = imgOpacity; if( repeat === 'no-repeat' ){ if( shouldClip ){ context.save(); if( rs.pathCache ){ context.clip( rs.pathCache ); } else { r.nodeShapes[r.getNodeShape(node)].draw( context, nodeX, nodeY, nodeW, nodeH); context.clip(); } } r.safeDrawImage( context, img, 0, 0, imgW, imgH, x, y, w, h ); if( shouldClip ){ context.restore(); } } else { var pattern = context.createPattern( img, repeat ); context.fillStyle = pattern; r.nodeShapes[r.getNodeShape(node)].draw( context, nodeX, nodeY, nodeW, nodeH); context.translate(x, y); context.fill(); context.translate(-x, -y); } context.globalAlpha = gAlpha; }; module.exports = CRp;
mit
voodootikigod/node-serialport
packages/serialport/examples/open-event.js
472
/* eslint-disable node/no-missing-require */ // Open event example const SerialPort = require('serialport') const port = new SerialPort('/dev/tty-usbserial1') port.on('open', () => { console.log('Port Opened') }) port.write('main screen turn on', err => { if (err) { return console.log('Error: ', err.message) } console.log('message written') }) port.on('data', data => { /* get a buffer of data from the serial port */ console.log(data.toString()) })
mit
Skywalker-11/spongycastle
core/src/main/java/org/spongycastle/asn1/misc/MiscObjectIdentifiers.java
4840
package org.spongycastle.asn1.misc; import org.spongycastle.asn1.ASN1ObjectIdentifier; public interface MiscObjectIdentifiers { // // Netscape // iso/itu(2) joint-assign(16) us(840) uscompany(1) netscape(113730) cert-extensions(1) } // /** Netscape cert extensions OID base: 2.16.840.1.113730.1 */ static final ASN1ObjectIdentifier netscape = new ASN1ObjectIdentifier("2.16.840.1.113730.1"); /** Netscape cert CertType OID: 2.16.840.1.113730.1.1 */ static final ASN1ObjectIdentifier netscapeCertType = netscape.branch("1"); /** Netscape cert BaseURL OID: 2.16.840.1.113730.1.2 */ static final ASN1ObjectIdentifier netscapeBaseURL = netscape.branch("2"); /** Netscape cert RevocationURL OID: 2.16.840.1.113730.1.3 */ static final ASN1ObjectIdentifier netscapeRevocationURL = netscape.branch("3"); /** Netscape cert CARevocationURL OID: 2.16.840.1.113730.1.4 */ static final ASN1ObjectIdentifier netscapeCARevocationURL = netscape.branch("4"); /** Netscape cert RenewalURL OID: 2.16.840.1.113730.1.7 */ static final ASN1ObjectIdentifier netscapeRenewalURL = netscape.branch("7"); /** Netscape cert CApolicyURL OID: 2.16.840.1.113730.1.8 */ static final ASN1ObjectIdentifier netscapeCApolicyURL = netscape.branch("8"); /** Netscape cert SSLServerName OID: 2.16.840.1.113730.1.12 */ static final ASN1ObjectIdentifier netscapeSSLServerName = netscape.branch("12"); /** Netscape cert CertComment OID: 2.16.840.1.113730.1.13 */ static final ASN1ObjectIdentifier netscapeCertComment = netscape.branch("13"); // // Verisign // iso/itu(2) joint-assign(16) us(840) uscompany(1) verisign(113733) cert-extensions(1) } // /** Verisign OID base: 2.16.840.1.113733.1 */ static final ASN1ObjectIdentifier verisign = new ASN1ObjectIdentifier("2.16.840.1.113733.1"); /** Verisign CZAG (Country,Zip,Age,Gender) Extension OID: 2.16.840.1.113733.1.6.3 */ static final ASN1ObjectIdentifier verisignCzagExtension = verisign.branch("6.3"); static final ASN1ObjectIdentifier verisignPrivate_6_9 = verisign.branch("6.9"); static final ASN1ObjectIdentifier verisignOnSiteJurisdictionHash = verisign.branch("6.11"); static final ASN1ObjectIdentifier verisignBitString_6_13 = verisign.branch("6.13"); /** Verisign D&amp;B D-U-N-S number Extension OID: 2.16.840.1.113733.1.6.15 */ static final ASN1ObjectIdentifier verisignDnbDunsNumber = verisign.branch("6.15"); static final ASN1ObjectIdentifier verisignIssStrongCrypto = verisign.branch("8.1"); // // Novell // iso/itu(2) country(16) us(840) organization(1) novell(113719) // /** Novell OID base: 2.16.840.1.113719 */ static final ASN1ObjectIdentifier novell = new ASN1ObjectIdentifier("2.16.840.1.113719"); /** Novell SecurityAttribs OID: 2.16.840.1.113719.1.9.4.1 */ static final ASN1ObjectIdentifier novellSecurityAttribs = novell.branch("1.9.4.1"); // // Entrust // iso(1) member-body(16) us(840) nortelnetworks(113533) entrust(7) // /** NortelNetworks Entrust OID base: 1.2.840.113533.7 */ static final ASN1ObjectIdentifier entrust = new ASN1ObjectIdentifier("1.2.840.113533.7"); /** NortelNetworks Entrust VersionExtension OID: 1.2.840.113533.7.65.0 */ static final ASN1ObjectIdentifier entrustVersionExtension = entrust.branch("65.0"); /** cast5CBC OBJECT IDENTIFIER ::= {iso(1) member-body(2) us(840) nt(113533) nsn(7) algorithms(66) 10} SEE RFC 2984 */ ASN1ObjectIdentifier cast5CBC = entrust.branch("66.10"); // // Ascom // ASN1ObjectIdentifier as_sys_sec_alg_ideaCBC = new ASN1ObjectIdentifier("1.3.6.1.4.1.188.7.1.1.2"); // // Peter Gutmann's Cryptlib // ASN1ObjectIdentifier cryptlib = new ASN1ObjectIdentifier("1.3.6.1.4.1.3029"); ASN1ObjectIdentifier cryptlib_algorithm = cryptlib.branch("1"); ASN1ObjectIdentifier cryptlib_algorithm_blowfish_ECB = cryptlib_algorithm.branch("1.1"); ASN1ObjectIdentifier cryptlib_algorithm_blowfish_CBC = cryptlib_algorithm.branch("1.2"); ASN1ObjectIdentifier cryptlib_algorithm_blowfish_CFB = cryptlib_algorithm.branch("1.3"); ASN1ObjectIdentifier cryptlib_algorithm_blowfish_OFB = cryptlib_algorithm.branch("1.4"); // // Blake2b // ASN1ObjectIdentifier blake2 = new ASN1ObjectIdentifier("1.3.6.1.4.1.1722.12.2"); ASN1ObjectIdentifier id_blake2b160 = blake2.branch("1.5"); ASN1ObjectIdentifier id_blake2b256 = blake2.branch("1.8"); ASN1ObjectIdentifier id_blake2b384 = blake2.branch("1.12"); ASN1ObjectIdentifier id_blake2b512 = blake2.branch("1.16"); }
mit
yiwen-luo/LeetCode
Python/expression-add-operators.py
2085
# Time: O(4^n) # Space: O(n) # # Given a string that contains only digits 0-9 # and a target value, return all possibilities # to add operators +, -, or * between the digits # so they evaluate to the target value. # # Examples: # "123", 6 -> ["1+2+3", "1*2*3"] # "232", 8 -> ["2*3+2", "2+3*2"] # "00", 0 -> ["0+0", "0-0", "0*0"] # "3456237490", 9191 -> [] # class Solution(object): def addOperators(self, num, target): """ :type num: str :type target: int :rtype: List[str] """ result, expr = [], [] val, i = 0, 0 val_str = "" while i < len(num): val = val * 10 + ord(num[i]) - ord('0') val_str += num[i] # Avoid "00...". if str(val) != val_str: break expr.append(val_str) self.addOperatorsDFS(num, target, i + 1, 0, val, expr, result) expr.pop() i += 1 return result def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result): if pos == len(num) and operand1 + operand2 == target: result.append("".join(expr)) else: val, i = 0, pos val_str = "" while i < len(num): val = val * 10 + ord(num[i]) - ord('0') val_str += num[i] # Avoid "00...". if str(val) != val_str: break # Case '+': expr.append("+" + val_str) self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result) expr.pop() # Case '-': expr.append("-" + val_str) self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result) expr.pop() # Case '*': expr.append("*" + val_str) self.addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result) expr.pop() i += 1
mit
ekg/vg
src/dinucleotide_machine.hpp
1415
/** * \file dinucleotide_machine.hpp * * Defines a nondeterministic finite automaton over dinucleotides * */ #ifndef VG_DINUCLEOTIDE_MACHINE_GRAPH_HPP_INCLUDED #define VG_DINUCLEOTIDE_MACHINE_GRAPH_HPP_INCLUDED #include <string> #include <limits> #include <cstdint> #include <iostream> namespace vg { using namespace std; /* * Represents a non-deterministic finite automaton whose states * correspond to dinucleotides */ class DinucleotideMachine { public: DinucleotideMachine(); ~DinucleotideMachine() = default; /// Return an empty dinucleotide set uint32_t init_state() const; /// Get the dinucleotide set that results from extending the set by the given character /// Ns are valid, but will result in no matches uint32_t update_state(uint32_t state, char next) const; /// Get the union of two dinucleotide sets uint32_t merge_state(uint32_t state_1, uint32_t state_2) const; /// Return true if the set includes this dinucleotide. Only valid for dinucleotides of ACGT (never N). bool matches(uint32_t state, const char* dinucleotide) const; /// Same semantics as above bool matches(uint32_t state, const string& dinucleotide) const; private: // lookup table for transitions uint32_t transition_table[256]; // ASCII-indexed conversion from char to table index uint32_t nt_table[256]; }; } #endif
mit
komalsukhani/deb-lombok.ast
src/main/lombok/ast/grammar/TypesParser.java
6062
/* * Copyright (C) 2010 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.ast.grammar; import lombok.ast.Node; import org.parboiled.BaseParser; import org.parboiled.Rule; import org.parboiled.annotations.SuppressSubnodes; public class TypesParser extends BaseParser<Node> { final ParserGroup group; final TypesActions actions; public TypesParser(ParserGroup group) { actions = new TypesActions(group.getSource()); this.group = group; } public Rule nonArrayType() { return FirstOf(primitiveType(), referenceType()); } /** * @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#4.2">JLS section 4.2</a> */ public Rule type() { return Sequence( nonArrayType(), set(), ZeroOrMore(Sequence( Ch('['), group.basics.optWS(), Ch(']'), group.basics.optWS())), set(actions.setArrayDimensionsOfType(value(), texts("ZeroOrMore/Sequence")))).label("type"); } /** * @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#4.2">JLS section 4.2</a> */ public Rule primitiveType() { return Sequence( rawPrimitiveType(), set(actions.createPrimitiveType(lastText())), group.basics.optWS()); } @SuppressSubnodes Rule rawPrimitiveType() { return Sequence( FirstOf("boolean", "int", "long", "double", "float", "short", "char", "byte", "void"), group.basics.testLexBreak()); } /** * @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#4.3">JLS section 4.3</a> */ public Rule referenceType() { return Sequence( referenceTypePart().label("head"), ZeroOrMore(dotReferenceTypePart().label("tail")), set(actions.createReferenceType(value("head"), values("ZeroOrMore/tail")))); } Rule dotReferenceTypePart() { return Sequence( Ch('.'), group.basics.optWS(), group.basics.identifier().label("partName"), Optional(typeArguments()), set(actions.createTypeReferencePart(node("partName"), value("Optional/typeArguments"))), group.basics.optWS()); } Rule referenceTypePart() { return Sequence( group.basics.identifier().label("partName"), Optional(typeArguments()), set(actions.createTypeReferencePart(node("partName"), value("Optional/typeArguments"))), group.basics.optWS()); } public Rule plainReferenceType() { return Sequence( plainReferenceTypePart().label("head"), ZeroOrMore(dotPlainReferenceTypePart().label("tail")), set(actions.createReferenceType(value("head"), values("ZeroOrMore/tail")))); } Rule plainReferenceTypePart() { return Sequence( group.basics.identifier().label("partName"), set(actions.createTypeReferencePart(node("partName"), null)), group.basics.optWS()); } Rule dotPlainReferenceTypePart() { return Sequence( Ch('.'), group.basics.optWS(), group.basics.identifier().label("partName"), set(actions.createTypeReferencePart(node("partName"), null)), group.basics.optWS()); } public Rule typeVariables() { return Optional(Sequence( Ch('<'), group.basics.optWS(), Optional(Sequence( typeVariable().label("head"), ZeroOrMore(Sequence( Ch(','), group.basics.optWS(), typeVariable().label("tail"))))), Ch('>'), set(actions.createTypeVariables(value("Optional/Sequence/head"), values("Optional/Sequence/ZeroOrMore/Sequence/tail"))), group.basics.optWS())); } Rule typeVariable() { return Sequence( group.basics.identifier(), Optional(Sequence( Sequence( String("extends"), group.basics.testLexBreak(), group.basics.optWS()), type(), ZeroOrMore(Sequence( Ch('&'), group.basics.optWS(), type())))), set(actions.createTypeVariable(value("identifier"), value("Optional/Sequence/type"), values("Optional/Sequence/ZeroOrMore/Sequence/type")))); } /** * @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#4.5">JLS section 4.5</a> */ public Rule typeArguments() { return Optional(Sequence( Ch('<'), group.basics.optWS(), Optional(Sequence( typeArgument().label("head"), ZeroOrMore(Sequence( Ch(','), group.basics.optWS(), typeArgument().label("tail"))))), Ch('>'), set(actions.createTypeArguments(value("Optional/Sequence/head"), values("Optional/Sequence/ZeroOrMore/Sequence/tail"))), group.basics.optWS())).label("typeArguments"); } public Rule typeArgument() { return FirstOf( type(), Sequence( Ch('?').label("qmark"), group.basics.optWS(), FirstOf(String("extends"), String("super")).label("boundType"), group.basics.testLexBreak(), group.basics.optWS(), type(), set(actions.createWildcardedType(node("qmark"), node("boundType"), text("boundType"), value("type")))), Sequence( Ch('?').label("qmark"), set(actions.createUnboundedWildcardType(node("qmark"))), group.basics.optWS())); } }
mit
Azure/azure-sdk-for-go
services/preview/network/mgmt/2021-03-01-preview/network/servicetags.go
3996
package network // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // ServiceTagsClient is the network Client type ServiceTagsClient struct { BaseClient } // NewServiceTagsClient creates an instance of the ServiceTagsClient client. func NewServiceTagsClient(subscriptionID string) ServiceTagsClient { return NewServiceTagsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewServiceTagsClientWithBaseURI creates an instance of the ServiceTagsClient client using a custom endpoint. Use // this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewServiceTagsClientWithBaseURI(baseURI string, subscriptionID string) ServiceTagsClient { return ServiceTagsClient{NewWithBaseURI(baseURI, subscriptionID)} } // List gets a list of service tag information resources. // Parameters: // location - the location that will be used as a reference for version (not as a filter based on location, you // will get the list of service tags with prefix details across all regions but limited to the cloud that your // subscription belongs to). func (client ServiceTagsClient) List(ctx context.Context, location string) (result ServiceTagsListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServiceTagsClient.List") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ListPreparer(ctx, location) if err != nil { err = autorest.NewErrorWithError(err, "network.ServiceTagsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.ServiceTagsClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.ServiceTagsClient", "List", resp, "Failure responding to request") return } return } // ListPreparer prepares the List request. func (client ServiceTagsClient) ListPreparer(ctx context.Context, location string) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-02-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/serviceTags", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ServiceTagsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client ServiceTagsClient) ListResponder(resp *http.Response) (result ServiceTagsListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
mit
luissancheza/sice
js/jqwidgets/demos/react/app/grid/customcolumneditor/app.js
8259
import React from 'react'; import ReactDOM from 'react-dom'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; import JqxInput from '../../../jqwidgets-react/react_jqxinput.js'; import JqxDropDownList from '../../../jqwidgets-react/react_jqxdropdownlist.js'; import JqxSlider from '../../../jqwidgets-react/react_jqxslider.js'; class App extends React.Component { render() { let source = { localdata: generatedata(200), datatype: 'array', updaterow: (rowid, rowdata, commit) => { // synchronize with the server - send update command // call commit with parameter true if the synchronization with the server is successful // and with parameter false if the synchronization failder. commit(true); }, datafields: [ { name: 'firstname', type: 'string' }, { name: 'lastname', type: 'string' }, { name: 'productname', type: 'string' }, { name: 'available', type: 'bool' }, { name: 'quantity', type: 'number' }, { name: 'price', type: 'number' }, { name: 'date', type: 'date' } ] }; let dataAdapter = new $.jqx.dataAdapter(source); let getEditorDataAdapter = (datafield) => { let source = { localdata: generatedata(200), datatype: 'array', datafields: [ { name: 'firstname', type: 'string' }, { name: 'lastname', type: 'string' }, { name: 'productname', type: 'string' }, { name: 'available', type: 'bool' }, { name: 'quantity', type: 'number' }, { name: 'price', type: 'number' }, { name: 'date', type: 'date' } ] }; let dataAdapter = new $.jqx.dataAdapter(source, { uniqueDataFields: [datafield] }); return dataAdapter; } let input; let columns = [ { text: 'First Name', columntype: 'template', datafield: 'firstname', width: 80, createeditor: (row, cellvalue, editor, cellText, width, height) => { // construct the editor. let container = document.createElement('div'); editor[0].appendChild(container); input = ReactDOM.render( <JqxInput width={width} height={height} displayMember={'firstname'} source={getEditorDataAdapter('firstname')} /> ,container); }, initeditor: (row, cellvalue, editor, celltext, pressedkey) => { // set the editor's current value. The callback is called each time the editor is displayed. if (pressedkey) { input.val(pressedkey); input.selectLast(); } else { input.val(cellvalue); input.selectAll(); } }, geteditorvalue: (row, cellvalue, editor) => { // return the editor's value. return input.val(); } }, { text: 'Last Name', datafield: 'lastname', columntype: 'template', width: 80, createeditor: (row, cellvalue, editor, cellText, width, height) => { // construct the editor. let container = document.createElement('div'); editor[0].appendChild(container); input = ReactDOM.render( <JqxInput width={width} height={height} displayMember={'lastname'} source={getEditorDataAdapter('lastname')} /> , container); }, initeditor: (row, cellvalue, editor, celltext, pressedkey) => { // set the editor's current value. The callback is called each time the editor is displayed. if (pressedkey) { input.val(pressedkey); input.selectLast(); } else { input.val(cellvalue); input.selectAll(); } }, geteditorvalue: (row, cellvalue, editor) => { // return the editor's value. return input.val(); } }, { text: 'Products', columntype: 'template', datafield: 'productname', createeditor: (row, cellvalue, editor, cellText, width, height) => { // construct the editor. editor.jqxDropDownList({ checkboxes: true, source: getEditorDataAdapter('productname'), displayMember: 'productname', valueMember: 'productname', width: width, height: height, selectionRenderer: () => { return '<span style="top: 4px; position: relative;">Please Choose:</span>'; } }); }, initeditor: (row, cellvalue, editor, celltext, pressedkey) => { // set the editor's current value. The callback is called each time the editor is displayed. let items = editor.jqxDropDownList('getItems'); editor.jqxDropDownList('uncheckAll'); let values = cellvalue.split(/,\s*/); for (let j = 0; j < values.length; j++) { for (let i = 0; i < items.length; i++) { if (items[i].label === values[j]) { editor.jqxDropDownList('checkIndex', i); } } } }, geteditorvalue: (row, cellvalue, editor) => { // return the editor's value. return editor.val(); } }, { text: 'Quantity', width: 200, columntype: 'custom', datafield: 'quantity', createeditor: (row, cellvalue, editor, cellText, width, height) => { // construct the editor. editor.css('margin-top', '2px'); editor.jqxSlider({ step: 1, mode: 'fixed', showTicks: false, min: 0, max: 30, width: width, height: height }); }, initeditor: (row, cellvalue, editor, celltext, pressedkey) => { // set the editor's current value. The callback is called each time the editor is displayed. let value = parseInt(cellvalue); if (isNaN(value)) value = 0; editor.jqxSlider('setValue', value); }, geteditorvalue: (row, cellvalue, editor) => { // return the editor's value. return editor.val(); } } ]; return ( <JqxGrid width={850} source={dataAdapter} editable={true} columns={columns} selectionmode={'singlecell'} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
mit
PhotoArtLife/Personal-Blog
project/demo/mall/includes/lib/alipaySDK/aop/request/AlipaySiteprobeShopPublicBindRequest.php
1504
<?php /** * ALIPAY API: alipay.siteprobe.shop.public.bind request * * @author auto create * @since 1.0, 2014-12-18 09:03:32 */ class AlipaySiteprobeShopPublicBindRequest { /** * 店铺Id **/ private $bizContent; private $apiParas = array(); private $terminalType; private $terminalInfo; private $prodCode; private $apiVersion="1.0"; private $notifyUrl; public function setBizContent($bizContent) { $this->bizContent = $bizContent; $this->apiParas["biz_content"] = $bizContent; } public function getBizContent() { return $this->bizContent; } public function getApiMethodName() { return "alipay.siteprobe.shop.public.bind"; } public function setNotifyUrl($notifyUrl) { $this->notifyUrl=$notifyUrl; } public function getNotifyUrl() { return $this->notifyUrl; } public function getApiParas() { return $this->apiParas; } public function getTerminalType() { return $this->terminalType; } public function setTerminalType($terminalType) { $this->terminalType = $terminalType; } public function getTerminalInfo() { return $this->terminalInfo; } public function setTerminalInfo($terminalInfo) { $this->terminalInfo = $terminalInfo; } public function getProdCode() { return $this->prodCode; } public function setProdCode($prodCode) { $this->prodCode = $prodCode; } public function setApiVersion($apiVersion) { $this->apiVersion=$apiVersion; } public function getApiVersion() { return $this->apiVersion; } }
mit
morizotter/web100
vendor/bundle/ruby/2.0.0/gems/rake-10.2.2/lib/rake/cpu_counter.rb
2502
require 'rbconfig' # TODO: replace with IO.popen using array-style arguments in Rake 11 require 'open3' module Rake # Based on a script at: # http://stackoverflow.com/questions/891537/ruby-detect-number-of-cpus-installed class CpuCounter # :nodoc: all def self.count new.count_with_default end def count_with_default(default=4) count || default rescue StandardError default end def count if defined?(Java::Java) count_via_java_runtime else case RbConfig::CONFIG['host_os'] when /darwin9/ count_via_hwprefs_cpu_count when /darwin/ count_via_hwprefs_thread_count || count_via_sysctl when /linux/ count_via_cpuinfo when /bsd/ count_via_sysctl when /mswin|mingw/ count_via_win32 else # Try everything count_via_win32 || count_via_sysctl || count_via_hwprefs_thread_count || count_via_hwprefs_cpu_count end end end def count_via_java_runtime Java::Java.lang.Runtime.getRuntime.availableProcessors rescue StandardError nil end def count_via_win32 require 'win32ole' wmi = WIN32OLE.connect("winmgmts://") cpu = wmi.ExecQuery("select NumberOfCores from Win32_Processor") # TODO count hyper-threaded in this cpu.to_enum.first.NumberOfCores rescue StandardError, LoadError nil end def count_via_cpuinfo open('/proc/cpuinfo') { |f| f.readlines }.grep(/processor/).size rescue StandardError nil end def count_via_hwprefs_thread_count run 'hwprefs', 'thread_count' end def count_via_hwprefs_cpu_count run 'hwprefs', 'cpu_count' end def count_via_sysctl run 'sysctl', '-n', 'hw.ncpu' end def run(command, *args) cmd = resolve_command(command) if cmd Open3.popen3 cmd, *args do |_, out| out.read.to_i end else nil end end def resolve_command(command) look_for_command("/usr/sbin", command) || look_for_command("/sbin", command) || in_path_command(command) end def look_for_command(dir, command) path = File.join(dir, command) File.exist?(path) ? path : nil end def in_path_command(command) Open3.popen3 'which', command do |_, out,| out.eof? ? nil : command end end end end
mit
Hammerspoon/hammerspoon
extensions/menubar/menubar.lua
1533
--- === hs.menubar === --- --- Create and manage menubar icons local menubar = require "hs.libmenubar" local imagemod = require("hs.image") local geometry = require "hs.geometry" local screen = require "hs.screen" require("hs.styledtext") -- protects tables of constants menubar.priorities = ls.makeConstantsTable(menubar.priorities) -- This is the wrapper for hs.menubar:setIcon(). It is documented in internal.m local menubarObject = hs.getObjectMetatable("hs.menubar") menubarObject.setIcon = function(object, imagePath, template) local tmpImage = nil if type(imagePath) == "userdata" then tmpImage = imagePath elseif type(imagePath) == "string" then if string.sub(imagePath, 1, 6) == "ASCII:" then tmpImage = imagemod.imageFromASCII(string.sub(imagePath, 7, -1)) else tmpImage = imagemod.imageFromPath(imagePath) end end return object:_setIcon(tmpImage, template) end --- hs.menubar:frame() -> hs.geometry rect --- Method --- Returns the menubar item frame --- --- Parameters: --- * None --- --- Returns: --- * an hs.geometry rect describing the menubar item's frame or nil if the menubar item is not currently in the menubar. --- --- Notes: --- * This will return a frame even if no icon or title is set function menubarObject:frame() local sf = screen.mainScreen():fullFrame() local f = self:_frame() if f then f.y = sf.h - f.y - f.h return geometry(f) else return nil end end return menubar
mit
reorder/viacoin
src/qt/transactiondesc.cpp
13163
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactiondesc.h" #include "bitcoinunits.h" #include "guiutil.h" #include "paymentserver.h" #include "transactionrecord.h" #include "base58.h" #include "consensus/consensus.h" #include "main.h" #include "script/script.h" #include "timedata.h" #include "util.h" #include "wallet/db.h" #include "wallet/wallet.h" #include <stdint.h> #include <string> QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) { AssertLockHeld(cs_main); if (!CheckFinalTx(wtx)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) return tr("Open for %n more block(s)", "", wtx.nLockTime - chainActive.Height()); else return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime)); } else { int nDepth = wtx.GetDepthInMainChain(); if (nDepth < 0) return tr("conflicted with a transaction with %1 confirmations").arg(-nDepth); else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) return tr("%1/offline").arg(nDepth); else if (nDepth == 0) return tr("0/unconfirmed, %1").arg((wtx.InMempool() ? tr("in memory pool") : tr("not in memory pool"))) + (wtx.isAbandoned() ? ", "+tr("abandoned") : ""); else if (nDepth < 6) return tr("%1/unconfirmed").arg(nDepth); else return tr("%1 confirmations").arg(nDepth); } } QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit) { static const int nMaturity = Params().GetConsensus().fPowNoRetargeting ? COINBASE_MATURITY_REGTEST : COINBASE_MATURITY; QString strHTML; LOCK2(cs_main, wallet->cs_wallet); strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; int64_t nTime = wtx.GetTxTime(); CAmount nCredit = wtx.GetCredit(ISMINE_ALL); CAmount nDebit = wtx.GetDebit(ISMINE_ALL); CAmount nNet = nCredit - nDebit; strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx); int nRequests = wtx.GetRequestCount(); if (nRequests != -1) { if (nRequests == 0) strHTML += tr(", has not been successfully broadcast yet"); else if (nRequests > 0) strHTML += tr(", broadcast through %n node(s)", "", nRequests); } strHTML += "<br>"; strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>"; // // From // if (wtx.IsCoinBase()) { strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>"; } else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty()) { // Online transaction strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>"; } else { // Offline transaction if (nNet > 0) { // Credit if (CBitcoinAddress(rec->address).IsValid()) { CTxDestination address = CBitcoinAddress(rec->address).Get(); if (wallet->mapAddressBook.count(address)) { strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>"; strHTML += "<b>" + tr("To") + ":</b> "; strHTML += GUIUtil::HtmlEscape(rec->address); QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only"); if (!wallet->mapAddressBook[address].name.empty()) strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")"; else strHTML += " (" + addressOwned + ")"; strHTML += "<br>"; } } } } // // To // if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty()) { // Online transaction std::string strAddress = wtx.mapValue["to"]; strHTML += "<b>" + tr("To") + ":</b> "; CTxDestination dest = CBitcoinAddress(strAddress).Get(); if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " "; strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>"; } // // Amount // if (wtx.IsCoinBase() && nCredit == 0) { // // Coinbase // CAmount nUnmatured = 0; BOOST_FOREACH(const CTxOut& txout, wtx.vout) nUnmatured += wallet->GetCredit(txout, ISMINE_ALL); strHTML += "<b>" + tr("Credit") + ":</b> "; if (wtx.IsInMainChain()) strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")"; else strHTML += "(" + tr("not accepted") + ")"; strHTML += "<br>"; } else if (nNet > 0) { // // Credit // strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + "<br>"; } else { isminetype fAllFromMe = ISMINE_SPENDABLE; BOOST_FOREACH(const CTxIn& txin, wtx.vin) { isminetype mine = wallet->IsMine(txin); if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { isminetype mine = wallet->IsMine(txout); if(fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe) { if(fAllFromMe & ISMINE_WATCH_ONLY) strHTML += "<b>" + tr("From") + ":</b> " + tr("watch-only") + "<br>"; // // Debit // BOOST_FOREACH(const CTxOut& txout, wtx.vout) { // Ignore change isminetype toSelf = wallet->IsMine(txout); if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE)) continue; if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty()) { // Offline transaction CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { strHTML += "<b>" + tr("To") + ":</b> "; if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString()); if(toSelf == ISMINE_SPENDABLE) strHTML += " (own address)"; else if(toSelf & ISMINE_WATCH_ONLY) strHTML += " (watch-only)"; strHTML += "<br>"; } } strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + "<br>"; if(toSelf) strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + "<br>"; } if (fAllToMe) { // Payment to self CAmount nChange = wtx.GetChange(); CAmount nValue = nCredit - nChange; strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>"; strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>"; } CAmount nTxFee = nDebit - wtx.GetValueOut(); if (nTxFee > 0) strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + "<br>"; } else { // // Mixed debit transaction // BOOST_FOREACH(const CTxIn& txin, wtx.vin) if (wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; } } strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>"; // // Message // if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty()) strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>"; if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty()) strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>"; strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxID() + "<br>"; strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>"; // Message from normal bitcoin:URI (bitcoin:123...?message=example) Q_FOREACH (const PAIRTYPE(std::string, std::string)& r, wtx.vOrderForm) if (r.first == "Message") strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>"; // // PaymentRequest info: // Q_FOREACH (const PAIRTYPE(std::string, std::string)& r, wtx.vOrderForm) { if (r.first == "PaymentRequest") { PaymentRequestPlus req; req.parse(QByteArray::fromRawData(r.second.data(), r.second.size())); QString merchant; if (req.getMerchant(PaymentServer::getCertStore(), merchant)) strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>"; } } if (wtx.IsCoinBase()) { quint32 numBlocksToMaturity = nMaturity + 1; strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>"; } // // Debug view // if (fDebug) { strHTML += "<hr><br>" + tr("Debug information") + "<br><br>"; BOOST_FOREACH(const CTxIn& txin, wtx.vin) if(wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if(wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; strHTML += "<br><b>" + tr("Transaction") + ":</b><br>"; strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true); strHTML += "<br><b>" + tr("Inputs") + ":</b>"; strHTML += "<ul>"; BOOST_FOREACH(const CTxIn& txin, wtx.vin) { COutPoint prevout = txin.prevout; CCoins prev; if(pcoinsTip->GetCoins(prevout.hash, prev)) { if (prevout.n < prev.vout.size()) { strHTML += "<li>"; const CTxOut &vout = prev.vout[prevout.n]; CTxDestination address; if (ExtractDestination(vout.scriptPubKey, address)) { if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; strHTML += QString::fromStdString(CBitcoinAddress(address).ToString()); } strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue); strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>"; strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>"; } } } strHTML += "</ul>"; } strHTML += "</font></html>"; return strHTML; }
mit
kontur-csharper/testing
cs/Challenge/Infrastructure/IncorrectImplementationAttribute.cs
130
using System; namespace Challenge.Infrastructure { public class IncorrectImplementationAttribute : Attribute { } }
mit
DevinLow/DevinLow.github.io
test/scripts/filters/index.js
341
'use strict'; describe('Filters', () => { require('./backtick_code_block'); require('./excerpt'); require('./external_link'); require('./i18n_locals'); require('./meta_generator'); require('./new_post_path'); require('./post_permalink'); require('./render_post'); require('./save_database'); require('./titlecase'); });
mit
samoatesgames/Ludumdare30
Unity/Assets/Photon Unity Networking/Demos/PUNGuide_M2H/_Tutorial 2/C#/Tutorial_2A3.cs
1474
using UnityEngine; using System.Collections; public class Tutorial_2A3 : Photon.MonoBehaviour { /* * Sending our movement via RPCs. This is bad habit though: * something as constant as movement should be transferred via * OnSerializePhotonView by observing a script. * */ private Vector3 lastPosition; void Update() { if (PhotonNetwork.isMasterClient) { //LOCAL MOVEMENT Vector3 moveDirection = new Vector3(-1 * Input.GetAxis("Vertical"), 0, Input.GetAxis("Horizontal")); float speed = 5; transform.Translate(speed * moveDirection * Time.deltaTime); //SHARE POSITION VIA RPC if (Vector3.Distance(transform.position, lastPosition) >= 0.05f) { //Save some network bandwidth; only send a RPC when the position has moved more than 0.05f lastPosition = transform.position; //Send the position Vector3 over to the others; in this case all clients photonView.RPC("SetPosition", PhotonTargets.Others, transform.position); } } } [RPC] void SetPosition(Vector3 newPos) { //In this case, this function is always ran on the Clients //The server requested all clients to run this function (line 25). transform.position = newPos; } }
mit
quentinbernet/quentinbernet.github.io
node_modules/caniuse-lite/data/features/webgl2.js
960
module.exports={A:{A:{"2":"K D G E A B iB"},B:{"1":"AB","2":"2 C d J M H I"},C:{"1":"0 1 3 4 7 8 9 u v w x y z IB BB CB DB GB","2":"2 fB FB F N K D G E A B C d J M H I O P Q R S T ZB YB","194":"l m n","450":"6 U V W X Y Z a b c e f g h i j k","2242":"o L q r s t"},D:{"1":"0 1 3 4 7 8 9 z IB BB CB DB GB SB OB MB lB NB KB AB PB QB","2":"2 6 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l","578":"m n o L q r s t u v w x y"},E:{"2":"F N K D G E A RB JB TB UB VB WB","1090":"5 B C XB p aB"},F:{"1":"0 1 m n o L q r s t u v w x y z","2":"5 6 E B C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l bB cB dB eB p EB gB"},G:{"2":"G JB hB HB jB kB LB mB nB oB pB qB rB sB","1090":"tB uB"},H:{"2":"vB"},I:{"2":"4 FB F wB xB yB zB HB 0B 1B"},J:{"2":"D A"},K:{"1":"L","2":"5 A B C p EB"},L:{"1":"KB"},M:{"1":"3"},N:{"2":"A B"},O:{"2":"2B"},P:{"1":"5B 6B 7B","2":"F 3B 4B"},Q:{"578":"8B"},R:{"2":"9B"},S:{"2242":"AC"}},B:6,C:"WebGL 2.0"};
mit
paulpv/robolectric
robolectric/src/test/java/org/robolectric/shadows/ShadowCursorAdapterTest.java
4864
package org.robolectric.shadows; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.Shadows; import org.robolectric.TestRunners; import java.util.ArrayList; import java.util.List; import static android.widget.CursorAdapter.FLAG_AUTO_REQUERY; import static android.widget.CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER; import static org.assertj.core.api.Assertions.assertThat; @RunWith(TestRunners.WithDefaults.class) public class ShadowCursorAdapterTest { private Cursor curs; private CursorAdapter adapter; private SQLiteDatabase database; @Before public void setUp() throws Exception { database = SQLiteDatabase.create(null); database.execSQL("CREATE TABLE table_name(_id INT PRIMARY KEY, name VARCHAR(255));"); String[] inserts = { "INSERT INTO table_name (_id, name) VALUES(1234, 'Chuck');", "INSERT INTO table_name (_id, name) VALUES(1235, 'Julie');", "INSERT INTO table_name (_id, name) VALUES(1236, 'Chris');", "INSERT INTO table_name (_id, name) VALUES(1237, 'Brenda');", "INSERT INTO table_name (_id, name) VALUES(1238, 'Jane');" }; for (String insert : inserts) { database.execSQL(insert); } String sql = "SELECT * FROM table_name;"; curs = database.rawQuery(sql, null); adapter = new TestAdapter(curs); } @Test public void testChangeCursor() { assertThat(adapter.getCursor()).isNotNull(); assertThat(adapter.getCursor()).isSameAs(curs); adapter.changeCursor(null); assertThat(curs.isClosed()).isTrue(); assertThat(adapter.getCursor()).isNull(); } @Test public void testSwapCursor() { assertThat(adapter.getCursor()).isNotNull(); assertThat(adapter.getCursor()).isSameAs(curs); Cursor oldCursor = adapter.swapCursor(null); assertThat(oldCursor).isSameAs(curs); assertThat(curs.isClosed()).isFalse(); assertThat(adapter.getCursor()).isNull(); } @Test public void testCount() { assertThat(adapter.getCount()).isEqualTo(curs.getCount()); adapter.changeCursor(null); assertThat(adapter.getCount()).isEqualTo(0); } @Test public void testGetItemId() { for (int i = 0; i < 5; i++) { assertThat(adapter.getItemId(i)).isEqualTo((long) 1234 + i); } } @Test public void testGetView() { List<View> views = new ArrayList<View>(); for (int i = 0; i < 5; i++) { views.add(new View(RuntimeEnvironment.application)); } Shadows.shadowOf(adapter).setViews(views); for (int i = 0; i < 5; i++) { assertThat(adapter.getView(i, null, null)).isSameAs(views.get(i)); } } @Test public void shouldNotRegisterObserversIfNoFlagsAreSet() throws Exception { adapter = new TestAdapterWithFlags(curs, 0); assertThat(Shadows.shadowOf(adapter).mChangeObserver).isNull(); assertThat(Shadows.shadowOf(adapter).mDataSetObserver).isNull(); } @Test public void shouldRegisterObserversWhenRegisterObserverFlagIsSet() throws Exception { adapter = new TestAdapterWithFlags(curs, FLAG_REGISTER_CONTENT_OBSERVER); assertThat(Shadows.shadowOf(adapter).mChangeObserver).isNotNull(); assertThat(Shadows.shadowOf(adapter).mDataSetObserver).isNotNull(); } @Test public void shouldRegisterObserversWhenAutoRequeryFlagIsSet() throws Exception { adapter = new TestAdapterWithFlags(curs, FLAG_AUTO_REQUERY); assertThat(Shadows.shadowOf(adapter).mChangeObserver).isNotNull(); assertThat(Shadows.shadowOf(adapter).mDataSetObserver).isNotNull(); } @Test public void shouldNotErrorOnCursorChangeWhenNoFlagsAreSet() throws Exception { adapter = new TestAdapterWithFlags(curs, 0); adapter.changeCursor(database.rawQuery("SELECT * FROM table_name;", null)); assertThat(adapter.getCursor()).isNotSameAs(curs); } private class TestAdapter extends CursorAdapter { public TestAdapter(Cursor curs) { super(RuntimeEnvironment.application, curs, false); } @Override public void bindView(View view, Context context, Cursor cursor) { } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return null; } } private class TestAdapterWithFlags extends CursorAdapter { public TestAdapterWithFlags(Cursor c, int flags) { super(RuntimeEnvironment.application, c, flags); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return null; } @Override public void bindView(View view, Context context, Cursor cursor) { } } }
mit
maria-shahid-aspose/Aspose.Email-for-.NET
Examples/CSharp/Knowledge-Base/AsposeEmailOutlookSampleApp.Designer.cs
5891
namespace Aspose.Email.Examples.CSharp.Email.Knowledge.Base { partial class AsposeEmailOutlookSampleApp { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.From = new System.Windows.Forms.Label(); this.txtBody = new System.Windows.Forms.TextBox(); this.txtSubject = new System.Windows.Forms.TextBox(); this.txtTo = new System.Windows.Forms.TextBox(); this.txtFrom = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(162, 207); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(135, 31); this.button1.TabIndex = 17; this.button1.Text = "Load Message"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(70, 161); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(31, 13); this.label3.TabIndex = 16; this.label3.Text = "Body"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(70, 118); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(43, 13); this.label2.TabIndex = 15; this.label2.Text = "Subject"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(60, 67); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(20, 13); this.label1.TabIndex = 14; this.label1.Text = "To"; // // From // this.From.AutoSize = true; this.From.Location = new System.Drawing.Point(60, 26); this.From.Name = "From"; this.From.Size = new System.Drawing.Size(30, 13); this.From.TabIndex = 13; this.From.Text = "From"; // // txtBody // this.txtBody.Location = new System.Drawing.Point(155, 154); this.txtBody.Name = "txtBody"; this.txtBody.Size = new System.Drawing.Size(143, 20); this.txtBody.TabIndex = 12; // // txtSubject // this.txtSubject.Location = new System.Drawing.Point(155, 111); this.txtSubject.Name = "txtSubject"; this.txtSubject.Size = new System.Drawing.Size(143, 20); this.txtSubject.TabIndex = 11; // // txtTo // this.txtTo.Location = new System.Drawing.Point(155, 67); this.txtTo.Name = "txtTo"; this.txtTo.Size = new System.Drawing.Size(143, 20); this.txtTo.TabIndex = 10; // // txtFrom // this.txtFrom.Location = new System.Drawing.Point(155, 23); this.txtFrom.Name = "txtFrom"; this.txtFrom.Size = new System.Drawing.Size(143, 20); this.txtFrom.TabIndex = 9; // // AsposeEmailOutlookSampleApp // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(359, 261); this.Controls.Add(this.button1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.From); this.Controls.Add(this.txtBody); this.Controls.Add(this.txtSubject); this.Controls.Add(this.txtTo); this.Controls.Add(this.txtFrom); this.Name = "AsposeEmailOutlookSampleApp"; this.Text = "AsposeEmailOutlookSampleApp"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label From; private System.Windows.Forms.TextBox txtBody; private System.Windows.Forms.TextBox txtSubject; private System.Windows.Forms.TextBox txtTo; private System.Windows.Forms.TextBox txtFrom; } }
mit
basarat/typescript-collections
src/lib/arrays.ts
6107
import * as util from './util'; /** * Returns the position of the first occurrence of the specified item * within the specified array.4 * @param {*} array the array in which to search the element. * @param {Object} item the element to search. * @param {function(Object,Object):boolean=} equalsFunction optional function used to * check equality between 2 elements. * @return {number} the position of the first occurrence of the specified element * within the specified array, or -1 if not found. */ export function indexOf<T>(array: T[], item: T, equalsFunction?: util.IEqualsFunction<T>): number { const equals = equalsFunction || util.defaultEquals; const length = array.length; for (let i = 0; i < length; i++) { if (equals(array[i], item)) { return i; } } return -1; } /** * Returns the position of the last occurrence of the specified element * within the specified array. * @param {*} array the array in which to search the element. * @param {Object} item the element to search. * @param {function(Object,Object):boolean=} equalsFunction optional function used to * check equality between 2 elements. * @return {number} the position of the last occurrence of the specified element * within the specified array or -1 if not found. */ export function lastIndexOf<T>(array: T[], item: T, equalsFunction?: util.IEqualsFunction<T>): number { const equals = equalsFunction || util.defaultEquals; const length = array.length; for (let i = length - 1; i >= 0; i--) { if (equals(array[i], item)) { return i; } } return -1; } /** * Returns true if the specified array contains the specified element. * @param {*} array the array in which to search the element. * @param {Object} item the element to search. * @param {function(Object,Object):boolean=} equalsFunction optional function to * check equality between 2 elements. * @return {boolean} true if the specified array contains the specified element. */ export function contains<T>(array: T[], item: T, equalsFunction?: util.IEqualsFunction<T>): boolean { return indexOf(array, item, equalsFunction) >= 0; } /** * Removes the first ocurrence of the specified element from the specified array. * @param {*} array the array in which to search element. * @param {Object} item the element to search. * @param {function(Object,Object):boolean=} equalsFunction optional function to * check equality between 2 elements. * @return {boolean} true if the array changed after this call. */ export function remove<T>(array: T[], item: T, equalsFunction?: util.IEqualsFunction<T>): boolean { const index = indexOf(array, item, equalsFunction); if (index < 0) { return false; } array.splice(index, 1); return true; } /** * Returns the number of elements in the specified array equal * to the specified object. * @param {Array} array the array in which to determine the frequency of the element. * @param {Object} item the element whose frequency is to be determined. * @param {function(Object,Object):boolean=} equalsFunction optional function used to * check equality between 2 elements. * @return {number} the number of elements in the specified array * equal to the specified object. */ export function frequency<T>(array: T[], item: T, equalsFunction?: util.IEqualsFunction<T>): number { const equals = equalsFunction || util.defaultEquals; const length = array.length; let freq = 0; for (let i = 0; i < length; i++) { if (equals(array[i], item)) { freq++; } } return freq; } /** * Returns true if the two specified arrays are equal to one another. * Two arrays are considered equal if both arrays contain the same number * of elements, and all corresponding pairs of elements in the two * arrays are equal and are in the same order. * @param {Array} array1 one array to be tested for equality. * @param {Array} array2 the other array to be tested for equality. * @param {function(Object,Object):boolean=} equalsFunction optional function used to * check equality between elemements in the arrays. * @return {boolean} true if the two arrays are equal */ export function equals<T>(array1: T[], array2: T[], equalsFunction?: util.IEqualsFunction<T>): boolean { const equals = equalsFunction || util.defaultEquals; if (array1.length !== array2.length) { return false; } const length = array1.length; for (let i = 0; i < length; i++) { if (!equals(array1[i], array2[i])) { return false; } } return true; } /** * Returns shallow a copy of the specified array. * @param {*} array the array to copy. * @return {Array} a copy of the specified array */ export function copy<T>(array: T[]): T[] { return array.concat(); } /** * Swaps the elements at the specified positions in the specified array. * @param {Array} array The array in which to swap elements. * @param {number} i the index of one element to be swapped. * @param {number} j the index of the other element to be swapped. * @return {boolean} true if the array is defined and the indexes are valid. */ export function swap<T>(array: T[], i: number, j: number): boolean { if (i < 0 || i >= array.length || j < 0 || j >= array.length) { return false; } const temp = array[i]; array[i] = array[j]; array[j] = temp; return true; } export function toString<T>(array: T[]): string { return '[' + array.toString() + ']'; } /** * Executes the provided function once for each element present in this array * starting from index 0 to length - 1. * @param {Array} array The array in which to iterate. * @param {function(Object):*} callback function to execute, it is * invoked with one argument: the element value, to break the iteration you can * optionally return false. */ export function forEach<T>(array: T[], callback: util.ILoopFunction<T>): void { for (const ele of array) { if (callback(ele) === false) { return; } } }
mit
laszpio/planner
lib/services/mailing_list.rb
1699
class MailingList SUBSCRIBED = 'subscribed'.freeze MEMBER_EXISTS = 'Member Exists'.freeze attr_reader :list_id def initialize(list_id) @list_id = list_id end def subscribe(email, first_name, last_name) return if disabled? begin client.lists(list_id).members .create(body: { email_address: email, status: 'subscribed', merge_fields: { FNAME: first_name, LNAME: last_name } }) rescue Gibbon::MailChimpError => e reactivate_subscription(email, first_name, last_name) if e.title.eql?(MEMBER_EXISTS) end end handle_asynchronously :subscribe def unsubscribe(email) return if disabled? client.lists(list_id).members(md5_hashed_email_address(email)) .update(body: { status: 'unsubscribed' }) rescue Gibbon::MailChimpError false end handle_asynchronously :unsubscribe def reactivate_subscription(email, first_name, last_name) return if disabled? client.lists(list_id).members(md5_hashed_email_address(email)) .upsert(body: { email_address: email, status: 'subscribed', merge_fields: { FNAME: first_name, LNAME: last_name } }) end def subscribed?(email) return if disabled? info = client.lists(list_id).members(md5_hashed_email_address(email)).retrieve info.body[:status].eql?(SUBSCRIBED) rescue Gibbon::MailChimpError false end private def client @client ||= Gibbon::Request.new end def md5_hashed_email_address(email) require 'digest' Digest::MD5.hexdigest(email.downcase) end def disabled? !ENV['MAILCHIMP_KEY'] end end
mit
alberskib/mockito
test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
12230
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.util.reflection; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.internal.util.reflection.GenericMetadataSupport.inferFrom; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class GenericMetadataSupportTest { interface GenericsSelfReference<T extends GenericsSelfReference<T>> { T self(); } interface UpperBoundedTypeWithClass<E extends Number & Comparable<E>> { E get(); } interface UpperBoundedTypeWithInterfaces<E extends Comparable<E> & Cloneable> { E get(); } interface ListOfNumbers extends List<Number> {} interface ListOfAnyNumbers<N extends Number & Cloneable> extends List<N> {} interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> { Set<Number> remove(Object key); // override with fixed ParameterizedType List<? super Integer> returning_wildcard_with_class_lower_bound(); List<? super K> returning_wildcard_with_typeVar_lower_bound(); List<? extends K> returning_wildcard_with_typeVar_upper_bound(); K returningK(); <O extends K> List<O> paramType_with_type_params(); <S, T extends S> T two_type_params(); <O extends K> O typeVar_with_type_params(); } static class StringList extends ArrayList<String> { } @Test public void typeVariable_of_self_type() { GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class)); assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class); } @Test public void can_get_raw_type_from_Class() throws Exception { assertThat(inferFrom(ListOfAnyNumbers.class).rawType()).isEqualTo(ListOfAnyNumbers.class); assertThat(inferFrom(ListOfNumbers.class).rawType()).isEqualTo(ListOfNumbers.class); assertThat(inferFrom(GenericsNest.class).rawType()).isEqualTo(GenericsNest.class); assertThat(inferFrom(StringList.class).rawType()).isEqualTo(StringList.class); } @Test public void can_get_raw_type_from_ParameterizedType() throws Exception { assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class); assertThat(inferFrom(ListOfNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class); assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).rawType()).isEqualTo(Map.class); assertThat(inferFrom(StringList.class.getGenericSuperclass()).rawType()).isEqualTo(ArrayList.class); } @Test public void can_get_type_variables_from_Class() throws Exception { assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("K"); assertThat(inferFrom(ListOfNumbers.class).actualTypeArguments().keySet()).isEmpty(); assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("N"); assertThat(inferFrom(Map.class).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V"); assertThat(inferFrom(Serializable.class).actualTypeArguments().keySet()).isEmpty(); assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty(); } @Test public void can_get_type_variables_from_ParameterizedType() throws Exception { assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V"); assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("E"); assertThat(inferFrom(Integer.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("T"); assertThat(inferFrom(StringBuilder.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).isEmpty(); assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty(); } @Test public void typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(StringList.class).resolveGenericReturnType(firstNamedMethod("iterator", StringList.class)); assertThat(genericMetadata.rawType()).isEqualTo(Iterator.class); assertThat(genericMetadata.actualTypeArguments().values()).contains(String.class); } @Test public void typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("get", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Set.class); assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class); } @Test public void bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returningK", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class); GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0)); assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class); } @Test public void fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("remove", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Set.class); assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class); } @Test public void paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("values", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Collection.class); GenericMetadataSupport fromTypeVariableE = inferFrom(typeVariableValue(genericMetadata.actualTypeArguments(), "E")); assertThat(fromTypeVariableE.rawType()).isEqualTo(Set.class); assertThat(fromTypeVariableE.actualTypeArguments().values()).contains(Number.class); } @Test public void paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("paramType_with_type_params", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); Type firstBoundOfE = ((GenericMetadataSupport.TypeVarBoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E")).firstBound(); assertThat(inferFrom(firstBoundOfE).rawType()).isEqualTo(Comparable.class); } @Test public void typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("typeVar_with_type_params", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class); GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0)); assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class); } @Test public void class_return_type_of____append____resolved_to_StringBuilder_and_type_arguments() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(StringBuilder.class).resolveGenericReturnType(firstNamedMethod("append", StringBuilder.class)); assertThat(genericMetadata.rawType()).isEqualTo(StringBuilder.class); assertThat(genericMetadata.actualTypeArguments()).isEmpty(); } @Test public void paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_class_lower_bound", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E"); assertThat(boundedType.firstBound()).isEqualTo(Integer.class); assertThat(boundedType.interfaceBounds()).isEmpty(); } @Test public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_lower_bound", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E"); assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class); assertThat(boundedType.interfaceBounds()).contains(Cloneable.class); } @Test public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_upper_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception { GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_upper_bound", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E"); assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class); assertThat(boundedType.interfaceBounds()).contains(Cloneable.class); } private Type typeVariableValue(Map<TypeVariable, Type> typeVariables, String typeVariableName) { for (Map.Entry<TypeVariable, Type> typeVariableTypeEntry : typeVariables.entrySet()) { if (typeVariableTypeEntry.getKey().getName().equals(typeVariableName)) { return typeVariableTypeEntry.getValue(); } } fail("'" + typeVariableName + "' was not found in " + typeVariables); return null; // unreachable } private Method firstNamedMethod(String methodName, Class<?> clazz) { for (Method method : clazz.getMethods()) { boolean protect_against_different_jdk_ordering_avoiding_bridge_methods = !method.isBridge(); if (method.getName().contains(methodName) && protect_against_different_jdk_ordering_avoiding_bridge_methods) { return method; } } throw new IllegalStateException("The method : '" + methodName + "' do not exist in '" + clazz.getSimpleName() + "'"); } }
mit
Im0rtality/coldbreeze-demo
src/Sylius/Bundle/FixturesBundle/DataFixtures/ORM/LoadProductOptionData.php
2078
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\FixturesBundle\DataFixtures\ORM; use Doctrine\Common\Persistence\ObjectManager; /** * Default product options to play with Sylius. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class LoadProductOptionData extends DataFixture { /** * {@inheritdoc} */ public function load(ObjectManager $manager) { // T-Shirt size option. $option = $this->createOption('T-Shirt size', 'Size', array('S', 'M', 'L', 'XL', 'XXL')); $manager->persist($option); // T-Shirt color option. $option = $this->createOption('T-Shirt color', 'Color', array('Red', 'Blue', 'Green')); $manager->persist($option); // Sticker size option. $option = $this->createOption('Sticker size', 'Size', array('3"','5"','7"')); $manager->persist($option); // Mug type option. $option = $this->createOption('Mug type', 'Type', array('Medium mug','Double mug','MONSTER mug')); $manager->persist($option); $manager->flush(); } /** * {@inheritdoc} */ public function getOrder() { return 3; } /** * Create an option. * * @param string $name * @param string $presentation * @param array $values */ protected function createOption($name, $presentation, array $values) { $option = $this ->getProductOptionRepository() ->createNew() ; $option->setName($name); $option->setPresentation($presentation); foreach ($values as $text) { $value = $this->getProductOptionValueRepository()->createNew(); $value->setValue($text); $option->addValue($value); } $this->setReference('Sylius.Option.'.$name, $option); return $option; } }
mit
tectronics/crocodile-msrp
src/Status.js
1049
/* * Crocodile MSRP - http://code.google.com/p/crocodile-msrp/ * Copyright (c) 2012 Crocodile RCS Ltd * http://www.crocodile-rcs.com * Released under the MIT license - see LICENSE.TXT */ var CrocMSRP = (function(CrocMSRP) { /** @constant */ CrocMSRP.Status = { OK: 200, BAD_REQUEST: 400, UNAUTHORIZED: 401, FORBIDDEN: 403, REQUEST_TIMEOUT: 408, STOP_SENDING: 413, UNSUPPORTED_MEDIA: 415, INTERVAL_OUT_OF_BOUNDS: 423, SESSION_DOES_NOT_EXIST: 481, INTERNAL_SERVER_ERROR: 500, // Not actually defined in spec/registry! NOT_IMPLEMENTED: 501, WRONG_CONNECTION: 506 }; /** @constant */ CrocMSRP.StatusComment = { 200: 'OK', 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 408: 'Request Timeout', 413: 'Stop Sending Message', 415: 'Unsupported Media Type', 423: 'Interval Out-of-Bounds', 481: 'Session Does Not Exist', 500: 'Internal Server Error', // Not actually defined in spec/registry! 501: 'Not Implemented', 506: 'Wrong Connection' }; return CrocMSRP; }(CrocMSRP || {}));
mit
dspringate/experiment-two
js/main.js
2902
/* Jonathan Snook - MIT License - https://github.com/snookca/prepareTransition */ (function(a){a.fn.prepareTransition=function(){return this.each(function(){var b=a(this);b.one("TransitionEnd webkitTransitionEnd transitionend oTransitionEnd",function(){b.removeClass("is-transitioning")});var c=["transition-duration","-moz-transition-duration","-webkit-transition-duration","-o-transition-duration"];var d=0;a.each(c,function(a,c){d=parseFloat(b.css(c))||d});if(d!=0){b.addClass("is-transitioning");b[0].offsetWidth}})}})(jQuery); /* replaceUrlParam - http://stackoverflow.com/questions/7171099/how-to-replace-url-parameter-with-javascript-jquery */ function replaceUrlParam(e,r,a){var n=new RegExp("("+r+"=).*?(&|$)"),c=e;return c=e.search(n)>=0?e.replace(n,"$1"+a+"$2"):c+(c.indexOf("?")>0?"&":"?")+r+"="+a}; // Site functions window.site = window.site || {}; site.cacheSelectors = function () { site.cache = { // General $html : $('html'), $body : $('document.body') }; }; site.init = function () { site.cacheSelectors(); site.smoothScroll(); site.expandSearch(); }; site.smoothScroll = function () { $(".scroll").click( function(event) { event.preventDefault(); //calculate destination place var dest = 0; if ($(this.hash).offset().top > $(document).height() - $(window).height()) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().top; } // go to destination $('html, body').animate({scrollTop:dest}, 1000, 'swing'); }); }; site.expandSearch = function () { $(document).ready(function(){ var submitIcon = $('.searchbox-icon'); var inputBox = $('.searchbox-input'); var searchBox = $('.searchbox'); var isOpen = false; submitIcon.click(function(){ if(isOpen == false){ searchBox.addClass('searchbox-open'); inputBox.focus(); isOpen = true; } else { searchBox.removeClass('searchbox-open'); inputBox.focusout(); isOpen = false; } }); submitIcon.mouseup(function(){ return false; }); searchBox.mouseup(function(){ return false; }); $(document).mouseup(function(){ if(isOpen == true){ $('.searchbox-icon').css('display','block'); submitIcon.click(); } }); }); function buttonUp(){ var inputVal = $('.searchbox-input').val(); inputVal = $.trim(inputVal).length; if( inputVal !== 0){ $('.searchbox-icon').css('display','none'); } else { $('.searchbox-input').val(''); $('.searchbox-icon').css('display','block'); } } }; // Initialise Site's JS on docready $(site.init);
mit
n8many/MagicMirror
tests/e2e/modules_position_spec.js
1124
const helpers = require("./global-setup"); const describe = global.describe; const it = global.it; describe("Position of modules", function () { helpers.setupTimeout(this); var app = null; describe("Using helloworld", function () { after(function () { return helpers.stopApplication(app); }); before(function () { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/positions.js"; return helpers.startApplication({ args: ["js/electron.js"] }).then(function (startedApp) { app = startedApp; }); }); var positions = ["top_bar", "top_left", "top_center", "top_right", "upper_third", "middle_center", "lower_third", "bottom_left", "bottom_center", "bottom_right", "bottom_bar", "fullscreen_above", "fullscreen_below"]; var position; var className; for (idx in positions) { position = positions[idx]; className = position.replace("_", "."); it("show text in " + position, function () { return app.client.waitUntilWindowLoaded() .getText("." + className).should.eventually.equal("Text in " + position); }); } }); });
mit
davalb/Sylius
src/Sylius/Bundle/PaymentBundle/spec/Form/Type/PaymentMethodTypeSpec.php
2225
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\PaymentBundle\Form\Type; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Sylius\Bundle\PaymentBundle\Form\Type\PaymentMethodType; use Sylius\Bundle\ResourceBundle\Form\EventSubscriber\AddCodeFormSubscriber; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormTypeInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * @author Paweł Jędrzejewski <pawel@sylius.org> * @author Mateusz Zalewski <mateusz.zalewski@lakion.com> */ final class PaymentMethodTypeSpec extends ObjectBehavior { function let() { $this->beConstructedWith('PaymentMethod', ['sylius']); } function it_is_initializable() { $this->shouldHaveType(PaymentMethodType::class); } function it_is_a_form_type() { $this->shouldImplement(FormTypeInterface::class); } function it_builds_form_with_proper_fields( FormBuilder $builder ) { $builder ->add('translations', 'sylius_translations', Argument::any()) ->shouldBeCalled() ->willReturn($builder); $builder ->add('enabled', 'checkbox', Argument::any()) ->willReturn($builder) ; $builder ->add('gateway', 'sylius_payment_gateway_choice', Argument::any()) ->willReturn($builder) ; $builder ->addEventSubscriber(Argument::type(AddCodeFormSubscriber::class)) ->willReturn($builder) ; $this->buildForm($builder, []); } function it_defines_assigned_data_class(OptionsResolver $resolver) { $resolver ->setDefaults([ 'data_class' => 'PaymentMethod', 'validation_groups' => ['sylius'], ]) ->shouldBeCalled() ; $this->configureOptions($resolver); } function it_has_valid_name() { $this->getName()->shouldReturn('sylius_payment_method'); } }
mit
kwagyeman/openmv
scripts/examples/OpenMV/14-WiFi-Shield/scan.py
352
# Scan Example # # This example shows how to scan for networks with the WiFi shield. import time, network wlan = network.WINC() print("\nFirmware version:", wlan.fw_version()) while (True): scan_result = wlan.scan() for ap in scan_result: print("Channel:%d RSSI:%d Auth:%d BSSID:%s SSID:%s"%(ap)) print() time.sleep_ms(1000)
mit
nailsapp/site-components
application/config/config.php
105
<?php /* load the base config file from the package */ require NAILS_COMMON_PATH . 'config/config.php';
mit
martinbaillie/traefik
testhelpers/helpers.go
714
package testhelpers import ( "fmt" "io" "net/http" "net/url" ) // Intp returns a pointer to the given integer value. func Intp(i int) *int { return &i } // MustNewRequest creates a new http get request or panics if it can't func MustNewRequest(method, urlStr string, body io.Reader) *http.Request { request, err := http.NewRequest(method, urlStr, body) if err != nil { panic(fmt.Sprintf("failed to create HTTP %s Request for '%s': %s", method, urlStr, err)) } return request } // MustParseURL parses a URL or panics if it can't func MustParseURL(rawURL string) *url.URL { u, err := url.Parse(rawURL) if err != nil { panic(fmt.Sprintf("failed to parse URL '%s': %s", rawURL, err)) } return u }
mit
danielkay/primeng
src/app/showcase/components/accordion/accordiondemo.ts
517
import {Component} from '@angular/core'; import {Message} from '../../../components/common/api'; @Component({ templateUrl: './accordiondemo.html' }) export class AccordionDemo { msgs: Message[]; onTabClose(event) { this.msgs = []; this.msgs.push({severity:'info', summary:'Tab Closed', detail: 'Index: ' + event.index}); } onTabOpen(event) { this.msgs = []; this.msgs.push({severity:'info', summary:'Tab Expanded', detail: 'Index: ' + event.index}); } }
mit
yagweb/pythonnet
src/embed_tests/TestNamedArguments.cs
1333
using System; using NUnit.Framework; using Python.Runtime; namespace Python.EmbeddingTest { public class TestNamedArguments { [OneTimeSetUp] public void SetUp() { PythonEngine.Initialize(); } [OneTimeTearDown] public void Dispose() { PythonEngine.Shutdown(); } /// <summary> /// Test named arguments support through Py.kw method /// </summary> [Test] public void TestKeywordArgs() { dynamic a = CreateTestClass(); var result = (int)a.Test3(2, Py.kw("a4", 8)); Assert.AreEqual(12, result); } /// <summary> /// Test keyword arguments with .net named arguments /// </summary> [Test] public void TestNamedArgs() { dynamic a = CreateTestClass(); var result = (int)a.Test3(2, a4: 8); Assert.AreEqual(12, result); } private static PyObject CreateTestClass() { var locals = new PyDict(); PythonEngine.Exec(@" class cmTest3: def Test3(self, a1 = 1, a2 = 1, a3 = 1, a4 = 1): return a1 + a2 + a3 + a4 a = cmTest3() ", null, locals.Handle); return locals.GetItem("a"); } } }
mit
UKForeignOffice/ETD-prototype-upload
node_modules/node-sass/lib/extensions.js
11161
/*! * node-sass: lib/extensions.js */ var eol = require('os').EOL, fs = require('fs'), pkg = require('../package.json'), mkdir = require('mkdirp'), path = require('path'), defaultBinaryPath = path.join(__dirname, '..', 'vendor'); /** * Get the human readable name of the Platform that is running * * @param {string} platform - An OS platform to match, or null to fallback to * the current process platform * @return {Object} The name of the platform if matched, false otherwise * * @api public */ function getHumanPlatform(platform) { switch (platform || process.platform) { case 'darwin': return 'OS X'; case 'freebsd': return 'FreeBSD'; case 'linux': return 'Linux'; case 'linux_musl': return 'Linux/musl'; case 'win32': return 'Windows'; default: return false; } } /** * Provides a more readable version of the architecture * * @param {string} arch - An instruction architecture name to match, or null to * lookup the current process architecture * @return {Object} The value of the process architecture, or false if unknown * * @api public */ function getHumanArchitecture(arch) { switch (arch || process.arch) { case 'ia32': return '32-bit'; case 'x86': return '32-bit'; case 'x64': return '64-bit'; default: return false; } } /** * Get the friendly name of the Node environment being run * * @param {Object} abi - A Node Application Binary Interface value, or null to * fallback to the current Node ABI * @return {Object} Returns a string name of the Node environment or false if * unmatched * * @api public */ function getHumanNodeVersion(abi) { switch (parseInt(abi || process.versions.modules, 10)) { case 11: return 'Node 0.10.x'; case 14: return 'Node 0.12.x'; case 42: return 'io.js 1.x'; case 43: return 'io.js 1.1.x'; case 44: return 'io.js 2.x'; case 45: return 'io.js 3.x'; case 46: return 'Node.js 4.x'; case 47: return 'Node.js 5.x'; case 48: return 'Node.js 6.x'; case 49: return 'Electron 1.3.x'; case 50: return 'Electron 1.4.x'; case 51: return 'Node.js 7.x'; case 53: return 'Electron 1.6.x'; case 57: return 'Node.js 8.x'; case 59: return 'Node.js 9.x'; default: return false; } } /** * Get a human readable description of where node-sass is running to support * user error reporting when something goes wrong * * @param {string} env - The name of the native bindings that is to be parsed * @return {string} A description of what os, architecture, and Node version * that is being run * * @api public */ function getHumanEnvironment(env) { var binding = env.replace(/_binding\.node$/, ''), parts = binding.split('-'), platform = getHumanPlatform(parts[0]), arch = getHumanArchitecture(parts[1]), runtime = getHumanNodeVersion(parts[2]); if (parts.length !== 3) { return 'Unknown environment (' + binding + ')'; } if (!platform) { platform = 'Unsupported platform (' + parts[0] + ')'; } if (!arch) { arch = 'Unsupported architecture (' + parts[1] + ')'; } if (!runtime) { runtime = 'Unsupported runtime (' + parts[2] + ')'; } return [ platform, arch, 'with', runtime, ].join(' '); } /** * Get the value of the binaries under the default path * * @return {Array} The currently installed node-sass bindings * * @api public */ function getInstalledBinaries() { return fs.readdirSync(defaultBinaryPath); } /** * Check that an environment matches the whitelisted values or the current * environment if no parameters are passed * * @param {string} platform - The name of the OS platform(darwin, win32, etc...) * @param {string} arch - The instruction set architecture of the Node environment * @param {string} abi - The Node Application Binary Interface * @return {Boolean} True, if node-sass supports the current platform, false otherwise * * @api public */ function isSupportedEnvironment(platform, arch, abi) { return ( false !== getHumanPlatform(platform) && false !== getHumanArchitecture(arch) && false !== getHumanNodeVersion(abi) ); } /** * Get the value of a CLI argument * * @param {String} name * @param {Array} args * @api private */ function getArgument(name, args) { var flags = args || process.argv.slice(2), index = flags.lastIndexOf(name); if (index === -1 || index + 1 >= flags.length) { return null; } return flags[index + 1]; } /** * Get binary name. * If environment variable SASS_BINARY_NAME, * .npmrc variable sass_binary_name or * process argument --binary-name is provided, * return it as is, otherwise make default binary * name: {platform}-{arch}-{v8 version}.node * * @api public */ function getBinaryName() { var binaryName, variant, platform = process.platform; if (getArgument('--sass-binary-name')) { binaryName = getArgument('--sass-binary-name'); } else if (process.env.SASS_BINARY_NAME) { binaryName = process.env.SASS_BINARY_NAME; } else if (process.env.npm_config_sass_binary_name) { binaryName = process.env.npm_config_sass_binary_name; } else if (pkg.nodeSassConfig && pkg.nodeSassConfig.binaryName) { binaryName = pkg.nodeSassConfig.binaryName; } else { variant = getPlatformVariant(); if (variant) { platform += '_' + variant; } binaryName = [ platform, '-', process.arch, '-', process.versions.modules ].join(''); } return [binaryName, 'binding.node'].join('_'); } /** * Determine the URL to fetch binary file from. * By default fetch from the node-sass distribution * site on GitHub. * * The default URL can be overriden using * the environment variable SASS_BINARY_SITE, * .npmrc variable sass_binary_site or * or a command line option --sass-binary-site: * * node scripts/install.js --sass-binary-site http://example.com/ * * The URL should to the mirror of the repository * laid out as follows: * * SASS_BINARY_SITE/ * * v3.0.0 * v3.0.0/freebsd-x64-14_binding.node * .... * v3.0.0 * v3.0.0/freebsd-ia32-11_binding.node * v3.0.0/freebsd-x64-42_binding.node * ... etc. for all supported versions and platforms * * @api public */ function getBinaryUrl() { var site = getArgument('--sass-binary-site') || process.env.SASS_BINARY_SITE || process.env.npm_config_sass_binary_site || (pkg.nodeSassConfig && pkg.nodeSassConfig.binarySite) || 'https://github.com/sass/node-sass/releases/download'; return [site, 'v' + pkg.version, getBinaryName()].join('/'); } /** * Get binary path. * If environment variable SASS_BINARY_PATH, * .npmrc variable sass_binary_path or * process argument --sass-binary-path is provided, * select it by appending binary name, otherwise * make default binary path using binary name. * Once the primary selection is made, check if * callers wants to throw if file not exists before * returning. * * @api public */ function getBinaryPath() { var binaryPath; if (getArgument('--sass-binary-path')) { binaryPath = getArgument('--sass-binary-path'); } else if (process.env.SASS_BINARY_PATH) { binaryPath = process.env.SASS_BINARY_PATH; } else if (process.env.npm_config_sass_binary_path) { binaryPath = process.env.npm_config_sass_binary_path; } else if (pkg.nodeSassConfig && pkg.nodeSassConfig.binaryPath) { binaryPath = pkg.nodeSassConfig.binaryPath; } else { binaryPath = path.join(defaultBinaryPath, getBinaryName().replace(/_(?=binding\.node)/, '/')); } return binaryPath; } /** * An array of paths suitable for use as a local disk cache of the binding. * * @return {[]String} an array of paths * @api public */ function getCachePathCandidates() { return [ process.env.npm_config_sass_binary_cache, process.env.npm_config_cache, ].filter(function(_) { return _; }); } /** * The most suitable location for caching the binding on disk. * * Given the candidates directories provided by `getCachePathCandidates()` this * returns the first writable directory. By treating the candidate directories * as a prioritised list this method is deterministic, assuming no change to the * local environment. * * @return {String} directory to cache binding * @api public */ function getBinaryCachePath() { var i, cachePath, cachePathCandidates = getCachePathCandidates(); for (i = 0; i < cachePathCandidates.length; i++) { cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version); try { mkdir.sync(cachePath); return cachePath; } catch (e) { // Directory is not writable, try another } } return ''; } /** * The cached binding * * Check the candidates directories provided by `getCachePathCandidates()` for * the binding file, if it exists. By treating the candidate directories * as a prioritised list this method is deterministic, assuming no change to the * local environment. * * @return {String} path to cached binary * @api public */ function getCachedBinary() { var i, cachePath, cacheBinary, cachePathCandidates = getCachePathCandidates(), binaryName = getBinaryName(); for (i = 0; i < cachePathCandidates.length; i++) { cachePath = path.join(cachePathCandidates[i], pkg.name, pkg.version); cacheBinary = path.join(cachePath, binaryName); if (fs.existsSync(cacheBinary)) { return cacheBinary; } } return ''; } /** * Does the supplied binary path exist * * @param {String} binaryPath * @api public */ function hasBinary(binaryPath) { return fs.existsSync(binaryPath); } /** * Get Sass version information * * @api public */ function getVersionInfo(binding) { return [ ['node-sass', pkg.version, '(Wrapper)', '[JavaScript]'].join('\t'), ['libsass ', binding.libsassVersion(), '(Sass Compiler)', '[C/C++]'].join('\t'), ].join(eol); } /** * Gets the platform variant, currently either an empty string or 'musl' for Linux/musl platforms. * * @api public */ function getPlatformVariant() { var contents = ''; if (process.platform !== 'linux') { return ''; } try { contents = fs.readFileSync(process.execPath); // Buffer.indexOf was added in v1.5.0 so cast to string for old node // Delay contents.toStrings because it's expensive if (!contents.indexOf) { contents = contents.toString(); } if (contents.indexOf('libc.musl-x86_64.so.1') !== -1) { return 'musl'; } } catch (err) { } // eslint-disable-line no-empty return ''; } module.exports.hasBinary = hasBinary; module.exports.getBinaryUrl = getBinaryUrl; module.exports.getBinaryName = getBinaryName; module.exports.getBinaryPath = getBinaryPath; module.exports.getBinaryCachePath = getBinaryCachePath; module.exports.getCachedBinary = getCachedBinary; module.exports.getCachePathCandidates = getCachePathCandidates; module.exports.getVersionInfo = getVersionInfo; module.exports.getHumanEnvironment = getHumanEnvironment; module.exports.getInstalledBinaries = getInstalledBinaries; module.exports.isSupportedEnvironment = isSupportedEnvironment;
mit
pdeboer/wikilanguage
lib/jung2/jung-samples/src/main/java/edu/uci/ics/jung/samples/DrawnIconVertexDemo.java
7238
/* * Copyright (c) 2003, the JUNG Project and the Regents of the University of * California All rights reserved. * * This software is open-source under the BSD license; see either "license.txt" * or http://jung.sourceforge.net/license.txt for a description. * */ package edu.uci.ics.jung.samples; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import org.apache.commons.collections15.Transformer; import edu.uci.ics.jung.algorithms.layout.FRLayout; import edu.uci.ics.jung.graph.DirectedSparseGraph; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.visualization.GraphZoomScrollPane; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.control.ScalingControl; import edu.uci.ics.jung.visualization.decorators.PickableEdgePaintTransformer; import edu.uci.ics.jung.visualization.decorators.PickableVertexPaintTransformer; import edu.uci.ics.jung.visualization.decorators.ToStringLabeller; import edu.uci.ics.jung.visualization.renderers.DefaultEdgeLabelRenderer; import edu.uci.ics.jung.visualization.renderers.DefaultVertexLabelRenderer; /** * A demo that shows drawn Icons as vertices * * @author Tom Nelson * */ public class DrawnIconVertexDemo { /** * the graph */ Graph<Integer,Number> graph; /** * the visual component and renderer for the graph */ VisualizationViewer<Integer,Number> vv; public DrawnIconVertexDemo() { // create a simple graph for the demo graph = new DirectedSparseGraph<Integer,Number>(); Integer[] v = createVertices(10); createEdges(v); vv = new VisualizationViewer<Integer,Number>(new FRLayout<Integer,Number>(graph)); vv.getRenderContext().setVertexLabelTransformer(new Transformer<Integer,String>(){ public String transform(Integer v) { return "Vertex "+v; }}); vv.getRenderContext().setVertexLabelRenderer(new DefaultVertexLabelRenderer(Color.cyan)); vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.cyan)); vv.getRenderContext().setVertexIconTransformer(new Transformer<Integer,Icon>() { /* * Implements the Icon interface to draw an Icon with background color and * a text label */ public Icon transform(final Integer v) { return new Icon() { public int getIconHeight() { return 20; } public int getIconWidth() { return 20; } public void paintIcon(Component c, Graphics g, int x, int y) { if(vv.getPickedVertexState().isPicked(v)) { g.setColor(Color.yellow); } else { g.setColor(Color.red); } g.fillOval(x, y, 20, 20); if(vv.getPickedVertexState().isPicked(v)) { g.setColor(Color.black); } else { g.setColor(Color.white); } g.drawString(""+v, x+6, y+15); }}; }}); vv.getRenderContext().setVertexFillPaintTransformer(new PickableVertexPaintTransformer<Integer>(vv.getPickedVertexState(), Color.white, Color.yellow)); vv.getRenderContext().setEdgeDrawPaintTransformer(new PickableEdgePaintTransformer<Number>(vv.getPickedEdgeState(), Color.black, Color.lightGray)); vv.setBackground(Color.white); // add my listener for ToolTips vv.setVertexToolTipTransformer(new ToStringLabeller<Integer>()); // create a frome to hold the graph final JFrame frame = new JFrame(); Container content = frame.getContentPane(); final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv); content.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final ModalGraphMouse gm = new DefaultModalGraphMouse<Integer,Number>(); vv.setGraphMouse(gm); final ScalingControl scaler = new CrossoverScalingControl(); JButton plus = new JButton("+"); plus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1.1f, vv.getCenter()); } }); JButton minus = new JButton("-"); minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1/1.1f, vv.getCenter()); } }); JPanel controls = new JPanel(); controls.add(plus); controls.add(minus); controls.add(((DefaultModalGraphMouse<Integer,Number>) gm).getModeComboBox()); content.add(controls, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } /** * create some vertices * @param count how many to create * @return the Vertices in an array */ private Integer[] createVertices(int count) { Integer[] v = new Integer[count]; for (int i = 0; i < count; i++) { v[i] = new Integer(i); graph.addVertex(v[i]); } return v; } /** * create edges for this demo graph * @param v an array of Vertices to connect */ void createEdges(Integer[] v) { graph.addEdge(new Double(Math.random()), v[0], v[1], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[0], v[3], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[0], v[4], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[4], v[5], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[3], v[5], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[1], v[2], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[1], v[4], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[8], v[2], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[3], v[8], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[6], v[7], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[7], v[5], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[0], v[9], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[9], v[8], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[7], v[6], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[6], v[5], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[4], v[2], EdgeType.DIRECTED); graph.addEdge(new Double(Math.random()), v[5], v[4], EdgeType.DIRECTED); } /** * a driver for this demo */ public static void main(String[] args) { new DrawnIconVertexDemo(); } }
mit
Koderz/RuntimeMeshComponent
Source/RuntimeMeshComponent/Private/RuntimeMeshRendering.cpp
1451
// Copyright 2016-2020 TriAxis Games L.L.C. All Rights Reserved. #include "RuntimeMeshRendering.h" #include "RuntimeMeshComponentPlugin.h" #include "RuntimeMeshSectionProxy.h" FRuntimeMeshVertexBuffer::FRuntimeMeshVertexBuffer(bool bInIsDynamicBuffer, int32 DefaultVertexSize) : bIsDynamicBuffer(bInIsDynamicBuffer) , VertexSize(DefaultVertexSize) , NumVertices(0) , ShaderResourceView(nullptr) { } void FRuntimeMeshVertexBuffer::InitRHI() { } void FRuntimeMeshVertexBuffer::ReleaseRHI() { ShaderResourceView.SafeRelease(); FVertexBuffer::ReleaseRHI(); } FRuntimeMeshIndexBuffer::FRuntimeMeshIndexBuffer(bool bInIsDynamicBuffer) : bIsDynamicBuffer(bInIsDynamicBuffer) , IndexSize(CalculateStride(false)) , NumIndices(0) { } void FRuntimeMeshIndexBuffer::InitRHI() { } FRuntimeMeshVertexFactory::FRuntimeMeshVertexFactory(ERHIFeatureLevel::Type InFeatureLevel) : FLocalVertexFactory(InFeatureLevel, "FRuntimeMeshVertexFactory") { } /** Init function that can be called on any thread, and will do the right thing (enqueue command if called on main thread) */ void FRuntimeMeshVertexFactory::Init(FLocalVertexFactory::FDataType VertexStructure) { if (IsInRenderingThread()) { SetData(VertexStructure); } else { // Send the command to the render thread ENQUEUE_RENDER_COMMAND(InitRuntimeMeshVertexFactory)( [this, VertexStructure](FRHICommandListImmediate & RHICmdList) { Init(VertexStructure); } ); } }
mit
lanice/gloperate
source/examples/globjects-painters/screenaligned/ScreenAligned.cpp
2366
#include "ScreenAligned.h" #include <random> #include <glbinding/gl/gl.h> #include <globjects/logging.h> #include <gloperate/painter/ViewportCapability.h> #include <gloperate/painter/TargetFramebufferCapability.h> using namespace gloperate; using namespace globjects; using namespace gl; ScreenAligned::ScreenAligned(ResourceManager & resourceManager, const cpplocate::ModuleInfo & moduleInfo) : Painter("ScreenAligned", resourceManager, moduleInfo) { // Setup painter m_targetFramebufferCapability = addCapability(new gloperate::TargetFramebufferCapability()); m_viewportCapability = addCapability(new gloperate::ViewportCapability()); } ScreenAligned::~ScreenAligned() { } void ScreenAligned::onInitialize() { #ifdef __APPLE__ Shader::clearGlobalReplacements(); Shader::globalReplace("#version 140", "#version 150"); debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl; #endif gl::glClearColor(0.2f, 0.3f, 0.4f, 1.f); createAndSetupTexture(); createAndSetupGeometry(); } void ScreenAligned::onPaint() { if (m_viewportCapability->hasChanged()) { glViewport(m_viewportCapability->x(), m_viewportCapability->y(), m_viewportCapability->width(), m_viewportCapability->height()); m_viewportCapability->setChanged(false); } globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer(); if (!fbo) { fbo = globjects::Framebuffer::defaultFBO(); } fbo->bind(GL_FRAMEBUFFER); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_quad->draw(); globjects::Framebuffer::unbind(GL_FRAMEBUFFER); } void ScreenAligned::createAndSetupTexture() { static const int w(256); static const int h(256); unsigned char data[w * h * 4]; std::random_device rd; std::mt19937 generator(rd()); std::poisson_distribution<> r(0.2); for (int i = 0; i < w * h * 4; ++i) { data[i] = static_cast<unsigned char>(255 - static_cast<unsigned char>(r(generator) * 255)); } m_texture = globjects::Texture::createDefault(gl::GL_TEXTURE_2D); m_texture->image2D(0, gl::GL_RGBA8, w, h, 0, gl::GL_RGBA, gl::GL_UNSIGNED_BYTE, data); } void ScreenAligned::createAndSetupGeometry() { m_quad = new gloperate::ScreenAlignedQuad(m_texture); m_quad->setSamplerUniform(0); }
mit
mfloresn90/AndroidStudioSources
Vuforia/app/src/main/java/com/vuforia/samples/SampleApplication/utils/LoadingDialogHandler.java
1507
/*=============================================================================== Copyright (c) 2016 PTC Inc. All Rights Reserved. Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved. Vuforia is a trademark of PTC Inc., registered in the United States and other countries. ===============================================================================*/ package com.vuforia.samples.SampleApplication.utils; import java.lang.ref.WeakReference; import android.app.Activity; import android.os.Handler; import android.os.Message; import android.view.View; public final class LoadingDialogHandler extends Handler { private final WeakReference<Activity> mActivity; // Constants for Hiding/Showing Loading dialog public static final int HIDE_LOADING_DIALOG = 0; public static final int SHOW_LOADING_DIALOG = 1; public View mLoadingDialogContainer; public LoadingDialogHandler(Activity activity) { mActivity = new WeakReference<Activity>(activity); } public void handleMessage(Message msg) { Activity imageTargets = mActivity.get(); if (imageTargets == null) { return; } if (msg.what == SHOW_LOADING_DIALOG) { mLoadingDialogContainer.setVisibility(View.VISIBLE); } else if (msg.what == HIDE_LOADING_DIALOG) { mLoadingDialogContainer.setVisibility(View.GONE); } } }
mit
Atvaark/Emurado
HaloOnline.Server.Model/Clan/ClanMember.cs
201
using HaloOnline.Server.Model.User; namespace HaloOnline.Server.Model.Clan { public class ClanMember { public UserId Id { get; set; } public int ClanRole { get; set; } } }
mit
dsm-sogeti-usa-llc/sogeti-academy
src/dotnet/src/Application/Topics/Queries/GetList/TopicViewModel.cs
200
namespace Sogeti.Academy.Application.Topics.Queries.GetList { public class TopicViewModel { public string Id { get; set; } public string Name { get; set; } public int Votes { get; set; } } }
mit
TomasVotruba/doctrine2
tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php
6345
<?php declare(strict_types=1); namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Annotation as ORM; use Doctrine\Tests\OrmFunctionalTestCase; /** * @group DDC-1080 */ class DDC1080Test extends OrmFunctionalTestCase { public function testHydration() : void { $this->schemaTool->createSchema( [ $this->em->getClassMetadata(DDC1080Foo::class), $this->em->getClassMetadata(DDC1080Bar::class), $this->em->getClassMetadata(DDC1080FooBar::class), ] ); $foo1 = new DDC1080Foo(); $foo1->setFooTitle('foo title 1'); $foo2 = new DDC1080Foo(); $foo2->setFooTitle('foo title 2'); $bar1 = new DDC1080Bar(); $bar1->setBarTitle('bar title 1'); $bar2 = new DDC1080Bar(); $bar2->setBarTitle('bar title 2'); $bar3 = new DDC1080Bar(); $bar3->setBarTitle('bar title 3'); $foobar1 = new DDC1080FooBar(); $foobar1->setFoo($foo1); $foobar1->setBar($bar1); $foobar1->setOrderNr(0); $foobar2 = new DDC1080FooBar(); $foobar2->setFoo($foo1); $foobar2->setBar($bar2); $foobar2->setOrderNr(0); $foobar3 = new DDC1080FooBar(); $foobar3->setFoo($foo1); $foobar3->setBar($bar3); $foobar3->setOrderNr(0); $this->em->persist($foo1); $this->em->persist($foo2); $this->em->persist($bar1); $this->em->persist($bar2); $this->em->persist($bar3); $this->em->flush(); $this->em->persist($foobar1); $this->em->persist($foobar2); $this->em->persist($foobar3); $this->em->flush(); $this->em->clear(); $foo = $this->em->find(DDC1080Foo::class, $foo1->getFooID()); $fooBars = $foo->getFooBars(); self::assertCount(3, $fooBars, 'Should return three foobars.'); } } /** * @ORM\Entity * @ORM\Table(name="foo") */ class DDC1080Foo { /** * @ORM\Id * @ORM\Column(name="fooID", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $fooID; /** @ORM\Column(name="fooTitle", type="string") */ protected $fooTitle; /** * @ORM\OneToMany(targetEntity=DDC1080FooBar::class, mappedBy="foo", cascade={"persist"}) * @ORM\OrderBy({"orderNr"="ASC"}) */ protected $fooBars; public function __construct() { $this->fooBars = new ArrayCollection(); } /** * @return the $fooID */ public function getFooID() { return $this->fooID; } /** * @return the $fooTitle */ public function getFooTitle() { return $this->fooTitle; } /** * @return the $fooBars */ public function getFooBars() { return $this->fooBars; } /** * @param field_type $fooID */ public function setFooID($fooID) { $this->fooID = $fooID; } /** * @param field_type $fooTitle */ public function setFooTitle($fooTitle) { $this->fooTitle = $fooTitle; } /** * @param field_type $fooBars */ public function setFooBars($fooBars) { $this->fooBars = $fooBars; } } /** * @ORM\Entity * @ORM\Table(name="bar") */ class DDC1080Bar { /** * @ORM\Id * @ORM\Column(name="barID", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $barID; /** @ORM\Column(name="barTitle", type="string") */ protected $barTitle; /** * @ORM\OneToMany(targetEntity=DDC1080FooBar::class, mappedBy="bar", cascade={"persist"}) * @ORM\OrderBy({"orderNr"="ASC"}) */ protected $fooBars; public function __construct() { $this->fooBars = new ArrayCollection(); } /** * @return the $barID */ public function getBarID() { return $this->barID; } /** * @return the $barTitle */ public function getBarTitle() { return $this->barTitle; } /** * @return the $fooBars */ public function getFooBars() { return $this->fooBars; } /** * @param field_type $barID */ public function setBarID($barID) { $this->barID = $barID; } /** * @param field_type $barTitle */ public function setBarTitle($barTitle) { $this->barTitle = $barTitle; } /** * @param field_type $fooBars */ public function setFooBars($fooBars) { $this->fooBars = $fooBars; } } /** * @ORM\Table(name="fooBar") * @ORM\Entity */ class DDC1080FooBar { /** * @ORM\ManyToOne(targetEntity=DDC1080Foo::class) * @ORM\JoinColumn(name="fooID", referencedColumnName="fooID") * @ORM\Id */ protected $foo; /** * @ORM\ManyToOne(targetEntity=DDC1080Bar::class) * @ORM\JoinColumn(name="barID", referencedColumnName="barID") * @ORM\Id */ protected $bar; /** * @ORM\Column(name="orderNr", type="integer", nullable=false) * * @var int orderNr */ protected $orderNr; /** * Retrieve the foo property * * @return DDC1080Foo */ public function getFoo() { return $this->foo; } /** * Set the foo property * * @param DDC1080Foo $foo * * @return DDC1080FooBar */ public function setFoo($foo) { $this->foo = $foo; return $this; } /** * Retrieve the bar property * * @return DDC1080Bar */ public function getBar() { return $this->bar; } /** * Set the bar property * * @param DDC1080Bar $bar * * @return DDC1080FooBar */ public function setBar($bar) { $this->bar = $bar; return $this; } /** * Retrieve the orderNr property * * @return int|null */ public function getOrderNr() { return $this->orderNr; } /** * Set the orderNr property * * @param int|null $orderNr * * @return DDC1080FooBar */ public function setOrderNr($orderNr) { $this->orderNr = $orderNr; return $this; } }
mit
sapk-fork/gitea
vendor/github.com/go-redis/redis/v7/internal/pool/pool_sticky.go
1647
package pool import ( "context" "sync" ) type StickyConnPool struct { pool *ConnPool reusable bool cn *Conn closed bool mu sync.Mutex } var _ Pooler = (*StickyConnPool)(nil) func NewStickyConnPool(pool *ConnPool, reusable bool) *StickyConnPool { return &StickyConnPool{ pool: pool, reusable: reusable, } } func (p *StickyConnPool) NewConn(context.Context) (*Conn, error) { panic("not implemented") } func (p *StickyConnPool) CloseConn(*Conn) error { panic("not implemented") } func (p *StickyConnPool) Get(ctx context.Context) (*Conn, error) { p.mu.Lock() defer p.mu.Unlock() if p.closed { return nil, ErrClosed } if p.cn != nil { return p.cn, nil } cn, err := p.pool.Get(ctx) if err != nil { return nil, err } p.cn = cn return cn, nil } func (p *StickyConnPool) putUpstream() { p.pool.Put(p.cn) p.cn = nil } func (p *StickyConnPool) Put(cn *Conn) {} func (p *StickyConnPool) removeUpstream(reason error) { p.pool.Remove(p.cn, reason) p.cn = nil } func (p *StickyConnPool) Remove(cn *Conn, reason error) { p.removeUpstream(reason) } func (p *StickyConnPool) Len() int { p.mu.Lock() defer p.mu.Unlock() if p.cn == nil { return 0 } return 1 } func (p *StickyConnPool) IdleLen() int { p.mu.Lock() defer p.mu.Unlock() if p.cn == nil { return 1 } return 0 } func (p *StickyConnPool) Stats() *Stats { return nil } func (p *StickyConnPool) Close() error { p.mu.Lock() defer p.mu.Unlock() if p.closed { return ErrClosed } p.closed = true if p.cn != nil { if p.reusable { p.putUpstream() } else { p.removeUpstream(ErrClosed) } } return nil }
mit
quyen/my_rails_settings
test/settings_test.rb
4607
require 'test_helper' class SettingsTest < Test::Unit::TestCase setup_db def setup Settings.create(:var => 'test', :value => 'foo') Settings.create(:var => 'test2', :value => 'bar') end def teardown Settings.delete_all end def tests_defaults_false Settings.defaults[:foo] = false assert_equal false, Settings.foo end def test_defaults Settings.defaults[:foo] = 'default foo' assert_nil Settings.target(:foo) assert_equal 'default foo', Settings.foo Settings.foo = 'bar' assert_equal 'bar', Settings.foo assert_not_nil Settings.target(:foo) end def test_get assert_setting 'foo', :test assert_setting 'bar', :test2 end def test_update assert_assign_setting '321', :test end def test_create assert_assign_setting '123', :onetwothree end def test_complex_serialization complex = [1, '2', {:three => true}] Settings.complex = complex assert_equal complex, Settings.complex end def test_serialization_of_float Settings.float = 0.01 Settings.reload assert_equal 0.01, Settings.float assert_equal 0.02, Settings.float * 2 end def test_target_scope user1 = User.create :name => 'First user' user2 = User.create :name => 'Second user' assert_assign_setting 1, :one, user1 assert_assign_setting 2, :two, user2 assert_setting 1, :one, user1 assert_setting 2, :two, user2 assert_setting nil, :one assert_setting nil, :two assert_setting nil, :two, user1 assert_setting nil, :one, user2 assert_equal({ "one" => 1}, user1.settings.all('one')) assert_equal({ "two" => 2}, user2.settings.all('two')) assert_equal({ "one" => 1}, user1.settings.all('o')) assert_equal({}, user1.settings.all('non_existing_var')) end def test_named_scope user_without_settings = User.create :name => 'User without settings' user_with_settings = User.create :name => 'User with settings' user_with_settings.settings.one = '1' user_with_settings.settings.two = '2' assert_equal [user_with_settings], User.with_settings assert_equal [user_with_settings], User.with_settings_for('one') assert_equal [user_with_settings], User.with_settings_for('two') assert_equal [], User.with_settings_for('foo') assert_equal [user_without_settings], User.without_settings assert_equal [user_without_settings], User.without_settings_for('one') assert_equal [user_without_settings], User.without_settings_for('two') assert_equal [user_without_settings, user_with_settings], User.without_settings_for('foo') end def test_all assert_equal({ "test2" => "bar", "test" => "foo" }, Settings.all) assert_equal({ "test2" => "bar" }, Settings.all('test2')) assert_equal({ "test2" => "bar", "test" => "foo" }, Settings.all('test')) assert_equal({}, Settings.all('non_existing_var')) end def test_merge assert_raise(TypeError) do Settings.merge! :test, { :a => 1 } end Settings[:hash] = { :one => 1 } Settings.merge! :hash, { :two => 2 } assert_equal({ :one => 1, :two => 2 }, Settings[:hash]) assert_raise(ArgumentError) do Settings.merge! :hash, 123 end Settings.merge! :empty_hash, { :two => 2 } assert_equal({ :two => 2 }, Settings[:empty_hash]) end def test_destroy Settings.destroy :test assert_equal nil, Settings.test end private def assert_setting(value, key, scope_target=nil) key = key.to_sym if scope_target assert_equal value, scope_target.instance_eval("settings.#{key}") assert_equal value, scope_target.settings[key.to_sym] assert_equal value, scope_target.settings[key.to_s] else assert_equal value, eval("Settings.#{key}") assert_equal value, Settings[key.to_sym] assert_equal value, Settings[key.to_s] end end def assert_assign_setting(value, key, scope_target=nil) key = key.to_sym if scope_target assert_equal value, (scope_target.settings[key] = value) assert_setting value, key, scope_target scope_target.settings[key] = nil assert_equal value, (scope_target.settings[key.to_s] = value) assert_setting value, key, scope_target else assert_equal value, (Settings[key] = value) assert_setting value, key Settings[key] = nil assert_equal value, (Settings[key.to_s] = value) assert_setting value, key end end end
mit
ermshiperete/GitVersion
src/GitVersion.Core/Configuration/Init/SetConfig/ConfigureBranches.cs
2566
using System; using System.Collections.Generic; using System.Linq; using GitVersion.Configuration.Init.Wizard; using GitVersion.Logging; using GitVersion.Model.Configuration; namespace GitVersion.Configuration.Init.SetConfig { public class ConfigureBranches : ConfigInitWizardStep { public ConfigureBranches(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } protected override StepResult HandleResult(string result, Queue<ConfigInitWizardStep> steps, Config config, string workingDirectory) { if (int.TryParse(result, out var parsed)) { if (parsed == 0) { steps.Enqueue(StepFactory.CreateStep<EditConfigStep>()); return StepResult.Ok(); } try { var foundBranch = OrderedBranches(config).ElementAt(parsed - 1); var branchConfig = foundBranch.Value; if (branchConfig == null) { branchConfig = new BranchConfig { Name = foundBranch.Key }; config.Branches.Add(foundBranch.Key, branchConfig); } steps.Enqueue(StepFactory.CreateStep<ConfigureBranch>().WithData(foundBranch.Key, branchConfig)); return StepResult.Ok(); } catch (ArgumentOutOfRangeException) { } } return StepResult.InvalidResponseSelected(); } protected override string GetPrompt(Config config, string workingDirectory) { return @"Which branch would you like to configure: 0) Go Back " + string.Join(System.Environment.NewLine, OrderedBranches(config).Select((c, i) => $"{i + 1}) {c.Key}")); } private static IOrderedEnumerable<KeyValuePair<string, BranchConfig>> OrderedBranches(Config config) { var defaultConfig = new ConfigurationBuilder().Build(); var defaultConfigurationBranches = defaultConfig.Branches .Where(k => !config.Branches.ContainsKey(k.Key)) // Return an empty branch config .Select(v => new KeyValuePair<string, BranchConfig>(v.Key, null)); return config.Branches.Union(defaultConfigurationBranches).OrderBy(b => b.Key); } protected override string DefaultResult => "0"; } }
mit
zweidner/hubzero-cms
core/components/com_feedback/site/views/media/tmpl/display.php
2685
<?php /** * @package hubzero-cms * @copyright Copyright 2005-2019 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ // No direct access defined('_HZEXEC_') or die(); $this->css() ->js('media.js'); ?> <form action="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller); ?>" method="post" enctype="multipart/form-data" name="filelist" id="filelist"> <?php if ($this->getError()) { ?> <p class="error"><?php echo $this->getError(); ?></p> <?php } ?> <table> <tbody> <?php $k = 0; if ($this->file && file_exists($this->file_path . DS . $this->file)) { $this_size = filesize($this->file_path . DS . $this->file); list($ow, $oh, $type, $attr) = getimagesize($this->file_path . DS . $this->file); // scale if image is bigger than 120w x120h $num = max($ow/120, $oh/120); if ($num > 1) { $mw = round($ow/$num); $mh = round($oh/$num); } else { $mw = $ow; $mh = $oh; } ?> <tr> <td> <img src="<?php echo $this->webpath . DS . $this->path . DS . $this->file; ?>" alt="" id="conimage" height="<?php echo $mh; ?>" width="<?php echo $mw; ?>" /> </td> <td width="100%"> <input type="hidden" name="conimg" value="<?php echo $this->escape($this->webpath . DS . $this->path . DS . $this->file); ?>" /> <input type="hidden" name="task" value="delete" /> <input type="hidden" name="file" id="file" value="<?php echo $this->escape($this->file); ?>" /> <input type="submit" name="submit" value="<?php echo Lang::txt('JACTION_DELETE'); ?>" /> </td> </tr> <?php } else { ?> <tr> <td> <img src="<?php echo $this->default_picture; ?>" alt="" id="oimage" name="oimage" /> </td> <td> <p><?php echo Lang::txt('COM_FEEDBACK_STORY_ADD_PICTURE'); ?><br /><small>(gif/jpg/jpeg/png - 200K max)</small></p> </td> </tr> <tr> <td colspan="2"> <input type="hidden" name="conimg" value="" /> <input type="hidden" name="task" value="upload" /> <input type="hidden" name="currentfile" value="<?php echo $this->escape($this->file); ?>" /> <input type="file" name="upload" id="upload" size="10" /> <input type="submit" value="<?php echo Lang::txt('COM_FEEDBACK_UPLOAD'); ?>" /> </td> </tr> <?php } ?> </tbody> </table> <input type="hidden" name="option" value="<?php echo $this->option; ?>" /> <input type="hidden" name="controller" value="<?php echo $this->controller; ?>" /> <input type="hidden" name="tmpl" value="component" /> <input type="hidden" name="id" value="<?php echo $this->id; ?>" /> </form>
mit