repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
joakimbeng/absurd
tests/data/css/config/B.js
88
module.exports = function(A) { A.add({ 'header.a': { background: '#222' } }); }
mit
quxiaolong1504/marshmallow
marshmallow/marshalling.py
12220
# -*- coding: utf-8 -*- """Utility classes and values used for marshalling and unmarshalling objects to and from primitive types. .. warning:: This module is treated as private API. Users should not need to use this module directly. """ from __future__ import unicode_literals from marshmallow import utils from marshmallow.utils import missing from marshmallow.compat import text_type, iteritems from marshmallow.exceptions import ( ValidationError, ) __all__ = [ 'Marshaller', 'Unmarshaller', ] class ErrorStore(object): def __init__(self): #: Dictionary of errors stored during serialization self.errors = {} #: List of `Field` objects which have validation errors self.error_fields = [] #: List of field_names which have validation errors self.error_field_names = [] #: True while (de)serializing a collection self._pending = False def reset_errors(self): self.errors = {} self.error_field_names = [] self.error_fields = [] def get_errors(self, index=None): if index is not None: errors = self.errors.get(index, {}) self.errors[index] = errors else: errors = self.errors return errors def call_and_store(self, getter_func, data, field_name, field_obj, index=None): """Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`. :param callable getter_func: Function for getting the serialized/deserialized value from ``data``. :param data: The data passed to ``getter_func``. :param str field_name: Field name. :param FieldABC field_obj: Field object that performs the serialization/deserialization behavior. :param int index: Index of the item being validated, if validating a collection, otherwise `None`. """ try: value = getter_func(data) except ValidationError as err: # Store validation errors self.error_fields.append(field_obj) self.error_field_names.append(field_name) errors = self.get_errors(index=index) # Warning: Mutation! if isinstance(err.messages, dict): errors[field_name] = err.messages else: errors.setdefault(field_name, []).extend(err.messages) value = missing return value class Marshaller(ErrorStore): """Callable class responsible for serializing data and storing errors. :param str prefix: Optional prefix that will be prepended to all the serialized field names. """ def __init__(self, prefix=''): self.prefix = prefix ErrorStore.__init__(self) def serialize(self, obj, fields_dict, many=False, strict=False, accessor=None, dict_class=dict, index_errors=True, index=None): """Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields. :param obj: The actual object(s) from which the fields are taken from :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param bool many: Set to `True` if ``data`` should be serialized as a collection. :param bool strict: If `True`, raise errors if invalid data are passed in instead of failing silently and storing the errors. :param callable accessor: Function to use for getting values from ``obj``. :param type dict_class: Dictionary class used to construct the output. :param bool index_errors: Whether to store the index of invalid items in ``self.errors`` when ``many=True``. :param int index: Index of the item being serialized (for storing errors) if serializing a collection, otherwise `None`. :return: A dictionary of the marshalled data .. versionchanged:: 1.0.0 Renamed from ``marshal``. """ # Reset errors dict if not serializing a collection if not self._pending: self.reset_errors() if many and obj is not None: self._pending = True ret = [self.serialize(d, fields_dict, many=False, strict=strict, dict_class=dict_class, accessor=accessor, index=idx, index_errors=index_errors) for idx, d in enumerate(obj)] self._pending = False return ret items = [] for attr_name, field_obj in iteritems(fields_dict): if getattr(field_obj, 'load_only', False): continue if not self.prefix: key = attr_name else: key = ''.join([self.prefix, attr_name]) getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor) value = self.call_and_store( getter_func=getter, data=obj, field_name=key, field_obj=field_obj, index=(index if index_errors else None) ) if value is missing: continue items.append((key, value)) if self.errors and strict: raise ValidationError( self.errors, field_names=self.error_field_names, fields=self.error_fields ) return dict_class(items) # Make an instance callable __call__ = serialize # Key used for schema-level validation errors SCHEMA = '_schema' class Unmarshaller(ErrorStore): """Callable class responsible for deserializing data and storing errors. .. versionadded:: 1.0.0 """ def _run_validator(self, validator_func, output, original_data, fields_dict, index=None, strict=False, many=False, pass_original=False): try: if pass_original: # Pass original, raw data (before unmarshalling) res = validator_func(output, original_data) else: res = validator_func(output) if res is False: func_name = utils.get_callable_name(validator_func) raise ValidationError('Schema validator {0}({1}) is False'.format( func_name, dict(output) )) except ValidationError as err: errors = self.get_errors(index=index) # Store or reraise errors if err.field_names: field_names = err.field_names field_objs = [fields_dict[each] for each in field_names] else: field_names = [SCHEMA] field_objs = [] for field_name in field_names: if isinstance(err.messages, (list, tuple)): # self.errors[field_name] may be a dict if schemas are nested if isinstance(errors.get(field_name), dict): errors[field_name].setdefault( SCHEMA, [] ).extend(err.messages) else: errors.setdefault(field_name, []).extend(err.messages) elif isinstance(err.messages, dict): errors.setdefault(field_name, []).append(err.messages) else: errors.setdefault(field_name, []).append(text_type(err)) if strict: raise ValidationError( self.errors, fields=field_objs, field_names=field_names ) def _validate(self, validators, output, original_data, fields_dict, index=None, strict=False): """Perform schema-level validation. Stores errors if ``strict`` is `False`. """ for validator_func in validators: self._run_validator(validator_func, output, original_data, fields_dict, index=index, strict=strict) return output def deserialize(self, data, fields_dict, many=False, validators=None, preprocess=None, postprocess=None, strict=False, dict_class=dict, index_errors=True, index=None): """Deserialize ``data`` based on the schema defined by ``fields_dict``. :param dict data: The data to deserialize. :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param bool many: Set to `True` if ``data`` should be deserialized as a collection. :param list validators: List of validation functions to apply to the deserialized dictionary. :param list preprocess: List of pre-processing functions. :param bool strict: If `True`, raise errors if invalid data are passed in instead of failing silently and storing the errors. :param type dict_class: Dictionary class used to construct the output. :param bool index_errors: Whether to store the index of invalid items in ``self.errors`` when ``many=True``. :param int index: Index of the item being serialized (for storing errors) if serializing a collection, otherwise `None`. :return: A dictionary of the deserialized data. """ # Reset errors if not deserializing a collection if not self._pending: self.reset_errors() if many and data is not None: self._pending = True ret = [self.deserialize(d, fields_dict, many=False, validators=validators, preprocess=preprocess, strict=strict, dict_class=dict_class, index=idx, index_errors=index_errors) for idx, d in enumerate(data)] self._pending = False return ret original_data = data if data is not None: items = [] for attr_name, field_obj in iteritems(fields_dict): if field_obj.dump_only: continue key = fields_dict[attr_name].attribute or attr_name try: raw_value = data.get(attr_name, missing) except AttributeError: msg = 'Data must be a dict, got a {0}'.format(data.__class__.__name__) raise ValidationError( msg, field_names=[attr_name], fields=[field_obj] ) field_name = attr_name if raw_value is missing and field_obj.load_from: field_name = field_obj.load_from raw_value = data.get(field_obj.load_from, missing) if raw_value is missing: _miss = field_obj.missing raw_value = _miss() if callable(_miss) else _miss if raw_value is missing and not field_obj.required: continue value = self.call_and_store( getter_func=field_obj.deserialize, data=raw_value, field_name=field_name, field_obj=field_obj, index=(index if index_errors else None) ) if value is not missing: items.append((key, value)) ret = dict_class(items) else: ret = None if preprocess: preprocess = preprocess or [] for func in preprocess: ret = func(ret) if validators: validators = validators or [] ret = self._validate(validators, ret, original_data, fields_dict=fields_dict, strict=strict, index=(index if index_errors else None)) if self.errors and strict: raise ValidationError( self.errors, field_names=self.error_field_names, fields=self.error_fields ) return ret # Make an instance callable __call__ = deserialize
mit
mca62511/charityakita-static
archive/mail/program/lib/Roundcube/rcube_mime.php
30598
<?php /* +-----------------------------------------------------------------------+ | This file is part of the Roundcube Webmail client | | Copyright (C) 2005-2012, The Roundcube Dev Team | | Copyright (C) 2011-2012, Kolab Systems AG | | | | Licensed under the GNU General Public License version 3 or | | any later version with exceptions for skins & plugins. | | See the README file for a full license statement. | | | | PURPOSE: | | MIME message parsing utilities | +-----------------------------------------------------------------------+ | Author: Thomas Bruederli <roundcube@gmail.com> | | Author: Aleksander Machniak <alec@alec.pl> | +-----------------------------------------------------------------------+ */ /** * Class for parsing MIME messages * * @package Framework * @subpackage Storage * @author Thomas Bruederli <roundcube@gmail.com> * @author Aleksander Machniak <alec@alec.pl> */ class rcube_mime { private static $default_charset; /** * Object constructor. */ function __construct($default_charset = null) { self::$default_charset = $default_charset; } /** * Returns message/object character set name * * @return string Characted set name */ public static function get_charset() { if (self::$default_charset) { return self::$default_charset; } if ($charset = rcube::get_instance()->config->get('default_charset')) { return $charset; } return RCUBE_CHARSET; } /** * Parse the given raw message source and return a structure * of rcube_message_part objects. * * It makes use of the PEAR:Mail_mimeDecode library * * @param string The message source * @return object rcube_message_part The message structure */ public static function parse_message($raw_body) { $mime = new Mail_mimeDecode($raw_body); $struct = $mime->decode(array('include_bodies' => true, 'decode_bodies' => true)); return self::structure_part($struct); } /** * Recursive method to convert a Mail_mimeDecode part into a rcube_message_part object * * @param object A message part struct * @param int Part count * @param string Parent MIME ID * * @return object rcube_message_part */ private static function structure_part($part, $count=0, $parent='') { $struct = new rcube_message_part; $struct->mime_id = $part->mime_id ? $part->mime_id : (empty($parent) ? (string)$count : "$parent.$count"); $struct->headers = $part->headers; $struct->ctype_primary = $part->ctype_primary; $struct->ctype_secondary = $part->ctype_secondary; $struct->mimetype = $part->ctype_primary . '/' . $part->ctype_secondary; $struct->ctype_parameters = $part->ctype_parameters; if ($part->headers['content-transfer-encoding']) $struct->encoding = $part->headers['content-transfer-encoding']; if ($part->ctype_parameters['charset']) $struct->charset = $part->ctype_parameters['charset']; $part_charset = $struct->charset ? $struct->charset : self::get_charset(); // determine filename if (($filename = $part->d_parameters['filename']) || ($filename = $part->ctype_parameters['name'])) { $struct->filename = rcube_mime::decode_mime_string($filename, $part_charset); } // copy part body and convert it to UTF-8 if necessary $struct->body = $part->ctype_primary == 'text' || !$part->ctype_parameters['charset'] ? rcube_charset::convert($part->body, $part_charset) : $part->body; $struct->size = strlen($part->body); $struct->disposition = $part->disposition; foreach ((array)$part->parts as $child_part) { $struct->parts[] = self::structure_part($child_part, ++$count, $struct->mime_id); } return $struct; } /** * Split an address list into a structured array list * * @param string $input Input string * @param int $max List only this number of addresses * @param boolean $decode Decode address strings * @param string $fallback Fallback charset if none specified * @param boolean $addronly Return flat array with e-mail addresses only * * @return array Indexed list of addresses */ static function decode_address_list($input, $max = null, $decode = true, $fallback = null, $addronly = false) { $a = self::parse_address_list($input, $decode, $fallback); $out = array(); $j = 0; // Special chars as defined by RFC 822 need to in quoted string (or escaped). $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]'; if (!is_array($a)) return $out; foreach ($a as $val) { $j++; $address = trim($val['address']); if ($addronly) { $out[$j] = $address; } else { $name = trim($val['name']); if ($name && $address && $name != $address) $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address); else if ($address) $string = $address; else if ($name) $string = $name; $out[$j] = array('name' => $name, 'mailto' => $address, 'string' => $string); } if ($max && $j==$max) break; } return $out; } /** * Decode a message header value * * @param string $input Header value * @param string $fallback Fallback charset if none specified * * @return string Decoded string */ public static function decode_header($input, $fallback = null) { $str = self::decode_mime_string((string)$input, $fallback); return $str; } /** * Decode a mime-encoded string to internal charset * * @param string $input Header value * @param string $fallback Fallback charset if none specified * * @return string Decoded string */ public static function decode_mime_string($input, $fallback = null) { $default_charset = !empty($fallback) ? $fallback : self::get_charset(); // rfc: all line breaks or other characters not found // in the Base64 Alphabet must be ignored by decoding software // delete all blanks between MIME-lines, differently we can // receive unnecessary blanks and broken utf-8 symbols $input = preg_replace("/\?=\s+=\?/", '?==?', $input); // encoded-word regexp $re = '/=\?([^?]+)\?([BbQq])\?([^\n]*?)\?=/'; // Find all RFC2047's encoded words if (preg_match_all($re, $input, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { // Initialize variables $tmp = array(); $out = ''; $start = 0; foreach ($matches as $idx => $m) { $pos = $m[0][1]; $charset = $m[1][0]; $encoding = $m[2][0]; $text = $m[3][0]; $length = strlen($m[0][0]); // Append everything that is before the text to be decoded if ($start != $pos) { $substr = substr($input, $start, $pos-$start); $out .= rcube_charset::convert($substr, $default_charset); $start = $pos; } $start += $length; // Per RFC2047, each string part "MUST represent an integral number // of characters . A multi-octet character may not be split across // adjacent encoded-words." However, some mailers break this, so we // try to handle characters spanned across parts anyway by iterating // through and aggregating sequential encoded parts with the same // character set and encoding, then perform the decoding on the // aggregation as a whole. $tmp[] = $text; if ($next_match = $matches[$idx+1]) { if ($next_match[0][1] == $start && $next_match[1][0] == $charset && $next_match[2][0] == $encoding ) { continue; } } $count = count($tmp); $text = ''; // Decode and join encoded-word's chunks if ($encoding == 'B' || $encoding == 'b') { // base64 must be decoded a segment at a time for ($i=0; $i<$count; $i++) $text .= base64_decode($tmp[$i]); } else { //if ($encoding == 'Q' || $encoding == 'q') { // quoted printable can be combined and processed at once for ($i=0; $i<$count; $i++) $text .= $tmp[$i]; $text = str_replace('_', ' ', $text); $text = quoted_printable_decode($text); } $out .= rcube_charset::convert($text, $charset); $tmp = array(); } // add the last part of the input string if ($start != strlen($input)) { $out .= rcube_charset::convert(substr($input, $start), $default_charset); } // return the results return $out; } // no encoding information, use fallback return rcube_charset::convert($input, $default_charset); } /** * Decode a mime part * * @param string $input Input string * @param string $encoding Part encoding * @return string Decoded string */ public static function decode($input, $encoding = '7bit') { switch (strtolower($encoding)) { case 'quoted-printable': return quoted_printable_decode($input); case 'base64': return base64_decode($input); case 'x-uuencode': case 'x-uue': case 'uue': case 'uuencode': return convert_uudecode($input); case '7bit': default: return $input; } } /** * Split RFC822 header string into an associative array * @access private */ public static function parse_headers($headers) { $a_headers = array(); $headers = preg_replace('/\r?\n(\t| )+/', ' ', $headers); $lines = explode("\n", $headers); $c = count($lines); for ($i=0; $i<$c; $i++) { if ($p = strpos($lines[$i], ': ')) { $field = strtolower(substr($lines[$i], 0, $p)); $value = trim(substr($lines[$i], $p+1)); if (!empty($value)) $a_headers[$field] = $value; } } return $a_headers; } /** * @access private */ private static function parse_address_list($str, $decode = true, $fallback = null) { // remove any newlines and carriage returns before $str = preg_replace('/\r?\n(\s|\t)?/', ' ', $str); // extract list items, remove comments $str = self::explode_header_string(',;', $str, true); $result = array(); // simplified regexp, supporting quoted local part $email_rx = '(\S+|("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+"))@\S+'; foreach ($str as $key => $val) { $name = ''; $address = ''; $val = trim($val); if (preg_match('/(.*)<('.$email_rx.')>$/', $val, $m)) { $address = $m[2]; $name = trim($m[1]); } else if (preg_match('/^('.$email_rx.')$/', $val, $m)) { $address = $m[1]; $name = ''; } // special case (#1489092) else if (preg_match('/(\s*<MAILER-DAEMON>)$/', $val, $m)) { $address = 'MAILER-DAEMON'; $name = substr($val, 0, -strlen($m[1])); } else { $name = $val; } // dequote and/or decode name if ($name) { if ($name[0] == '"' && $name[strlen($name)-1] == '"') { $name = substr($name, 1, -1); $name = stripslashes($name); } if ($decode) { $name = self::decode_header($name, $fallback); } } if (!$address && $name) { $address = $name; } if ($address) { $result[$key] = array('name' => $name, 'address' => $address); } } return $result; } /** * Explodes header (e.g. address-list) string into array of strings * using specified separator characters with proper handling * of quoted-strings and comments (RFC2822) * * @param string $separator String containing separator characters * @param string $str Header string * @param bool $remove_comments Enable to remove comments * * @return array Header items */ public static function explode_header_string($separator, $str, $remove_comments = false) { $length = strlen($str); $result = array(); $quoted = false; $comment = 0; $out = ''; for ($i=0; $i<$length; $i++) { // we're inside a quoted string if ($quoted) { if ($str[$i] == '"') { $quoted = false; } else if ($str[$i] == "\\") { if ($comment <= 0) { $out .= "\\"; } $i++; } } // we are inside a comment string else if ($comment > 0) { if ($str[$i] == ')') { $comment--; } else if ($str[$i] == '(') { $comment++; } else if ($str[$i] == "\\") { $i++; } continue; } // separator, add to result array else if (strpos($separator, $str[$i]) !== false) { if ($out) { $result[] = $out; } $out = ''; continue; } // start of quoted string else if ($str[$i] == '"') { $quoted = true; } // start of comment else if ($remove_comments && $str[$i] == '(') { $comment++; } if ($comment <= 0) { $out .= $str[$i]; } } if ($out && $comment <= 0) { $result[] = $out; } return $result; } /** * Interpret a format=flowed message body according to RFC 2646 * * @param string $text Raw body formatted as flowed text * * @return string Interpreted text with unwrapped lines and stuffed space removed */ public static function unfold_flowed($text) { $text = preg_split('/\r?\n/', $text); $last = -1; $q_level = 0; foreach ($text as $idx => $line) { if (preg_match('/^(>+)/', $line, $m)) { // remove quote chars $q = strlen($m[1]); $line = preg_replace('/^>+/', '', $line); // remove (optional) space-staffing $line = preg_replace('/^ /', '', $line); // The same paragraph (We join current line with the previous one) when: // - the same level of quoting // - previous line was flowed // - previous line contains more than only one single space (and quote char(s)) if ($q == $q_level && isset($text[$last]) && $text[$last][strlen($text[$last])-1] == ' ' && !preg_match('/^>+ {0,1}$/', $text[$last]) ) { $text[$last] .= $line; unset($text[$idx]); } else { $last = $idx; } } else { $q = 0; if ($line == '-- ') { $last = $idx; } else { // remove space-stuffing $line = preg_replace('/^\s/', '', $line); if (isset($text[$last]) && $line && $text[$last] != '-- ' && $text[$last][strlen($text[$last])-1] == ' ' ) { $text[$last] .= $line; unset($text[$idx]); } else { $text[$idx] = $line; $last = $idx; } } } $q_level = $q; } return implode("\r\n", $text); } /** * Wrap the given text to comply with RFC 2646 * * @param string $text Text to wrap * @param int $length Length * @param string $charset Character encoding of $text * * @return string Wrapped text */ public static function format_flowed($text, $length = 72, $charset=null) { $text = preg_split('/\r?\n/', $text); foreach ($text as $idx => $line) { if ($line != '-- ') { if (preg_match('/^(>+)/', $line, $m)) { // remove quote chars $level = strlen($m[1]); $line = preg_replace('/^>+/', '', $line); // remove (optional) space-staffing and spaces before the line end $line = preg_replace('/(^ | +$)/', '', $line); $prefix = str_repeat('>', $level) . ' '; $line = $prefix . self::wordwrap($line, $length - $level - 2, " \r\n$prefix", false, $charset); } else if ($line) { $line = self::wordwrap(rtrim($line), $length - 2, " \r\n", false, $charset); // space-stuffing $line = preg_replace('/(^|\r\n)(From| |>)/', '\\1 \\2', $line); } $text[$idx] = $line; } } return implode("\r\n", $text); } /** * Improved wordwrap function with multibyte support. * The code is based on Zend_Text_MultiByte::wordWrap(). * * @param string $string Text to wrap * @param int $width Line width * @param string $break Line separator * @param bool $cut Enable to cut word * @param string $charset Charset of $string * @param bool $wrap_quoted When enabled quoted lines will not be wrapped * * @return string Text */ public static function wordwrap($string, $width=75, $break="\n", $cut=false, $charset=null, $wrap_quoted=true) { // Note: Never try to use iconv instead of mbstring functions here // Iconv's substr/strlen are 100x slower (#1489113) if ($charset && $charset != RCUBE_CHARSET && function_exists('mb_internal_encoding')) { mb_internal_encoding($charset); } // Convert \r\n to \n, this is our line-separator $string = str_replace("\r\n", "\n", $string); $separator = "\n"; // must be 1 character length $result = array(); while (($stringLength = mb_strlen($string)) > 0) { $breakPos = mb_strpos($string, $separator, 0); // quoted line (do not wrap) if ($wrap_quoted && $string[0] == '>') { if ($breakPos === $stringLength - 1 || $breakPos === false) { $subString = $string; $cutLength = null; } else { $subString = mb_substr($string, 0, $breakPos); $cutLength = $breakPos + 1; } } // next line found and current line is shorter than the limit else if ($breakPos !== false && $breakPos < $width) { if ($breakPos === $stringLength - 1) { $subString = $string; $cutLength = null; } else { $subString = mb_substr($string, 0, $breakPos); $cutLength = $breakPos + 1; } } else { $subString = mb_substr($string, 0, $width); // last line if ($breakPos === false && $subString === $string) { $cutLength = null; } else { $nextChar = mb_substr($string, $width, 1); if ($nextChar === ' ' || $nextChar === $separator) { $afterNextChar = mb_substr($string, $width + 1, 1); // Note: mb_substr() does never return False if ($afterNextChar === false || $afterNextChar === '') { $subString .= $nextChar; } $cutLength = mb_strlen($subString) + 1; } else { $spacePos = mb_strrpos($subString, ' ', 0); if ($spacePos !== false) { $subString = mb_substr($subString, 0, $spacePos); $cutLength = $spacePos + 1; } else if ($cut === false) { $spacePos = mb_strpos($string, ' ', 0); if ($spacePos !== false && ($breakPos === false || $spacePos < $breakPos)) { $subString = mb_substr($string, 0, $spacePos); $cutLength = $spacePos + 1; } else if ($breakPos === false) { $subString = $string; $cutLength = null; } else { $subString = mb_substr($string, 0, $breakPos); $cutLength = $breakPos + 1; } } else { $cutLength = $width; } } } } $result[] = $subString; if ($cutLength !== null) { $string = mb_substr($string, $cutLength, ($stringLength - $cutLength)); } else { break; } } if ($charset && $charset != RCUBE_CHARSET && function_exists('mb_internal_encoding')) { mb_internal_encoding(RCUBE_CHARSET); } return implode($break, $result); } /** * A method to guess the mime_type of an attachment. * * @param string $path Path to the file or file contents * @param string $name File name (with suffix) * @param string $failover Mime type supplied for failover * @param boolean $is_stream Set to True if $path contains file contents * @param boolean $skip_suffix Set to True if the config/mimetypes.php mappig should be ignored * * @return string * @author Till Klampaeckel <till@php.net> * @see http://de2.php.net/manual/en/ref.fileinfo.php * @see http://de2.php.net/mime_content_type */ public static function file_content_type($path, $name, $failover = 'application/octet-stream', $is_stream = false, $skip_suffix = false) { $mime_type = null; $mime_magic = rcube::get_instance()->config->get('mime_magic'); $mime_ext = $skip_suffix ? null : @include(RCUBE_CONFIG_DIR . '/mimetypes.php'); // use file name suffix with hard-coded mime-type map if (is_array($mime_ext) && $name) { if ($suffix = substr($name, strrpos($name, '.')+1)) { $mime_type = $mime_ext[strtolower($suffix)]; } } // try fileinfo extension if available if (!$mime_type && function_exists('finfo_open')) { // null as a 2nd argument should be the same as no argument // this however is not true on all systems/versions if ($mime_magic) { $finfo = finfo_open(FILEINFO_MIME, $mime_magic); } else { $finfo = finfo_open(FILEINFO_MIME); } if ($finfo) { if ($is_stream) $mime_type = finfo_buffer($finfo, $path); else $mime_type = finfo_file($finfo, $path); finfo_close($finfo); } } // try PHP's mime_content_type if (!$mime_type && !$is_stream && function_exists('mime_content_type')) { $mime_type = @mime_content_type($path); } // fall back to user-submitted string if (!$mime_type) { $mime_type = $failover; } else { // Sometimes (PHP-5.3?) content-type contains charset definition, // Remove it (#1487122) also "charset=binary" is useless $mime_type = array_shift(preg_split('/[; ]/', $mime_type)); } return $mime_type; } /** * Get mimetype => file extension mapping * * @param string Mime-Type to get extensions for * @return array List of extensions matching the given mimetype or a hash array with ext -> mimetype mappings if $mimetype is not given */ public static function get_mime_extensions($mimetype = null) { static $mime_types, $mime_extensions; // return cached data if (is_array($mime_types)) { return $mimetype ? $mime_types[$mimetype] : $mime_extensions; } // load mapping file $file_paths = array(); if ($mime_types = rcube::get_instance()->config->get('mime_types')) { $file_paths[] = $mime_types; } // try common locations if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { $file_paths[] = 'C:/xampp/apache/conf/mime.types.'; } else { $file_paths[] = '/etc/mime.types'; $file_paths[] = '/etc/httpd/mime.types'; $file_paths[] = '/etc/httpd2/mime.types'; $file_paths[] = '/etc/apache/mime.types'; $file_paths[] = '/etc/apache2/mime.types'; $file_paths[] = '/usr/local/etc/httpd/conf/mime.types'; $file_paths[] = '/usr/local/etc/apache/conf/mime.types'; } foreach ($file_paths as $fp) { if (@is_readable($fp)) { $lines = file($fp, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); break; } } $mime_types = $mime_extensions = array(); $regex = "/([\w\+\-\.\/]+)\t+([\w\s]+)/i"; foreach((array)$lines as $line) { // skip comments or mime types w/o any extensions if ($line[0] == '#' || !preg_match($regex, $line, $matches)) continue; $mime = $matches[1]; foreach (explode(' ', $matches[2]) as $ext) { $ext = trim($ext); $mime_types[$mime][] = $ext; $mime_extensions[$ext] = $mime; } } // fallback to some well-known types most important for daily emails if (empty($mime_types)) { $mime_extensions = (array) @include(RCUBE_CONFIG_DIR . '/mimetypes.php'); foreach ($mime_extensions as $ext => $mime) { $mime_types[$mime][] = $ext; } } // Add some known aliases that aren't included by some mime.types (#1488891) // the order is important here so standard extensions have higher prio $aliases = array( 'image/gif' => array('gif'), 'image/png' => array('png'), 'image/x-png' => array('png'), 'image/jpeg' => array('jpg', 'jpeg', 'jpe'), 'image/jpg' => array('jpg', 'jpeg', 'jpe'), 'image/pjpeg' => array('jpg', 'jpeg', 'jpe'), 'image/tiff' => array('tif'), 'message/rfc822' => array('eml'), 'text/x-mail' => array('eml'), ); foreach ($aliases as $mime => $exts) { $mime_types[$mime] = array_unique(array_merge((array) $mime_types[$mime], $exts)); foreach ($exts as $ext) { if (!isset($mime_extensions[$ext])) { $mime_extensions[$ext] = $mime; } } } return $mimetype ? $mime_types[$mimetype] : $mime_extensions; } /** * Detect image type of the given binary data by checking magic numbers. * * @param string $data Binary file content * * @return string Detected mime-type or jpeg as fallback */ public static function image_content_type($data) { $type = 'jpeg'; if (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png'; else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif'; else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico'; // else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg'; return 'image/' . $type; } }
mit
alinasmirnova/BenchmarkDotNet
src/BenchmarkDotNet/Parameters/ParameterInstances.cs
1334
using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Extensions; namespace BenchmarkDotNet.Parameters { public class ParameterInstances { public IReadOnlyList<ParameterInstance> Items { get; } public int Count => Items.Count; public ParameterInstance this[int index] => Items[index]; public object this[string name] => Items.FirstOrDefault(item => item.Name == name)?.Value; private string printInfo; public ParameterInstances(IReadOnlyList<ParameterInstance> items) { Items = items; } public string FolderInfo => string.Join("_", Items.Select(p => $"{p.Name}-{p.ToDisplayText()}")).AsValidFileName(); public string DisplayInfo => Items.Any() ? "[" + string.Join(", ", Items.Select(p => $"{p.Name}={p.ToDisplayText()}")) + "]" : ""; public string ValueInfo => Items.Any() ? "[" + string.Join(", ", Items.Select(p => $"{p.Name}={p.Value?.ToString() ?? ParameterInstance.NullParameterTextRepresentation}")) + "]" : ""; public string PrintInfo => printInfo ?? (printInfo = string.Join("&", Items.Select(p => $"{p.Name}={p.ToDisplayText()}"))); public ParameterInstance GetArgument(string name) => Items.Single(parameter => parameter.IsArgument && parameter.Name == name); } }
mit
yonglehou/autorest
AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Models/Widget.cs
894
// 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 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDictionary.Models { using System; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; /// <summary> /// </summary> public partial class Widget { /// <summary> /// </summary> [JsonProperty(PropertyName = "integer")] public int? Integer { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "string")] public string StringProperty { get; set; } } }
mit
innogames/gitlabhq
spec/support/shared_examples/features/integrations/user_activates_mattermost_slash_command_integration_shared_examples.rb
1053
# frozen_string_literal: true RSpec.shared_examples 'user activates the Mattermost Slash Command integration' do it 'shows a help message' do expect(page).to have_content('Use this service to perform common') end it 'shows a token placeholder' do token_placeholder = find_field('service_token')['placeholder'] expect(token_placeholder).to eq('XXxxXXxxXXxxXXxxXXxxXXxx') end it 'redirects to the integrations page after saving but not activating' do token = ('a'..'z').to_a.join fill_in 'service_token', with: token click_active_checkbox click_save_integration expect(current_path).to eq(edit_path) expect(page).to have_content('Mattermost slash commands settings saved, but not active.') end it 'redirects to the integrations page after activating' do token = ('a'..'z').to_a.join fill_in 'service_token', with: token click_save_integration expect(current_path).to eq(edit_path) expect(page).to have_content('Mattermost slash commands settings saved and active.') end end
mit
stuhood/specs
src/test/scala/org/specs/matcher/numericMatchersSpec.scala
5411
/** * Copyright (c) 2007-2011 Eric Torreborre <etorreborre@yahoo.com> * * 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. Neither the name of specs nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * 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 org.specs.matcher import org.specs.runner._ class numericMatchersSpec extends MatchersSpecification { "Numeric matchers" should { "provide a 'be_<' matcher: 1 must be_<(2)" in { 1 must be_<(2) expectation(1 must be_<(1)) must failWith("1 is not less than 1") expectation(1 aka "the number" must be_<(1)) must failWith("the number 1 is not less than 1") expectation(1.0 must be_<(1.0)) must failWith("1.0 is not less than 1.0") } "provide a 'beLessThan' matcher: 1 must beLessThan(2)" in { 1 must beLessThan(2) expectation(1 must beLessThan(1)) must failWith("1 is not less than 1") expectation(1 aka "the number" must beLessThan(1)) must failWith("the number 1 is not less than 1") } "provide a 'be_<=' matcher: 1 must be_<=(2)" in { 2 must be_<=(2) expectation(1 must be_<=(0)) must failWith("1 is greater than 0") expectation(1 aka "the number" must be_<=(0)) must failWith("the number 1 is greater than 0") } "provide a 'beLessThanOrEqualTo' matcher: 1 must beLessThanOrEqual(2)" in { 2 must beLessThanOrEqualTo(2) expectation(1 must beLessThanOrEqualTo(0)) must failWith("1 is greater than 0") expectation(1 aka "the number" must beLessThanOrEqualTo(0)) must failWith("the number 1 is greater than 0") } "provide a 'be_>' matcher: 2 must be_>(1)" in { 2 must be_>(1) expectation(1 must be_>(2)) must failWith("1 is less than 2") expectation(1 aka "the number" must be_>(2)) must failWith("the number 1 is less than 2") expectation(1.0 must be_>(2.0)) must failWith("1.0 is less than 2.0") } "provide a 'beGreaterThan' matcher: 2 must beGreaterThan(1)" in { 2 must beGreaterThan(1) expectation(1 must beGreaterThan(2)) must failWith("1 is less than 2") expectation(1 aka "the number" must beGreaterThan(2)) must failWith("the number 1 is less than 2") } "provide a 'be_>=' matcher: 2 must be_>=(1)" in { 2 must be_>=(1) expectation(0 must be_>=(1)) must failWith("0 is less than 1") expectation(0 aka "the number" must be_>=(1)) must failWith("the number 0 is less than 1") } "provide a 'beGreaterThanOrEqualTo' matcher: 2 must beGreaterThanOrEqualTo(1)" in { 2 must beGreaterThanOrEqualTo(1) expectation(0 must beGreaterThanOrEqualTo(1)) must failWith("0 is less than 1") expectation(0 aka "the number" must beGreaterThanOrEqualTo(1)) must failWith("the number 0 is less than 1") } "provide a 'must beCloseTo' matcher: 1.2 must beCloseTo(1.0, 0.5)" in { 1.2 must beCloseTo(1.0, 0.5) 1 must beCloseTo(1, 1) expectation(1.2 must beCloseTo(1.0, 0.1)) must failWith("1.2 is not close to 1.0 +/- 0.1") expectation(1.2 aka "the number" must beCloseTo(1.0, 0.1)) must failWith("the number 1.2 is not close to 1.0 +/- 0.1") expectation(1.2 must not(beCloseTo(1.0, 0.2))) must failWith("1.2 is close to 1.0 +/- 0.2") } "provide a 'must beCloseTo' matcher: 1.2 must beCloseTo(1.0 +/- 0.5)" in { 1.2 must be closeTo (1.0 +/- 0.5) } "provide a 'be <' matcher" in { 1 must be <(2) } "provide a 'be lessThan' matcher" in { 1 must be lessThan(2) } "provide a 'be <=' matcher" in { 2 must be <=(2) } "provide a 'be lessThanOrEqualTo' matcher" in { 2 must be lessThanOrEqualTo(2) } "provide a 'be >(1)' matcher" in { 2 must be >(1) expectation(2 must be >(2)) must failWith("2 is equal to 2") } "provide a 'be > 1' matcher" in { 2 must be > 1 expectation(2 must be > 2) must failWith("2 is equal to 2") } "provide a 'be greaterThan' matcher" in { 2 must be greaterThan(1) } "provide a 'be >=' matcher" in { 2 must be >=(1) } "provide a 'be greaterThanOrEqualTo' matcher" in { 2 must be greaterThanOrEqualTo(1) } "provide a 'must be closeTo' matcher" in { 1.2 must be closeTo(1.0, 0.5) } "provide a 'must be ~' matcher" in { 1.2 must be ~(1.0, 0.5) } } }
mit
capslockLtsPool/bp
src/qt/optionsmodel.cpp
9050
#include "optionsmodel.h" #include "bitcoinunits.h" #include <QSettings> #include "init.h" #include "walletdb.h" #include "guiutil.h" OptionsModel::OptionsModel(QObject *parent) : QAbstractListModel(parent) { Init(); } bool static ApplyProxySettings() { QSettings settings; CService addrProxy(settings.value("addrProxy", "127.0.0.1:9050").toString().toStdString()); int nSocksVersion(settings.value("nSocksVersion", 5).toInt()); if (!settings.value("fUseProxy", false).toBool()) { addrProxy = CService(); nSocksVersion = 0; return false; } if (nSocksVersion && !addrProxy.IsValid()) return false; if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); #endif SetNameProxy(addrProxy, nSocksVersion); } return true; } void OptionsModel::Init() { QSettings settings; // These are Qt-only settings: nDisplayUnit = settings.value("nDisplayUnit", BitcoinUnits::BTC).toInt(); bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool(); fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool(); fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool(); nTransactionFee = settings.value("nTransactionFee").toLongLong(); language = settings.value("language", "").toString(); // These are shared with core Bitcoin; we want // command-line options to override the GUI settings: if (settings.contains("fUseUPnP")) SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()); if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool()) SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()); if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool()) SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString()); if (settings.contains("detachDB")) SoftSetBoolArg("-detachdb", settings.value("detachDB").toBool()); if (!language.isEmpty()) SoftSetArg("-lang", language.toStdString()); } bool OptionsModel::Upgrade() { QSettings settings; if (settings.contains("bImportFinished")) return false; // Already upgraded settings.setValue("bImportFinished", true); // Move settings from old wallet.dat (if any): CWalletDB walletdb("wallet.dat"); QList<QString> intOptions; intOptions << "nDisplayUnit" << "nTransactionFee"; foreach(QString key, intOptions) { int value = 0; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } QList<QString> boolOptions; boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP"; foreach(QString key, boolOptions) { bool value = false; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } try { CAddress addrProxyAddress; if (walletdb.ReadSetting("addrProxy", addrProxyAddress)) { settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } catch (std::ios_base::failure &e) { // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress CService addrProxy; if (walletdb.ReadSetting("addrProxy", addrProxy)) { settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } ApplyProxySettings(); Init(); return true; } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return QVariant(GUIUtil::GetStartOnSystemStartup()); case MinimizeToTray: return QVariant(fMinimizeToTray); case MapPortUPnP: return settings.value("fUseUPnP", GetBoolArg("-upnp", true)); case MinimizeOnClose: return QVariant(fMinimizeOnClose); case ProxyUse: return settings.value("fUseProxy", false); case ProxyIP: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(QString::fromStdString(proxy.first.ToStringIP())); else return QVariant(QString::fromStdString("127.0.0.1")); } case ProxyPort: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.first.GetPort()); else return QVariant(9050); } case ProxySocksVersion: return settings.value("nSocksVersion", 5); case Fee: return QVariant(nTransactionFee); case DisplayUnit: return QVariant(nDisplayUnit); case DisplayAddresses: return QVariant(bDisplayAddresses); case DetachDatabases: return QVariant(bitdb.GetDetach()); case Language: return settings.value("language", ""); default: return QVariant(); } } return QVariant(); } bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: fUseUPnP = value.toBool(); settings.setValue("fUseUPnP", fUseUPnP); MapPort(); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; case ProxyUse: settings.setValue("fUseProxy", value.toBool()); ApplyProxySettings(); break; case ProxyIP: { proxyType proxy; proxy.first = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); CNetAddr addr(value.toString().toStdString()); proxy.first.SetIP(addr); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxyPort: { proxyType proxy; proxy.first = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); proxy.first.SetPort(value.toInt()); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxySocksVersion: { proxyType proxy; proxy.second = 5; GetProxy(NET_IPV4, proxy); proxy.second = value.toInt(); settings.setValue("nSocksVersion", proxy.second); successful = ApplyProxySettings(); } break; case Fee: nTransactionFee = value.toLongLong(); settings.setValue("nTransactionFee", nTransactionFee); break; case DisplayUnit: nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); break; case DisplayAddresses: bDisplayAddresses = value.toBool(); settings.setValue("bDisplayAddresses", bDisplayAddresses); break; case DetachDatabases: { bool fDetachDB = value.toBool(); bitdb.SetDetach(fDetachDB); settings.setValue("detachDB", fDetachDB); } break; case Language: settings.setValue("language", value); break; default: break; } } emit dataChanged(index, index); return successful; } qint64 OptionsModel::getTransactionFee() { return nTransactionFee; } bool OptionsModel::getMinimizeToTray() { return fMinimizeToTray; } bool OptionsModel::getMinimizeOnClose() { return fMinimizeOnClose; } int OptionsModel::getDisplayUnit() { return nDisplayUnit; } bool OptionsModel::getDisplayAddresses() { return bDisplayAddresses; }
mit
mcliment/DefinitelyTyped
types/dom-serial/index.d.ts
1766
// Type definitions for non-npm package Web Serial API based on spec and Chromium implementation 0.1 // Project: https://wicg.github.io/serial/ // Definitions by: Maciej Mroziński <https://github.com/maciejmrozinski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped type EventHandler = (event: Event) => void; interface SerialPortInfoBase { serialNumber: string; manufacturer: string; locationId: string; vendorId: string; vendor: string; productId: string; product: string; } interface SerialPortFilter { usbVendorId: number; usbProductId?: number; } interface SerialPortInfo extends SerialPortInfoBase, SerialPortFilter {} // mix spec and Chromium implementation type ParityType = 'none' | 'even' | 'odd' | 'mark' | 'space'; type FlowControlType = 'none' | 'hardware'; interface SerialOptions { baudrate: number; // Chromium implementation (spec: baudRate) dataBits?: number; stopBits?: number; parity?: ParityType; buffersize?: number; // Chromium implementation (spec: bufferSize) flowControl?: FlowControlType; } interface SerialPort { open(options: SerialOptions): Promise<void>; readonly readable: ReadableStream; // Chromium implementation (spec: in) readonly writable: WritableStream; // Chromium implementation (spec: out) getInfo(): Partial<SerialPortInfo>; } interface SerialPortRequestOptions { filters: SerialPortFilter[]; } interface Serial extends EventTarget { onconnect: EventHandler; ondisconnect: EventHandler; getPorts(): Promise<SerialPort[]>; requestPort(options?: SerialPortRequestOptions): Promise<SerialPort>; // Chromium implementation (spec: SerialOptions) } interface Navigator { readonly serial: Serial; }
mit
jeraldfeller/jbenterprises
google-adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201609/cm/BiddingStrategyPage.php
1123
<?php namespace Google\AdsApi\AdWords\v201609\cm; /** * This file was generated from WSDL. DO NOT EDIT. */ class BiddingStrategyPage extends \Google\AdsApi\AdWords\v201609\cm\Page { /** * @var \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy[] $entries */ protected $entries = null; /** * @param int $totalNumEntries * @param string $PageType * @param \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy[] $entries */ public function __construct($totalNumEntries = null, $PageType = null, array $entries = null) { parent::__construct($totalNumEntries, $PageType); $this->entries = $entries; } /** * @return \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy[] */ public function getEntries() { return $this->entries; } /** * @param \Google\AdsApi\AdWords\v201609\cm\SharedBiddingStrategy[] $entries * @return \Google\AdsApi\AdWords\v201609\cm\BiddingStrategyPage */ public function setEntries(array $entries) { $this->entries = $entries; return $this; } }
mit
shutchings/azure-sdk-for-net
src/SDKs/Automation/Management.Automation/Generated/Models/OperationDisplay.cs
2414
// 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. namespace Microsoft.Azure.Management.Automation.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Automation; using Newtonsoft.Json; using System.Linq; /// <summary> /// Provider, Resource and Operation values /// </summary> public partial class OperationDisplay { /// <summary> /// Initializes a new instance of the OperationDisplay class. /// </summary> public OperationDisplay() { CustomInit(); } /// <summary> /// Initializes a new instance of the OperationDisplay class. /// </summary> /// <param name="provider">Service provider: /// Microsoft.Automation</param> /// <param name="resource">Resource on which the operation is /// performed: Runbooks, Jobs etc.</param> /// <param name="operation">Operation type: Read, write, delete, /// etc.</param> public OperationDisplay(string provider = default(string), string resource = default(string), string operation = default(string)) { Provider = provider; Resource = resource; Operation = operation; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets service provider: Microsoft.Automation /// </summary> [JsonProperty(PropertyName = "provider")] public string Provider { get; set; } /// <summary> /// Gets or sets resource on which the operation is performed: /// Runbooks, Jobs etc. /// </summary> [JsonProperty(PropertyName = "resource")] public string Resource { get; set; } /// <summary> /// Gets or sets operation type: Read, write, delete, etc. /// </summary> [JsonProperty(PropertyName = "operation")] public string Operation { get; set; } } }
mit
verdan/material-ui
docs/src/app/components/PropTypeDescription.js
4867
import React, {Component, PropTypes} from 'react'; import {parse} from 'react-docgen'; import {parse as parseDoctrine} from 'doctrine'; import MarkdownElement from './MarkdownElement'; import recast from 'recast'; require('./prop-type-description.css'); function getDeprecatedInfo(type) { const deprecatedPropType = 'deprecated(PropTypes.'; const indexStart = type.raw.indexOf(deprecatedPropType); if (indexStart !== -1) { return { propTypes: type.raw.substring(indexStart + deprecatedPropType.length, type.raw.indexOf(',')), explanation: recast.parse(type.raw).program.body[0].expression.arguments[1].value, }; } return false; } function generatePropType(type) { switch (type.name) { case 'func': return 'function'; case 'custom': const deprecatedInfo = getDeprecatedInfo(type); if (deprecatedInfo !== false) { return generatePropType({ name: deprecatedInfo.propTypes, }); } return type.raw; case 'enum': const values = type.value.map((v) => v.value).join('<br>&nbsp;'); return `enum:<br>&nbsp;${values}<br>`; default: return type.name; } } function generateDescription(required, description, type) { let deprecated = ''; if (type.name === 'custom') { const deprecatedInfo = getDeprecatedInfo(type); if (deprecatedInfo) { deprecated = `*Deprecated*. ${deprecatedInfo.explanation}<br><br>`; } } const parsed = parseDoctrine(description); // two new lines result in a newline in the table. all other new lines // must be eliminated to prevent markdown mayhem. const jsDocText = parsed.description.replace(/\n\n/g, '<br>').replace(/\n/g, ' '); if (parsed.tags.some((tag) => tag.title === 'ignore')) return null; let signature = ''; if (type.name === 'func' && parsed.tags.length > 0) { // Remove new lines from tag descriptions to avoid markdown errors. parsed.tags.forEach((tag) => { if (tag.description) { tag.description = tag.description.replace(/\n/g, ' '); } }); // Split up the parsed tags into 'arguments' and 'returns' parsed objects. If there's no // 'returns' parsed object (i.e., one with title being 'returns'), make one of type 'void'. const parsedLength = parsed.tags.length; let parsedArgs = []; let parsedReturns; if (parsed.tags[parsedLength - 1].title === 'returns') { parsedArgs = parsed.tags.slice(0, parsedLength - 1); parsedReturns = parsed.tags[parsedLength - 1]; } else { parsedArgs = parsed.tags; parsedReturns = {type: {name: 'void'}}; } signature += '<br><br>**Signature:**<br>`function('; signature += parsedArgs.map((tag) => `${tag.name}: ${tag.type.name}`).join(', '); signature += `) => ${parsedReturns.type.name}` + '`<br>'; signature += parsedArgs.map((tag) => `*${tag.name}:* ${tag.description}`).join('<br>'); if (parsedReturns.description) { signature += `<br> *returns* (${parsedReturns.type.name}): ${parsedReturns.description}`; } } return `${deprecated} ${jsDocText}${signature}`; } const styles = { footnote: { fontSize: '90%', paddingLeft: '15px', }, }; class PropTypeDescription extends Component { static propTypes = { code: PropTypes.string, header: PropTypes.string.isRequired, }; static defaultProps = { header: '### Properties', }; render() { const { code, header, } = this.props; let requiredProps = 0; let text = `${header} | Name | Type | Default | Description | |:-----|:-----|:-----|:-----|\n`; const componentInfo = parse(code); for (let key in componentInfo.props) { const prop = componentInfo.props[key]; const description = generateDescription(prop.required, prop.description, prop.type); if (description === null) continue; let defaultValue = ''; if (prop.defaultValue) { defaultValue = prop.defaultValue.value.replace(/\n/g, ''); } if (prop.required) { key = `<span style="color: #31a148">${key} \*</span>`; requiredProps += 1; } if (prop.type.name === 'custom') { if (getDeprecatedInfo(prop.type)) { key = `~~${key}~~`; } } text += `| ${key} | ${generatePropType(prop.type)} | ${defaultValue} | ${description} |\n`; } text += 'Other properties (not documented) are applied to the root element.'; const requiredPropFootnote = (requiredProps === 1) ? '* required property' : (requiredProps > 1) ? '* required properties' : ''; return ( <div className="propTypeDescription"> <MarkdownElement text={text} /> <div style={styles.footnote}> {requiredPropFootnote} </div> </div> ); } } export default PropTypeDescription;
mit
corneliusweig/rollup
test/function/samples/deconflict-parameter-defaults/_config.js
100
module.exports = { description: 'consistently deconflict variable names for parameter defaults' };
mit
ENCODE-DCC/dna-me-pipeline
dnanexus/dme-align-pe/resources/usr/bin/mott-trim-pe.py
5028
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2014 Junko Tsuji # This script computes scores based on running sum # algorithm (mott trimming algorithm) to trim 3' # ends of reads, with the score below threshould. from itertools import izip from optparse import OptionParser import sys, os.path, re nPat = re.compile('N', re.IGNORECASE) def checkargs(opts, inFastq, outFastq): if len(inFastq) != len(outFastq): raise Exception("input the same number of input/output files") if len(inFastq) > 1 and len(inFastq) != 2: raise Exception("input two intput/output files for paired-end reads") for out in outFastq: if os.path.exists(out): raise Exception("output " + out + " exists") if opts.fqtype.lower() == "sanger": return 33 if opts.fqtype.lower() == "illumina": return 64 raise Exception("input correct fastq type") def dotrim(entry, cutoff, base, minlen): index = -1 minValue = 100000000 scoreValue = 0 rawseq = entry[1][::-1] rawqual = entry[3][::-1] for i in range(len(rawseq)): qscore = ord(rawqual[i]) - base scoreValue += (qscore - cutoff) if scoreValue < minValue: minValue = scoreValue index = i + 1 if minValue > cutoff: seq = rawseq[::-1] qual = rawqual[::-1] else: seq = rawseq[index:][::-1] qual = rawqual[index:][::-1] L = len(seq) part = "0,"+str(L) if len(nPat.findall(seq)) != L and L >= minlen: return [entry[0]+":"+part, seq, entry[2], qual] else: return [] def readFastq(inFile): entry = [] lcount = 0 for line in open(inFile): line = line.rstrip("\n") if line == "": continue; lcount += 1 entry.append(line) if lcount == 4: yield entry lcount = 0 entry = [] def mottTrim(opts, args): inFastq = args[1].split(",") outFastq = args[0].split(",") base = checkargs(opts, inFastq, outFastq) if len(inFastq) == 2: out1 = open(outFastq[0], "w") out2 = open(outFastq[1], "w") if opts.single_pair == True: sg1 = open(outFastq[0]+".single", "w") sg2 = open(outFastq[1]+".single", "w") for r1, r2 in izip(readFastq(inFastq[0]), readFastq(inFastq[1])): r1 = dotrim(r1, opts.cutoff, base, opts.minlen) r2 = dotrim(r2, opts.cutoff, base, opts.minlen) if r1 != [] and r2 != []: out1.write("\n".join(r1)+"\n") out2.write("\n".join(r2)+"\n") else: if opts.single_pair == True: if r1 == [] and r2 != []: sg2.write("\n".join(r2)+"\n"); if r2 == [] and r1 != []: sg1.write("\n".join(r1)+"\n"); out1.close() out2.close() if opts.single_pair == True: sg1.close() sg2.close() else: out = open(outFastq[0], "w") for r in readFastq(inFastq[0]): r = dotrim(r, opts.cutoff, base, opts.minlen) if r != []: out.write("\n".join(r)+"\n") out.close() if __name__ == "__main__": prog = os.path.basename(sys.argv[0]) usage = "%prog [options] trimmedOut(s) readFastq(s)" description = '''Trim 3' or both ends of reads using mott trimming algorithm. For paired-end reads, input two comma-separated fastq files. Trimmed paired-end reads will be "synchronized" (i.e. all trimmed reads have their pairs).''' op = OptionParser(usage=usage, description=description) op.add_option("-q", "--quality-cutoff", dest="cutoff", type="int", action="store", default=3, help="PHRED quality score cutoff (default=%default)", metavar="VALUE") op.add_option("-m", "--min-length", dest="minlen", type="int", action="store", default=30, help="Minimum length of trimmed reads (default=%default)", metavar="VALUE") op.add_option("-t", "--fastq-type", dest="fqtype", type="string", action="store", default="sanger", help="PHRED quality score format: 'sanger' (base=33), 'illumina' (base=64) (default='%default')", metavar="TYPE") op.add_option("-a", "--single-pair", dest="single_pair", action="store_true", default=False, help="Print single paired-end reads (i.e. reads which lose their pairs)") (opts, args) = op.parse_args() if len(args) != 2: raise Exception("specify input/output file names") try: mottTrim(opts, args) except KeyboardInterrupt: pass except Exception, e: sys.exit(prog + ": error: " + str(e))
mit
rippo/testing.casperjs.presentation.vscode.50mins
Tests/Page.Object.Pattern.Typescript/Typings/phantomjs.d.ts
8420
// Type definitions for PhantomJS v1.9.0 API // Project: https://github.com/ariya/phantomjs/wiki/API-Reference // Definitions by: Jed Hunsaker <https://github.com/jedhunsaker>, Mike Keesey <https://github.com/keesey> // Definitions: https://github.com/borisyankov/DefinitelyTyped declare function require(module: string): any; declare var phantom: Phantom; interface Phantom { // Properties args: string[]; // DEPRECATED cookies: Cookie[]; cookiesEnabled: boolean; libraryPath: string; page : any; scriptName: string; // DEPRECATED version: { major: number; minor: number; patch: number; }; // Functions addCookie(cookie: Cookie): boolean; clearCookies(): void; deleteCookie(cookieName: string): boolean; exit(returnValue?: any): boolean; injectJs(filename: string): boolean; // Callbacks onError: (msg: string, trace: string[]) => any; } interface System { pid: number; platform: string; os: { architecture: string; name: string; version: string; }; env: { [name: string]: string; }; args: string[]; } interface WebPage { // Properties canGoBack: boolean; canGoForward: boolean; clipRect: ClipRect; content: string; cookies: Cookie[]; customHeaders: { [name: string]: string; }; event: any; // :TODO: elaborate this when documentation improves focusedFrameName: string; frameContent: string; frameName: string; framePlainText: string; frameTitle: string; frameUrl: string; framesCount: number; framesName: any; // :TODO: elaborate this when documentation improves libraryPath: string; navigationLocked: boolean; offlineStoragePath: string; offlineStorageQuota: number; ownsPages: boolean; pages: WebPage[]; pagesWindowName: string; paperSize: PaperSize; plainText: string; scrollPosition: TopLeft; settings: WebPageSettings; title: string; url: string; viewportSize: Size; windowName: string; zoomFactor: number; // Functions addCookie(cookie: Cookie): boolean; childFramesCount(): number; // DEPRECATED childFramesName(): string; // DEPRECATED clearCookies(): void; close(): void; currentFrameName(): string; // DEPRECATED deleteCookie(cookieName: string): boolean; evaluate(fn: Function, ...args: any[]): any; evaluateAsync(fn: Function): void; evaluateJavascript(str: string): any; // :TODO: elaborate this when documentation improves getPage(windowName: string): WebPage; go(index: number): void; goBack(): void; goForward(): void; includeJs(url: string, callback: Function): void; injectJs(filename: string): boolean; open(url: string, callback: (status: string) => any): void; open(url: string, method: string, callback: (status: string) => any): void; open(url: string, method: string, data: any, callback: (status: string) => any): void; openUrl(url: string, httpConf: any, settings: any): void; // :TODO: elaborate this when documentation improves release(): void; // DEPRECATED reload(): void; render(filename: string): void; renderBase64(format: string): string; sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string): void; sendEvent(keyboardEventType: string, keyOrKeys: any, aNull?: any, bNull?: any, modifier?: number): void; setContent(content: string, url: string): void; stop(): void; switchToFocusedFrame(): void; switchToFrame(frameName: string): void; switchToFrame(framePosition: number): void; switchToChildFrame(frameName: string): void; switchToChildFrame(framePosition: number): void; switchToMainFrame(): void; // DEPRECATED switchToParentFrame(): void; // DEPRECATED uploadFile(selector: string, filename: string): void; // Callbacks onAlert: (msg: string) => any; onCallback: Function; // EXPERIMENTAL onClosing: (closingPage: WebPage) => any; onConfirm: (msg: string) => boolean; onConsoleMessage: (msg: string, lineNum?: number, sourceId?: string) => any; onError: (msg: string, trace: string[]) => any; onFilePicker: (oldFile: string) => string; onInitialized: () => any; onLoadFinished: (status: string) => any; onLoadStarted: () => any; onNavigationRequested: (url: string, type: string, willNavigate: boolean, main: boolean) => any; onPageCreated: (newPage: WebPage) => any; onPrompt: (msg: string, defaultVal: string) => string; onResourceError: (resourceError: ResourceError) => any; onResourceReceived: (response: ResourceResponse) => any; onResourceRequested: (requestData: ResourceRequest, networkRequest: NetworkRequest) => any; onUrlChanged: (targetUrl: string) => any; // Callback triggers closing(closingPage: WebPage): void; initialized(): void; javaScriptAlertSent(msg: string): void; javaScriptConsoleMessageSent(msg: string, lineNum?: number, sourceId?: string): void; loadFinished(status: string): void; loadStarted(): void; navigationRequested(url: string, type: string, willNavigate: boolean, main: boolean): void; rawPageCreated(newPage: WebPage): void; resourceReceived(response: ResourceResponse): void; resourceRequested(requestData: ResourceRequest, networkRequest: NetworkRequest): void; urlChanged(targetUrl: string): void; } interface ResourceError { id: number; url: string; errorCode: string; errorString: string; } interface ResourceResponse { id: number; url: string; time: Date; headers: { [name: string]: string; }; bodySize: number; contentType?: string; redirectURL?: string; stage: string; status: number; statusText: string; } interface ResourceRequest { id: number; method: string; url: string; time: Date; headers: { [name: string]: string; }; } interface NetworkRequest { abort(): void; changeUrl(url: string): void; setHeader(name: string, value: string): void; } interface PaperSize { width?: string; height?: string; border: string; format?: string; orientation?: string; } interface WebPageSettings { javascriptEnabled: boolean; loadImages: boolean; localToRemoteUrlAccessEnabled: boolean; userAgent: string; userName: string; password: string; XSSAuditingEnabled: boolean; webSecurityEnabled: boolean; resourceTimeout: number; } interface FileSystem { // Properties separator: string; workingDirectory: string; // Functions // Query Functions list(path: string): string[]; absolute(path: string): string; exists(path: string): boolean; isDirectory(path: string): boolean; isFile(path: string): boolean; isAbsolute(path: string): boolean; isExecutable(path: string): boolean; isReadable(path: string): boolean; isWritable(path: string): boolean; isLink(path: string): boolean; readLink(path: string): string; // Directory Functions changeWorkingDirectory(path: string): void; makeDirectory(path: string): void; makeTree(path: string): void; removeDirectory(path: string): void; removeTree(path: string): void; copyTree(source: string, destination: string): void; // File Functions open(path: string, mode: string): Stream; open(path: string, options: { mode: string; charset?: string; }): Stream; read(path: string): string; write(path: string, content: string, mode: string): void; size(path: string): number; remove(path: string): void; copy(source: string, destination: string): void; move(source: string, destination: string): void; touch(path: string): void; } interface Stream { atEnd(): boolean; close(): void; flush(): void; read(): string; readLine(): string; seek(position: number): void; write(data: string): void; writeLine(data: string): void; } interface WebServer { port: number; listen(port: number, cb?: (request: WebServerRequest, response: WebServerResponse) => void): boolean; listen(ipAddressPort: string, cb?: (request: WebServerRequest, response: WebServerResponse) => void): boolean; close(): void; } interface WebServerRequest { method: string; url: string; httpVersion: number; headers: { [name: string]: string; }; post: string; postRaw: string; } interface WebServerResponse { headers: { [name: string]: string; }; setHeader(name: string, value: string): void; header(name: string): string; statusCode: number; setEncoding(encoding: string): void; write(data: string): void; writeHead(statusCode: number, headers?: { [name: string]: string; }): void; close(): void; closeGracefully(): void; } interface TopLeft { top: number; left: number; } interface Size { width: number; height: number; } interface ClipRect extends TopLeft, Size { } interface Cookie { name: string; value: string; domain?: string; }
mit
Xannn94/of
app/Modules/Search/Resources/Views/message.blade.php
263
@extends('layouts.inner') @section('content') @if($errors->has('query')) @foreach($errors->get('query') as $error) <div class="alert alert-danger"> {{ $error }} </div> @endforeach @endif @endsection
mit
Soullivaneuh/alice
src/Generator/Resolver/ResolvingContext.php
2036
<?php /* * This file is part of the Alice package. * * (c) Nelmio <hello@nelm.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Nelmio\Alice\Generator\Resolver; use Nelmio\Alice\Throwable\Exception\Generator\Resolver\CircularReferenceException; use Nelmio\Alice\Throwable\Exception\Generator\Resolver\CircularReferenceExceptionFactory; /** * Counter to keep track of the parameters, fixtures etc. being resolved and detect circular references. */ final class ResolvingContext { /** * @var array */ private $resolving = []; public function __construct(string $key = null) { if (null !== $key) { $this->add($key); } } /** * Returns the existing instance if is an object or create a new one otherwise. It also ensure that the key will be * added also it won't increment the counter if already present. * * @param self|null $resolving * @param string $key * * @return self */ public static function createFrom(self $resolving = null, string $key): self { $instance = null === $resolving ? new self() : $resolving; if (false === $instance->has($key)) { $instance->add($key); } return $instance; } public function has(string $key): bool { return array_key_exists($key, $this->resolving); } public function add(string $key) { $this->resolving[$key] = array_key_exists($key, $this->resolving) ? $this->resolving[$key] + 1 : 1 ; } /** * @param string $key * * @throws CircularReferenceException */ public function checkForCircularReference(string $key) { if (true === $this->has($key) && 1 < $this->resolving[$key]) { throw CircularReferenceExceptionFactory::createForParameter($key, $this->resolving); } } }
mit
virla01/ax-framework
Ocrend/vendor/twig/twig/src/Node/CheckSecurityNode.php
177
<?php namespace Twig\Node; require __DIR__.'/../../lib/Twig/Node/CheckSecurity.php'; if (\false) { class CheckSecurityNode extends \Twig_Node_CheckSecurity { } }
mit
jotson/1gam-jan2013
zoetrope/core/tween.lua
8531
-- Class: Tween -- A tween transitions a property from one state to another -- in in-game time. A tween instance is designed to manage -- many of these transitions at once, in fact. In order for it -- to work properly, it must receive update events, so it must -- be added somewhere in the current view or app. If you are using -- the <View> class, this is already done for you. Tween = Sprite:extend{ tweens = {}, visible = false, active = false, solid = false, -- Property: easers -- These are different methods of easing a tween, and -- can be set via the ease property of an individual tween. -- They should be referred to by their key name, not the property -- (e.g. 'linear', no Tweener.easers.linear). -- See http://www.gizma.com/easing/ for details. easers = { linear = function (elapsed, start, change, duration) return change * elapsed / duration + start end, quadIn = function (elapsed, start, change, duration) elapsed = elapsed / duration return change * elapsed * elapsed + start end, quadOut = function (elapsed, start, change, duration) elapsed = elapsed / duration return - change * elapsed * (elapsed - 2) + start end, quadInOut = function (elapsed, start, change, duration) elapsed = elapsed / (duration / 2) if (elapsed < 1) then return change / 2 * elapsed * elapsed + start else elapsed = elapsed - 1 return - change / 2 * (elapsed * (elapsed - 2) - 1) + start end end }, -- Method: reverseForever -- A utility function; if set via <Promise.andAfter()> for an individual -- tween, it reverses the tween that just happened. Use this to get a tween -- to repeat back and forth indefinitely (e.g. to have something glow). reverseForever = function (tween, tweener) tween.to = tween.from tweener:start(tween.target, tween.property, tween.to, tween.duration, tween.ease):andThen(Tween.reverseForever) end, -- Method: reverseOnce -- A utility function; if set via <Promise.andAfter()> for an individual -- tween, it reverses the tween that just happened-- then stops the tween after that. reverseOnce = function (tween, tweener) tween.to = tween.from tweener:start(tween.target, tween.property, tween.to, tween.duration, tween.ease) end, -- Method: start -- Begins a tweened transition, overriding any existing tween. -- -- Arguments: -- target - target object -- property - Usually, this is a string name of a property of the target object. -- You may also specify a table of getter and setter methods instead, -- i.e. { myGetter, mySetter }. In either case, the property or functions -- must work with either number values, or tables of numbers. -- to - destination value, either number or color table -- duration - how long the tween should last in seconds, default 1 -- ease - function name (in Tween.easers) to use to control how the value changes, default 'linear' -- -- Returns: -- A <Promise> that is fulfilled when the tween completes. If the object is already -- in the state requested, the promise resolves immediately. The tween object returns two -- things to the promise: a table of properties about the tween that match the arguments initially -- passed, and a reference to the Tween that completing the tween. start = function (self, target, property, to, duration, ease) duration = duration or 1 ease = ease or 'linear' local propType = type(property) if STRICT then assert(type(target) == 'table' or type(target) == 'userdata', 'target must be a table or userdata') assert(propType == 'string' or propType == 'number' or propType == 'table', 'property must be a key or table of getter/setter methods') if propType == 'string' or propType == 'number' then assert(target[property], 'no such property ' .. tostring(property) .. ' on target') end assert(type(duration) == 'number', 'duration must be a number') assert(self.easers[ease], 'easer ' .. ease .. ' is not defined') end -- check for an existing tween for this target and property for i, existing in ipairs(self.tweens) do if target == existing.target and property == existing.property then if to == existing.to then return existing.promise else table.remove(self.tweens, i) end end end -- add it tween = { target = target, property = property, propType = propType, to = to, duration = duration, ease = ease } tween.from = self:getTweenValue(tween) tween.type = type(tween.from) -- calculate change; if it's trivial, skip the tween if tween.type == 'number' then tween.change = tween.to - tween.from if math.abs(tween.change) < NEARLY_ZERO then return Promise:new{ state = 'fulfilled', _resolvedWith = { tween, self } } end elseif tween.type == 'table' then tween.change = {} local skip = true for i, value in ipairs(tween.from) do tween.change[i] = tween.to[i] - tween.from[i] if math.abs(tween.change[i]) > NEARLY_ZERO then skip = false end end if skip then return Promise:new{ state = 'fulfilled', _resolvedWith = { tween, self } } end else error('tweened property must either be a number or a table of numbers, is ' .. tween.type) end tween.elapsed = 0 tween.promise = Promise:new() table.insert(self.tweens, tween) self.active = true return tween.promise end, -- Method: status -- Returns how much time is left for a particular tween to run. -- -- Arguments: -- target - target object -- property - name of the property being tweened, or getter -- (as set in the orignal <start()> call) -- -- Returns: -- Either the time left in the tween, or nil if there is -- no tween matching the arguments passed. status = function (self, target, property) for _, t in pairs(self.tweens) do if t.target == target then if t.property == property or (type(t.property) == 'table' and t.property[1] == property) then return t.duration - t.elapsed end end end return nil end, -- Method: stop -- Stops a tween. The promise associated with it will be failed. -- -- Arguments: -- target - tween target -- property - name of property being tweened, or getter (as set in the original <start()> call); -- if omitted, stops all tweens on the target -- -- Returns: -- nothing stop = function (self, target, property) local found = false for i, tween in ipairs(self.tweens) do if tween.target == target and (tween.property == property or (type(tween.property) == 'table' and tween.property[1] == property) or not property) then found = true tween.promise:fail('Tween stopped') table.remove(self.tweens, i) end end if STRICT and not found then local info = debug.getinfo(2, 'Sl') print('Warning: asked to stop a tween, but no active tweens match it (' .. info.short_src .. ', line ' .. info.currentline .. ')') end end, update = function (self, elapsed) for i, tween in ipairs(self.tweens) do self.active = true tween.elapsed = tween.elapsed + elapsed if tween.elapsed >= tween.duration then -- tween is completed self:setTweenValue(tween, tween.to) table.remove(self.tweens, i) tween.promise:fulfill(tween, self) else -- move tween towards finished state if tween.type == 'number' then self:setTweenValue(tween, self.easers[tween.ease](tween.elapsed, tween.from, tween.change, tween.duration)) elseif tween.type == 'table' then local now = {} for i, value in ipairs(tween.from) do now[i] = self.easers[tween.ease](tween.elapsed, tween.from[i], tween.change[i], tween.duration) end self:setTweenValue(tween, now) end end end self.active = (#self.tweens > 0) end, getTweenValue = function (self, tween) if tween.propType == 'string' or tween.propType == 'number' then return tween.target[tween.property] else return tween.property[1](tween.target) end end, setTweenValue = function (self, tween, value) if tween.propType == 'string' or tween.propType == 'number' then tween.target[tween.property] = value else tween.property[2](tween.target, value) end end, __tostring = function (self) local result = 'Tween (' if self.active then result = result .. 'active, ' result = result .. #self.tweens .. ' tweens running' else result = result .. 'inactive' end return result .. ')' end }
mit
chonglou/itpkg_old
db/schema.rb
27480
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20150227031740) do create_table "certificates", force: :cascade do |t| t.text "cert", limit: 65535, null: false t.text "csr", limit: 65535 t.text "encrypted_key", limit: 65535, null: false t.string "encrypted_key_salt", limit: 255, null: false t.string "encrypted_key_iv", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" end create_table "chat_messages", force: :cascade do |t| t.string "to", limit: 255, null: false t.string "body", limit: 1024, null: false t.integer "flag", limit: 4, default: 0, null: false t.datetime "created", null: false t.string "node", limit: 255 t.string "domain", limit: 255 t.string "resource", limit: 255 t.string "subject", limit: 500 end add_index "chat_messages", ["domain"], name: "index_chat_messages_on_domain", using: :btree add_index "chat_messages", ["node"], name: "index_chat_messages_on_node", using: :btree add_index "chat_messages", ["resource"], name: "index_chat_messages_on_resource", using: :btree add_index "chat_messages", ["to"], name: "index_chat_messages_on_to", using: :btree create_table "confirmations", force: :cascade do |t| t.string "subject", limit: 255, null: false t.integer "status", limit: 4, default: 0, null: false t.string "token", limit: 36, null: false t.text "encrypted_extra", limit: 65535, null: false t.string "encrypted_extra_salt", limit: 255, null: false t.string "encrypted_extra_iv", limit: 255, null: false t.integer "user_id", limit: 4, default: 0, null: false t.datetime "deadline", null: false t.datetime "created_at" t.datetime "updated_at" end add_index "confirmations", ["token"], name: "index_confirmations_on_token", unique: true, using: :btree create_table "contacts", force: :cascade do |t| t.integer "user_id", limit: 4, null: false t.string "logo", limit: 255, null: false t.string "username", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" t.string "qq", limit: 255 t.string "wechat", limit: 255 t.string "phone", limit: 255 t.string "fax", limit: 255 t.string "address", limit: 255 t.string "weibo", limit: 255 t.string "linkedin", limit: 255 t.string "facebook", limit: 255 t.string "skype", limit: 255 t.text "others", limit: 65535 end add_index "contacts", ["username"], name: "index_contacts_on_username", using: :btree create_table "dns_acls", force: :cascade do |t| t.string "country", limit: 255 t.string "region", limit: 255, default: "*", null: false t.string "city", limit: 255, default: "*", null: false t.datetime "created_at" t.datetime "updated_at" end add_index "dns_acls", ["city"], name: "index_dns_acls_on_city", using: :btree add_index "dns_acls", ["country", "region", "city"], name: "index_dns_acls_on_country_and_region_and_city", unique: true, using: :btree add_index "dns_acls", ["country"], name: "index_dns_acls_on_country", using: :btree add_index "dns_acls", ["region"], name: "index_dns_acls_on_region", using: :btree create_table "dns_counts", force: :cascade do |t| t.string "zone", limit: 255, null: false t.integer "count", limit: 4, default: 0, null: false t.integer "code", limit: 4, default: 0 t.datetime "created_at" t.datetime "updated_at" end add_index "dns_counts", ["zone"], name: "index_dns_counts_on_zone", using: :btree create_table "dns_records", force: :cascade do |t| t.string "zone", limit: 255, null: false t.string "host", limit: 255, default: "@", null: false t.string "flag", limit: 8, null: false t.text "data", limit: 65535 t.integer "ttl", limit: 4, default: 86400, null: false t.integer "mx_priority", limit: 4 t.integer "refresh", limit: 4 t.integer "retry", limit: 4 t.integer "expire", limit: 4 t.integer "minimum", limit: 4 t.integer "serial", limit: 8 t.string "resp_person", limit: 255 t.string "primary_ns", limit: 255 t.integer "code", limit: 4, default: 0 t.datetime "created_at" t.datetime "updated_at" end add_index "dns_records", ["flag"], name: "index_dns_records_on_flag", using: :btree add_index "dns_records", ["host", "zone", "flag", "code"], name: "index_dns_records_on_host_and_zone_and_flag_and_code", unique: true, using: :btree add_index "dns_records", ["host", "zone"], name: "index_dns_records_on_host_and_zone", using: :btree add_index "dns_records", ["host"], name: "index_dns_records_on_host", using: :btree add_index "dns_records", ["zone"], name: "index_dns_records_on_zone", using: :btree create_table "dns_xfrs", force: :cascade do |t| t.string "zone", limit: 255, null: false t.string "client", limit: 255, null: false t.integer "code", limit: 4, default: 0 t.datetime "created_at" t.datetime "updated_at" end add_index "dns_xfrs", ["client"], name: "index_dns_xfrs_on_client", using: :btree add_index "dns_xfrs", ["zone", "client"], name: "index_dns_xfrs_on_zone_and_client", unique: true, using: :btree add_index "dns_xfrs", ["zone"], name: "index_dns_xfrs_on_zone", using: :btree create_table "documents", force: :cascade do |t| t.integer "project_id", limit: 4, null: false t.string "name", limit: 255, null: false t.string "ext", limit: 5 t.integer "status", limit: 2, default: 0, null: false t.datetime "created_at" t.datetime "updated_at" t.string "avatar", limit: 255, null: false t.integer "size", limit: 4, default: 0, null: false t.text "details", limit: 65535 end create_table "email_aliases", force: :cascade do |t| t.integer "domain_id", limit: 4, null: false t.string "source", limit: 128, null: false t.string "destination", limit: 128, null: false t.datetime "created_at" t.datetime "updated_at" end create_table "email_domains", force: :cascade do |t| t.string "name", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "email_domains", ["name"], name: "index_email_domains_on_name", unique: true, using: :btree create_table "email_users", force: :cascade do |t| t.integer "domain_id", limit: 4, null: false t.string "password", limit: 255, null: false t.string "email", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "email_users", ["email"], name: "index_email_users_on_email", unique: true, using: :btree create_table "feedbacks", force: :cascade do |t| t.string "name", limit: 255 t.string "email", limit: 255 t.string "phone_number", limit: 255 t.text "content", limit: 65535 t.integer "status", limit: 4 t.boolean "active", limit: 1 t.integer "project_id", limit: 4 t.integer "user_id", limit: 4 t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "feedbacks", ["project_id"], name: "index_feedbacks_on_project_id", using: :btree add_index "feedbacks", ["user_id"], name: "index_feedbacks_on_user_id", using: :btree create_table "finance_scores", force: :cascade do |t| t.integer "project_id", limit: 4, null: false t.integer "user_id", limit: 4, null: false t.decimal "val", precision: 10, default: 0, null: false t.integer "tag_id", limit: 4, null: false t.string "title", limit: 255, null: false t.decimal "balance", precision: 10, default: 0, null: false t.datetime "created_at" t.datetime "updated_at" end create_table "finance_tags", force: :cascade do |t| t.integer "project_id", limit: 4, null: false t.string "name", limit: 32, null: false t.datetime "created_at" t.datetime "updated_at" end create_table "histories", force: :cascade do |t| t.string "url", limit: 255, null: false t.text "data", limit: 65535, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "histories", ["url"], name: "index_histories_on_url", using: :btree create_table "logging_nodes", force: :cascade do |t| t.integer "flag", limit: 2, default: 0, null: false t.string "name", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" t.string "vip", limit: 15, null: false end add_index "logging_nodes", ["name"], name: "index_logging_nodes_on_name", using: :btree add_index "logging_nodes", ["vip"], name: "index_logging_nodes_on_vip", unique: true, using: :btree create_table "logging_searches", force: :cascade do |t| t.string "name", limit: 255, null: false t.string "message", limit: 255, default: ".*", null: false t.string "vip", limit: 255, default: ".*", null: false t.string "hostname", limit: 255, default: ".*", null: false t.string "tag", limit: 255, default: ".*", null: false t.datetime "created_at" t.datetime "updated_at" end create_table "logs", force: :cascade do |t| t.integer "user_id", limit: 4, null: false t.string "message", limit: 255, null: false t.datetime "created", null: false end create_table "monitor_nodes", force: :cascade do |t| t.integer "flag", limit: 2, default: 0, null: false t.string "name", limit: 255, null: false t.text "encrypted_cfg", limit: 65535, null: false t.string "encrypted_cfg_salt", limit: 255, null: false t.string "encrypted_cfg_iv", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" t.string "vip", limit: 15, null: false t.integer "status", limit: 2, default: 0, null: false t.integer "space", limit: 4, default: 60, null: false t.datetime "next_run", default: '9999-12-31 23:59:59', null: false end add_index "monitor_nodes", ["name"], name: "index_monitor_nodes_on_name", using: :btree add_index "monitor_nodes", ["vip"], name: "index_monitor_nodes_on_vip", unique: true, using: :btree create_table "node_types", force: :cascade do |t| t.string "name", limit: 255, null: false t.text "dockerfile", limit: 65535, null: false t.integer "creator_id", limit: 4, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "node_types", ["name"], name: "index_node_types_on_name", unique: true, using: :btree create_table "node_users", force: :cascade do |t| t.integer "node_id", limit: 4, null: false t.integer "user_id", limit: 4, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "node_users", ["node_id", "user_id"], name: "index_node_users_on_node_id_and_user_id", unique: true, using: :btree create_table "nodes", force: :cascade do |t| t.integer "creator_id", limit: 4, null: false t.integer "node_type_id", limit: 4, null: false t.integer "name", limit: 4, null: false t.text "encrypted_keys", limit: 65535, null: false t.string "encrypted_keys_salt", limit: 255, null: false t.string "encrypted_keys_iv", limit: 255, null: false t.text "encrypted_cfg", limit: 65535, null: false t.string "encrypted_cfg_salt", limit: 255, null: false t.string "encrypted_cfg_iv", limit: 255, null: false t.integer "status", limit: 4, default: 0, null: false t.string "nid", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "nodes", ["nid"], name: "index_nodes_on_nid", unique: true, using: :btree create_table "notices", force: :cascade do |t| t.integer "user_id", limit: 4, null: false t.text "body", limit: 65535, null: false t.datetime "created_at" t.datetime "updated_at" end create_table "nt_ports", force: :cascade do |t| t.integer "node_type_id", limit: 4, null: false t.integer "s_port", limit: 4, null: false t.boolean "tcp", limit: 1, default: true, null: false t.integer "t_port", limit: 4, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "nt_ports", ["node_type_id", "tcp", "t_port"], name: "index_nt_ports_on_node_type_id_and_tcp_and_t_port", unique: true, using: :btree create_table "nt_templates", force: :cascade do |t| t.string "name", limit: 255, null: false t.text "body", limit: 65535, null: false t.string "mode", limit: 3, default: "400", null: false t.string "owner", limit: 16, default: "root:root", null: false t.integer "node_type_id", limit: 4, null: false t.integer "version", limit: 4, default: 0, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "nt_templates", ["mode"], name: "index_nt_templates_on_mode", using: :btree add_index "nt_templates", ["name"], name: "index_nt_templates_on_name", using: :btree add_index "nt_templates", ["node_type_id", "name"], name: "index_nt_templates_on_node_type_id_and_name", unique: true, using: :btree add_index "nt_templates", ["owner"], name: "index_nt_templates_on_owner", using: :btree create_table "nt_vars", force: :cascade do |t| t.integer "node_type_id", limit: 4, null: false t.string "name", limit: 255, null: false t.integer "flag", limit: 4, default: 0, null: false t.text "def_v", limit: 65535 t.datetime "created_at" t.datetime "updated_at" end add_index "nt_vars", ["node_type_id", "name"], name: "index_nt_vars_on_node_type_id_and_name", unique: true, using: :btree create_table "nt_volumes", force: :cascade do |t| t.integer "node_type_id", limit: 4, null: false t.string "s_path", limit: 255, null: false t.string "t_path", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "nt_volumes", ["node_type_id", "t_path"], name: "index_nt_volumes_on_node_type_id_and_t_path", unique: true, using: :btree create_table "projects", force: :cascade do |t| t.string "name", limit: 255, null: false t.text "details", limit: 65535 t.datetime "created_at" t.datetime "updated_at" t.boolean "active", limit: 1, default: true end add_index "projects", ["name"], name: "index_projects_on_name", using: :btree create_table "repositories", force: :cascade do |t| t.string "name", limit: 16, null: false t.string "title", limit: 255, null: false t.boolean "enable", limit: 1, default: true, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "repositories", ["name"], name: "index_repositories_on_name", unique: true, using: :btree create_table "roles", force: :cascade do |t| t.string "name", limit: 255 t.integer "resource_id", limit: 4 t.string "resource_type", limit: 255 t.datetime "created_at" t.datetime "updated_at" end add_index "roles", ["name", "resource_type", "resource_id"], name: "index_roles_on_name_and_resource_type_and_resource_id", using: :btree add_index "roles", ["name"], name: "index_roles_on_name", using: :btree create_table "rss_sites", force: :cascade do |t| t.string "url", limit: 255, null: false t.string "title", limit: 255 t.string "logo", limit: 255 t.datetime "last_sync" t.datetime "created_at" t.datetime "updated_at" end add_index "rss_sites", ["url"], name: "index_rss_sites_on_url", unique: true, using: :btree create_table "settings", force: :cascade do |t| t.string "var", limit: 255, null: false t.text "value", limit: 65535 t.integer "thing_id", limit: 4 t.string "thing_type", limit: 30 t.datetime "created_at" t.datetime "updated_at" end add_index "settings", ["thing_type", "thing_id", "var"], name: "index_settings_on_thing_type_and_thing_id_and_var", unique: true, using: :btree create_table "ssh_keys", force: :cascade do |t| t.integer "user_id", limit: 4, null: false t.text "public_key", limit: 65535, null: false t.text "encrypted_private_key", limit: 65535, null: false t.string "encrypted_private_key_salt", limit: 255, null: false t.string "encrypted_private_key_iv", limit: 255, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "ssh_keys", ["user_id"], name: "index_ssh_keys_on_user_id", unique: true, using: :btree create_table "stories", force: :cascade do |t| t.string "title", limit: 255, null: false t.integer "project_id", limit: 4, null: false t.integer "point", limit: 4, default: 0, null: false t.integer "status", limit: 1, default: 0, null: false t.text "description", limit: 65535 t.datetime "created_at" t.datetime "updated_at" t.boolean "active", limit: 1, default: true t.datetime "plan_start_time" t.datetime "real_start_time" t.datetime "plan_finish_time" t.datetime "real_finish_time" end create_table "stories_story_tags", id: false, force: :cascade do |t| t.integer "story_id", limit: 4 t.integer "story_tag_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" end create_table "stories_story_types", id: false, force: :cascade do |t| t.integer "story_id", limit: 4 t.integer "story_type_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" end create_table "story_comments", force: :cascade do |t| t.text "content", limit: 65535 t.integer "user_id", limit: 4 t.integer "story_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" t.boolean "active", limit: 1, default: true end add_index "story_comments", ["story_id"], name: "index_story_comments_on_story_id", using: :btree add_index "story_comments", ["user_id"], name: "index_story_comments_on_user_id", using: :btree create_table "story_followers", force: :cascade do |t| t.integer "story_id", limit: 4 t.integer "user_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" end create_table "story_owners", force: :cascade do |t| t.integer "story_id", limit: 4 t.integer "user_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" end create_table "story_tags", force: :cascade do |t| t.string "name", limit: 255 t.string "icon", limit: 255 t.integer "project_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" end create_table "story_types", force: :cascade do |t| t.string "name", limit: 255 t.string "icon", limit: 255 t.integer "project_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" end create_table "task_comments", force: :cascade do |t| t.text "content", limit: 65535 t.integer "user_id", limit: 4 t.integer "task_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" t.boolean "active", limit: 1, default: true end add_index "task_comments", ["task_id"], name: "index_task_comments_on_task_id", using: :btree add_index "task_comments", ["user_id"], name: "index_task_comments_on_user_id", using: :btree create_table "tasks", force: :cascade do |t| t.integer "story_id", limit: 4, null: false t.text "details", limit: 65535, null: false t.datetime "created_at" t.datetime "updated_at" t.integer "priority", limit: 2, default: 0, null: false t.boolean "active", limit: 1, default: true t.datetime "plan_start_time" t.datetime "real_start_time" t.datetime "plan_finish_time" t.datetime "real_finish_time" t.integer "point", limit: 4 t.integer "status", limit: 1 end create_table "translations", force: :cascade do |t| t.integer "zh-CN", limit: 4 t.integer "en", limit: 4 t.string "flag", limit: 8, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "translations", ["flag"], name: "index_translations_on_flag", using: :btree create_table "users", force: :cascade do |t| t.string "email", limit: 255, default: "", null: false t.string "encrypted_password", limit: 255, default: "", null: false t.string "reset_password_token", limit: 255 t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", limit: 4, default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip", limit: 255 t.string "last_sign_in_ip", limit: 255 t.string "confirmation_token", limit: 255 t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.string "unconfirmed_email", limit: 255 t.integer "failed_attempts", limit: 4, default: 0, null: false t.string "unlock_token", limit: 255 t.datetime "locked_at" t.datetime "created_at" t.datetime "updated_at" t.string "label", limit: 255, null: false t.string "first_name", limit: 255 t.string "last_name", limit: 255 t.string "encrypted_chat_password", limit: 255 t.string "encrypted_chat_password_salt", limit: 255 t.string "encrypted_chat_password_iv", limit: 255 t.string "uid", limit: 36, null: false t.string "recent_contacts_ids", limit: 255 end add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true, using: :btree add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree add_index "users", ["label"], name: "index_users_on_label", unique: true, using: :btree add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree add_index "users", ["uid"], name: "index_users_on_uid", unique: true, using: :btree add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true, using: :btree create_table "users_roles", id: false, force: :cascade do |t| t.integer "user_id", limit: 4 t.integer "role_id", limit: 4 end add_index "users_roles", ["user_id", "role_id"], name: "index_users_roles_on_user_id_and_role_id", using: :btree create_table "vpn_logs", force: :cascade do |t| t.string "user", limit: 255, null: false t.string "trusted_ip", limit: 32 t.string "trusted_port", limit: 16 t.string "remote_ip", limit: 32 t.string "remote_port", limit: 16 t.string "message", limit: 255 t.datetime "start_time", null: false t.datetime "end_time", null: false t.float "received", limit: 24, default: 0.0, null: false t.float "sent", limit: 24, default: 0.0, null: false end add_index "vpn_logs", ["user"], name: "index_vpn_logs_on_user", using: :btree create_table "vpn_users", force: :cascade do |t| t.string "name", limit: 255, null: false t.string "email", limit: 255 t.string "phone", limit: 255 t.string "password", limit: 255, null: false t.boolean "online", limit: 1, default: false t.boolean "enable", limit: 1, default: false t.date "start_date", null: false t.date "end_date", null: false t.datetime "created_at" t.datetime "updated_at" end add_index "vpn_users", ["name"], name: "index_vpn_users_on_name", unique: true, using: :btree create_table "wikis", force: :cascade do |t| t.string "title", limit: 255, null: false t.text "body", limit: 65535, null: false t.integer "status", limit: 2, default: 0, null: false t.datetime "created_at" t.datetime "updated_at" end add_index "wikis", ["title"], name: "index_wikis_on_title", using: :btree create_table "wikis_users", id: false, force: :cascade do |t| t.integer "wikis_id", limit: 4 t.datetime "created_at" t.datetime "updated_at" end end
mit
lucasmichot/PHP-CS-Fixer
src/Fixer/Operator/AlignEqualsFixerHelper.php
1769
<?php /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\Operator; use PhpCsFixer\AbstractAlignFixerHelper; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Carlos Cirello <carlos.cirello.nl@gmail.com> * @author Graham Campbell <graham@alt-three.com> */ final class AlignEqualsFixerHelper extends AbstractAlignFixerHelper { /** * {@inheritdoc} */ protected function injectAlignmentPlaceholders(Tokens $tokens, $startAt, $endAt) { for ($index = $startAt; $index < $endAt; ++$index) { $token = $tokens[$index]; if ($token->equals('=')) { $tokens[$index] = new Token(sprintf(self::ALIGNABLE_PLACEHOLDER, $this->deepestLevel).$token->getContent()); continue; } if ($token->isGivenKind(T_FUNCTION)) { ++$this->deepestLevel; continue; } if ($token->equals('(')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->equals('[')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } } } }
mit
shawila/chat-bot
app/helpers/users/omniauth_callback_helper.rb
41
module Users::OmniauthCallbackHelper end
mit
ycwuaa/teamform-seed
app/fish/js/fish.js
3954
teamapp.controller('fishCtrl', ['$scope', "$rootScope", "$firebaseObject", "$firebaseArray", function($scope,$rootScope, $firebaseObject, $firebaseArray) { //FAKE $rootScope.clickedEvent $scope.currentEvent = $rootScope.clickedEvent.$id; $scope.currentUser = $rootScope.currentUser.id; $scope.events = $rootScope.events; $scope.users = $rootScope.users; $scope.teams = $rootScope.teams; var allData = $firebaseObject(firebase.database().ref("/")); $scope.processData=function(allData, currentEventID, currentTeamID, currentUserID){ var events = allData.events; var curEvent = {eventName: events[currentEventID].eventName, eventDescription: events[currentEventID].description, eventBG: events[currentEventID].imageURL}; var teamsCurEvent = []; var teams = allData.teams; //select teams in this event for (var key in teams){ var t = teams[key]; if (t.belongstoEvent == currentEventID && (key == currentTeamID || t.isPrivate == false)){ t.teamID = key; teamsCurEvent.push(t); } } //move my team in the first position for (var i = 0; i < teamsCurEvent.length; i++){ if (teamsCurEvent[i].teamID == currentTeamID){ var temp = teamsCurEvent[0]; teamsCurEvent[0] = teamsCurEvent[i]; teamsCurEvent[i] = temp; } } return {event: curEvent, team: teamsCurEvent, user: allData.users}; } $scope.quitTeam=function(){ $firebaseObject(firebase.database().ref('users/' + $scope.currentUser + '/teamsAsMember/' + $scope.currentTeam)).$remove(); $firebaseObject(firebase.database().ref('teams/' + $scope.currentTeam + '/membersID/' + $scope.currentUser)).$remove(); $firebaseObject(firebase.database().ref('events/' + $scope.currentEvent + '/allTeams/'+ $scope.currentTeam + '/member/' + $scope.currentUser)).$remove(); }; $scope.clickCount = 0; $scope.showBody=function(id){ $(".collapsible-body-"+id).slideToggle(100); $scope.clickCount++; }; allData.$loaded().then(function(data){ $scope.preprocessData(data); }); $scope.preprocessData=function(allData){ for (var i in allData.users[$scope.currentUser].teamsAsMember){ candidate = allData.users[$scope.currentUser].teamsAsMember[i]; if (allData.teams[candidate]!=undefined &&allData.teams[candidate].belongstoEvent == $scope.currentEvent){ $scope.currentTeam = candidate; break; } } $scope.readyData = $scope.processData(allData, $scope.currentEvent, $scope.currentTeam, $scope.currentUser); }; $scope.initShowBody=function(id){ if ($scope.clickCount == 0){ $(".collapsible-body-"+id).slideToggle(100); } }; $scope.projectEuler001=function(r){ for(var e=0,o=1;r>o;o++)(o%3===0||o%5===0)&&(e+=o); return e; }; $scope.projectEuler002=function(r){ for(var n,e,o=0,t=1,u=2;r>u;)o+=u,n=t+2*u,e=2*t+3*u,t=n,u=e; return o; }; $scope.projectEuler003=function(r){ for(var n=2;r>n*n;)r%n?n++:r/=n; return r; }; $scope.projectEuler004=function(r){ function e(r){ return n=r+"",n.split("").reverse().join("") }; var o=0,t=0; for(i=Math.pow(10,r)-1;i>=Math.pow(10,r-1);i--) for(j=Math.pow(10,r)-1;j>=Math.pow(10,r-1);j--) number=i*j,number==e(number)&&(o=number,o>t&&(t=o)); return t; }; $scope.projectEuler005=function(r){ function n(r,e){ return e>r&&n(e,r),r%e==0?e:n(e,r%e) } function e(r,e){ return r*e/n(r,e) }function o(r){ for(var n=1,o=1;r>=o;o++)n=e(n,o); return n; } return o(r); }; }]); // teamapp.directive("fishNavi", function() { // return { // restrict: "E", // templateUrl: "fish/fish-navi.html", // }; // });
mit
mdxs/gae-init
main/auth/bitbucket.py
1735
# coding: utf-8 from __future__ import absolute_import import flask import auth import config import model import util from main import app bitbucket_config = dict( access_token_method='POST', access_token_url='https://bitbucket.org/site/oauth2/access_token', api_base_url='https://api.bitbucket.org/2.0/', authorize_url='https://bitbucket.org/site/oauth2/authorize', client_id=config.CONFIG_DB.bitbucket_key, client_secret=config.CONFIG_DB.bitbucket_secret, client_kwargs={'scope': 'email'}, ) bitbucket = auth.create_oauth_app(bitbucket_config, 'bitbucket') @app.route('/api/auth/callback/bitbucket/') def bitbucket_authorized(): err = flask.request.args.get('error') if err in ['access_denied']: flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url()) id_token = bitbucket.authorize_access_token() if id_token is None: flask.flash('You denied the request to sign in.') return flask.redirect(util.get_next_url()) me = bitbucket.get('user') user_db = retrieve_user_from_bitbucket(me.json()) return auth.signin_user_db(user_db) @app.route('/signin/bitbucket/') def signin_bitbucket(): return auth.signin_oauth(bitbucket) def retrieve_user_from_bitbucket(response): auth_id = 'bitbucket_%s' % response['username'] user_db = model.User.get_by('auth_ids', auth_id) if user_db: return user_db emails_response = bitbucket.get('user/emails') emails = emails_response.json().get('values', []) email = ''.join([e['email'] for e in emails if e['is_primary']][0:1]) return auth.create_user_db( auth_id=auth_id, name=response['display_name'], username=response['username'], email=email, verified=bool(email), )
mit
salimfadhley/jenkinsapi
examples/how_to/create_nested_views.py
2192
""" How to create nested views using NestedViews Jenkins plugin This example requires NestedViews plugin to be installed in Jenkins You need to have at least one job in your Jenkins to see views """ from __future__ import print_function import logging from pkg_resources import resource_string from jenkinsapi.views import Views from jenkinsapi.jenkins import Jenkins log_level = getattr(logging, 'DEBUG') logging.basicConfig(level=log_level) logger = logging.getLogger() jenkins_url = "http://127.0.0.1:8080/" jenkins = Jenkins(jenkins_url) job_name = 'foo_job2' xml = resource_string('examples', 'addjob.xml') j = jenkins.create_job(jobname=job_name, xml=xml) # Create ListView in main view logger.info('Attempting to create new nested view') top_view = jenkins.views.create('TopView', Views.NESTED_VIEW) logger.info('top_view is %s', top_view) if top_view is None: logger.error('View was not created') else: logger.info('View has been created') print('top_view.views=', top_view.views.keys()) logger.info('Attempting to create view inside nested view') sub_view = top_view.views.create('SubView') if sub_view is None: logger.info('View was not created') else: logger.error('View has been created') logger.info('Attempting to delete sub_view') del top_view.views['SubView'] if 'SubView' in top_view.views: logger.error('SubView was not deleted') else: logger.info('SubView has been deleted') # Another way of creating sub view # This way sub view will have jobs in it logger.info('Attempting to create view with jobs inside nested view') top_view.views['SubView'] = job_name if 'SubView' not in top_view.views: logger.error('View was not created') else: logger.info('View has been created') logger.info('Attempting to delete sub_view') del top_view.views['SubView'] if 'SubView' in top_view.views: logger.error('SubView was not deleted') else: logger.info('SubView has been deleted') logger.info('Attempting to delete top view') del jenkins.views['TopView'] if 'TopView' not in jenkins.views: logger.info('View has been deleted') else: logger.error('View was not deleted') # Delete job that we created jenkins.delete_job(job_name)
mit
ReactTraining/history
packages/history/__tests__/TestSequences/ReplaceNewLocation.js
583
import expect from 'expect'; import { execSteps } from './utils.js'; export default (history, done) => { let steps = [ ({ location }) => { expect(location).toMatchObject({ pathname: '/' }); history.replace('/home?the=query#the-hash'); }, ({ action, location }) => { expect(action).toBe('REPLACE'); expect(location).toMatchObject({ pathname: '/home', search: '?the=query', hash: '#the-hash', state: null, key: expect.any(String) }); } ]; execSteps(steps, history, done); };
mit
luchaoshuai/aspnetboilerplate
src/Abp.Zero.Common/DynamicEntityProperties/DynamicPropertyStore.cs
3608
using System.Collections.Generic; using System.Threading.Tasks; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; namespace Abp.DynamicEntityProperties { public class DynamicPropertyStore : IDynamicPropertyStore, ITransientDependency { private readonly IRepository<DynamicProperty> _dynamicPropertyRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public DynamicPropertyStore( IRepository<DynamicProperty> dynamicPropertyRepository, IUnitOfWorkManager unitOfWorkManager) { _dynamicPropertyRepository = dynamicPropertyRepository; _unitOfWorkManager = unitOfWorkManager; } public virtual DynamicProperty Get(int id) { return _unitOfWorkManager.WithUnitOfWork(() => _dynamicPropertyRepository.Get(id) ); } public virtual async Task<DynamicProperty> GetAsync(int id) { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => await _dynamicPropertyRepository.GetAsync(id) ); } public virtual DynamicProperty Get(string propertyName) { return _unitOfWorkManager.WithUnitOfWork(() => { return _dynamicPropertyRepository.FirstOrDefault(x => x.PropertyName == propertyName); }); } public virtual async Task<DynamicProperty> GetAsync(string propertyName) { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { return await _dynamicPropertyRepository.FirstOrDefaultAsync(x => x.PropertyName == propertyName); }); } public virtual List<DynamicProperty> GetAll() { return _unitOfWorkManager.WithUnitOfWork(() => _dynamicPropertyRepository.GetAllList()); } public virtual async Task<List<DynamicProperty>> GetAllAsync() { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => await _dynamicPropertyRepository.GetAllListAsync() ); } public virtual void Add(DynamicProperty dynamicProperty) { _unitOfWorkManager.WithUnitOfWork(() => { _dynamicPropertyRepository.Insert(dynamicProperty); }); } public virtual async Task AddAsync(DynamicProperty dynamicProperty) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => await _dynamicPropertyRepository.InsertAsync(dynamicProperty) ); } public virtual void Update(DynamicProperty dynamicProperty) { _unitOfWorkManager.WithUnitOfWork(() => { _dynamicPropertyRepository.Update(dynamicProperty); }); } public virtual async Task UpdateAsync(DynamicProperty dynamicProperty) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => await _dynamicPropertyRepository.UpdateAsync(dynamicProperty) ); } public virtual void Delete(int id) { _unitOfWorkManager.WithUnitOfWork(() => { _dynamicPropertyRepository.Delete(id); }); } public virtual async Task DeleteAsync(int id) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => await _dynamicPropertyRepository.DeleteAsync(id) ); } } }
mit
ukparliament/parliament.uk-prototype
app/controllers/houses/parties/members_controller.rb
3960
module Houses module Parties class MembersController < ApplicationController before_action :data_check, :build_request ROUTE_MAP = { index: proc { |params| ParliamentHelper.parliament_request.house_party_members.set_url_params({house_id: params[:house_id], party_id: params[:party_id] }) }, a_to_z_current: proc { |params| ParliamentHelper.parliament_request.house_party_current_members_a_to_z.set_url_params({ house_id: params[:house_id], party_id: params[:party_id] }) }, current: proc { |params| ParliamentHelper.parliament_request.house_party_current_members.set_url_params({ house_id: params[:house_id], party_id: params[:party_id] }) }, letters: proc { |params| ParliamentHelper.parliament_request.house_party_members_by_initial.set_url_params({ house_id: params[:house_id], party_id: params[:party_id], initial: params[:letter] }) }, current_letters: proc { |params| ParliamentHelper.parliament_request.house_party_current_members_by_initial.set_url_params({ house_id: params[:house_id], party_id: params[:party_id], initial: params[:letter] }) }, a_to_z: proc { |params| ParliamentHelper.parliament_request.house_party_members_a_to_z.set_url_params({ house_id: params[:house_id], party_id: params[:party_id] }) } }.freeze def index @house, @party, @people, @letters = RequestHelper.filter_response_data( @request, 'http://id.ukpds.org/schema/House', 'http://id.ukpds.org/schema/Party', 'http://id.ukpds.org/schema/Person', ::Grom::Node::BLANK ) @house = @house.first @party = @party.first @people = @people.sort_by(:sort_name) @letters = @letters.map(&:value) @current_person_type, @other_person_type = HousesHelper.person_type_string(@house) end def letters @house, @party, @people, @letters = RequestHelper.filter_response_data( @request, 'http://id.ukpds.org/schema/House', 'http://id.ukpds.org/schema/Party', 'http://id.ukpds.org/schema/Person', ::Grom::Node::BLANK ) @house = @house.first @party = @party.first @people = @people.sort_by(:sort_name) @letters = @letters.map(&:value) @current_person_type, @other_person_type = HousesHelper.person_type_string(@house) end def current @house, @party, @people, @letters = RequestHelper.filter_response_data( @request, 'http://id.ukpds.org/schema/House', 'http://id.ukpds.org/schema/Party', 'http://id.ukpds.org/schema/Person', ::Grom::Node::BLANK ) @house = @house.first @party = @party.first @people = @people.sort_by(:sort_name) @letters = @letters.map(&:value) @current_person_type, @other_person_type = HousesHelper.person_type_string(@house) end def current_letters @house, @party, @people, @letters = RequestHelper.filter_response_data( @request, 'http://id.ukpds.org/schema/House', 'http://id.ukpds.org/schema/Party', 'http://id.ukpds.org/schema/Person', ::Grom::Node::BLANK ) @house = @house.first @party = @party.first @people = @people.sort_by(:sort_name) @letters = @letters.map(&:value) @current_person_type, @other_person_type = HousesHelper.person_type_string(@house) end def a_to_z @house_id = params[:house_id] @party_id = params[:party_id] @letters = RequestHelper.process_available_letters(ROUTE_MAP[:a_to_z].call(params)) end def a_to_z_current @house_id = params[:house_id] @party_id = params[:party_id] @letters = RequestHelper.process_available_letters(ROUTE_MAP[:a_to_z_current].call(params)) end end end end
mit
godotgildor/igv
src/org/broad/igv/ui/legend/LohLegendPanel.java
3330
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.legend; import org.broad.igv.PreferenceManager; import org.broad.igv.track.TrackType; import org.broad.igv.ui.FontManager; import java.awt.*; /** * @author jrobinso */ public class LohLegendPanel extends HeatmapLegendPanel { public LohLegendPanel() { super(TrackType.LOH); } @Override public void paintLegend(Graphics g) { Graphics2D g2D = null; try { g2D = (Graphics2D) g.create(); if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.ENABLE_ANTIALISING)) { g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } g2D.setFont(FontManager.getFont(10)); FontMetrics fm = g2D.getFontMetrics(); int dh = fm.getHeight() / 2 + 3; int x = 0; int y = getHeight() / 2; String label = "Loss"; int labelWidth = (int) fm.getStringBounds(label, g2D).getWidth(); g2D.setColor(colorScale.getMaxColor()); g2D.fillRect(x, y, 10, 10); g2D.setColor(Color.BLACK); g2D.drawRect(x, y, 10, 10); g2D.drawString(label, x + 20, y + dh); x += labelWidth + 60; label = "Retained"; labelWidth = (int) fm.getStringBounds(label, g2D).getWidth(); g2D.setColor(colorScale.getMidColor()); g2D.fillRect(x, y, 10, 10); g2D.setColor(Color.BLACK); g2D.drawRect(x, y, 10, 10); g2D.drawString(label, x + 20, y + dh); x += labelWidth + 60; label = "Conflict"; labelWidth = (int) fm.getStringBounds(label, g2D).getWidth(); g2D.setColor(colorScale.getMinColor()); g2D.fillRect(x, y, 10, 10); g2D.setColor(Color.BLACK); g2D.drawRect(x, y, 10, 10); g2D.drawString(label, x + 20, y + dh); x += labelWidth + 60; } finally { g2D.dispose(); } } }
mit
vancarney/apihero-module-browserify
lib/apihero-module-browserify.js
215
// Generated by CoffeeScript 1.9.3 var browserify; browserify = require('browserify'); module.exports.browserify = browserify; module.exports.init = function(app, options, callback) { return callback(null); };
mit
smmbllsm/aleph
aleph/static/js/directives/responsePager.js
1520
import aleph from '../aleph'; aleph.directive('responsePager', ['$timeout', function ($timeout) { return { restrict: 'E', scope: { 'response': '=', 'load': '&load' }, templateUrl: 'templates/response_pager.html', link: function (scope, element, attrs, model) { var pageOffset = function(page) { return (page-1) * scope.response.limit; } scope.$watch('response', function(e) { scope.showPager = false; scope.pages = []; var pagesCount = Math.ceil(scope.response.total / scope.response.limit); if (pagesCount <= 1) { return; } var pages = [], current = (scope.response.offset / scope.response.limit) + 1, num = Math.ceil(scope.response.total / scope.response.limit), range = 2, low = current - range, high = current + range; if (low < 1) { low = 1; high = Math.min((2*range)+1, num); } if (high > num) { high = num; low = Math.max(1, num - (2*range)+1); } for (var page = low; page <= high; page++) { pages.push({ page: page, offset: pageOffset(page), current: page == current }); } scope.prev = current == low ? -1 : pageOffset(current - 1); scope.next = current == high ? -1 : pageOffset(current + 1); scope.showPager = true; scope.pages = pages; }); } }; }]);
mit
DualSpark/rusoto
rusoto/services/cur/src/lib.rs
1438
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to generate the changes. // // ================================================================= #![doc( html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png" )] //! <p><p>The AWS Cost and Usage Report API enables you to programmatically create, query, and delete AWS Cost and Usage report definitions.</p> <p>AWS Cost and Usage reports track the monthly AWS costs and usage associated with your AWS account. The report contains line items for each unique combination of AWS product, usage type, and operation that your AWS account uses. You can configure the AWS Cost and Usage report to show only the data that you want, using the AWS Cost and Usage API.</p> <p>Service Endpoint</p> <p>The AWS Cost and Usage Report API provides the following endpoint:</p> <ul> <li> <p>cur.us-east-1.amazonaws.com</p> </li> </ul></p> //! //! If you're using the service, you're probably looking for [CostAndUsageReportClient](struct.CostAndUsageReportClient.html) and [CostAndUsageReport](trait.CostAndUsageReport.html). mod custom; mod generated; pub use custom::*; pub use generated::*;
mit
blockstack/opendig
src/index.ts
97
import * as publicExports from './public' export default publicExports export * from './public'
mit
hanumakanthvvn/rubocop
lib/rubocop/cop/lint/empty_when.rb
855
# frozen_string_literal: true module RuboCop module Cop module Lint # This cop checks for the presence of `when` branches without a body. # # @example # # @bad # case foo # when bar then 1 # when baz then # nothing # end class EmptyWhen < Cop MSG = 'Avoid `when` branches without a body.'.freeze def on_case(node) _cond_node, *when_nodes, _else_node = *node when_nodes.each do |when_node| check_when(when_node) end end private def check_when(when_node) return unless empty_when_body?(when_node) add_offense(when_node, when_node.source_range, MSG) end def empty_when_body?(when_node) !when_node.to_a.last end end end end end
mit
kelvinatorr/tiffanyandkelvin
app/js/jquery.quicksand.js
19077
/* Quicksand 1.4 Reorder and filter items with a nice shuffling animation. Copyright (c) 2010 Jacek Galanciak (razorjack.net) and agilope.com Big thanks for Piotr Petrus (riddle.pl) for deep code review and wonderful docs & demos. Dual licensed under the MIT and GPL version 2 licenses. http://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt http://github.com/jquery/jquery/blob/master/GPL-LICENSE.txt Project site: http://razorjack.net/quicksand Github site: http://github.com/razorjack/quicksand */ (function($) { var cloneWithCanvases = function(jqueryObject) { var clonedJqueryObject = jqueryObject.clone(); var canvases = jqueryObject.find('canvas'); if (canvases.length) { var clonedCanvases = clonedJqueryObject.find('canvas'); clonedCanvases.each(function(index) { var context = this.getContext('2d'); context.drawImage(canvases.get(index), 0, 0); }); } return clonedJqueryObject; }; $.fn.quicksand = function(collection, customOptions) { var options = { duration : 750, easing : 'swing', attribute : 'data-id', // attribute to recognize same items within source and dest adjustHeight : 'auto', // 'dynamic' animates height during shuffling (slow), 'auto' adjusts it // before or after the animation, false leaves height constant adjustWidth : 'auto', // 'dynamic' animates width during shuffling (slow), // 'auto' adjusts it before or after the animation, false leaves width constant useScaling : false, // enable it if you're using scaling effect enhancement : function(c) {}, // Visual enhacement (eg. font replacement) function for cloned elements selector : '> *', atomic : false, dx : 0, dy : 0, maxWidth : 0, retainExisting : true // disable if you want the collection of items to be replaced completely by incoming items. }, nativeScaleSupport = (function() { var prefixes = 'transform WebkitTransform MozTransform OTransform msTransform'.split(' '), el = document.createElement('div'); for (var i = 0; i < prefixes.length; i++) { if (typeof el.style[prefixes[i]] != 'undefined') { return true; } } return false; })(); $.extend(options, customOptions); // Can the browser do scaling? if (!nativeScaleSupport || (typeof ($.fn.scale) == 'undefined')) { options.useScaling = false; } var callbackFunction; if (typeof (arguments[1]) == 'function') { callbackFunction = arguments[1]; } else if (typeof (arguments[2] == 'function')) { callbackFunction = arguments[2]; } return this.each(function(i) { var val; var animationQueue = []; // used to store all the animation params before starting the animation; // solves initial animation slowdowns var $collection; if (typeof(options.attribute) == 'function') { $collection = $(collection); } else { $collection = cloneWithCanvases($(collection).filter('[' + options.attribute + ']')); // destination (target) collection } var $sourceParent = $(this); // source, the visible container of source collection var sourceHeight = $(this).css('height'); // used to keep height and document flow during the animation var sourceWidth = $(this).css('width'); // used to keep width and document flow during the animation var destHeight, destWidth; var adjustHeightOnCallback = false; var adjustWidthOnCallback = false; var offset = $($sourceParent).offset(); // offset of visible container, used in animation calculations var offsets = []; // coordinates of every source collection item var $source = $(this).find(options.selector); // source collection items var width = $($source).innerWidth(); // need for the responsive design // Replace the collection and quit if IE6 if (navigator.userAgent.match(/msie [6]/i)) { $sourceParent.html('').append($collection); return; } // Gets called when any animation is finished var postCallbackPerformed = 0; // prevents the function from being called more than one time var postCallback = function() { $(this).css('margin', '').css('position', '').css('top', '').css('left', '').css('opacity', ''); if (!postCallbackPerformed) { postCallbackPerformed = 1; if (!options.atomic) { // hack: used to be: $sourceParent.html($dest.html()); // put target HTML into visible source container // but new webkit builds cause flickering when replacing the collections var $toDelete = $sourceParent.find(options.selector); if (!options.retainExisting) { $sourceParent.prepend($dest.find(options.selector)); $toDelete.remove(); } else { // Avoid replacing elements because we may have already altered items in significant // ways and it would be bad to have to do it again. (i.e. lazy load images) // But $dest holds the correct ordering. So we must re-sequence items in $sourceParent to match. var $keepElements = $([]); $dest.find(options.selector).each(function(i) { var $matchedElement = $([]); if (typeof (options.attribute) == 'function') { var val = options.attribute($(this)); $toDelete.each(function() { if (options.attribute(this) == val) { $matchedElement = $(this); return false; } }); } else { $matchedElement = $toDelete.filter( '[' + options.attribute + '="'+ $(this).attr(options.attribute) + '"]'); } if ($matchedElement.length > 0) { // There is a matching element in the $toDelete list and in $dest // list, so make sure it is in the right location within $sourceParent // and put it in the list of elements we need to not delete. $keepElements = $keepElements.add($matchedElement); if (i === 0) { $sourceParent.prepend($matchedElement); } else { $matchedElement.insertAfter($sourceParent.find(options.selector).get(i - 1)); } } }); // Remove whatever is remaining from the DOM $toDelete.not($keepElements).remove(); } if (adjustHeightOnCallback) { $sourceParent.css('height', destHeight); } if (adjustWidthOnCallback) { $sourceParent.css('width', sourceWidth); } } options.enhancement($sourceParent); // Perform custom visual enhancements on a newly replaced collection if (typeof callbackFunction == 'function') { callbackFunction.call(this); } } if (false === options.adjustHeight) { $sourceParent.css('height', 'auto'); } if (false === options.adjustWidth) { $sourceParent.css('width', 'auto'); } }; // Position: relative situations var $correctionParent = $sourceParent.offsetParent(); var correctionOffset = $correctionParent.offset(); if ($correctionParent.css('position') == 'relative') { if ($correctionParent.get(0).nodeName.toLowerCase() != 'body') { correctionOffset.top += (parseFloat($correctionParent.css('border-top-width')) || 0); correctionOffset.left += (parseFloat($correctionParent.css('border-left-width')) || 0); } } else { correctionOffset.top -= (parseFloat($correctionParent.css('border-top-width')) || 0); correctionOffset.left -= (parseFloat($correctionParent.css('border-left-width')) || 0); correctionOffset.top -= (parseFloat($correctionParent.css('margin-top')) || 0); correctionOffset.left -= (parseFloat($correctionParent.css('margin-left')) || 0); } // perform custom corrections from options (use when Quicksand fails to detect proper correction) if (isNaN(correctionOffset.left)) { correctionOffset.left = 0; } if (isNaN(correctionOffset.top)) { correctionOffset.top = 0; } correctionOffset.left -= options.dx; correctionOffset.top -= options.dy; // keeps nodes after source container, holding their position $sourceParent.css('height', $(this).height()); $sourceParent.css('width', $(this).width()); // get positions of source collections $source.each(function(i) { offsets[i] = $(this).offset(); }); // stops previous animations on source container $(this).stop(); var dx = 0; var dy = 0; $source.each(function(i) { $(this).stop(); // stop animation of collection items var rawObj = $(this).get(0); if (rawObj.style.position == 'absolute') { dx = -options.dx; dy = -options.dy; } else { dx = options.dx; dy = options.dy; } rawObj.style.position = 'absolute'; rawObj.style.margin = '0'; if (!options.adjustWidth) { rawObj.style.width = (width + 'px'); // sets the width to the current element // with even if it has been changed // by a responsive design } rawObj.style.top = (offsets[i].top- parseFloat(rawObj.style.marginTop) - correctionOffset.top + dy) + 'px'; rawObj.style.left = (offsets[i].left- parseFloat(rawObj.style.marginLeft) - correctionOffset.left + dx) + 'px'; if (options.maxWidth > 0 && offsets[i].left > options.maxWidth) { rawObj.style.display = 'none'; } }); // create temporary container with destination collection var $dest = cloneWithCanvases($($sourceParent)); var rawDest = $dest.get(0); rawDest.innerHTML = ''; rawDest.setAttribute('id', ''); rawDest.style.height = 'auto'; rawDest.style.width = $sourceParent.width() + 'px'; $dest.append($collection); // Inserts node into HTML. Note that the node is under visible source container in the exactly same position // The browser render all the items without showing them (opacity: 0.0) No offset calculations are needed, // the browser just extracts position from underlayered destination items and sets animation to destination positions. $dest.insertBefore($sourceParent); $dest.css('opacity', 0.0); rawDest.style.zIndex = -1; rawDest.style.margin = '0'; rawDest.style.position = 'absolute'; rawDest.style.top = offset.top - correctionOffset.top + 'px'; rawDest.style.left = offset.left - correctionOffset.left + 'px'; if (options.adjustHeight === 'dynamic') { // If destination container has different height than source container the height can be animated, // adjusting it to destination height $sourceParent.animate({ height : $dest.height() }, options.duration, options.easing); } else if (options.adjustHeight === 'auto') { destHeight = $dest.height(); if (parseFloat(sourceHeight) < parseFloat(destHeight)) { // Adjust the height now so that the items don't move out of the container $sourceParent.css('height', destHeight); } else { // Adjust later, on callback adjustHeightOnCallback = true; } } if (options.adjustWidth === 'dynamic') { // If destination container has different width than source container the width can be animated, // adjusting it to destination width $sourceParent.animate({ width : $dest.width() }, options.duration, options.easing); } else if (options.adjustWidth === 'auto') { destWidth = $dest.width(); if (parseFloat(sourceWidth) < parseFloat(destWidth)) { // Adjust the height now so that the items don't move out of the container $sourceParent.css('width', destWidth); } else { // Adjust later, on callback adjustWidthOnCallback = true; } } // Now it's time to do shuffling animation. First of all, we need to identify same elements within // source and destination collections $source.each(function(i) { var destElement = []; if (typeof (options.attribute) == 'function') { val = options.attribute($(this)); $collection.each(function() { if (options.attribute(this) == val) { destElement = $(this); return false; } }); } else { destElement = $collection.filter('[' + options.attribute + '="' + $(this).attr(options.attribute) + '"]'); } if (destElement.length) { // The item is both in source and destination collections. It it's under different position, let's move it if (!options.useScaling) { animationQueue.push({ element : $(this), dest : destElement, style : { top : $(this).offset().top, left : $(this).offset().left, opacity : "" }, animation : { top : destElement.offset().top - correctionOffset.top, left : destElement.offset().left - correctionOffset.left, opacity : 1.0 } }); } else { animationQueue.push({ element : $(this), dest : destElement, style : { top : $(this).offset().top, left : $(this).offset().left, opacity : "" }, animation : { top : destElement.offset().top - correctionOffset.top, left : destElement.offset().left - correctionOffset.left, opacity : 1.0, scale : '1.0' } }); } } else { // The item from source collection is not present in destination collections. Let's remove it if (!options.useScaling) { animationQueue.push({ element : $(this), style : { top : $(this).offset().top, left : $(this).offset().left, opacity : "" }, animation : { opacity : '0.0' } }); } else { animationQueue.push({ element : $(this), style : { top : $(this).offset().top, left : $(this).offset().left, opacity : "" }, animation : { opacity : '0.0', scale : '0.0' } }); } } }); $collection.each(function(i) { // Grab all items from target collection not present in visible source collection var sourceElement = []; var destElement = []; if (typeof (options.attribute) == 'function') { val = options.attribute($(this)); $source.each(function() { if (options.attribute(this) == val) { sourceElement = $(this); return false; } }); $collection.each(function() { if (options.attribute(this) == val) { destElement = $(this); return false; } }); } else { sourceElement = $source.filter('[' + options.attribute + '="' + $(this).attr(options.attribute) + '"]'); destElement = $collection.filter('[' + options.attribute + '="' + $(this).attr(options.attribute) + '"]'); } var animationOptions; if (sourceElement.length === 0 && destElement.length > 0) { // No such element in source collection... if (!options.useScaling) { animationOptions = {opacity : '1.0'}; } else { animationOptions = {opacity : '1.0', scale : '1.0'}; } // Let's create it var d = cloneWithCanvases(destElement); var rawDestElement = d.get(0); rawDestElement.style.position = 'absolute'; rawDestElement.style.margin = '0'; if (!options.adjustWidth) { // sets the width to the current element with even if it has been changed by a responsive design rawDestElement.style.width = width + 'px'; } rawDestElement.style.top = destElement.offset().top - correctionOffset.top + 'px'; rawDestElement.style.left = destElement.offset().left - correctionOffset.left + 'px'; d.css('opacity', 0.0); // IE if (options.useScaling) { d.scale(0.0); } d.appendTo($sourceParent); if (options.maxWidth === 0 || destElement.offset().left < options.maxWidth) { animationQueue.push({element : $(d), dest : destElement,animation : animationOptions}); } } }); $dest.remove(); if (!options.atomic) { options.enhancement($sourceParent); // Perform custom visual enhancements during the animation for (i = 0; i < animationQueue.length; i++) { animationQueue[i].element.animate(animationQueue[i].animation, options.duration, options.easing, postCallback); } } else { $toDelete = $sourceParent.find(options.selector); $sourceParent.prepend($dest.find(options.selector)); for (i = 0; i < animationQueue.length; i++) { if (animationQueue[i].dest && animationQueue[i].style) { var destElement = animationQueue[i].dest; var destOffset = destElement.offset(); destElement.css({ position : 'relative', top : (animationQueue[i].style.top - destOffset.top), left : (animationQueue[i].style.left - destOffset.left) }); destElement.animate({top : "0", left : "0"}, options.duration, options.easing, postCallback); } else { animationQueue[i].element.animate(animationQueue[i].animation, options.duration, options.easing, postCallback); } } $toDelete.remove(); } }); }; }(jQuery));
mit
nyaamara/osu
osu.Desktop.VisualTests/Tests/TestCaseDrawings.cs
2595
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using osu.Framework.Testing; using osu.Game.Screens.Tournament; using osu.Game.Screens.Tournament.Teams; namespace osu.Desktop.VisualTests.Tests { internal class TestCaseDrawings : TestCase { public override string Description => "Tournament drawings"; public override void Reset() { base.Reset(); Add(new Drawings { TeamList = new TestTeamList(), }); } private class TestTeamList : ITeamList { public IEnumerable<DrawingsTeam> Teams { get; } = new[] { new DrawingsTeam { FlagName = "GB", FullName = "United Kingdom", Acronym = "UK" }, new DrawingsTeam { FlagName = "FR", FullName = "France", Acronym = "FRA" }, new DrawingsTeam { FlagName = "CN", FullName = "China", Acronym = "CHN" }, new DrawingsTeam { FlagName = "AU", FullName = "Australia", Acronym = "AUS" }, new DrawingsTeam { FlagName = "JP", FullName = "Japan", Acronym = "JPN" }, new DrawingsTeam { FlagName = "RO", FullName = "Romania", Acronym = "ROM" }, new DrawingsTeam { FlagName = "IT", FullName = "Italy", Acronym = "PIZZA" }, new DrawingsTeam { FlagName = "VE", FullName = "Venezuela", Acronym = "VNZ" }, new DrawingsTeam { FlagName = "US", FullName = "United States of America", Acronym = "USA" }, }; } } }
mit
jhernandezme/go-multasgt
vendor/github.com/h2non/gock/_examples/add_matchers/matchers.go
631
package main import ( "fmt" "net/http" "gopkg.in/h2non/gock.v1" ) func main() { defer gock.Off() gock.New("http://httpbin.org"). Get("/"). AddMatcher(func(req *http.Request, ereq *gock.Request) (bool, error) { return req.URL.Scheme == "http", nil }). AddMatcher(func(req *http.Request, ereq *gock.Request) (bool, error) { return req.Method == ereq.Method, nil }). Reply(204). SetHeader("Server", "gock") res, err := http.Get("http://httpbin.org/get") if err != nil { fmt.Errorf("Error: %s", err) } fmt.Printf("Status: %d\n", res.StatusCode) fmt.Printf("Server header: %s\n", res.Header.Get("Server")) }
mit
timfeid/framework-1
tests/Database/DatabaseSQLiteSchemaGrammarTest.php
19159
<?php use Mockery as m; use Illuminate\Database\Schema\Blueprint; class DatabaseSQLiteSchemaGrammarTest extends PHPUnit_Framework_TestCase { public function tearDown() { m::close(); } public function testBasicCreateTable() { $blueprint = new Blueprint('users'); $blueprint->create(); $blueprint->increments('id'); $blueprint->string('email'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('create table "users" ("id" integer not null primary key autoincrement, "email" varchar not null)', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->increments('id'); $blueprint->string('email'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(2, count($statements)); $expected = [ 'alter table "users" add column "id" integer not null primary key autoincrement', 'alter table "users" add column "email" varchar not null', ]; $this->assertEquals($expected, $statements); } public function testDropTable() { $blueprint = new Blueprint('users'); $blueprint->drop(); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('drop table "users"', $statements[0]); } public function testDropTableIfExists() { $blueprint = new Blueprint('users'); $blueprint->dropIfExists(); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('drop table if exists "users"', $statements[0]); } public function testDropUnique() { $blueprint = new Blueprint('users'); $blueprint->dropUnique('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('drop index foo', $statements[0]); } public function testDropIndex() { $blueprint = new Blueprint('users'); $blueprint->dropIndex('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('drop index foo', $statements[0]); } public function testRenameTable() { $blueprint = new Blueprint('users'); $blueprint->rename('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" rename to "foo"', $statements[0]); } public function testAddingPrimaryKey() { $blueprint = new Blueprint('users'); $blueprint->create(); $blueprint->string('foo')->primary(); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('create table "users" ("foo" varchar not null, primary key ("foo"))', $statements[0]); } public function testAddingForeignKey() { $blueprint = new Blueprint('users'); $blueprint->create(); $blueprint->string('foo')->primary(); $blueprint->string('order_id'); $blueprint->foreign('order_id')->references('id')->on('orders'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('create table "users" ("foo" varchar not null, "order_id" varchar not null, foreign key("order_id") references "orders"("id"), primary key ("foo"))', $statements[0]); } public function testAddingUniqueKey() { $blueprint = new Blueprint('users'); $blueprint->unique('foo', 'bar'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('create unique index bar on "users" ("foo")', $statements[0]); } public function testAddingIndex() { $blueprint = new Blueprint('users'); $blueprint->index(['foo', 'bar'], 'baz'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('create index baz on "users" ("foo", "bar")', $statements[0]); } public function testAddingIncrementingID() { $blueprint = new Blueprint('users'); $blueprint->increments('id'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]); } public function testAddingSmallIncrementingID() { $blueprint = new Blueprint('users'); $blueprint->smallIncrements('id'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]); } public function testAddingMediumIncrementingID() { $blueprint = new Blueprint('users'); $blueprint->mediumIncrements('id'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]); } public function testAddingBigIncrementingID() { $blueprint = new Blueprint('users'); $blueprint->bigIncrements('id'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]); } public function testAddingString() { $blueprint = new Blueprint('users'); $blueprint->string('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->string('foo', 100); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->string('foo', 100)->nullable()->default('bar'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" varchar null default \'bar\'', $statements[0]); } public function testAddingText() { $blueprint = new Blueprint('users'); $blueprint->text('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]); } public function testAddingBigInteger() { $blueprint = new Blueprint('users'); $blueprint->bigInteger('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->bigInteger('foo', true); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]); } public function testAddingInteger() { $blueprint = new Blueprint('users'); $blueprint->integer('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->integer('foo', true); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]); } public function testAddingMediumInteger() { $blueprint = new Blueprint('users'); $blueprint->mediumInteger('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->mediumInteger('foo', true); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]); } public function testAddingTinyInteger() { $blueprint = new Blueprint('users'); $blueprint->tinyInteger('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->tinyInteger('foo', true); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]); } public function testAddingSmallInteger() { $blueprint = new Blueprint('users'); $blueprint->smallInteger('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]); $blueprint = new Blueprint('users'); $blueprint->smallInteger('foo', true); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]); } public function testAddingFloat() { $blueprint = new Blueprint('users'); $blueprint->float('foo', 5, 2); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" float not null', $statements[0]); } public function testAddingDouble() { $blueprint = new Blueprint('users'); $blueprint->double('foo', 15, 8); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" float not null', $statements[0]); } public function testAddingDecimal() { $blueprint = new Blueprint('users'); $blueprint->decimal('foo', 5, 2); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" numeric not null', $statements[0]); } public function testAddingBoolean() { $blueprint = new Blueprint('users'); $blueprint->boolean('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" tinyint not null', $statements[0]); } public function testAddingEnum() { $blueprint = new Blueprint('users'); $blueprint->enum('foo', ['bar', 'baz']); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]); } public function testAddingJson() { $blueprint = new Blueprint('users'); $blueprint->json('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]); } public function testAddingJsonb() { $blueprint = new Blueprint('users'); $blueprint->jsonb('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]); } public function testAddingDate() { $blueprint = new Blueprint('users'); $blueprint->date('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" date not null', $statements[0]); } public function testAddingDateTime() { $blueprint = new Blueprint('users'); $blueprint->dateTime('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]); } public function testAddingDateTimeTz() { $blueprint = new Blueprint('users'); $blueprint->dateTimeTz('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]); } public function testAddingTime() { $blueprint = new Blueprint('users'); $blueprint->time('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" time not null', $statements[0]); } public function testAddingTimeTz() { $blueprint = new Blueprint('users'); $blueprint->timeTz('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" time not null', $statements[0]); } public function testAddingTimeStamp() { $blueprint = new Blueprint('users'); $blueprint->timestamp('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]); } public function testAddingTimeStampTz() { $blueprint = new Blueprint('users'); $blueprint->timestampTz('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]); } public function testAddingTimeStamps() { $blueprint = new Blueprint('users'); $blueprint->timestamps(); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(2, count($statements)); $expected = [ 'alter table "users" add column "created_at" datetime not null', 'alter table "users" add column "updated_at" datetime not null', ]; $this->assertEquals($expected, $statements); } public function testAddingTimeStampsTz() { $blueprint = new Blueprint('users'); $blueprint->timestampsTz(); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(2, count($statements)); $expected = [ 'alter table "users" add column "created_at" datetime not null', 'alter table "users" add column "updated_at" datetime not null', ]; $this->assertEquals($expected, $statements); } public function testAddingRememberToken() { $blueprint = new Blueprint('users'); $blueprint->rememberToken(); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "remember_token" varchar null', $statements[0]); } public function testAddingBinary() { $blueprint = new Blueprint('users'); $blueprint->binary('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" blob not null', $statements[0]); } public function testAddingUuid() { $blueprint = new Blueprint('users'); $blueprint->uuid('foo'); $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); $this->assertEquals(1, count($statements)); $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]); } protected function getConnection() { return m::mock('Illuminate\Database\Connection'); } public function getGrammar() { return new Illuminate\Database\Schema\Grammars\SQLiteGrammar; } }
mit
croquet-australia/croquet-australia.com.au
source/CroquetAustralia.Website/gulpconfig.js
1020
/*global module */ module.exports = function() { 'use strict'; var clientDirectory = '.'; var appJsFiles = ['./app/**/*.js', '!./App/_references.js']; var layoutDirectory = './Layouts/Shared'; // todo: var cssDirectory = './app/css'; // todo: var lessDirectory = './app/less'; var config = { // Files // files are arrays for possible future use. appJsFiles: appJsFiles, jsFiles: ['./*.js'].concat(appJsFiles), javaScriptLayoutFile: layoutDirectory + '/AfterRenderBody.cshtml', sassFiles: ['./app/styles/styles.scss'], // Directories layoutDirectory: layoutDirectory, // Options injectOptions: { ignorePath: clientDirectory.substr(1) // clientDirectory expect for leading . }, wiredepOptions: { bowerJson: require('./bower.json'), directory: clientDirectory + '/bower_components/', ignorePath: '../..' } }; return config; };
mit
samphippen/vagrant
plugins/commands/box/plugin.rb
333
require "vagrant" module VagrantPlugins module CommandBox class Plugin < Vagrant.plugin("1") name "box command" description "The `box` command gives you a way to manage boxes." command("box") do require File.expand_path("../command/root", __FILE__) Command::Root end end end end
mit
petergill/cap_bootstrap
lib/cap_bootstrap/recipes/check.rb
520
Capistrano::Configuration.instance(:must_exist).load do namespace :check do desc "Make sure local git is in sync with remote." task :revision, roles: :web do unless `git rev-parse HEAD` == `git rev-parse origin/#{branch}` puts "WARNING: HEAD is not the same as origin/#{branch}" puts "Run `git push` to sync changes." exit end end before "deploy", "check:revision" before "deploy:migrations", "check:revision" before "deploy:cold", "check:revision" end end
mit
yethee/wsdl2phpgenerator
tests/src/Unit/ArrayTypeTest.php
4461
<?php namespace Wsdl2PhpGenerator\Tests\Unit; use Wsdl2PhpGenerator\ArrayType; use Wsdl2PhpGenerator\Config; /** * Unit test for the ArrayType class. */ class ArrayTypeTest extends CodeGenerationTestCase { /** * The name of the class that we are generating * @var string */ protected $testClassName = 'ArrayTypeTestClass'; /** * The items that the generated class will contain * @var array */ private $items; /** * The generated class * @var ArrayType */ private $class; protected function setUp() { // Add a mostly dummy configuration. We are not going to read or write any files here. // The important part is the accessors part. $config = new Config(array( 'inputFile' => null, 'outputDir' => null, 'constructorParamsDefaultToNull' => true, )); $arrayType = new ArrayType($config, $this->testClassName); $arrayType->addMember('Dummy[]', 'Dummy', false); // Generate the class and load it into memory $this->generateClass($arrayType); $this->items = array( 'zero' => 3, 'one' => FALSE, 'two' => 'good job', 'three' => new \stdClass(), 'four' => array(), ); $this->class = new \ArrayTypeTestClass($this->items); } /** * Test if class exists and is correctly defined. */ public function testClassExists() { $this->assertClassExists($this->testClassName); $this->assertClassImplementsInterface($this->testClassName, 'ArrayAccess'); $this->assertClassImplementsInterface($this->testClassName, 'Iterator'); $this->assertClassImplementsInterface($this->testClassName, 'Countable'); } /** * Test if class implements the ArrayAccess interface correctly. */ public function testArrayAccessImplementation() { $this->assertClassHasMethod($this->testClassName, 'offsetExists'); $this->assertClassHasMethod($this->testClassName, 'offsetGet'); $this->assertClassHasMethod($this->testClassName, 'offsetSet'); $this->assertClassHasMethod($this->testClassName, 'offsetUnset'); foreach ($this->items as $k => $v) { // Tests offsetExists() $this->assertTrue(isset($this->class[$k])); // Tests offsetGet() $this->assertSame($this->items[$k], $this->class[$k]); } // Tests offsetExists() $this->assertFalse(isset($this->class['doesntExists'])); // Tests offsetSet() $this->class['newItem'] = 'newValue'; $this->assertSame('newValue', $this->class['newItem']); $this->class[] = 'newValue2'; $this->assertSame('newValue2', $this->class[0]); $this->class[] = 'newValue3'; $this->assertSame('newValue3', $this->class[1]); // Tests offsetUnset() unset($this->class['newItem']); $this->assertFalse(isset($this->class['newItem'])); } /** * Test if class implements the Iterator interface correctly. */ public function testIteratorImplementation() { $this->assertClassHasMethod($this->testClassName, 'current'); $this->assertClassHasMethod($this->testClassName, 'key'); $this->assertClassHasMethod($this->testClassName, 'next'); $this->assertClassHasMethod($this->testClassName, 'rewind'); $this->assertClassHasMethod($this->testClassName, 'valid'); // Test all Iterator methods // (both cycles must pass) $itemCount = count($this->items); for ($n = 0; $n < 2; ++$n) { $i = 0; reset($this->items); foreach ($this->class as $key => $val) { if ($i >= $itemCount) { $this->fail("Iterator overflow!"); } $this->assertSame(key($this->items), $key); $this->assertSame(current($this->items), $val); next($this->items); ++$i; } $this->assertSame($itemCount, $i); } } /** * Test if class implements the Countable interface correctly. */ public function testCountableImplementation() { $this->assertClassHasMethod($this->testClassName, 'count'); $this->assertCount(count($this->items), $this->class); } }
mit
gioialab/opendatagentedigioia
node_modules/js-cookie/test/tests.js
15386
/*global lifecycle: true*/ QUnit.module('read', lifecycle); QUnit.test('simple value', function (assert) { assert.expect(1); document.cookie = 'c=v'; assert.strictEqual(Cookies.get('c'), 'v', 'should return value'); }); QUnit.test('empty value', function (assert) { assert.expect(1); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, which // resulted in a bug while reading such a cookie. Cookies.set('c', ''); assert.strictEqual(Cookies.get('c'), '', 'should return value'); }); QUnit.test('not existing', function (assert) { assert.expect(1); assert.strictEqual(Cookies.get('whatever'), undefined, 'return undefined'); }); // github.com/carhartl/jquery-cookie/issues/50 QUnit.test('equality sign in cookie value', function (assert) { assert.expect(1); Cookies.set('c', 'foo=bar'); assert.strictEqual(Cookies.get('c'), 'foo=bar', 'should include the entire value'); }); // github.com/carhartl/jquery-cookie/issues/215 QUnit.test('percent character in cookie value', function (assert) { assert.expect(1); document.cookie = 'bad=foo%'; assert.strictEqual(Cookies.get('bad'), 'foo%', 'should read the percent character'); }); QUnit.test('percent character in cookie value mixed with encoded values', function (assert) { assert.expect(1); document.cookie = 'bad=foo%bar%22baz%bax%3D'; assert.strictEqual(Cookies.get('bad'), 'foo%bar"baz%bax=', 'should read the percent character'); }); // github.com/carhartl/jquery-cookie/pull/88 // github.com/carhartl/jquery-cookie/pull/117 QUnit.test('malformed cookie value in IE', function (assert) { assert.expect(1); var done = assert.async(); // Sandbox in an iframe so that we can poke around with document.cookie. var iframe = document.createElement('iframe'); iframe.src = 'malformed_cookie.html'; addEvent(iframe, 'load', function () { if (iframe.contentWindow.ok) { assert.strictEqual(iframe.contentWindow.testValue, 'two', 'reads all cookie values, skipping duplicate occurences of "; "'); } else { // Skip the test where we can't stub document.cookie using // Object.defineProperty. Seems to work fine in // Chrome, Firefox and IE 8+. assert.ok(true, 'N/A'); } done(); }); document.body.appendChild(iframe); }); // github.com/js-cookie/js-cookie/pull/171 QUnit.test('missing leading semicolon', function (assert) { assert.expect(1); var done = assert.async(); // Sandbox in an iframe so that we can poke around with document.cookie. var iframe = document.createElement('iframe'); var loadedSuccessfully = true; iframe.src = 'missing_semicolon.html'; addEvent(iframe, 'load', function () { iframe.contentWindow.onerror = function () { loadedSuccessfully = false; }; assert.strictEqual(loadedSuccessfully, true, 'can\'t throw Object is not a function error'); done(); }); document.body.appendChild(iframe); }); QUnit.test('Call to read all when there are cookies', function (assert) { Cookies.set('c', 'v'); Cookies.set('foo', 'bar'); assert.deepEqual(Cookies.get(), { c: 'v', foo: 'bar' }, 'returns object containing all cookies'); }); QUnit.test('Call to read all when there are no cookies at all', function (assert) { assert.deepEqual(Cookies.get(), {}, 'returns empty object'); }); QUnit.test('RFC 6265 - reading cookie-octet enclosed in DQUOTE', function (assert) { assert.expect(1); document.cookie = 'c="v"'; assert.strictEqual(Cookies.get('c'), 'v', 'should simply ignore quoted strings'); }); // github.com/js-cookie/js-cookie/issues/196 QUnit.test('Call to read cookie when there is another unrelated cookie with malformed encoding in the name', function (assert) { assert.expect(2); document.cookie = 'BS%BS=1'; document.cookie = 'c=v'; assert.strictEqual(Cookies.get('c'), 'v', 'should not throw a URI malformed exception when retrieving a single cookie'); assert.deepEqual(Cookies.get(), { c: 'v' }, 'should not throw a URI malformed exception when retrieving all cookies'); document.cookie = 'BS%BS=1; expires=Thu, 01 Jan 1970 00:00:00 GMT'; }); // github.com/js-cookie/js-cookie/pull/62 QUnit.test('Call to read cookie when there is another unrelated cookie with malformed encoding in the value', function (assert) { assert.expect(2); document.cookie = 'invalid=%A1'; document.cookie = 'c=v'; assert.strictEqual(Cookies.get('c'), 'v', 'should not throw a URI malformed exception when retrieving a single cookie'); assert.deepEqual(Cookies.get(), { c: 'v' }, 'should not throw a URI malformed exception when retrieving all cookies'); Cookies.withConverter(unescape).remove('invalid'); }); // github.com/js-cookie/js-cookie/issues/145 QUnit.test('Call to read cookie when passing an Object Literal as the second argument', function (assert) { assert.expect(1); Cookies.get('name', { path: '' }); assert.strictEqual(document.cookie, '', 'should not create a cookie'); }); // github.com/js-cookie/js-cookie/issues/238 QUnit.test('Call to read cookie when there is a window.json variable globally', function (assert) { assert.expect(1); window.json = true; Cookies.set('boolean', true); assert.strictEqual(typeof Cookies.get('boolean'), 'string', 'should not change the returned type'); // IE 6-8 throw an exception if trying to delete a window property // See stackoverflow.com/questions/1073414/deleting-a-window-property-in-ie/1824228 try { delete window.json; } catch (e) {} }); QUnit.module('write', lifecycle); QUnit.test('String primitive', function (assert) { assert.expect(1); Cookies.set('c', 'v'); assert.strictEqual(Cookies.get('c'), 'v', 'should write value'); }); QUnit.test('String object', function (assert) { assert.expect(1); Cookies.set('c', new String('v')); assert.strictEqual(Cookies.get('c'), 'v', 'should write value'); }); QUnit.test('value "[object Object]"', function (assert) { assert.expect(1); Cookies.set('c', '[object Object]'); assert.strictEqual(Cookies.get('c'), '[object Object]', 'should write value'); }); QUnit.test('number', function (assert) { assert.expect(1); Cookies.set('c', 1234); assert.strictEqual(Cookies.get('c'), '1234', 'should write value'); }); QUnit.test('null', function (assert) { assert.expect(1); Cookies.set('c', null); assert.strictEqual(Cookies.get('c'), 'null', 'should write value'); }); QUnit.test('undefined', function (assert) { assert.expect(1); Cookies.set('c', undefined); assert.strictEqual(Cookies.get('c'), 'undefined', 'should write value'); }); QUnit.test('expires option as days from now', function (assert) { assert.expect(1); var sevenDaysFromNow = new Date(); sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 21); var expected = 'c=v; expires=' + sevenDaysFromNow.toUTCString(); var actual = Cookies.set('c', 'v', { expires: 21 }).substring(0, expected.length); assert.strictEqual(actual, expected, 'should write the cookie string with expires'); }); QUnit.test('expires option as fraction of a day', function (assert) { assert.expect(1); var now = new Date().getTime(); var stringifiedDate = Cookies.set('c', 'v', { expires: 0.5 }).split('; ')[1].split('=')[1]; var expires = Date.parse(stringifiedDate); // When we were using Date.setDate() fractions have been ignored // and expires resulted in the current date. Allow 1000 milliseconds // difference for execution time. assert.ok(expires > now + 1000, 'should write expires attribute with the correct date'); }); QUnit.test('expires option as Date instance', function (assert) { assert.expect(1); var sevenDaysFromNow = new Date(); sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 7); var expected = 'c=v; expires=' + sevenDaysFromNow.toUTCString(); var actual = Cookies.set('c', 'v', { expires: sevenDaysFromNow }).substring(0, expected.length); assert.strictEqual(actual, expected, 'should write the cookie string with expires'); }); QUnit.test('return value', function (assert) { assert.expect(1); var expected = 'c=v'; var actual = Cookies.set('c', 'v').substring(0, expected.length); assert.strictEqual(actual, expected, 'should return written cookie string'); }); QUnit.test('default path attribute', function (assert) { assert.expect(1); assert.ok(Cookies.set('c', 'v').match(/path=\//), 'should read the default path'); }); QUnit.test('API for changing defaults', function (assert) { assert.expect(3); Cookies.defaults.path = '/foo'; assert.ok(Cookies.set('c', 'v').match(/path=\/foo/), 'should use attributes from defaults'); Cookies.remove('c', { path: '/foo' }); assert.ok(Cookies.set('c', 'v', { path: '/bar' }).match(/path=\/bar/), 'attributes argument has precedence'); Cookies.remove('c', { path: '/bar' }); delete Cookies.defaults.path; assert.ok(Cookies.set('c', 'v').match(/path=\//), 'should roll back to the default path'); }); // github.com/js-cookie/js-cookie/pull/54 QUnit.test('false secure value', function (assert) { assert.expect(1); var expected = 'c=v; path=/'; var actual = Cookies.set('c', 'v', {secure: false}); assert.strictEqual(actual, expected, 'false should not modify path in cookie string'); }); QUnit.test('undefined attribute value', function (assert) { assert.expect(4); assert.strictEqual(Cookies.set('c', 'v', { expires: undefined }), 'c=v; path=/', 'should not write undefined expires attribute'); assert.strictEqual(Cookies.set('c', 'v', { path: undefined }), 'c=v', 'should not write undefined path attribute'); assert.strictEqual(Cookies.set('c', 'v', { domain: undefined }), 'c=v; path=/', 'should not write undefined domain attribute'); assert.strictEqual(Cookies.set('c', 'v', { secure: undefined }), 'c=v; path=/', 'should not write undefined secure attribute'); }); QUnit.module('remove', lifecycle); QUnit.test('deletion', function (assert) { assert.expect(1); Cookies.set('c', 'v'); Cookies.remove('c'); assert.strictEqual(document.cookie, '', 'should delete the cookie'); }); QUnit.test('with attributes', function (assert) { assert.expect(1); var attributes = { path: '/' }; Cookies.set('c', 'v', attributes); Cookies.remove('c', attributes); assert.strictEqual(document.cookie, '', 'should delete the cookie'); }); QUnit.test('passing attributes reference', function (assert) { assert.expect(1); var attributes = { path: '/' }; Cookies.set('c', 'v', attributes); Cookies.remove('c', attributes); assert.deepEqual(attributes, { path: '/' }, 'won\'t alter attributes object'); }); QUnit.module('converters', lifecycle); // github.com/carhartl/jquery-cookie/pull/166 QUnit.test('provide a way for decoding characters encoded by the escape function', function (assert) { assert.expect(1); document.cookie = 'c=%u5317%u4eac'; assert.strictEqual(Cookies.withConverter(unescape).get('c'), '北京', 'should convert chinese characters correctly'); }); QUnit.test('should decode a malformed char that matches the decodeURIComponent regex', function (assert) { assert.expect(1); document.cookie = 'c=%E3'; var cookies = Cookies.withConverter(unescape); assert.strictEqual(cookies.get('c'), 'ã', 'should convert the character correctly'); cookies.remove('c', { path: '' }); }); QUnit.test('should be able to conditionally decode a single malformed cookie', function (assert) { assert.expect(4); var cookies = Cookies.withConverter(function (value, name) { if (name === 'escaped') { return unescape(value); } }); document.cookie = 'escaped=%u5317'; assert.strictEqual(cookies.get('escaped'), '北', 'should use a custom method for escaped cookie'); document.cookie = 'encoded=%E4%BA%AC'; assert.strictEqual(cookies.get('encoded'), '京', 'should use the default encoding for the rest'); assert.deepEqual(cookies.get(), { escaped: '北', encoded: '京' }, 'should retrieve everything'); Object.keys(cookies.get()).forEach(function (name) { cookies.remove(name, { path: '' }); }); assert.strictEqual(document.cookie, '', 'should remove everything'); }); // github.com/js-cookie/js-cookie/issues/70 QUnit.test('should be able to create a write decoder', function (assert) { assert.expect(1); Cookies.withConverter({ write: function (value) { return value.replace('+', '%2B'); } }).set('c', '+'); assert.strictEqual(document.cookie, 'c=%2B', 'should call the write converter'); }); QUnit.test('should be able to use read and write decoder', function (assert) { assert.expect(1); document.cookie = 'c=%2B'; var cookies = Cookies.withConverter({ read: function (value) { return value.replace('%2B', '+'); } }); assert.strictEqual(cookies.get('c'), '+', 'should call the read converter'); }); QUnit.module('JSON handling', lifecycle); QUnit.test('Number', function (assert) { assert.expect(2); Cookies.set('c', 1); assert.strictEqual(Cookies.getJSON('c'), 1, 'should handle a Number'); assert.strictEqual(Cookies.get('c'), '1', 'should return a String'); }); QUnit.test('Boolean', function (assert) { assert.expect(2); Cookies.set('c', true); assert.strictEqual(Cookies.getJSON('c'), true, 'should handle a Boolean'); assert.strictEqual(Cookies.get('c'), 'true', 'should return a Boolean'); }); QUnit.test('Array Literal', function (assert) { assert.expect(2); Cookies.set('c', ['v']); assert.deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Literal'); assert.strictEqual(Cookies.get('c'), '["v"]', 'should return a String'); }); QUnit.test('Array Constructor', function (assert) { /*jshint -W009 */ assert.expect(2); var value = new Array(); value[0] = 'v'; Cookies.set('c', value); assert.deepEqual(Cookies.getJSON('c'), ['v'], 'should handle Array Constructor'); assert.strictEqual(Cookies.get('c'), '["v"]', 'should return a String'); }); QUnit.test('Object Literal', function (assert) { assert.expect(2); Cookies.set('c', {k: 'v'}); assert.deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Literal'); assert.strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String'); }); QUnit.test('Object Constructor', function (assert) { /*jshint -W010 */ assert.expect(2); var value = new Object(); value.k = 'v'; Cookies.set('c', value); assert.deepEqual(Cookies.getJSON('c'), {k: 'v'}, 'should handle Object Constructor'); assert.strictEqual(Cookies.get('c'), '{"k":"v"}', 'should return a String'); }); QUnit.test('Use String(value) for unsupported objects that do not stringify into JSON', function (assert) { assert.expect(2); Cookies.set('date', new Date(2015, 04, 13, 0, 0, 0, 0)); assert.strictEqual(Cookies.get('date').indexOf('"'), -1, 'should not quote the stringified Date object'); assert.strictEqual(Cookies.getJSON('date').indexOf('"'), -1, 'should not quote the stringified Date object'); }); QUnit.test('Call to read all cookies with mixed json', function (assert) { Cookies.set('c', { foo: 'bar' }); Cookies.set('c2', 'v'); assert.deepEqual(Cookies.getJSON(), { c: { foo: 'bar' }, c2: 'v' }, 'returns JSON parsed cookies'); assert.deepEqual(Cookies.get(), { c: '{"foo":"bar"}', c2: 'v' }, 'returns unparsed cookies'); }); QUnit.module('noConflict', lifecycle); QUnit.test('do not conflict with existent globals', function (assert) { assert.expect(2); var Cookies = window.Cookies.noConflict(); Cookies.set('c', 'v'); assert.strictEqual(Cookies.get('c'), 'v', 'should work correctly'); assert.strictEqual(window.Cookies, 'existent global', 'should restore the original global'); window.Cookies = Cookies; });
mit
ValveSoftware/vogl
src/vogleditor/vogleditor_tracereplayer.cpp
13054
#include "vogleditor_apicalltreeitem.h" #include "vogleditor_apicallitem.h" #include "vogleditor_frameitem.h" #include "vogleditor_tracereplayer.h" #include "vogl_find_files.h" #include "vogl_file_utils.h" #include "vogl_gl_replayer.h" #include "vogleditor_output.h" vogleditor_traceReplayer::vogleditor_traceReplayer() : m_pTraceReplayer(vogl_new(vogl_gl_replayer)) { } vogleditor_traceReplayer::~vogleditor_traceReplayer() { if (m_pTraceReplayer != NULL) { vogl_delete(m_pTraceReplayer); m_pTraceReplayer = NULL; } } void vogleditor_traceReplayer::enable_screenshot_capturing(std::string screenshot_prefix) { m_screenshot_prefix = screenshot_prefix; } void vogleditor_traceReplayer::enable_fs_preprocessor(std::string fs_preprocessor) { m_fs_preprocessor = fs_preprocessor; } bool vogleditor_traceReplayer::process_events() { SDL_Event wnd_event; while (SDL_PollEvent(&wnd_event)) { switch (wnd_event.type) { case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_RESTORED: { m_pTraceReplayer->update_window_dimensions(); break; } case SDL_WINDOWEVENT_MOVED: case SDL_WINDOWEVENT_RESIZED: { m_pTraceReplayer->update_window_dimensions(); break; } case SDL_WINDOWEVENT: { switch (wnd_event.window.event) { case SDL_WINDOWEVENT_CLOSE: vogl_message_printf("Exiting\n"); return false; break; default: break; }; break; } default: break; } } return true; } bool vogleditor_traceReplayer::applying_snapshot_and_process_resize(const vogl_gl_state_snapshot *pSnapshot) { vogl_gl_replayer::status_t status = m_pTraceReplayer->begin_applying_snapshot(pSnapshot, false); bool bStatus = true; while (status == vogl_gl_replayer::cStatusResizeWindow) { vogleditor_output_message("Waiting for replay window to resize."); // Pump X events in case the window is resizing if (process_events()) { status = m_pTraceReplayer->process_pending_window_resize(); } else { bStatus = false; break; } } if (bStatus && status != vogl_gl_replayer::cStatusOK) { vogleditor_output_error("Replay unable to apply snapshot"); bStatus = false; } return bStatus; } vogleditor_tracereplayer_result vogleditor_traceReplayer::take_state_snapshot_if_needed(vogleditor_gl_state_snapshot **ppNewSnapshot, uint32_t apiCallNumber) { vogleditor_tracereplayer_result result = VOGLEDITOR_TRR_SUCCESS; if (ppNewSnapshot != NULL) { // get the snapshot after the selected api call if ((!*ppNewSnapshot) && (m_pTraceReplayer->get_last_processed_call_counter() == static_cast<int64_t>(apiCallNumber))) { dynamic_string info; vogleditor_output_message(info.format("Taking snapshot on API call # %u...", apiCallNumber).c_str()); vogl_gl_state_snapshot *pNewSnapshot = m_pTraceReplayer->snapshot_state(); if (pNewSnapshot == NULL) { result = VOGLEDITOR_TRR_ERROR; vogleditor_output_error("... snapshot failed!"); } else { result = VOGLEDITOR_TRR_SNAPSHOT_SUCCESS; vogleditor_output_message("... snapshot succeeded!\n"); *ppNewSnapshot = vogl_new(vogleditor_gl_state_snapshot, pNewSnapshot); if (*ppNewSnapshot == NULL) { result = VOGLEDITOR_TRR_ERROR; vogleditor_output_error("Allocating memory for snapshot container failed!"); vogl_delete(pNewSnapshot); } } } } return result; } inline bool status_indicates_end(vogl_gl_replayer::status_t status) { return (status == vogl_gl_replayer::cStatusHardFailure) || (status == vogl_gl_replayer::cStatusAtEOF); } vogleditor_tracereplayer_result vogleditor_traceReplayer::recursive_replay_apicallTreeItem(vogleditor_apiCallTreeItem *pItem, vogleditor_gl_state_snapshot **ppNewSnapshot, uint64_t apiCallNumber) { vogleditor_tracereplayer_result result = VOGLEDITOR_TRR_SUCCESS; if (pItem->frameItem() != NULL && m_screenshot_prefix.size() > 0) { // take screenshot m_pTraceReplayer->snapshot_backbuffer(); dynamic_string screenshot_filename; pItem->frameItem()->set_screenshot_filename(screenshot_filename.format("%s_%07" PRIu64 ".png", m_screenshot_prefix.c_str(), pItem->frameItem()->frameNumber())); } vogleditor_apiCallItem *pApiCall = pItem->apiCallItem(); if (pApiCall != NULL) { vogl_trace_packet *pTrace_packet = pApiCall->getTracePacket(); vogl_gl_replayer::status_t status = vogl_gl_replayer::cStatusOK; // See if a window resize or snapshot is pending. If a window resize is pending we must delay a while and pump X events until the window is resized. while (m_pTraceReplayer->get_has_pending_window_resize() || m_pTraceReplayer->get_pending_apply_snapshot()) { // Pump X events in case the window is resizing if (process_events()) { status = m_pTraceReplayer->process_pending_window_resize(); if (status != vogl_gl_replayer::cStatusResizeWindow) break; } else { // most likely the window wants to close, so let's return return VOGLEDITOR_TRR_USER_EXIT; } } // process pending trace packets (this could include glXMakeCurrent) if (!status_indicates_end(status) && m_pTraceReplayer->has_pending_packets()) { status = m_pTraceReplayer->process_pending_packets(); // if that was successful, check to see if a state snapshot is needed if (!status_indicates_end(status)) { // update gl entrypoints if needed if (vogl_is_make_current_entrypoint(pTrace_packet->get_entrypoint_id()) && load_gl()) { vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper); } result = take_state_snapshot_if_needed(ppNewSnapshot, apiCallNumber); } } // replay the trace packet if (!status_indicates_end(status)) status = m_pTraceReplayer->process_next_packet(*pTrace_packet); // if that was successful, check to see if a state snapshot is needed if (!status_indicates_end(status)) { // update gl entrypoints if needed if (vogl_is_make_current_entrypoint(pTrace_packet->get_entrypoint_id()) && load_gl()) { vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper); } result = take_state_snapshot_if_needed(ppNewSnapshot, apiCallNumber); } else { // replaying the trace packet failed, set as error result = VOGLEDITOR_TRR_ERROR; dynamic_string info; vogleditor_output_error(info.format("Unable to replay gl entrypoint at call %" PRIu64, pTrace_packet->get_call_counter()).c_str()); } } if (result == VOGLEDITOR_TRR_SUCCESS && pItem->has_snapshot() && pItem->get_snapshot()->is_edited() && pItem->get_snapshot()->is_valid()) { if (applying_snapshot_and_process_resize(pItem->get_snapshot()->get_snapshot())) { result = VOGLEDITOR_TRR_SUCCESS; } } if (result == VOGLEDITOR_TRR_SUCCESS) { for (int i = 0; i < pItem->childCount(); i++) { result = recursive_replay_apicallTreeItem(pItem->child(i), ppNewSnapshot, apiCallNumber); if (result != VOGLEDITOR_TRR_SUCCESS) break; // Pump X events in case the window is resizing if (process_events() == false) { // most likely the window wants to close, so let's return return VOGLEDITOR_TRR_USER_EXIT; } } } return result; } vogleditor_tracereplayer_result vogleditor_traceReplayer::replay(vogl_trace_file_reader *m_pTraceReader, vogleditor_apiCallTreeItem *pRootItem, vogleditor_gl_state_snapshot **ppNewSnapshot, uint64_t apiCallNumber, bool endlessMode) { // reset to beginnning of trace file. m_pTraceReader->seek_to_frame(0); int initial_window_width = 1280; int initial_window_height = 1024; if (!m_window.open(initial_window_width, initial_window_height)) { vogleditor_output_error("Failed opening GL replayer window!"); return VOGLEDITOR_TRR_ERROR; } uint replayer_flags = cGLReplayerForceDebugContexts; if (m_screenshot_prefix.size() > 0) { replayer_flags |= cGLReplayerDumpScreenshots; m_pTraceReplayer->set_screenshot_prefix(m_screenshot_prefix.c_str()); } if (m_fs_preprocessor.size() > 0) { replayer_flags |= cGLReplayerFSPreprocessor; m_pTraceReplayer->set_fs_preprocessor(m_fs_preprocessor.c_str()); // Only check FSpp options when FS preprocessor is enabled if (m_fs_preprocessor_options.size() > 0) m_pTraceReplayer->set_fs_preprocessor_options(m_fs_preprocessor_options.c_str()); if (m_fs_preprocessor_prefix.size() > 0) m_pTraceReplayer->set_fs_preprocessor_prefix(m_fs_preprocessor_prefix.c_str()); } if (!m_pTraceReplayer->init(replayer_flags, &m_window, m_pTraceReader->get_sof_packet(), m_pTraceReader->get_multi_blob_manager())) { vogleditor_output_error("Failed initializing GL replayer!"); m_window.close(); return VOGLEDITOR_TRR_ERROR; } timer tm; tm.start(); vogleditor_tracereplayer_result result = VOGLEDITOR_TRR_SUCCESS; for (;;) { if (process_events() == false) { result = VOGLEDITOR_TRR_USER_EXIT; break; } if (pRootItem->childCount() > 0) { vogleditor_apiCallTreeItem *pFirstFrame = pRootItem->child(0); bool bStatus = true; // if the first snapshot has not been edited, then restore it here, otherwise it will get restored in the recursive call below. if (pFirstFrame->has_snapshot() && !pFirstFrame->get_snapshot()->is_edited()) { // Attempt to initialize GL func pointers here so they're available when loading from a snapshot at start of trace if (load_gl()) vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper); bStatus = applying_snapshot_and_process_resize(pFirstFrame->get_snapshot()->get_snapshot()); } if (bStatus) { // replay each API call. result = recursive_replay_apicallTreeItem(pRootItem, ppNewSnapshot, apiCallNumber); if (result == VOGLEDITOR_TRR_ERROR) { QString msg = QString("Replay ending abruptly at frame index %1, global api call %2").arg(m_pTraceReplayer->get_frame_index()).arg(m_pTraceReplayer->get_last_processed_call_counter()); vogleditor_output_error(msg.toStdString().c_str()); break; } else if (result == VOGLEDITOR_TRR_SNAPSHOT_SUCCESS) { break; } else if (result == VOGLEDITOR_TRR_USER_EXIT) { vogleditor_output_message("Replay stopped"); break; } else { QString msg = QString("At trace EOF, frame index %1").arg(m_pTraceReplayer->get_frame_index()); vogleditor_output_message(msg.toStdString().c_str()); if (!endlessMode) { break; } } } else { break; } } } m_pTraceReplayer->deinit(); m_window.close(); return result; } bool vogleditor_traceReplayer::pause() { VOGL_ASSERT(!"Not implemented"); return false; } bool vogleditor_traceReplayer::restart() { VOGL_ASSERT(!"Not implemented"); return false; } bool vogleditor_traceReplayer::trim() { VOGL_ASSERT(!"Not implemented"); return false; } bool vogleditor_traceReplayer::stop() { VOGL_ASSERT(!"Not implemented"); return false; }
mit
andineck/connect-livereload
test/app.options.src-ignore.js
1224
var express = require("express"); var app = express(); // load liveReload script app.use(require('../index.js')({ port: 35730, src: "http://localhost/livereload.js?snipver=2", ignore: [] })); // load static content before routing takes place app.use(express["static"](__dirname + "/fixtures")); app.get("/default-test", function (req, res) { var html = '<html><head></head><body><p>default test </p></body></html>'; res.send(html); }); app.get("/index.html", function (req, res) { var html = '<html><head></head><body><p>default test </p></body></html>'; res.send(html); }); // start the server if (!module.parent) { var port = settings.webserver.port || 3000; app.listen(port); console.log("Express app started on port " + port); } // run the tests var request = require('supertest'); var assert = require('assert'); describe('GET /default-test', function () { it('respond with inserted script', function (done) { request(app) .get('/default-test') .set('Accept', 'text/html') .expect(200) .end(function (err, res) { assert(~res.text.indexOf('http://localhost/livereload.js?snipver=2')); if (err) return done(err); done() }); }) });
mit
seanbrady5535/jmagcoin2
src/qt/locale/bitcoin_fi.ts
144999
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fi" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Dogecoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Dogecoin Core&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Tämä on kokeellinen ohjelmisto. Levitetään MIT/X11 ohjelmistolisenssin alaisuudessa. Tarkemmat tiedot löytyvät tiedostosta COPYING tai osoitteesta http://www.opensource.org/licenses/mit-license.php. Tämä ohjelma sisältää OpenSSL projektin OpenSSL työkalupakin (http://www.openssl.org/), Eric Youngin (eay@cryptsoft.com) kehittämän salausohjelmiston sekä Thomas Bernardin UPnP ohjelmiston. </translation> </message> <message> <location filename="../utilitydialog.cpp" line="+29"/> <source>Copyright</source> <translation>Tekijänoikeus</translation> </message> <message> <location line="+0"/> <source>The Dogecoin Core developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+30"/> <source>Double-click to edit address or label</source> <translation>Kaksoisnapauta muokataksesi osoitetta tai nimeä</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Luo uusi osoite</translation> </message> <message> <location line="+3"/> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopioi valittu osoite leikepöydälle</translation> </message> <message> <location line="+3"/> <source>&amp;Copy</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>C&amp;lose</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+74"/> <source>&amp;Copy Address</source> <translation>&amp;Kopioi Osoite</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="-41"/> <source>Delete the currently selected address from the list</source> <translation>Poista valittu osoite listalta</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Vie auki olevan välilehden tiedot tiedostoon</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-27"/> <source>&amp;Delete</source> <translation>&amp;Poista</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-30"/> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Very sending addresses</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Much receiving addresses</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>These are your Dogecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>These are your Dogecoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Label</source> <translation>Kopioi &amp;Nimi</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Muokkaa</translation> </message> <message> <location line="+194"/> <source>Export Address List</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+13"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>There was an error trying to save the address list to %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+168"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Tunnuslauseen Dialogi</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Kirjoita tunnuslause</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Uusi tunnuslause</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Kiroita uusi tunnuslause uudelleen</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+40"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Anna lompakolle uusi tunnuslause.&lt;br/&gt;Käytä tunnuslausetta, jossa on ainakin &lt;b&gt;10 satunnaista mekkiä&lt;/b&gt; tai &lt;b&gt;kahdeksan sanaa&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Salaa lompakko</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause sen avaamiseksi.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Avaa lompakko</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Tätä toimintoa varten sinun täytyy antaa lompakon tunnuslause salauksen purkuun.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Pura lompakon salaus</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Vaihda tunnuslause</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Anna vanha ja uusi tunnuslause.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Vahvista lompakon salaus</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR DOGECOINS&lt;/b&gt;!</source> <translation>Varoitus: Jos salaat lompakkosi ja menetät tunnuslauseesi, &lt;b&gt;MENETÄT KAIKKI DOGECOINISI&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Haluatko varmasti salata lompakkosi?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>TÄRKEÄÄ: Kaikki vanhat lompakon varmuuskopiot pitäisi korvata uusilla suojatuilla varmuuskopioilla. Turvallisuussyistä edelliset varmuuskopiot muuttuvat turhiksi, kun aloitat suojatun lompakon käytön.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Varoitus: Caps Lock on käytössä!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Lompakko salattu</translation> </message> <message> <location line="-56"/> <source>Dogecoin Core will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Dogecoins from being stolen by malware infecting your computer.</source> <translation>Dogecoin sulkeutuu lopettaakseen salausprosessin. Muista, että salattukaan lompakko ei täysin suojaa sitä haittaohjelmien aiheuttamilta varkauksilta.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Lompakon salaus epäonnistui</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Lompakon salaaminen epäonnistui sisäisen virheen vuoksi. Lompakkoasi ei salattu.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Annetut tunnuslauseet eivät täsmää.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Lompakon avaaminen epäonnistui.</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Annettu tunnuslause oli väärä.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Lompakon salauksen purku epäonnistui.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Lompakon tunnuslause vaihdettiin onnistuneesti.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+295"/> <source>Sign &amp;message...</source> <translation>&amp;Allekirjoita viesti...</translation> </message> <message> <location line="+335"/> <source>Synchronizing with network...</source> <translation>Synkronoidaan verkon kanssa...</translation> </message> <message> <location line="-407"/> <source>&amp;Overview</source> <translation>&amp;Yleisnäkymä</translation> </message> <message> <location line="-137"/> <source>Node</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Show general overview of wallet</source> <translation>Lompakon tilanteen yleiskatsaus</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Rahansiirrot</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Selaa rahansiirtohistoriaa</translation> </message> <message> <location line="+17"/> <source>E&amp;xit</source> <translation>L&amp;opeta</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sulje ohjelma</translation> </message> <message> <location line="+7"/> <source>Show information about Dogecoin Core</source> <translation>Näytä tietoa Dogecoin-projektista</translation> </message> <message> <location line="+3"/> <location line="+2"/> <source>About &amp;Qt</source> <translation>Tietoja &amp;Qt</translation> </message> <message> <location line="+2"/> <source>Show information about Qt</source> <translation>Näytä tietoja QT:ta</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Asetukset...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Salaa lompakko...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Varmuuskopioi Lompakko...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Vaihda Tunnuslause...</translation> </message> <message> <location line="+10"/> <source>Very &amp;sending addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Much &amp;receiving addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open &amp;URI...</source> <translation type="unfinished"/> </message> <message> <location line="+325"/> <source>Importing blocks from disk...</source> <translation>Tuodaan lohkoja levyltä</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Ladataan lohkoindeksiä...</translation> </message> <message> <location line="-405"/> <source>Send coins to a Dogecoin address</source> <translation>Lähetä kolikoita Dogecoin-osoitteeseen</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Dogecoin Core</source> <translation>Muuta Dogecoinin konfiguraatioasetuksia</translation> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>Varmuuskopioi lompakko toiseen sijaintiin</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Vaihda lompakon salaukseen käytettävä tunnuslause</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Testausikkuna</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Avaa debuggaus- ja diagnostiikkakonsoli</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Varmista &amp;viesti...</translation> </message> <message> <location line="+430"/> <source>Dogecoin</source> <translation>Dogecoin</translation> </message> <message> <location line="-643"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+146"/> <source>&amp;Send</source> <translation>&amp;Lähetä</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Vastaanota</translation> </message> <message> <location line="+46"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation>&amp;Näytä / Piilota</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Näytä tai piilota Dogecoin-ikkuna</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Suojaa yksityiset avaimet, jotka kuuluvat lompakkoosi</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Dogecoin addresses to prove you own them</source> <translation>Allekirjoita viestisi omalla Dogecoin -osoitteellasi todistaaksesi, että omistat ne</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Dogecoin addresses</source> <translation>Varmista, että viestisi on allekirjoitettu määritetyllä Dogecoin -osoitteella</translation> </message> <message> <location line="+48"/> <source>&amp;File</source> <translation>&amp;Tiedosto</translation> </message> <message> <location line="+14"/> <source>&amp;Settings</source> <translation>&amp;Asetukset</translation> </message> <message> <location line="+9"/> <source>&amp;Help</source> <translation>&amp;Apua</translation> </message> <message> <location line="+15"/> <source>Tabs toolbar</source> <translation>Välilehtipalkki</translation> </message> <message> <location line="-284"/> <location line="+376"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-401"/> <source>Dogecoin Core</source> <translation>Dogecoin-ydin</translation> </message> <message> <location line="+163"/> <source>Request payments (generates QR codes and dogecoin: URIs)</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <location line="+2"/> <source>&amp;About Dogecoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open a dogecoin: URI or payment request</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the Dogecoin Core help message to get a list with possible Dogecoin Core command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+159"/> <location line="+5"/> <source>Dogecoin client</source> <translation>Dogecoin-asiakas</translation> </message> <message numerus="yes"> <location line="+142"/> <source>%n active connection(s) to Dogecoin network</source> <translation><numerusform>%n aktiivinen yhteys Dogecoin-verkkoon</numerusform><numerusform>%n aktiivista yhteyttä Dogecoin-verkkoon</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Käsitelty %1 lohkoa rahansiirtohistoriasta</translation> </message> <message numerus="yes"> <location line="+23"/> <source>%n hour(s)</source> <translation><numerusform>%n tunti</numerusform><numerusform>%n tuntia</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n viikko</numerusform><numerusform>%n viikkoa</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Last received block was generated %1 ago.</source> <translation>Viimeisin vastaanotettu lohko tuotettu %1.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Varoitus</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Tietoa</translation> </message> <message> <location line="-85"/> <source>Up to date</source> <translation>Rahansiirtohistoria on ajan tasalla</translation> </message> <message> <location line="+34"/> <source>Catching up...</source> <translation>Saavutetaan verkkoa...</translation> </message> <message> <location line="+130"/> <source>Sent transaction</source> <translation>Lähetetyt rahansiirrot</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Saapuva rahansiirto</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Päivä: %1 Määrä: %2 Tyyppi: %3 Osoite: %4</translation> </message> <message> <location line="+69"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;avoinna&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Lompakko on &lt;b&gt;salattu&lt;/b&gt; ja tällä hetkellä &lt;b&gt;lukittuna&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+438"/> <source>A fatal error occurred. Dogecoin Core can no longer continue safely and will quit.</source> <translation>Peruuttamaton virhe on tapahtunut. Dogecoin ei voi enää jatkaa turvallisesti ja sammutetaan.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+119"/> <source>Network Alert</source> <translation>Verkkohälytys</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="+29"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+63"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+10"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Aika</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Vahvistettu</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+42"/> <source>Copy address</source> <translation>Kopioi osoite</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopioi nimi</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+323"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>higher</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lower</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Dust</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+5"/> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+4"/> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <location line="-3"/> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <location line="+66"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Muokkaa osoitetta</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Nimi</translation> </message> <message> <location line="+10"/> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>&amp;Address</source> <translation>&amp;Osoite</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+28"/> <source>New receiving address</source> <translation>Uusi vastaanottava osoite</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Uusi lähettävä osoite</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Muokkaa vastaanottajan osoitetta</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Muokkaa lähtevää osoitetta</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Osoite &quot;%1&quot; on jo osoitekirjassa.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Dogecoin address.</source> <translation>Antamasi osoite &quot;%1&quot; ei ole validi Dogecoin-osoite.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Lompakkoa ei voitu avata.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Uuden avaimen luonti epäonnistui.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+65"/> <source>A new data directory will be created.</source> <translation>Luodaan uusi kansio.</translation> </message> <message> <location line="+22"/> <source>name</source> <translation>Nimi</translation> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation>Polku on jo olemassa, eikä se ole kansio.</translation> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageDialog</name> <message> <location filename="../forms/helpmessagedialog.ui" line="+19"/> <source>Dogecoin Core - Command-line options</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+38"/> <source>Dogecoin Core</source> <translation>Dogecoin-ydin</translation> </message> <message> <location line="+0"/> <source>version</source> <translation>versio</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>komentorivi parametrit</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Käyttöliittymäasetukset</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Set language, for example &quot;de_DE&quot; (default: system locale)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Käynnistä pienennettynä</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Näytä aloitusruutu käynnistettäessä (oletus: 1)</translation> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation>Tervetuloa</translation> </message> <message> <location line="+9"/> <source>Welcome to Dogecoin Core.</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where Dogecoin Core will store its data.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Dogecoin Core will download and store a copy of the Dogecoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation>Käytä oletuskansiota</translation> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation>Määritä oma kansio:</translation> </message> <message> <location filename="../intro.cpp" line="+85"/> <source>Dogecoin</source> <translation>Dogecoin</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OpenURIDialog</name> <message> <location filename="../forms/openuridialog.ui" line="+14"/> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>URI:</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <location filename="../openuridialog.cpp" line="+47"/> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Asetukset</translation> </message> <message> <location line="+13"/> <source>&amp;Main</source> <translation>&amp;Yleiset</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Maksa rahansiirtopalkkio</translation> </message> <message> <location line="+31"/> <source>Automatically start Dogecoin Core after logging in to the system.</source> <translation>Käynnistä Dogecoin kirjautumisen yhteydessä.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Dogecoin Core on system login</source> <translation>&amp;Käynnistä Dogecoin kirjautumisen yhteydessä</translation> </message> <message> <location line="+9"/> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation> </message> <message> <location line="+13"/> <source>MB</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Connect to the Dogecoin network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <location line="+224"/> <source>Active command-line options that override above options:</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="-323"/> <source>&amp;Network</source> <translation>&amp;Verkko</translation> </message> <message> <location line="+6"/> <source>Automatically open the Dogecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Avaa Dogecoin-asiakasohjelman portti reitittimellä automaattisesti. Tämä toimii vain, jos reitittimesi tukee UPnP:tä ja se on käytössä.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portin uudelleenohjaus &amp;UPnP:llä</translation> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation>Proxyn &amp;IP:</translation> </message> <message> <location line="+32"/> <source>&amp;Port:</source> <translation>&amp;Portti</translation> </message> <message> <location line="+25"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxyn Portti (esim. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versio:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Proxyn SOCKS-versio (esim. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Ikkuna</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Näytä ainoastaan ilmaisinalueella ikkunan pienentämisen jälkeen.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Pienennä ilmaisinalueelle työkalurivin sijasta</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Ikkunaa suljettaessa vain pienentää Dogecoin-ohjelman ikkunan lopettamatta itse ohjelmaa. Kun tämä asetus on valittuna, ohjelman voi sulkea vain valitsemalla Lopeta ohjelman valikosta.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>P&amp;ienennä suljettaessa</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Käyttöliittymä</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Käyttöliittymän kieli</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Dogecoin Core.</source> <translation>Tässä voit määritellä käyttöliittymän kielen. Muutokset astuvat voimaan seuraavan kerran, kun Dogecoin käynnistetään.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>Yksikkö jona dogecoin-määrät näytetään</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Valitse mitä yksikköä käytetään ensisijaisesti dogecoin-määrien näyttämiseen.</translation> </message> <message> <location line="+9"/> <source>Whether to show Dogecoin addresses in the transaction list or not.</source> <translation>Näytetäänkö Dogecoin-osoitteet rahansiirrot listassa vai ei.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Näytä osoitteet rahansiirrot listassa</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only)</source> <translation type="unfinished"/> </message> <message> <location line="+136"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Peruuta</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+67"/> <source>default</source> <translation>oletus</translation> </message> <message> <location line="+57"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+75"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+29"/> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>This change would require a client restart.</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The supplied proxy address is invalid.</source> <translation>Antamasi proxy-osoite on virheellinen.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Lomake</translation> </message> <message> <location line="+50"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Dogecoin network after a connection is established, but this process has not completed yet.</source> <translation>Näytetyt tiedot eivät välttämättä ole ajantasalla. Lompakkosi synkronoituu Dogecoin-verkon kanssa automaattisesti yhteyden muodostamisen jälkeen, mutta synkronointi on vielä meneillään.</translation> </message> <message> <location line="-155"/> <source>Unconfirmed:</source> <translation>Vahvistamatta:</translation> </message> <message> <location line="-83"/> <source>Wallet</source> <translation>Lompakko</translation> </message> <message> <location line="+51"/> <source>Confirmed:</source> <translation>Vahvistettu</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Immature:</source> <translation>Epäkypsää:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Louhittu saldo, joka ei ole vielä kypsynyt</translation> </message> <message> <location line="+16"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Tililläsi tällä hetkellä olevien Dogecoinien määrä</translation> </message> <message> <location line="+71"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Viimeisimmät rahansiirrot&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+120"/> <location line="+1"/> <source>out of sync</source> <translation>Ei ajan tasalla</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+403"/> <location line="+13"/> <source>URI handling</source> <translation>URI käsittely</translation> </message> <message> <location line="+1"/> <source>URI can not be parsed! This can be caused by an invalid Dogecoin address or malformed URI parameters.</source> <translation>URIa ei voitu jäsentää! Tämä voi johtua kelvottomasta Dogecoin-osoitteesta tai virheellisistä URI parametreista.</translation> </message> <message> <location line="+96"/> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <location line="-221"/> <location line="+212"/> <location line="+13"/> <location line="+95"/> <location line="+18"/> <location line="+16"/> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <location line="-353"/> <source>Cannot start dogecoin: click-to-pay handler</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Net manager warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation type="unfinished"/> </message> <message> <location line="+73"/> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+71"/> <location line="+11"/> <source>Dogecoin</source> <translation>Dogecoin</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> </context> <context> <name>QRImageWidget</name> <message> <location filename="../receiverequestdialog.cpp" line="+36"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Save QR Code</source> <translation>Tallenna QR-koodi</translation> </message> <message> <location line="+0"/> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Pääteohjelman nimi</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+359"/> <source>N/A</source> <translation>Ei saatavilla</translation> </message> <message> <location line="-223"/> <source>Client version</source> <translation>Pääteohjelman versio</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>T&amp;ietoa</translation> </message> <message> <location line="-10"/> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>General</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Using OpenSSL version</source> <translation>Käytössä oleva OpenSSL-versio</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Käynnistysaika</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Verkko</translation> </message> <message> <location line="+7"/> <source>Name</source> <translation>Nimi</translation> </message> <message> <location line="+23"/> <source>Number of connections</source> <translation>Yhteyksien lukumäärä</translation> </message> <message> <location line="+29"/> <source>Block chain</source> <translation>Lohkoketju</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Nykyinen Lohkojen määrä</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Arvioitu lohkojen kokonaismäärä</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Viimeisimmän lohkon aika</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Avaa</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsoli</translation> </message> <message> <location line="+72"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-521"/> <source>Build date</source> <translation>Kääntöpäiväys</translation> </message> <message> <location line="+206"/> <source>Debug log file</source> <translation>Debug lokitiedosto</translation> </message> <message> <location line="+7"/> <source>Open the Dogecoin Core debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Avaa lokitiedosto nykyisestä data-kansiosta. Tämä voi viedä useamman sekunnin, jos lokitiedosto on iso.</translation> </message> <message> <location line="+76"/> <source>Clear console</source> <translation>Tyhjennä konsoli</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Dogecoin Core RPC console.</source> <translation>Tervetuloa Dogecoin RPC konsoliin.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Ylös- ja alas-nuolet selaavat historiaa ja &lt;b&gt;Ctrl-L&lt;/b&gt; tyhjentää ruudun.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Kirjoita &lt;b&gt;help&lt;/b&gt; nähdäksesi yleiskatsauksen käytettävissä olevista komennoista.</translation> </message> <message> <location line="+122"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <location filename="../forms/receivecoinsdialog.ui" line="+83"/> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Label:</source> <translation>&amp;Nimi:</translation> </message> <message> <location line="-34"/> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>An optional label to associate with the new receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Dogecoin network.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Requested payments</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Show</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Remove</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <location filename="../forms/receiverequestdialog.ui" line="+29"/> <source>QR Code</source> <translation>QR-koodi</translation> </message> <message> <location line="+46"/> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location filename="../receiverequestdialog.cpp" line="+56"/> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+2"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+2"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location line="+2"/> <source>Message</source> <translation>Viesti</translation> </message> <message> <location line="+10"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Tuloksen URI liian pitkä, yritä lyhentää otsikon tekstiä / viestiä.</translation> </message> <message> <location line="+5"/> <source>Error encoding URI into QR Code.</source> <translation>Virhe käännettäessä URI:a QR-koodiksi.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <location filename="../recentrequeststablemodel.cpp" line="+24"/> <source>Date</source> <translation>Aika</translation> </message> <message> <location line="+0"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location line="+0"/> <source>Message</source> <translation>Viesti</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+38"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> <message> <location line="+9"/> <source>(no message)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+381"/> <location line="+80"/> <source>Send Coins</source> <translation>Lähetä Dogecoineja</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Määrä:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+115"/> <source>Send to multiple recipients at once</source> <translation>Lähetä monelle vastaanottajalle</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Lisää &amp;Vastaanottaja</translation> </message> <message> <location line="+20"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Tyhjennnä Kaikki</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+41"/> <source>Confirm the send action</source> <translation>Vahvista lähetys</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Lähetä</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-228"/> <source>Confirm send coins</source> <translation>Hyväksy Dogecoinien lähettäminen</translation> </message> <message> <location line="-74"/> <location line="+5"/> <location line="+5"/> <location line="+4"/> <source>%1 to %2</source> <translation type="unfinished"/> </message> <message> <location line="-136"/> <source>Enter a Dogecoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Anna Dogecoin-osoite (esim. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Total Amount %1 (= %2)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>or</source> <translation type="unfinished"/> </message> <message> <location line="+202"/> <source>The recipient address is not valid, please recheck.</source> <translation>Vastaanottajan osoite on virheellinen. Tarkista osoite.</translation> </message> <message> <location line="+3"/> <source>The amount to pay must be larger than 0.</source> <translation>Maksettavan summan tulee olla suurempi kuin 0 Dogecoinia.</translation> </message> <message> <location line="+3"/> <source>The amount exceeds your balance.</source> <translation>Määrä ylittää käytettävissä olevan saldon.</translation> </message> <message> <location line="+3"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Kokonaismäärä ylittää saldosi kun %1 maksukulu lisätään summaan.</translation> </message> <message> <location line="+3"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Sama osoite toistuu useamman kerran. Samaan osoitteeseen voi lähettää vain kerran per maksu.</translation> </message> <message> <location line="+3"/> <source>Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+112"/> <source>Warning: Invalid Dogecoin address</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>(no label)</source> <translation>(ei nimeä)</translation> </message> <message> <location line="-11"/> <source>Warning: Unknown change address</source> <translation type="unfinished"/> </message> <message> <location line="-366"/> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+131"/> <location line="+521"/> <location line="+536"/> <source>A&amp;mount:</source> <translation>M&amp;äärä:</translation> </message> <message> <location line="-1152"/> <source>Pay &amp;To:</source> <translation>Maksun saaja:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Osoite, johon Dogecoinit lähetetään (esim. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+30"/> <source>Enter a label for this address to add it to your address book</source> <translation>Anna nimi tälle osoitteelle, jos haluat lisätä sen osoitekirjaan</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="+57"/> <source>&amp;Label:</source> <translation>&amp;Nimi:</translation> </message> <message> <location line="-50"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-40"/> <source>This is a normal payment.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <location line="+524"/> <location line="+536"/> <source>Remove this entry</source> <translation type="unfinished"/> </message> <message> <location line="-1008"/> <source>Message:</source> <translation>Viesti:</translation> </message> <message> <location line="+10"/> <source>A message that was attached to the Dogecoin URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Dogecoin network.</source> <translation type="unfinished"/> </message> <message> <location line="+958"/> <source>This is a verified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="-991"/> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <location line="+459"/> <source>This is an unverified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <location line="+532"/> <source>Pay To:</source> <translation type="unfinished"/> </message> <message> <location line="-498"/> <location line="+536"/> <source>Memo:</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Dogecoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Anna Dogecoin-osoite (esim. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <location filename="../utilitydialog.cpp" line="+48"/> <source>Dogecoin Core is shutting down...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not shut down the computer until this window disappears.</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Allekirjoitukset - Allekirjoita / Varmista viesti</translation> </message> <message> <location line="+10"/> <source>&amp;Sign Message</source> <translation>&amp;Allekirjoita viesti</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Voit allekirjoittaa viestit omalla osoitteellasi todistaaksesi että omistat ne. Ole huolellinen, että et allekirjoita mitään epämääräistä, phishing-hyökkääjät voivat huijata sinua allekirjoittamaan luovuttamalla henkilöllisyytesi. Allekirjoita selvitys täysin yksityiskohtaisesti mihin olet sitoutunut.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Osoite, jolla viesti allekirjoitetaan (esimerkiksi DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose previously used address</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Liitä osoite leikepöydältä</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Kirjoita tähän viesti minkä haluat allekirjoittaa</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Allekirjoitus</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopioi tämänhetkinen allekirjoitus leikepöydälle</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Dogecoin address</source> <translation>Allekirjoita viesti todistaaksesi, että omistat tämän Dogecoin-osoitteen</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Allekirjoita &amp;viesti</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Tyhjennä kaikki allekirjoita-viesti-kentät</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>&amp;Tyhjennä Kaikki</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Varmista viesti</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Syötä allekirjoittava osoite, viesti ja allekirjoitus alla oleviin kenttiin varmistaaksesi allekirjoituksen aitouden. Varmista että kopioit kaikki kentät täsmälleen oikein, myös rivinvaihdot, välilyönnit, tabulaattorit, jne.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Osoite, jolla viesti allekirjoitettiin (esimerkiksi DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Dogecoin address</source> <translation>Tarkista viestin allekirjoitus varmistaaksesi, että se allekirjoitettiin tietyllä Dogecoin-osoitteella</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Varmista &amp;viesti...</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Tyhjennä kaikki varmista-viesti-kentät</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+29"/> <location line="+3"/> <source>Enter a Dogecoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Anna Dogecoin-osoite (esim. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klikkaa &quot;Allekirjoita Viesti luodaksesi allekirjoituksen </translation> </message> <message> <location line="+3"/> <source>Enter Dogecoin signature</source> <translation>Syötä Dogecoin-allekirjoitus</translation> </message> <message> <location line="+84"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Syötetty osoite on virheellinen.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Tarkista osoite ja yritä uudelleen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Syötetyn osoitteen avainta ei löydy.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Lompakon avaaminen peruttiin.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Yksityistä avainta syötetylle osoitteelle ei ole saatavilla.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Viestin allekirjoitus epäonnistui.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Viesti allekirjoitettu.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Allekirjoitusta ei pystytty tulkitsemaan.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Tarkista allekirjoitus ja yritä uudelleen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Allekirjoitus ei täsmää viestin tiivisteeseen.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Viestin varmistus epäonnistui.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Viesti varmistettu.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+28"/> <source>Dogecoin Core</source> <translation>Dogecoin-ydin</translation> </message> <message> <location line="+2"/> <source>The Dogecoin Core developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+79"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+28"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/vahvistamaton</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 vahvistusta</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Tila</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>lähetetty %n noodin läpi</numerusform><numerusform>lähetetty %n noodin läpi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Lähde</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generoitu</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Lähettäjä</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Saaja</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>oma osoite</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>nimi</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+53"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-125"/> <source>matures in %n more block(s)</source> <translation><numerusform>kypsyy %n lohkon kuluttua</numerusform><numerusform>kypsyy %n lohkon kuluttua</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>ei hyväksytty</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+53"/> <source>Debit</source> <translation>Debit</translation> </message> <message> <location line="-62"/> <source>Transaction fee</source> <translation>Maksukulu</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Netto määrä</translation> </message> <message> <location line="+6"/> <location line="+9"/> <source>Message</source> <translation>Viesti</translation> </message> <message> <location line="-7"/> <source>Comment</source> <translation>Viesti</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Siirtotunnus</translation> </message> <message> <location line="+18"/> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>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 &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Debug information</source> <translation>Debug tiedot</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Rahansiirto</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Sisääntulot</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>tosi</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>epätosi</translation> </message> <message> <location line="-232"/> <source>, has not been successfully broadcast yet</source> <translation>, ei ole vielä onnistuneesti lähetetty</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>tuntematon</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Rahansiirron yksityiskohdat</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Tämä ruutu näyttää yksityiskohtaisen tiedon rahansiirrosta</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+234"/> <source>Date</source> <translation>Päivämäärä</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+59"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+16"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Avoinna %1 asti</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Ei yhteyttä verkkoon (%1 vahvistusta)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Vahvistamatta (%1/%2 vahvistusta)</translation> </message> <message> <location line="-22"/> <location line="+25"/> <source>Confirmed (%1 confirmations)</source> <translation>Vahvistettu (%1 vahvistusta)</translation> </message> <message> <location line="-22"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tätä lohkoa ei vastaanotettu mistään muusta solmusta ja sitä ei mahdollisesti hyväksytä!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generoitu mutta ei hyväksytty</translation> </message> <message> <location line="+62"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Vastaanotettu</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Maksu itsellesi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(ei saatavilla)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Rahansiirron tila. Siirrä osoitin kentän päälle nähdäksesi vahvistusten lukumäärä.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Rahansiirron vastaanottamisen päivämäärä ja aika.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Rahansiirron laatu.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Rahansiirron kohteen Dogecoin-osoite</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Saldoon lisätty tai siitä vähennetty määrä.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+57"/> <location line="+16"/> <source>All</source> <translation>Kaikki</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Tänään</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Tällä viikolla</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Tässä kuussa</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Viime kuussa</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Tänä vuonna</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Alue...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Vastaanotettu osoitteella</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Saaja</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Itsellesi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Louhittu</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Muu</translation> </message> <message> <location line="+6"/> <source>Enter address or label to search</source> <translation>Anna etsittävä osoite tai tunniste</translation> </message> <message> <location line="+6"/> <source>Min amount</source> <translation>Minimimäärä</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopioi osoite</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopioi nimi</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopioi määrä</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Muokkaa nimeä</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Näytä rahansiirron yksityiskohdat</translation> </message> <message> <location line="+142"/> <source>Export Transaction History</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the transaction history to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Exporting Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The transaction history was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+9"/> <source>Confirmed</source> <translation>Vahvistettu</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Aika</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Laatu</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Nimi</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Osoite</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Määrä</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+107"/> <source>Range:</source> <translation>Alue:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>kenelle</translation> </message> </context> <context> <name>WalletFrame</name> <message> <location filename="../walletframe.cpp" line="+26"/> <source>No wallet has been loaded.</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+245"/> <source>Send Coins</source> <translation>Lähetä Dogecoineja</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+43"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Vie auki olevan välilehden tiedot tiedostoon</translation> </message> <message> <location line="+181"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Backup Failed</source> <translation>Varmuuskopio epäonnistui</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Backup Successful</source> <translation>Varmuuskopio Onnistui</translation> </message> </context> <context> <name>dogecoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+221"/> <source>Usage:</source> <translation>Käyttö:</translation> </message> <message> <location line="-54"/> <source>List commands</source> <translation>Lista komennoista</translation> </message> <message> <location line="-14"/> <source>Get help for a command</source> <translation>Hanki apua käskyyn</translation> </message> <message> <location line="+26"/> <source>Options:</source> <translation>Asetukset:</translation> </message> <message> <location line="+22"/> <source>Specify configuration file (default: dogecoin.conf)</source> <translation>Määritä asetustiedosto (oletus: dogecoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: dogecoind.pid)</source> <translation>Määritä pid-tiedosto (oletus: dogecoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Määritä data-hakemisto</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Aseta tietokannan välimuistin koko megatavuina (oletus: 25)</translation> </message> <message> <location line="-26"/> <source>Listen for connections on &lt;port&gt; (default: 22556 or testnet: 44556)</source> <translation>Kuuntele yhteyksiä portista &lt;port&gt; (oletus: 22556 tai testnet: 44556)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Pidä enintään &lt;n&gt; yhteyttä verkkoihin (oletus: 125)</translation> </message> <message> <location line="-51"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Yhdistä noodiin hakeaksesi naapurien osoitteet ja katkaise yhteys</translation> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation>Määritä julkinen osoitteesi</translation> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Kynnysarvo aikakatkaisulle heikosti toimiville verkoille (oletus: 100)</translation> </message> <message> <location line="-148"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekuntien määrä, kuinka kauan uudelleenkytkeydytään verkkoihin (oletus: 86400)</translation> </message> <message> <location line="-36"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Virhe valmisteltaessa RPC-portin %u avaamista kuunneltavaksi: %s</translation> </message> <message> <location line="+34"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 22555 or testnet: 44555)</source> <translation>Kuuntele JSON-RPC -yhteyksiä portista &lt;port&gt; (oletus: 22555 or testnet: 44555)</translation> </message> <message> <location line="+45"/> <source>Accept command line and JSON-RPC commands</source> <translation>Hyväksy merkkipohjaiset- ja JSON-RPC-käskyt</translation> </message> <message> <location line="+80"/> <source>Run in the background as a daemon and accept commands</source> <translation>Aja taustalla daemonina ja hyväksy komennot</translation> </message> <message> <location line="+39"/> <source>Use the test network</source> <translation>Käytä test -verkkoa</translation> </message> <message> <location line="-118"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Hyväksy yhteyksiä ulkopuolelta (vakioasetus: 1 jos -proxy tai -connect ei määritelty)</translation> </message> <message> <location line="-95"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=dogecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Dogecoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Virhe ilmennyt asetettaessa RPC-porttia %u IPv6:n kuuntelemiseksi, palataan takaisin IPv4:ään %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Kytkeydy annettuun osoitteeseen ja pidä linja aina auki. Käytä [host]:portin merkintätapaa IPv6:lle.</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Dogecoin Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Varoitus: -paytxfee on asetettu erittäin korkeaksi! Tämä on maksukulu jonka tulet maksamaan kun lähetät siirron.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Dogecoin Core will not work properly.</source> <translation>Varoitus: Tarkista että tietokoneesi kellonaika ja päivämäärä ovat paikkansapitäviä! Dogecoin ei toimi oikein väärällä päivämäärällä ja/tai kellonajalla.</translation> </message> <message> <location line="+3"/> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Dogecoin Core Daemon</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Dogecoin Core RPC client version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Block creation options:</source> <translation>Lohkon luonnin asetukset:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Yhidstä ainoastaan määrättyihin noodeihin</translation> </message> <message> <location line="+1"/> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect to JSON-RPC on &lt;port&gt; (default: 22555 or testnet: 44555)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Hae oma IP osoite (vakioasetus: 1 kun kuuntelemassa ja ei -externalip)</translation> </message> <message> <location line="+1"/> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Virhe avattaessa lohkoindeksiä</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Varoitus: Levytila on vähissä!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Virhe: Lompakko on lukittu, rahansiirtoa ei voida luoda</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Virhe: Järjestelmävirhe</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Ei onnistuttu kuuntelemaan missään portissa. Käytä -listen=0 jos haluat tätä.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Lohkon kirjoitus epäonnistui</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Fee per kB to add to transactions you send</source> <translation>palkkio per kB lisätty lähettämiisi rahansiirtoihin</translation> </message> <message> <location line="+1"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Hae naapureita DNS hauilla (vakioasetus: 1 paitsi jos -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Generoi kolikoita (vakio: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to Dogecoin Core server</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Start Dogecoin Core server</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Usage (deprecated, use dogecoin-cli):</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Wallet options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="-79"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Tuodaan lohkoja ulkoisesta blk000??.dat tiedostosta</translation> </message> <message> <location line="-105"/> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Information</source> <translation>Tietoa</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Suurin vastaanottopuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Suurin lähetyspuskuri yksittäiselle yhteydelle, &lt;n&gt;*1000 tavua (vakioasetus: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Yhdistä vain noodeihin verkossa &lt;net&gt; (IPv4, IPv6 tai Tor)</translation> </message> <message> <location line="+9"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL asetukset (katso Bitcoin Wikistä tarkemmat SSL ohjeet)</translation> </message> <message> <location line="+4"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Lähetä jäljitys/debug-tieto konsoliin, debug.log-tiedoston sijaan</translation> </message> <message> <location line="+6"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Asetan pienin lohkon koko tavuissa (vakioasetus: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Pienennä debug.log tiedosto käynnistyksen yhteydessä (vakioasetus: 1 kun ei -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Siirron vahvistus epäonnistui</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Määritä yhteyden aikakataisu millisekunneissa (vakioasetus: 5000)</translation> </message> <message> <location line="+6"/> <source>System error: </source> <translation>Järjestelmävirhe:</translation> </message> <message> <location line="+5"/> <source>Transaction amount too small</source> <translation>Siirtosumma liian pieni</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Siirtosumma liian iso</translation> </message> <message> <location line="+8"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Käytä UPnP:tä kuunneltavan portin avaamiseen (vakioasetus: 1 kun kuuntelemassa)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Käyttäjätunnus JSON-RPC-yhteyksille</translation> </message> <message> <location line="+7"/> <source>Warning</source> <translation>Varoitus</translation> </message> <message> <location line="+2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Varoitus: Tämä versio on vanhentunut, päivitys tarpeen!</translation> </message> <message> <location line="+2"/> <source>version</source> <translation>versio</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>Password for JSON-RPC connections</source> <translation>Salasana JSON-RPC-yhteyksille</translation> </message> <message> <location line="-70"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Salli JSON-RPC yhteydet tietystä ip-osoitteesta</translation> </message> <message> <location line="+80"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Lähetä käskyjä solmuun osoitteessa &lt;ip&gt; (oletus: 127.0.0.1)</translation> </message> <message> <location line="-132"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Suorita käsky kun paras lohko muuttuu (%s cmd on vaihdettu block hashin kanssa)</translation> </message> <message> <location line="+161"/> <source>Upgrade wallet to latest format</source> <translation>Päivitä lompakko uusimpaan formaattiin</translation> </message> <message> <location line="-24"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Aseta avainpoolin koko arvoon &lt;n&gt; (oletus: 100)</translation> </message> <message> <location line="-11"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Skannaa uudelleen lohkoketju lompakon puuttuvien rahasiirtojen vuoksi</translation> </message> <message> <location line="+38"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Käytä OpenSSL:ää (https) JSON-RPC-yhteyksille</translation> </message> <message> <location line="-30"/> <source>Server certificate file (default: server.cert)</source> <translation>Palvelimen sertifikaatti-tiedosto (oletus: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Palvelimen yksityisavain (oletus: server.pem)</translation> </message> <message> <location line="+16"/> <source>This help message</source> <translation>Tämä ohjeviesti</translation> </message> <message> <location line="+7"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kytkeytyminen %s tällä tietokonella ei onnistu (kytkeytyminen palautti virheen %d, %s)</translation> </message> <message> <location line="-107"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Salli DNS kyselyt -addnode, -seednode ja -connect yhteydessä</translation> </message> <message> <location line="+60"/> <source>Loading addresses...</source> <translation>Ladataan osoitteita...</translation> </message> <message> <location line="-37"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Lompakko vioittunut</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Dogecoin Core</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa: Tarvitset uudemman version Dogecoinista</translation> </message> <message> <location line="+98"/> <source>Wallet needed to be rewritten: restart Dogecoin Core to complete</source> <translation>Lompakko tarvitsee uudelleenkirjoittaa: käynnistä Dogecoin uudelleen</translation> </message> <message> <location line="-100"/> <source>Error loading wallet.dat</source> <translation>Virhe ladattaessa wallet.dat-tiedostoa</translation> </message> <message> <location line="+31"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Virheellinen proxy-osoite &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Tuntematon verkko -onlynet parametrina: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Tuntematon -socks proxy versio pyydetty: %i</translation> </message> <message> <location line="-101"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>-bind osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>-externalip osoitteen &apos;%s&apos; selvittäminen epäonnistui</translation> </message> <message> <location line="+48"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-paytxfee=&lt;amount&gt;: &apos;%s&apos; on virheellinen</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Virheellinen määrä</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Lompakon saldo ei riitä</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Ladataan lohkoindeksiä...</translation> </message> <message> <location line="-62"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Linää solmu mihin liittyä pitääksesi yhteyden auki</translation> </message> <message> <location line="-32"/> <source>Unable to bind to %s on this computer. Dogecoin Core is probably already running.</source> <translation>Kytkeytyminen %s ei onnistu tällä tietokoneella. Dogecoin on todennäköisesti jo ajamassa.</translation> </message> <message> <location line="+95"/> <source>Loading wallet...</source> <translation>Ladataan lompakkoa...</translation> </message> <message> <location line="-56"/> <source>Cannot downgrade wallet</source> <translation>Et voi päivittää lompakkoasi vanhempaan versioon</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Oletusosoitetta ei voi kirjoittaa</translation> </message> <message> <location line="+67"/> <source>Rescanning...</source> <translation>Skannataan uudelleen...</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>Lataus on valmis</translation> </message> <message> <location line="+85"/> <source>To use the %s option</source> <translation>Käytä %s optiota</translation> </message> <message> <location line="-77"/> <source>Error</source> <translation>Virhe</translation> </message> <message> <location line="-35"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Sinun täytyy asettaa rpcpassword=&lt;password&gt; asetustiedostoon: %s Jos tiedostoa ei ole, niin luo se ainoastaan omistajan kirjoitusoikeuksin.</translation> </message> </context> </TS>
mit
Romashka/SonataAdminBundle
Command/SetupAclCommand.php
2021
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\Command; use Sonata\AdminBundle\Util\AdminAclManipulatorInterface; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Class SetupAclCommand. * * @author Thomas Rabaix <thomas.rabaix@sonata-project.org> */ class SetupAclCommand extends ContainerAwareCommand { /** * {@inheritdoc} */ public function configure() { $this->setName('sonata:admin:setup-acl'); $this->setDescription('Install ACL for Admin Classes'); } /** * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Starting ACL AdminBundle configuration'); foreach ($this->getContainer()->get('sonata.admin.pool')->getAdminServiceIds() as $id) { try { $admin = $this->getContainer()->get($id); } catch (\Exception $e) { $output->writeln('<error>Warning : The admin class cannot be initiated from the command line</error>'); $output->writeln(sprintf('<error>%s</error>', $e->getMessage())); continue; } $manipulator = $this->getContainer()->get('sonata.admin.manipulator.acl.admin'); if (!$manipulator instanceof AdminAclManipulatorInterface) { $output->writeln(sprintf( 'The interface "AdminAclManipulatorInterface" is not implemented for %s: <info>ignoring</info>', get_class($manipulator) )); continue; } $manipulator->configureAcls($output, $admin); } } }
mit
ari-gold/cli
php/Terminus/Fetchers/Plugin.php
392
<?php namespace Terminus\Fetchers; class Plugin extends Base { protected $msg = "The '%s' plugin could not be found."; public function get( $name ) { foreach ( get_plugins() as $file => $_ ) { if ( $file === "$name.php" || ( dirname( $file ) === $name && $name !== '.' ) ) { return (object) compact( 'name', 'file' ); } } return false; } }
mit
stevengum97/BotBuilder
Node/examples/demo-skype-calling/app.js
10738
/*----------------------------------------------------------------------------- This Bot is a sample calling bot for Skype. It's designed to showcase whats possible on Skype using the BotBuilder SDK. The demo shows how to create a looping menu, recognize speech & DTMF, record messages, play multiple prompts, and even send a caller a chat message. # RUN THE BOT: You can run the bot locally using ngrok found at https://ngrok.com/. * Install and run ngrok in a console window using "ngrok http 3978". * Create a bot on https://dev.botframework.com and follow the steps to setup a Skype channel. Ensure that you enable calling support for your bots skype channel. * For the messaging endpoint in the Details for your Bot at dev.botframework.com, ensure you enter the https link from ngrok setup and set "<ngrok link>/api/messages" as your bots calling endpoint. * For the calling endpoint you setup on dev.botframework.com, copy the https link from ngrok setup and set "<ngrok link>/api/calls" as your bots calling endpoint. * Next you need to configure your bots CALLBACK_URL, MICROSOFT_APP_ID, and MICROSOFT_APP_PASSWORD environment variables. If you're running VSCode you can add these variables to your the bots launch.json file. If you're not using VSCode you'll need to setup these variables in a console window. - CALLBACK_URL: This should be the same endpoint you set as your calling endpoint in the developer portal. - MICROSOFT_APP_ID: This is the App ID assigned when you created your bot. - MICROSOFT_APP_PASSWORD: This was also assigned when you created your bot. * To use the bot you'll need to click the join link in the portal which will add it as a contact to your skype account. When you click on the bot in your skype client you should see an option to call your bot. If you're adding calling to an existing bot can take up to 24 hours for the calling option to show up. * You can run the bot by launching it from VSCode or running "node app.js" from a console window. Then call your bot from a skype client to start the demo. -----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------------- * Bot Storage: This is a great spot to register the private state storage for your bot. * We provide adapters for Azure Table, CosmosDb, SQL Azure, or you can implement your own! * For samples and documentation, see: https://github.com/Microsoft/BotBuilder-Azure * ---------------------------------------------------------------------------------------- */ var restify = require('restify'); var builder = require('../../core/'); var calling = require('../../calling/'); var prompts = require('./prompts'); //========================================================= // Bot Setup //========================================================= // Setup Restify Server var server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, function () { console.log('%s listening to %s', server.name, server.url); }); // Create chat bot var chatConnector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); var chatBot = new builder.UniversalBot(chatConnector); server.post('/api/messages', chatConnector.listen()); // Create calling bot var connector = new calling.CallConnector({ callbackUrl: process.env.CALLBACK_URL, appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); var bot = new calling.UniversalCallBot(connector); // use memory storage per https://github.com/Microsoft/BotBuilder/issues/3547 bot.set('storage', new builder.MemoryBotStorage()); server.post('/api/calls', connector.listen()); //========================================================= // Chat Dialogs //========================================================= chatBot.dialog('/', function (session) { session.send(prompts.chatGreeting); }); //========================================================= // Calling Dialogs //========================================================= bot.dialog('/', [ function (session) { // Send a greeting and start the menu. if (!session.userData.welcomed) { session.userData.welcomed = true; session.send(prompts.welcome); session.beginDialog('/demoMenu', { full: true }); } else { session.send(prompts.welcomeBack); session.beginDialog('/demoMenu', { full: false }); } }, function (session, results) { // Always say goodbye session.send(prompts.goodbye); } ]); bot.dialog('/demoMenu', [ function (session, args) { // Build up a stack of prompts to play var list = []; list.push(calling.Prompt.text(session, prompts.demoMenu.prompt)); if (!args || args.full) { list.push(calling.Prompt.text(session, prompts.demoMenu.choices)); list.push(calling.Prompt.text(session, prompts.demoMenu.help)); } // Prompt user to select a menu option calling.Prompts.choice(session, new calling.PlayPromptAction(session).prompts(list), [ { name: 'dtmf', speechVariation: ['dtmf'] }, { name: 'digits', speechVariation: ['digits'] }, { name: 'record', speechVariation: ['record', 'recordings'] }, { name: 'chat', speechVariation: ['chat', 'chat message'] }, { name: 'choices', speechVariation: ['choices', 'options', 'list'] }, { name: 'help', speechVariation: ['help', 'repeat'] }, { name: 'quit', speechVariation: ['quit', 'end call', 'hangup', 'goodbye'] } ]); }, function (session, results) { if (results.response) { switch (results.response.entity) { case 'choices': session.send(prompts.demoMenu.choices); session.replaceDialog('/demoMenu', { full: false }); break; case 'help': session.replaceDialog('/demoMenu', { full: true }); break; case 'quit': session.endDialog(); break; default: // Start demo session.beginDialog('/' + results.response.entity); break; } } else { // Exit the menu session.endDialog(prompts.canceled); } }, function (session, results) { // The menu runs a loop until the user chooses to (quit). session.replaceDialog('/demoMenu', { full: false }); } ]); bot.dialog('/dtmf', [ function (session) { session.send(prompts.dtmf.intro); calling.Prompts.choice(session, prompts.dtmf.prompt, [ { name: 'option A', dtmfVariation: '1' }, { name: 'option B', dtmfVariation: '2' }, { name: 'option C', dtmfVariation: '3' } ]); }, function (session, results) { if (results.response) { session.endDialog(prompts.dtmf.result, results.response.entity); } else { session.endDialog(prompts.canceled); } } ]); bot.dialog('/digits', [ function (session, args) { if (!args || args.full) { session.send(prompts.digits.intro); } calling.Prompts.digits(session, prompts.digits.prompt, 10, { stopTones: '#' }); }, function (session, results) { if (results.response) { // Confirm the users account is valid length otherwise reprompt. if (results.response.length >= 5) { var prompt = calling.PlayPromptAction.text(session, prompts.digits.confirm, results.response); calling.Prompts.confirm(session, prompt, results.response); } else { session.send(prompts.digits.inavlid); session.replaceDialog('/digits', { full: false }); } } else { session.endDialog(prompts.canceled); } }, function (session, results) { if (results.resumed == calling.ResumeReason.completed) { if (results.response) { session.endDialog(); } else { session.replaceDialog('/digits', { full: false }); } } else { session.endDialog(prompts.canceled); } } ]); bot.dialog('/record', [ function (session) { session.send(prompts.record.intro); calling.Prompts.record(session, prompts.record.prompt, { playBeep: true }); }, function (session, results) { if (results.response) { session.endDialog(prompts.record.result, results.response.lengthOfRecordingInSecs); } else { session.endDialog(prompts.canceled); } } ]); // Import botbuilder core library and setup chat bot bot.dialog('/chat', [ function (session) { session.send(prompts.chat.intro); calling.Prompts.confirm(session, prompts.chat.confirm); }, function (session, results) { if (results.response) { // Delete conversation field from address to trigger starting a new conversation. var address = session.message.address; delete address.conversation; // Create a new chat message and pass it callers address var msg = new builder.Message() .address(address) .attachments([ new builder.HeroCard(session) .title("Hero Card") .subtitle("Space Needle") .text("The <b>Space Needle</b> is an observation tower in Seattle, Washington, a landmark of the Pacific Northwest, and an icon of Seattle.") .images([ builder.CardImage.create(session, "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Seattlenighttimequeenanne.jpg/320px-Seattlenighttimequeenanne.jpg") ]) .tap(builder.CardAction.openUrl(session, "https://en.wikipedia.org/wiki/Space_Needle")) ]); // Send message through chat bot chatBot.send(msg, function (err) { session.endDialog(err ? prompts.chat.failed : prompts.chat.sent); }); } else { session.endDialog(prompts.canceled); } } ]);
mit
wKoza/angular
packages/compiler-cli/ngcc/test/entry_point_finder/targeted_entry_point_finder_spec.ts
32732
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem, relative} from '../../../src/ngtsc/file_system'; import {runInEachFileSystem, TestFile} from '../../../src/ngtsc/file_system/testing'; import {MockLogger} from '../../../src/ngtsc/logging/testing'; import {loadTestFiles} from '../../../test/helpers'; import {DependencyResolver} from '../../src/dependencies/dependency_resolver'; import {DtsDependencyHost} from '../../src/dependencies/dts_dependency_host'; import {EsmDependencyHost} from '../../src/dependencies/esm_dependency_host'; import {ModuleResolver} from '../../src/dependencies/module_resolver'; import {TargetedEntryPointFinder} from '../../src/entry_point_finder/targeted_entry_point_finder'; import {NGCC_VERSION} from '../../src/packages/build_marker'; import {NgccConfiguration, ProcessedNgccPackageConfig} from '../../src/packages/configuration'; import {EntryPoint} from '../../src/packages/entry_point'; import {PathMappings} from '../../src/path_mappings'; runInEachFileSystem(() => { describe('TargetedEntryPointFinder', () => { let fs: FileSystem; let resolver: DependencyResolver; let logger: MockLogger; let config: NgccConfiguration; let _Abs: typeof absoluteFrom; beforeEach(() => { fs = getFileSystem(); _Abs = absoluteFrom; logger = new MockLogger(); const srcHost = new EsmDependencyHost(fs, new ModuleResolver(fs)); const dtsHost = new DtsDependencyHost(fs); config = new NgccConfiguration(fs, _Abs('/')); resolver = new DependencyResolver(fs, logger, config, {esm2015: srcHost}, dtsHost); }); describe('findEntryPoints()', () => { it('should find a single entry-point with no dependencies', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['@angular/common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['@angular/common/http', '@angular/common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['@angular/common']), ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/sub_entry_points/node_modules'), undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(basePath, entryPoints)).toEqual([ ['common', 'common'], ]); }); it('should find dependencies of secondary entry-points within a package', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common/http/testing'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['common/http', 'common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['common']), ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/sub_entry_points/node_modules'), undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(basePath, entryPoints)).toEqual([ ['common', 'common'], ['common', 'common/http'], ['common', 'common/testing'], ['common', 'common/http/testing'], ]); }); it('should find dependencies inside a namespace', () => { const basePath = _Abs('/namespaced/node_modules'); const targetPath = _Abs('/namespaced/node_modules/@angular/common/http'); loadTestFiles([ ...createPackage(fs.resolve(basePath, '@angular'), 'common'), ...createPackage(fs.resolve(basePath, '@angular/common'), 'http', ['@angular/common']), ...createPackage( fs.resolve(basePath, '@angular/common/http'), 'testing', ['@angular/common/http', '@angular/common/testing']), ...createPackage(fs.resolve(basePath, '@angular/common'), 'testing', ['@angular/common']), ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/namespaced/node_modules'), undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(basePath, entryPoints)).toEqual([ ['@angular/common', '@angular/common'], ['@angular/common', '@angular/common/http'], ]); }); it('should return an empty array if the target path is not an entry-point', () => { const targetPath = _Abs('/no_packages/node_modules/should_not_be_found'); fs.ensureDir(_Abs('/no_packages/node_modules/should_not_be_found')); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/no_packages/node_modules'), undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(entryPoints).toEqual([]); }); it('should return an empty array if the target path is an ignored entry-point', () => { const basePath = _Abs('/project/node_modules'); const targetPath = _Abs('/project/node_modules/some-package'); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); loadTestFiles(createPackage(basePath, 'some-package')); spyOn(config, 'getPackageConfig') .and.returnValue( new ProcessedNgccPackageConfig(_Abs('/project/node_modules/some-package'), { entryPoints: { '.': {ignore: true}, }, })); const {entryPoints} = finder.findEntryPoints(); expect(entryPoints).toEqual([]); }); it('should return an empty array if the target path is not an Angular entry-point', () => { const targetPath = _Abs('/no_valid_entry_points/node_modules/some_package'); loadTestFiles([ { name: _Abs('/no_valid_entry_points/node_modules/some_package/package.json'), contents: '{}' }, ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/no_valid_entry_points/node_modules'), undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(entryPoints).toEqual([]); }); // https://github.com/angular/angular/issues/32302 it('should return an empty array if the target path is not an Angular entry-point with typings', () => { const targetPath = _Abs('/no_valid_entry_points/node_modules/some_package'); loadTestFiles([ { name: _Abs('/no_valid_entry_points/node_modules/some_package/package.json'), contents: '{"typings": "./index.d.ts"}' }, { name: _Abs('/no_valid_entry_points/node_modules/some_package/index.d.ts'), contents: 'export declare class MyClass {}' }, { name: _Abs('/no_valid_entry_points/node_modules/some_package/index.js'), contents: 'export class MyClass {}' }, ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/no_valid_entry_points/node_modules'), undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(entryPoints).toEqual([]); }); it('should handle nested node_modules folders', () => { const targetPath = _Abs('/nested_node_modules/node_modules/outer'); loadTestFiles([ ...createPackage(_Abs('/nested_node_modules/node_modules'), 'outer', ['inner']), ...createPackage(_Abs('/nested_node_modules/node_modules/outer/node_modules'), 'inner'), ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/nested_node_modules/node_modules'), undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(_Abs('/nested_node_modules/node_modules'), entryPoints)) .toEqual([ ['outer/node_modules/inner', 'outer/node_modules/inner'], ['outer', 'outer'], ]); }); it('should handle external node_modules folders (e.g. in a yarn workspace)', () => { // Note that neither the basePath and targetPath contain each other const basePath = _Abs('/nested_node_modules/packages/app/node_modules'); const targetPath = _Abs('/nested_node_modules/node_modules/package/entry-point'); loadTestFiles([ ...createPackage(_Abs('/nested_node_modules/node_modules'), 'package'), ...createPackage(_Abs('/nested_node_modules/node_modules/package'), 'entry-point'), ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(_Abs('/nested_node_modules'), entryPoints)).toEqual([ ['node_modules/package', 'node_modules/package/entry-point'], ]); }); it('should handle external node_modules folders (e.g. in a yarn workspace) for dependencies', () => { // The application being compiled is at `/project/packages/app` so the basePath sent to // ngcc is the `node_modules` below it const basePath = _Abs('/project/packages/app/node_modules'); // `packages/app` depends upon lib1, which has a private dependency on lib2 in its // own `node_modules` folder const lib2 = createPackage( _Abs('/project/node_modules/lib1/node_modules'), 'lib2', ['lib3/entry-point']); // `lib2` depends upon `lib3/entry-point` which has been hoisted all the way up to the // top level `node_modules` const lib3 = createPackage(_Abs('/project/node_modules'), 'lib3'); const lib3EntryPoint = createPackage(_Abs('/project/node_modules/lib3'), 'entry-point'); loadTestFiles([...lib2, ...lib3, ...lib3EntryPoint]); // The targetPath being processed is `lib2` and we expect it to find the correct // entry-point info for the `lib3/entry-point` dependency. const targetPath = _Abs('/project/node_modules/lib1/node_modules/lib2'); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(_Abs('/project/node_modules'), entryPoints)).toEqual([ ['lib3', 'lib3/entry-point'], ['lib1/node_modules/lib2', 'lib1/node_modules/lib2'], ]); }); it('should handle external node_modules folders (e.g. in a yarn workspace) for scoped dependencies', () => { // The application being compiled is at `/project/packages/app` so the basePath sent to // ngcc is the `node_modules` below it const basePath = _Abs('/project/packages/app/node_modules'); // `packages/app` depends upon lib1, which has a private dependency on lib2 in its // own `node_modules` folder const lib2 = createPackage( _Abs('/project/node_modules/lib1/node_modules'), 'lib2', ['@scope/lib3/entry-point']); // `lib2` depends upon `lib3/entry-point` which has been hoisted all the way up to the // top level `node_modules` const lib3 = createPackage(_Abs('/project/node_modules/@scope'), 'lib3'); const lib3EntryPoint = createPackage( _Abs('/project/node_modules/@scope/lib3'), 'entry-point', ['lib4/entry-point']); const lib4 = createPackage(_Abs('/project/node_modules/@scope/lib3/node_modules'), 'lib4'); const lib4EntryPoint = createPackage( _Abs('/project/node_modules/@scope/lib3/node_modules/lib4'), 'entry-point'); loadTestFiles([...lib2, ...lib3, ...lib3EntryPoint, ...lib4, ...lib4EntryPoint]); // The targetPath being processed is `lib2` and we expect it to find the correct // entry-point info for the `lib3/entry-point` dependency. const targetPath = _Abs('/project/node_modules/lib1/node_modules/lib2'); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(_Abs('/project/node_modules'), entryPoints)).toEqual([ ['@scope/lib3/node_modules/lib4', '@scope/lib3/node_modules/lib4/entry-point'], ['@scope/lib3', '@scope/lib3/entry-point'], ['lib1/node_modules/lib2', 'lib1/node_modules/lib2'], ]); }); it('should handle dependencies via pathMappings', () => { const basePath = _Abs('/path_mapped/node_modules'); const targetPath = _Abs('/path_mapped/node_modules/test'); const pathMappings: PathMappings = { baseUrl: '/path_mapped/dist', paths: { '@x/*': ['*'], '@y/*/test': ['lib/*/test'], '@z/*': ['../dist/moo/../*'], } }; loadTestFiles([ ...createPackage( _Abs('/path_mapped/node_modules'), 'test', ['pkg1', '@x/pkg2', '@y/pkg3/test', '@z/pkg5']), ...createPackage(_Abs('/path_mapped/node_modules'), 'pkg1'), ...createPackage(_Abs('/path_mapped/dist'), 'pkg2', ['pkg4']), ...createPackage(_Abs('/path_mapped/dist/pkg2/node_modules'), 'pkg4'), ...createPackage(_Abs('/path_mapped/dist/lib/pkg3'), 'test'), ...createPackage(_Abs('/path_mapped/dist'), 'pkg5'), ]); const srcHost = new EsmDependencyHost(fs, new ModuleResolver(fs, pathMappings)); const dtsHost = new DtsDependencyHost(fs, pathMappings); resolver = new DependencyResolver(fs, logger, config, {esm2015: srcHost}, dtsHost); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, pathMappings, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(basePath, entryPoints)).toEqual([ ['pkg1', 'pkg1'], ['../dist/pkg2/node_modules/pkg4', '../dist/pkg2/node_modules/pkg4'], ['../dist/pkg2', '../dist/pkg2'], ['../dist/lib/pkg3/test', '../dist/lib/pkg3/test'], ['../dist/pkg5', '../dist/pkg5'], ['test', 'test'], ]); }); it('should correctly compute the packagePath of secondary entry-points via pathMappings', () => { const basePath = _Abs('/path_mapped/node_modules'); const targetPath = _Abs('/path_mapped/dist/primary/secondary'); const pathMappings: PathMappings = { baseUrl: '/path_mapped/dist', paths: {'libs': ['primary'], 'extras': ['primary/*']} }; loadTestFiles([ ...createPackage(_Abs('/path_mapped/dist'), 'primary'), ...createPackage(_Abs('/path_mapped/dist/primary'), 'secondary'), ]); const srcHost = new EsmDependencyHost(fs, new ModuleResolver(fs, pathMappings)); const dtsHost = new DtsDependencyHost(fs, pathMappings); resolver = new DependencyResolver(fs, logger, config, {esm2015: srcHost}, dtsHost); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, pathMappings, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(entryPoints.length).toEqual(1); const entryPoint = entryPoints[0]; expect(entryPoint.name).toEqual('secondary'); expect(entryPoint.path).toEqual(_Abs('/path_mapped/dist/primary/secondary')); expect(entryPoint.packagePath).toEqual(_Abs('/path_mapped/dist/primary')); }); it('should correctly compute an entry-point whose path starts with the same string as another entry-point, via pathMappings', () => { const basePath = _Abs('/path_mapped/node_modules'); const targetPath = _Abs('/path_mapped/node_modules/test'); const pathMappings: PathMappings = { baseUrl: '/path_mapped/dist', paths: { 'lib1': ['my-lib/my-lib', 'my-lib'], 'lib2': ['my-lib/a', 'my-lib/a'], 'lib3': ['my-lib/b', 'my-lib/b'], 'lib4': ['my-lib-other/my-lib-other', 'my-lib-other'] } }; loadTestFiles([ ...createPackage(_Abs('/path_mapped/node_modules'), 'test', ['lib2', 'lib4']), ...createPackage(_Abs('/path_mapped/dist/my-lib'), 'my-lib'), ...createPackage(_Abs('/path_mapped/dist/my-lib'), 'a'), ...createPackage(_Abs('/path_mapped/dist/my-lib'), 'b'), ...createPackage(_Abs('/path_mapped/dist/my-lib-other'), 'my-lib-other'), ]); const srcHost = new EsmDependencyHost(fs, new ModuleResolver(fs, pathMappings)); const dtsHost = new DtsDependencyHost(fs, pathMappings); resolver = new DependencyResolver(fs, logger, config, {esm2015: srcHost}, dtsHost); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, pathMappings, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(basePath, entryPoints)).toEqual([ ['../dist/my-lib/a', '../dist/my-lib/a'], ['../dist/my-lib-other/my-lib-other', '../dist/my-lib-other/my-lib-other'], ['test', 'test'], ]); }); it('should handle pathMappings that map to files or non-existent directories', () => { const basePath = _Abs('/path_mapped/node_modules'); const targetPath = _Abs('/path_mapped/node_modules/test'); const pathMappings: PathMappings = { baseUrl: '/path_mapped/dist', paths: { '@test': ['pkg2/fesm2015/pkg2.js'], '@missing': ['pkg3'], } }; loadTestFiles([ ...createPackage(_Abs('/path_mapped/node_modules'), 'test', []), ...createPackage(_Abs('/path_mapped/dist'), 'pkg2'), ]); const srcHost = new EsmDependencyHost(fs, new ModuleResolver(fs, pathMappings)); const dtsHost = new DtsDependencyHost(fs, pathMappings); resolver = new DependencyResolver(fs, logger, config, {esm2015: srcHost}, dtsHost); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, pathMappings, targetPath); const {entryPoints} = finder.findEntryPoints(); expect(dumpEntryPointPaths(basePath, entryPoints)).toEqual([ ['test', 'test'], ]); }); function dumpEntryPointPaths( basePath: AbsoluteFsPath, entryPoints: EntryPoint[]): [string, string][] { return entryPoints.map( x => [relative(basePath, x.packagePath), relative(basePath, x.path)]); } }); describe('targetNeedsProcessingOrCleaning()', () => { it('should return false if there is no entry-point', () => { const targetPath = _Abs('/no_packages/node_modules/should_not_be_found'); fs.ensureDir(targetPath); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/no_packages/node_modules'), undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015'], true)).toBe(false); }); it('should return false if the target path is not a valid entry-point', () => { const targetPath = _Abs('/no_valid_entry_points/node_modules/some_package'); loadTestFiles([ { name: _Abs('/no_valid_entry_points/node_modules/some_package/package.json'), contents: '{}' }, ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/no_valid_entry_points/node_modules'), undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015'], true)).toBe(false); }); it('should return false if the target path is ignored by the config', () => { const basePath = _Abs('/project/node_modules'); const targetPath = _Abs('/project/node_modules/some-package'); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); loadTestFiles(createPackage(basePath, 'some-package')); spyOn(config, 'getPackageConfig') .and.returnValue( new ProcessedNgccPackageConfig(_Abs('/project/node_modules/some-package'), { entryPoints: { '.': {ignore: true}, }, })); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015'], true)).toBe(false); }); it('should false if the target path has no typings', () => { const targetPath = _Abs('/no_valid_entry_points/node_modules/some_package'); loadTestFiles([ { name: _Abs('/no_valid_entry_points/node_modules/some_package/package.json'), contents: '{"fesm2015": "./index.js"}' }, { name: _Abs('/no_valid_entry_points/node_modules/some_package/some_package.metadata.json'), contents: 'metadata info' }, { name: _Abs('/no_valid_entry_points/node_modules/some_package/index.js'), contents: 'export class MyClass {}' }, ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/no_valid_entry_points/node_modules'), undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015'], true)).toBe(false); }); it('should false if the target path is not compiled by Angular - i.e has no metadata file', () => { const targetPath = _Abs('/no_valid_entry_points/node_modules/some_package'); loadTestFiles([ { name: _Abs('/no_valid_entry_points/node_modules/some_package/package.json'), contents: '{"typings": "./index.d.ts", "fesm2015": "./index.js"}' }, { name: _Abs('/no_valid_entry_points/node_modules/some_package/index.d.ts'), contents: 'export declare class MyClass {}' }, { name: _Abs('/no_valid_entry_points/node_modules/some_package/index.js'), contents: 'export class MyClass {}' }, ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, _Abs('/no_valid_entry_points/node_modules'), undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015'], true)).toBe(false); }); describe('[compileAllFormats: true]', () => { it('should return true if none of the properties to consider have been processed', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common/http/testing'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['common/http', 'common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['common']), ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015', 'esm5'], true)).toBe(true); }); it('should return true if at least one of the properties to consider has not been processed', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common/http/testing'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['common/http', 'common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['common']), ]); // Add a build marker to the package.json const packageJsonPath = _Abs(`${targetPath}/package.json`); const packageJson = JSON.parse(fs.readFile(packageJsonPath)); packageJson.__processed_by_ivy_ngcc__ = { esm5: NGCC_VERSION, }; fs.writeFile(packageJsonPath, JSON.stringify(packageJson)); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015', 'esm5'], true)).toBe(true); }); it('should return false if all of the properties to consider have been processed', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common/http/testing'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['common/http', 'common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['common']), ]); // Add build markers to the package.json const packageJsonPath = _Abs(`${targetPath}/package.json`); const packageJson = JSON.parse(fs.readFile(packageJsonPath)); packageJson.__processed_by_ivy_ngcc__ = { fesm2015: NGCC_VERSION, esm5: NGCC_VERSION, main: NGCC_VERSION, }; fs.writeFile(packageJsonPath, JSON.stringify(packageJson)); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015', 'esm5'], true)).toBe(false); }); }); describe('[compileAllFormats: false]', () => { it('should return true if none of the properties to consider have been processed', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common/http/testing'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['common/http', 'common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['common']), ]); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015', 'esm5'], false)).toBe(true); }); it('should return true if the first of the properties to consider that is in the package.json has not been processed', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common/http/testing'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['common/http', 'common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['common']), ]); // Add build markers to the package.json const packageJsonPath = _Abs(`${targetPath}/package.json`); const packageJson = JSON.parse(fs.readFile(packageJsonPath)); packageJson.__processed_by_ivy_ngcc__ = { esm5: NGCC_VERSION, }; fs.writeFile(packageJsonPath, JSON.stringify(packageJson)); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015', 'esm5'], false)).toBe(true); }); it('should return false if the first of the properties to consider (that actually appear in the package.json) has been processed', () => { const basePath = _Abs('/sub_entry_points/node_modules'); const targetPath = _Abs('/sub_entry_points/node_modules/common/http/testing'); loadTestFiles([ ...createPackage(fs.resolve(basePath, ''), 'common'), ...createPackage(fs.resolve(basePath, 'common'), 'http', ['common']), ...createPackage( fs.resolve(basePath, 'common/http'), 'testing', ['common/http', 'common/testing']), ...createPackage(fs.resolve(basePath, 'common'), 'testing', ['common']), ]); // Add build markers to the package.json const packageJsonPath = _Abs(`${targetPath}/package.json`); const packageJson = JSON.parse(fs.readFile(packageJsonPath)); packageJson.__processed_by_ivy_ngcc__ = { fesm2015: NGCC_VERSION, }; fs.writeFile(packageJsonPath, JSON.stringify(packageJson)); const finder = new TargetedEntryPointFinder( fs, config, logger, resolver, basePath, undefined, targetPath); expect(finder.targetNeedsProcessingOrCleaning(['fesm2015', 'esm5'], false)) .toBe(false); }); }); }); function createPackage( basePath: AbsoluteFsPath, packageName: string, deps: string[] = []): TestFile[] { return [ { name: _Abs(`${basePath}/${packageName}/package.json`), contents: JSON.stringify({ name: packageName, typings: `./${packageName}.d.ts`, fesm2015: `./fesm2015/${packageName}.js`, esm5: `./esm5/${packageName}.js`, main: `./common/${packageName}.js`, }) }, { name: _Abs(`${basePath}/${packageName}/${packageName}.metadata.json`), contents: 'metadata info' }, { name: _Abs(`${basePath}/${packageName}/fesm2015/${packageName}.js`), contents: deps.map((dep, i) => `import * as i${i} from '${dep}';`).join('\n'), }, { name: _Abs(`${basePath}/${packageName}/esm5/${packageName}.js`), contents: deps.map((dep, i) => `import * as i${i} from '${dep}';`).join('\n'), }, { name: _Abs(`${basePath}/${packageName}/commonjs/${packageName}.js`), contents: deps.map((dep, i) => `var i${i} = require('${dep}');`).join('\n'), }, ]; } }); });
mit
Mulodo-PHP-Laravel-Training/laravel-homestead
scripts/homestead.rb
5888
class Homestead def Homestead.configure(config, settings) # Set The VM Provider ENV['VAGRANT_DEFAULT_PROVIDER'] = settings["provider"] ||= "virtualbox" # Configure Local Variable To Access Scripts From Remote Location scriptDir = File.dirname(__FILE__) # Prevent TTY Errors config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'" # Configure The Box config.vm.box = "laravel/homestead" config.vm.hostname = settings["hostname"] ||= "homestead" # Configure A Private Network IP config.vm.network :private_network, ip: settings["ip"] ||= "192.168.10.10" # Configure A Few VirtualBox Settings config.vm.provider "virtualbox" do |vb| vb.name = settings["name"] ||= "homestead" vb.customize ["modifyvm", :id, "--memory", settings["memory"] ||= "2048"] vb.customize ["modifyvm", :id, "--cpus", settings["cpus"] ||= "1"] vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"] vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"] vb.customize ["modifyvm", :id, "--ostype", "Ubuntu_64"] end # Configure A Few VMware Settings ["vmware_fusion", "vmware_workstation"].each do |vmware| config.vm.provider vmware do |v| v.vmx["displayName"] = "homestead" v.vmx["memsize"] = settings["memory"] ||= 2048 v.vmx["numvcpus"] = settings["cpus"] ||= 1 v.vmx["guestOS"] = "ubuntu-64" end end # Standardize Ports Naming Schema if (settings.has_key?("ports")) settings["ports"].each do |port| port["guest"] ||= port["to"] port["host"] ||= port["send"] port["protocol"] ||= "tcp" end else settings["ports"] = [] end # Default Port Forwarding default_ports = { 80 => 8000, 443 => 44300, 3306 => 33060, 5432 => 54320 } # Use Default Port Forwarding Unless Overridden default_ports.each do |guest, host| unless settings["ports"].any? { |mapping| mapping["guest"] == guest } config.vm.network "forwarded_port", guest: guest, host: host, auto_correct: true end end # Add Custom Ports From Configuration if settings.has_key?("ports") settings["ports"].each do |port| config.vm.network "forwarded_port", guest: port["guest"], host: port["host"], protocol: port["protocol"], auto_correct: true end end # Configure The Public Key For SSH Access if settings.include? 'authorize' config.vm.provision "shell" do |s| s.inline = "echo $1 | grep -xq \"$1\" /home/vagrant/.ssh/authorized_keys || echo $1 | tee -a /home/vagrant/.ssh/authorized_keys" s.args = [File.read(File.expand_path(settings["authorize"]))] end end # Copy The SSH Private Keys To The Box if settings.include? 'keys' settings["keys"].each do |key| config.vm.provision "shell" do |s| s.privileged = false s.inline = "echo \"$1\" > /home/vagrant/.ssh/$2 && chmod 600 /home/vagrant/.ssh/$2" s.args = [File.read(File.expand_path(key)), key.split('/').last] end end end # Register All Of The Configured Shared Folders if settings.include? 'folders' settings["folders"].each do |folder| mount_opts = [] if (folder["type"] == "nfs") mount_opts = folder["mount_opts"] ? folder["mount_opts"] : ['actimeo=1'] end config.vm.synced_folder folder["map"], folder["to"], type: folder["type"] ||= nil, mount_options: mount_opts end end # Install All The Configured Nginx Sites config.vm.provision "shell" do |s| s.path = scriptDir + "/clear-nginx.sh" end settings["sites"].each do |site| config.vm.provision "shell" do |s| if (site.has_key?("hhvm") && site["hhvm"]) s.path = scriptDir + "/serve-hhvm.sh" s.args = [site["map"], site["to"], site["port"] ||= "80", site["ssl"] ||= "443"] else s.path = scriptDir + "/serve.sh" s.args = [site["map"], site["to"], site["port"] ||= "80", site["ssl"] ||= "443"] end end end # Configure All Of The Configured Databases if settings.has_key?("databases") settings["databases"].each do |db| config.vm.provision "shell" do |s| s.path = scriptDir + "/create-mysql.sh" s.args = [db] end config.vm.provision "shell" do |s| s.path = scriptDir + "/create-postgres.sh" s.args = [db] end end end # Configure All Of The Server Environment Variables config.vm.provision "shell" do |s| s.path = scriptDir + "/clear-variables.sh" end if settings.has_key?("variables") settings["variables"].each do |var| config.vm.provision "shell" do |s| s.inline = "echo \"\nenv[$1] = '$2'\" >> /etc/php5/fpm/php-fpm.conf" s.args = [var["key"], var["value"]] end config.vm.provision "shell" do |s| s.inline = "echo \"\n# Set Homestead Environment Variable\nexport $1=$2\" >> /home/vagrant/.profile" s.args = [var["key"], var["value"]] end end config.vm.provision "shell" do |s| s.inline = "service php5-fpm restart" end end # Update Composer On Every Provision config.vm.provision "shell" do |s| s.inline = "/usr/local/bin/composer self-update" end # Configure Blackfire.io if settings.has_key?("blackfire") config.vm.provision "shell" do |s| s.path = scriptDir + "/blackfire.sh" s.args = [ settings["blackfire"][0]["id"], settings["blackfire"][0]["token"], settings["blackfire"][0]["client-id"], settings["blackfire"][0]["client-token"] ] end end end end
mit
angustas/company
node_modules/echarts/lib/component/axisPointer/axisTrigger.js
15096
var zrUtil = require('zrender/lib/core/util'); var modelUtil = require('../../util/model'); var modelHelper = require('./modelHelper'); var findPointFromSeries = require('./findPointFromSeries'); var each = zrUtil.each; var curry = zrUtil.curry; var get = modelUtil.makeGetter(); /** * Basic logic: check all axis, if they do not demand show/highlight, * then hide/downplay them. * * @param {Object} coordSysAxesInfo * @param {string} [currTrigger] 'click' | 'mousemove' | 'leave' * @param {Array.<number>} [point] x and y, which are mandatory, specify a point to * tigger axisPointer and tooltip. * @param {Object} [finder] {xAxisId: ...[], yAxisName: ...[], angleAxisIndex: ...[]} * These properties, which are optional, restrict target axes. * @param {Function} dispatchAction * @param {module:echarts/ExtensionAPI} api * @param {Object} [tooltipOption] * @param {string} [highDownKey] * @return {Object} content of event obj for echarts.connect. */ function axisTrigger( coordSysAxesInfo, currTrigger, point, finder, dispatchAction, ecModel, api, tooltipOption, highDownKey ) { finder = finder || {}; if (!point || point[0] == null || point[1] == null) { point = findPointFromSeries({ seriesIndex: finder.seriesIndex, // Do not use dataIndexInside from other ec instance. // FIXME: auto detect it? dataIndex: finder.dataIndex }, ecModel).point; } var axesInfo = coordSysAxesInfo.axesInfo; var shouldHide = currTrigger === 'leave' || illegalPoint(point); var outputFinder = {}; var showValueMap = {}; var dataByCoordSys = {list: [], map: {}}; var highlightBatch = []; var updaters = { showPointer: curry(showPointer, showValueMap), showTooltip: curry(showTooltip, dataByCoordSys), highlight: curry(highlight, highlightBatch) }; // Process for triggered axes. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) { var coordSysContainsPoint = coordSys.containPoint(point); each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) { var axis = axisInfo.axis; if (!shouldHide && coordSysContainsPoint && !notTargetAxis(finder, axis)) { processOnAxis(axisInfo, axis.pointToData(point), updaters, false, outputFinder); } }); }); // Process for linked axes. var linkTriggers = {}; each(axesInfo, function (tarAxisInfo, tarKey) { var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link. if (linkGroup && !showValueMap[tarKey]) { each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) { var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis. if (srcAxisInfo !== tarAxisInfo && srcValItem) { var val = srcValItem.value; linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper( val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo) ))); linkTriggers[tarAxisInfo.key] = val; } }); } }); each(linkTriggers, function (val, tarKey) { processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder); }); updateModelActually(showValueMap, axesInfo); dispatchTooltipActually(dataByCoordSys, point, tooltipOption, dispatchAction); dispatchHighDownActually(highlightBatch, dispatchAction, api, highDownKey); return outputFinder; } function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) { var axis = axisInfo.axis; if (axis.scale.isBlank() || !axis.containData(newValue)) { return; } if (!axisInfo.involveSeries) { updaters.showPointer(axisInfo, newValue); return; } // Heavy calculation. So put it after axis.containData checking. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo); var payloadBatch = payloadInfo.payloadBatch; var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect. // By defualt use the first involved series data as a sample to connect. if (payloadBatch[0] && outputFinder.seriesIndex == null) { zrUtil.extend(outputFinder, payloadBatch[0]); } // If no linkSource input, this process is for collecting link // target, where snap should not be accepted. if (!dontSnap && axisInfo.snap) { if (axis.containData(snapToValue) && snapToValue != null) { newValue = snapToValue; } } updaters.highlight('highlight', payloadBatch); updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be // incorrect "axis value ~ series value" mapping displayed in tooltip. updaters.showTooltip(axisInfo, payloadInfo, snapToValue); } function buildPayloadsBySeries(value, axisInfo) { var axis = axisInfo.axis; var dim = axis.dim; var snapToValue = value; var payloadBatch = []; var minDist = Number.MAX_VALUE; var minDiff = -1; each(axisInfo.seriesModels, function (series, idx) { var dataDim = series.coordDimToDataDim(dim); var seriesNestestValue; var dataIndices; if (series.getAxisTooltipData) { var result = series.getAxisTooltipData(dataDim, value, axis); dataIndices = result.dataIndices; seriesNestestValue = result.nestestValue; } else { dataIndices = series.getData().indicesOfNearest( dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex // when data length is not same. false, axis.type === 'category' ? 0.5 : null ); if (!dataIndices.length) { return; } seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]); } if (seriesNestestValue == null || !isFinite(seriesNestestValue)) { return; } var diff = value - seriesNestestValue; var dist = Math.abs(diff); // Consider category case if (dist <= minDist) { if (dist < minDist || (diff >= 0 && minDiff < 0)) { minDist = dist; minDiff = diff; snapToValue = seriesNestestValue; payloadBatch.length = 0; } each(dataIndices, function (dataIndex) { payloadBatch.push({ seriesIndex: series.seriesIndex, dataIndexInside: dataIndex, dataIndex: series.getData().getRawIndex(dataIndex) }); }); } }); return { payloadBatch: payloadBatch, snapToValue: snapToValue }; } function showPointer(showValueMap, axisInfo, value, payloadBatch) { showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch}; } function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) { var payloadBatch = payloadInfo.payloadBatch; var axis = axisInfo.axis; var axisModel = axis.model; var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys, // whose length will be used to judge whether dispatch action. if (!axisInfo.triggerTooltip || !payloadBatch.length) { return; } var coordSysModel = axisInfo.coordSys.model; var coordSysKey = modelHelper.makeKey(coordSysModel); var coordSysItem = dataByCoordSys.map[coordSysKey]; if (!coordSysItem) { coordSysItem = dataByCoordSys.map[coordSysKey] = { coordSysId: coordSysModel.id, coordSysIndex: coordSysModel.componentIndex, coordSysType: coordSysModel.type, coordSysMainType: coordSysModel.mainType, dataByAxis: [] }; dataByCoordSys.list.push(coordSysItem); } coordSysItem.dataByAxis.push({ axisDim: axis.dim, axisIndex: axisModel.componentIndex, axisType: axisModel.type, axisId: axisModel.id, value: value, // Caustion: viewHelper.getValueLabel is actually on "view stage", which // depends that all models have been updated. So it should not be performed // here. Considering axisPointerModel used here is volatile, which is hard // to be retrieve in TooltipView, we prepare parameters here. valueLabelOpt: { precision: axisPointerModel.get('label.precision'), formatter: axisPointerModel.get('label.formatter') }, seriesDataIndices: payloadBatch.slice() }); } function highlight(highlightBatch, actionType, batch) { highlightBatch.push.apply(highlightBatch, batch); } function updateModelActually(showValueMap, axesInfo) { // Basic logic: If no 'show' required, 'hide' this axisPointer. each(axesInfo, function (axisInfo, key) { var option = axisInfo.axisPointerModel.option; var valItem = showValueMap[key]; if (valItem) { !axisInfo.useHandle && (option.status = 'show'); option.value = valItem.value; // For label formatter param. option.seriesDataIndices = (valItem.payloadBatch || []).slice(); } // When always show (e.g., handle used), remain // original value and status. else { // If hide, value still need to be set, consider // click legend to toggle axis blank. !axisInfo.useHandle && (option.status = 'hide'); } }); } function dispatchTooltipActually(dataByCoordSys, point, tooltipOption, dispatchAction) { // Basic logic: If no showTip required, hideTip will be dispatched. if (illegalPoint(point) || !dataByCoordSys.list.length) { dispatchAction({type: 'hideTip'}); return; } // In most case only one axis (or event one series is used). It is // convinient to fetch payload.seriesIndex and payload.dataIndex // dirtectly. So put the first seriesIndex and dataIndex of the first // axis on the payload. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {}; dispatchAction({ type: 'showTip', escapeConnect: true, x: point[0], y: point[1], tooltipOption: tooltipOption, dataIndexInside: sampleItem.dataIndexInside, dataIndex: sampleItem.dataIndex, seriesIndex: sampleItem.seriesIndex, dataByCoordSys: dataByCoordSys.list }); } function dispatchHighDownActually(highlightBatch, dispatchAction, api, highDownKey) { // Basic logic: If nothing highlighted, should downplay all highlighted items. // This case will occur when mouse leave coordSys. // FIXME // (1) highlight status shoule be managemented in series.getData()? // (2) If axisPointer A triggerOn 'handle' and axisPointer B triggerOn // 'mousemove', items highlighted by A will be downplayed by B. // It will not be fixed until someone requires this scenario. // Consider items area hightlighted by 'handle', and globalListener may // downplay all items (including just highlighted ones) when mousemove. // So we use a highDownKey to separate them as a temporary solution. var zr = api.getZr(); highDownKey = 'lastHighlights' + (highDownKey || ''); var lastHighlights = get(zr)[highDownKey] || {}; var newHighlights = get(zr)[highDownKey] = {}; // Build hash map and remove duplicate incidentally. zrUtil.each(highlightBatch, function (batchItem) { var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex; newHighlights[key] = batchItem; }); // Diff. var toHighlight = []; var toDownplay = []; zrUtil.each(lastHighlights, function (batchItem, key) { !newHighlights[key] && toDownplay.push(batchItem); }); zrUtil.each(newHighlights, function (batchItem, key) { !lastHighlights[key] && toHighlight.push(batchItem); }); toDownplay.length && api.dispatchAction({ type: 'downplay', escapeConnect: true, batch: toDownplay }); toHighlight.length && api.dispatchAction({ type: 'highlight', escapeConnect: true, batch: toHighlight }); } function notTargetAxis(finder, axis) { var isTarget = 1; // If none of xxxAxisId and xxxAxisName and xxxAxisIndex exists in finder, // no axis is not target axis. each(finder, function (value, propName) { isTarget &= !(/^.+(AxisId|AxisName|AxisIndex)$/.test(propName)); }); !isTarget && each( [['AxisId', 'id'], ['AxisIndex', 'componentIndex'], ['AxisName', 'name']], function (prop) { var vals = modelUtil.normalizeToArray(finder[axis.dim + prop[0]]); isTarget |= zrUtil.indexOf(vals, axis.model[prop[1]]) >= 0; } ); return !isTarget; } function makeMapperParam(axisInfo) { var axisModel = axisInfo.axis.model; var item = {}; var dim = item.axisDim = axisInfo.axis.dim; item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex; item.axisName = item[dim + 'AxisName'] = axisModel.name; item.axisId = item[dim + 'AxisId'] = axisModel.id; return item; } function illegalPoint(point) { return point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]); } module.exports = axisTrigger;
mit
tpphu/react-pwa
src/redux/modules/survey.js
488
const IS_VALID = 'redux-example/survey/IS_VALID'; const IS_VALID_SUCCESS = 'redux-example/survey/IS_VALID_SUCCESS'; const IS_VALID_FAIL = 'redux-example/survey/IS_VALID_FAIL'; const initialState = {}; export default function reducer(state = initialState/* , action = {} */) { return state; } export function isValidEmail(data) { return { types: [IS_VALID, IS_VALID_SUCCESS, IS_VALID_FAIL], promise: ({ client }) => client.post('/survey/isValid', { data }) }; }
mit
etcinit/phabricator-slack-feed
vendor/github.com/etcinit/gonduit/requests/project_query.go
655
package requests import "github.com/etcinit/gonduit/constants" // ProjectQueryRequest represents a request to project.query. type ProjectQueryRequest struct { IDs []string `json:"ids"` Names []string `json:"names"` PHIDs []string `json:"phids"` Slugs []string `json:"slugs"` Icons []string `json:"icons"` Colors []string `json:"colors"` Status constants.ProjectStatus `json:"status"` Members []string `json:"members"` Limit uint64 `json:"limit"` Offset uint64 `json:"offset"` Request }
mit
warniel08/bretflix-finalproject
spec/controllers/profiles_controller_spec.rb
85
require 'rails_helper' RSpec.describe ProfilesController, type: :controller do end
mit
flftfqwxf/webpack
demo/extenal-and-lirbary/add.js
173
/** * Created by flftfqwxf on 16/5/28. */ var add= function () { console.log('this is extenal'); } var DEL= function () { console.log('this is extenal :DELETE') }
mit
tigerneil/deepy
deepy/layers/recurrent.py
6446
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import NeuralLayer from deepy.utils import build_activation, FLOATX import numpy as np import theano import theano.tensor as T from collections import OrderedDict OUTPUT_TYPES = ["sequence", "one"] INPUT_TYPES = ["sequence", "one"] class RNN(NeuralLayer): """ Recurrent neural network layer. """ def __init__(self, hidden_size, input_type="sequence", output_type="sequence", vector_core=None, hidden_activation="tanh", hidden_init=None, input_init=None, steps=None, persistent_state=False, reset_state_for_input=None, batch_size=None, go_backwards=False, mask=None, second_input_size=None, second_input=None): super(RNN, self).__init__("rnn") self._hidden_size = hidden_size self.output_dim = self._hidden_size self._input_type = input_type self._output_type = output_type self._hidden_activation = hidden_activation self._hidden_init = hidden_init self._vector_core = vector_core self._input_init = input_init self.persistent_state = persistent_state self.reset_state_for_input = reset_state_for_input self.batch_size = batch_size self._steps = steps self._go_backwards = go_backwards self._mask = mask.dimshuffle((1,0)) if mask else None self._second_input_size = second_input_size self._second_input = second_input self._sequence_map = OrderedDict() if input_type not in INPUT_TYPES: raise Exception("Input type of RNN is wrong: %s" % input_type) if output_type not in OUTPUT_TYPES: raise Exception("Output type of RNN is wrong: %s" % output_type) if self.persistent_state and not self.batch_size: raise Exception("Batch size must be set for persistent state mode") if mask and input_type == "one": raise Exception("Mask only works with sequence input") def _hidden_preact(self, h): return T.dot(h, self.W_h) if not self._vector_core else h * self.W_h def step(self, *vars): # Parse sequence sequence_map = dict(zip(self._sequence_map.keys(), vars[:len(self._sequence_map)])) if self._input_type == "sequence": x = sequence_map["x"] h = vars[-1] # Reset part of the state on condition if self.reset_state_for_input != None: h = h * T.neq(x[:, self.reset_state_for_input], 1).dimshuffle(0, 'x') # RNN core step z = x + self._hidden_preact(h) + self.B_h else: h = vars[-1] z = self._hidden_preact(h) + self.B_h # Second input if "second_input" in sequence_map: z += sequence_map["second_input"] new_h = self._hidden_act(z) # Apply mask if "mask" in sequence_map: mask = sequence_map["mask"].dimshuffle(0, 'x') new_h = mask * new_h + (1 - mask) * h return new_h def produce_input_sequences(self, x, mask=None, second_input=None): self._sequence_map.clear() if self._input_type == "sequence": self._sequence_map["x"] = T.dot(x, self.W_i) # Mask if mask: # (batch) self._sequence_map["mask"] = mask elif self._mask: # (time, batch) self._sequence_map["mask"] = self._mask # Second input if second_input: self._sequence_map["second_input"] = T.dot(second_input, self.W_i2) elif self._second_input: self._sequence_map["second_input"] = T.dot(self._second_input, self.W_i2) return self._sequence_map.values() def produce_initial_states(self, x): h0 = T.alloc(np.cast[FLOATX](0.), x.shape[0], self._hidden_size) if self._input_type == "sequence": if self.persistent_state: h0 = self.state else: h0 = x return [h0] def output(self, x): if self._input_type == "sequence": # Move middle dimension to left-most position # (sequence, batch, value) sequences = self.produce_input_sequences(x.dimshuffle((1,0,2))) else: sequences = self.produce_input_sequences(None) step_outputs = self.produce_initial_states(x) hiddens, _ = theano.scan(self.step, sequences=sequences, outputs_info=step_outputs, n_steps=self._steps, go_backwards=self._go_backwards) # Save persistent state if self.persistent_state: self.register_updates((self.state, hiddens[-1])) if self._output_type == "one": return hiddens[-1] elif self._output_type == "sequence": return hiddens.dimshuffle((1,0,2)) def setup(self): if self._input_type == "one" and self.input_dim != self._hidden_size: raise Exception("For RNN receives one vector as input, " "the hidden size should be same as last output dimension.") self._setup_params() self._setup_functions() def _setup_functions(self): self._hidden_act = build_activation(self._hidden_activation) def _setup_params(self): if not self._vector_core: self.W_h = self.create_weight(self._hidden_size, self._hidden_size, suffix="h", initializer=self._hidden_init) else: self.W_h = self.create_bias(self._hidden_size, suffix="h") self.W_h.set_value(self.W_h.get_value() + self._vector_core) self.B_h = self.create_bias(self._hidden_size, suffix="h") self.register_parameters(self.W_h, self.B_h) if self.persistent_state: self.state = self.create_matrix(self.batch_size, self._hidden_size, "rnn_state") self.register_free_parameters(self.state) else: self.state = None if self._input_type == "sequence": self.W_i = self.create_weight(self.input_dim, self._hidden_size, suffix="i", initializer=self._input_init) self.register_parameters(self.W_i) if self._second_input_size: self.W_i2 = self.create_weight(self._second_input_size, self._hidden_size, suffix="i2", initializer=self._input_init) self.register_parameters(self.W_i2)
mit
schryer/tg-modal
src/utils/scrollbarSize.js
773
let size; // Original source available at: https://github.com/react-bootstrap/dom-helpers/blob/master/src/util/scrollbarSize.js function getScrollbarSize(recalc) { if (!size || recalc) { if (typeof document !== 'undefined') { const scrollDiv = document.createElement('div'); scrollDiv.style.position = 'absolute'; scrollDiv.style.top = '-9999px'; scrollDiv.style.width = '50px'; scrollDiv.style.height = '50px'; scrollDiv.style.overflow = 'scroll'; document.body.appendChild(scrollDiv); size = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } } return size; } export default getScrollbarSize;
mit
ze-pequeno/mockito
src/main/java/org/mockito/internal/configuration/injection/scanner/MockScanner.java
2497
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.configuration.injection.scanner; import static org.mockito.internal.util.collections.Sets.newMockSafeHashSet; import java.lang.reflect.Field; import java.util.Set; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.internal.util.MockUtil; import org.mockito.internal.util.reflection.FieldReader; /** * Scan mocks, and prepare them if needed. */ public class MockScanner { private final Object instance; private final Class<?> clazz; /** * Creates a MockScanner. * * @param instance The test instance * @param clazz The class in the type hierarchy of this instance. */ public MockScanner(Object instance, Class<?> clazz) { this.instance = instance; this.clazz = clazz; } /** * Add the scanned and prepared mock instance to the given collection. * * <p> * The preparation of mocks consists only in defining a MockName if not already set. * </p> * * @param mocks Set of mocks */ public void addPreparedMocks(Set<Object> mocks) { mocks.addAll(scan()); } /** * Scan and prepare mocks for the given <code>testClassInstance</code> and <code>clazz</code> in the type hierarchy. * * @return A prepared set of mock */ private Set<Object> scan() { Set<Object> mocks = newMockSafeHashSet(); for (Field field : clazz.getDeclaredFields()) { // mock or spies only FieldReader fieldReader = new FieldReader(instance, field); Object mockInstance = preparedMock(fieldReader.read(), field); if (mockInstance != null) { mocks.add(mockInstance); } } return mocks; } private Object preparedMock(Object instance, Field field) { if (isAnnotatedByMockOrSpy(field)) { return instance; } if (isMockOrSpy(instance)) { MockUtil.maybeRedefineMockName(instance, field.getName()); return instance; } return null; } private boolean isAnnotatedByMockOrSpy(Field field) { return field.isAnnotationPresent(Spy.class) || field.isAnnotationPresent(Mock.class); } private boolean isMockOrSpy(Object instance) { return MockUtil.isMock(instance) || MockUtil.isSpy(instance); } }
mit
VioletLife/react
scripts/rollup/validate/eslintrc.rn.js
612
'use strict'; module.exports = { env: { commonjs: true, browser: true, }, globals: { // ES6 Map: true, Set: true, Symbol: true, Proxy: true, WeakMap: true, WeakSet: true, // Vendor specific MSApp: true, __REACT_DEVTOOLS_GLOBAL_HOOK__: true, // FB __DEV__: true, // Fabric. See https://github.com/facebook/react/pull/15490 // for more information nativeFabricUIManager: true, }, parserOptions: { ecmaVersion: 5, sourceType: 'script', }, rules: { 'no-undef': 'error', 'no-shadow-restricted-names': 'error', }, };
mit
xamarin/plugins
XPlat/YouTube.Player/ios/samples/YouTubePlayerSample/Models/YouTubeManager.cs
3338
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Google.Apis.Services; using Google.Apis.YouTube.v3; using UIKit; namespace YouTubePlayerSample { public class YouTubeManager { static readonly Lazy<YouTubeManager> lazy = new Lazy<YouTubeManager>(() => new YouTubeManager()); long maxResults = 50; YouTubeService youtubeService; HttpClient httpClient; public static YouTubeManager SharedInstance => lazy.Value; public static UIColor YouTubeColor { get; } = UIColor.FromRGBA(199, 11, 0, 255); public static UIColor BackgroundYouTubeColor { get; } = UIColor.FromRGBA(150, 7, 0, 255); public static UIColor DisabledColor { get; } = UIColor.FromWhiteAlpha(.5f, .5f); public long MaxResults { get { return maxResults; } set { if (maxResults < 0 || maxResults > 50) value = 50; maxResults = value; } } YouTubeManager() { youtubeService = new YouTubeService(new BaseClientService.Initializer { ApiKey = YouTubeApiKey.ApiKey, ApplicationName = "YouTubePlayerSample" }); httpClient = new HttpClient(); } public async Task<List<Video>> GetVideos(Search search) { var searchRequest = youtubeService.Search.List("snippet"); searchRequest.Q = search.Tags; searchRequest.PageToken = search.NextPageToken; searchRequest.MaxResults = maxResults; var searchResponse = await searchRequest.ExecuteAsync(); var videos = new List<Video>(); search.NextPageToken = searchResponse.NextPageToken; foreach (var searchResult in searchResponse.Items) { if (searchResult.Id.Kind != "youtube#video") continue; videos.Add(new Video { Id = searchResult.Id.VideoId, Title = searchResult.Snippet.Title, ThumbnailUrl = searchResult.Snippet.Thumbnails.Default__.Url }); } return videos; } public async Task<List<Video>> GetVideos(Playlist playlist) { var playlistRequest = youtubeService.PlaylistItems.List("snippet"); playlistRequest.PlaylistId = playlist.Id; playlistRequest.PageToken = playlist.NextPageToken; playlistRequest.MaxResults = maxResults; var playlistResponse = await playlistRequest.ExecuteAsync(); var videos = new List<Video>(); playlist.NextPageToken = playlistResponse.NextPageToken; foreach (var searchResult in playlistResponse.Items) videos.Add(new Video { Id = searchResult.Snippet.ResourceId.VideoId, Title = searchResult.Snippet.Title, ThumbnailUrl = searchResult.Snippet.Thumbnails?.Default__.Url }); return videos; } public async Task<string> DownloadThumbnail(Video video, CancellationToken ct) { ct.ThrowIfCancellationRequested(); var imageName = $"{video.Id}.jpg"; var imagePath = Path.Combine(Path.GetTempPath(), imageName); if (File.Exists(imagePath)) { ct.ThrowIfCancellationRequested(); return imagePath; } ct.ThrowIfCancellationRequested(); var bytes = await httpClient.GetByteArrayAsync(video.ThumbnailUrl); ct.ThrowIfCancellationRequested(); var fileStream = new FileStream(imagePath, FileMode.OpenOrCreate); await fileStream.WriteAsync(bytes, 0, bytes.Length); fileStream.Close(); ct.ThrowIfCancellationRequested(); return imagePath; } } }
mit
ScottHolden/azure-sdk-for-net
src/SDKs/Batch/DataPlane/Azure.Batch/Generated/ComputeNodeEndpointConfiguration.cs
1947
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// The endpoint configuration for the compute node. /// </summary> public partial class ComputeNodeEndpointConfiguration : IPropertyMetadata { private readonly IReadOnlyList<InboundEndpoint> inboundEndpoints; #region Constructors internal ComputeNodeEndpointConfiguration(Models.ComputeNodeEndpointConfiguration protocolObject) { this.inboundEndpoints = InboundEndpoint.ConvertFromProtocolCollectionReadOnly(protocolObject.InboundEndpoints); } #endregion Constructors #region ComputeNodeEndpointConfiguration /// <summary> /// Gets the list of inbound endpoints that are accessible on the compute node. /// </summary> public IReadOnlyList<InboundEndpoint> InboundEndpoints { get { return this.inboundEndpoints; } } #endregion // ComputeNodeEndpointConfiguration #region IPropertyMetadata bool IModifiable.HasBeenModified { //This class is compile time readonly so it cannot have been modified get { return false; } } bool IReadOnly.IsReadOnly { get { return true; } set { // This class is compile time readonly already } } #endregion // IPropertyMetadata } }
mit
mokuben/project_one
fuel/vendor/goaop/parser-reflection/tests/Stub/FileWithClasses55.php
5523
<?php namespace Go\ParserReflection\Stub; abstract class ExplicitAbstractClass {} abstract class ImplicitAbstractClass { private $a = 'foo'; protected $b = 'bar'; public $c = 'baz'; abstract function test(); } /** * Some docblock for the class */ final class FinalClass { public $args = []; public function __construct($a = null, &$b = null) { $this->args = array_slice(array($a, &$b), 0, func_num_args()); } } class BaseClass { protected static function prototypeMethod() { return __CLASS__; } } /** * @link https://bugs.php.net/bug.php?id=70957 self::class can not be resolved with reflection for abstract class */ abstract class AbstractClassWithMethods extends BaseClass { const TEST = 5; public function __construct(){} public function __destruct(){} public function explicitPublicFunc(){} function implicitPublicFunc(){} protected function protectedFunc(){} private function privateFunc(){} static function staticFunc(){} protected static function protectedStaticFunc(){} abstract function abstractFunc(); final function finalFunc(){} /** * @return string */ public static function funcWithDocAndBody() { static $a =5, $test = '1234'; return 'hello'; } public static function funcWithReturnArgs($a, $b = 100, $c = 10.0) { return [$a, $b, $c]; } public static function prototypeMethod() { return __CLASS__; } /** * @return \Generator */ public function generatorYieldFunc() { $index = 0; while ($index < 1e3) { yield $index; } } /** * @return int */ public function noGeneratorFunc() { $gen = function () { yield 10; }; return 10; } private function testParam($a, $b = null, $d = self::TEST) {} } class ClassWithProperties { private $privateProperty = 123; protected $protectedProperty = 'a'; public $publicProperty = 42.0; /** * Some message to test docBlock * * @var int */ private static $privateStaticProperty = 1; protected static $protectedStaticProperty = 'foo'; public static $publicStaticProperty = M_PI; } abstract class ClassWithMethodsAndProperties { public $publicProperty; protected $protectedProperty; private $privateProperty; static public $staticPublicProperty; static protected $staticProtectedProperty; static private $staticPrivateProperty; public function publicMethod() {} protected function protectedMethod() {} private function privateMethod() {} static public function publicStaticMethod() {} static protected function protectedStaticMethod() {} static private function privateStaticMethod() {} abstract public function publicAbstractMethod(); abstract protected function protectedAbstractMethod(); final public function publicFinalMethod() {} final protected function protectedFinalMethod() {} final private function privateFinalMethod() {} } interface SimpleInterface {} interface InterfaceWithMethod { function foo(); } trait SimpleTrait { function foo() { return __CLASS__; } } trait ConflictedSimpleTrait { function foo() { return 'BAZ'; } } class SimpleInheritance extends ExplicitAbstractClass {} /* * Current implementation returns wrong __toString description for the parent methods * @see https://github.com/goaop/parser-reflection/issues/55 abstract class SimpleAbstractInheritance extends ImplicitAbstractClass { public $b = 'bar1'; public $d = 'foobar'; private $e = 'foobaz'; } */ class ClassWithInterface implements SimpleInterface {} class ClassWithTrait { use SimpleTrait; } /* * Current implementation doesn't support trait adaptation, * @see https://github.com/goaop/parser-reflection/issues/54 * class ClassWithTraitAndAdaptation { use SimpleTrait { foo as protected fooBar; foo as private fooBaz; } } class ClassWithTraitAndConflict { use SimpleTrait, ConflictedSimpleTrait { foo as protected fooBar; ConflictedSimpleTrait::foo insteadof SimpleTrait; } } */ /* * Logic of prototype methods for interface and traits was changed since 7.0.6 * @see https://github.com/goaop/parser-reflection/issues/56 class ClassWithTraitAndInterface implements InterfaceWithMethod { use SimpleTrait; } */ class NoCloneable { private function __clone() {} } class NoInstantiable { private function __construct() {} } interface AbstractInterface { public function foo(); public function bar(); } class ClassWithScalarConstants { const A = 10, A1 = 11; const B = 42.0; const C = 'foo'; const D = false; const E = null; } class ClassWithMagicConstants { const A = __DIR__; const B = __FILE__; const C = __NAMESPACE__; const D = __CLASS__; const E = __LINE__; public static $a = self::A; protected static $b = self::B; private static $c = self::C; } const NS_CONST = 'test'; class ClassWithConstantsAndInheritance extends ClassWithMagicConstants { const A = 'overridden'; const H = M_PI; const J = NS_CONST; public static $h = self::H; } trait TraitWithProperties { private $a = 'foo'; protected $b = 'bar'; public $c = 'baz'; private static $as = 1; protected static $bs = __TRAIT__; public static $cs = 'foo'; }
mit
wahajashfaq/keryana
assets/editor/core/loader.js
7741
/** * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.loader} objects, which is used to * load core scripts and their dependencies from _source. */ if ( typeof CKEDITOR == 'undefined' ) CKEDITOR = {}; // jshint ignore:line if ( !CKEDITOR.loader ) { /** * Load core scripts and their dependencies from _source. * * @class * @singleton */ CKEDITOR.loader = ( function() { // Table of script names and their dependencies. var scripts = { '_bootstrap': [ 'config', 'creators/inline', 'creators/themedui', 'editable', 'ckeditor', 'plugins', 'scriptloader', 'style', 'tools', // The following are entries that we want to force loading at the end to avoid dependence recursion. 'dom/comment', 'dom/elementpath', 'dom/text', 'dom/rangelist', 'skin' ], 'ckeditor': [ 'ckeditor_basic', 'log', 'dom', 'dtd', 'dom/document', 'dom/element', 'dom/iterator', 'editor', 'event', 'htmldataprocessor', 'htmlparser', 'htmlparser/element', 'htmlparser/fragment', 'htmlparser/filter', 'htmlparser/basicwriter', 'template', 'tools' ], 'ckeditor_base': [], 'ckeditor_basic': [ 'editor_basic', 'env', 'event' ], 'command': [], 'config': [ 'ckeditor_base' ], 'dom': [], 'dom/comment': [ 'dom/node' ], 'dom/document': [ 'dom/node', 'dom/window' ], 'dom/documentfragment': [ 'dom/element' ], 'dom/element': [ 'dom', 'dom/document', 'dom/domobject', 'dom/node', 'dom/nodelist', 'tools' ], 'dom/elementpath': [ 'dom/element' ], 'dom/event': [], 'dom/iterator': [ 'dom/range' ], 'dom/node': [ 'dom/domobject', 'tools' ], 'dom/nodelist': [ 'dom/node' ], 'dom/domobject': [ 'dom/event' ], 'dom/range': [ 'dom/document', 'dom/documentfragment', 'dom/element', 'dom/walker' ], 'dom/rangelist': [ 'dom/range' ], 'dom/text': [ 'dom/node', 'dom/domobject' ], 'dom/walker': [ 'dom/node' ], 'dom/window': [ 'dom/domobject' ], 'dtd': [ 'tools' ], 'editable': [ 'editor', 'tools' ], 'editor': [ 'command', 'config', 'editor_basic', 'filter', 'focusmanager', 'keystrokehandler', 'lang', 'plugins', 'tools', 'ui' ], 'editor_basic': [ 'event' ], 'env': [], 'event': [], 'filter': [ 'dtd', 'tools' ], 'focusmanager': [], 'htmldataprocessor': [ 'htmlparser', 'htmlparser/basicwriter', 'htmlparser/fragment', 'htmlparser/filter' ], 'htmlparser': [], 'htmlparser/comment': [ 'htmlparser', 'htmlparser/node' ], 'htmlparser/element': [ 'htmlparser', 'htmlparser/fragment', 'htmlparser/node' ], 'htmlparser/fragment': [ 'htmlparser', 'htmlparser/comment', 'htmlparser/text', 'htmlparser/cdata' ], 'htmlparser/text': [ 'htmlparser', 'htmlparser/node' ], 'htmlparser/cdata': [ 'htmlparser', 'htmlparser/node' ], 'htmlparser/filter': [ 'htmlparser' ], 'htmlparser/basicwriter': [ 'htmlparser' ], 'htmlparser/node': [ 'htmlparser' ], 'keystrokehandler': [ 'event' ], 'lang': [], 'log': [ 'ckeditor_basic' ], 'plugins': [ 'resourcemanager' ], 'resourcemanager': [ 'scriptloader', 'tools' ], 'scriptloader': [ 'dom/element', 'env' ], 'selection': [ 'dom/range', 'dom/walker' ], 'skin': [], 'style': [ 'selection' ], 'template': [], 'tools': [ 'env' ], 'ui': [], 'creators/themedui': [], 'creators/inline': [] }; // The production implementation contains a fixed timestamp generated by the releaser. var timestamp = '%TIMESTAMP%'; // The development implementation contains a current timestamp. // %REMOVE_LINE% timestamp = ( CKEDITOR && CKEDITOR.timestamp ) || ( new Date() ).valueOf(); // %REMOVE_LINE% var getUrl = function( resource ) { if ( CKEDITOR && CKEDITOR.getUrl ) return CKEDITOR.getUrl( resource ); return CKEDITOR.basePath + resource + ( resource.indexOf( '?' ) >= 0 ? '&' : '?' ) + 't=' + timestamp; }; var pendingLoad = []; return { /** * The list of loaded scripts in their loading order. * * // Alert the loaded script names. * alert( CKEDITOR.loader.loadedScripts ); */ loadedScripts: [], /** * Table of script names and their dependencies. * * @property {Array} */ scripts: scripts, /** * @todo */ loadPending: function() { var scriptName = pendingLoad.shift(); if ( !scriptName ) return; var scriptSrc = getUrl( 'core/' + scriptName + '.js' ); var script = document.createElement( 'script' ); script.type = 'text/javascript'; script.src = scriptSrc; function onScriptLoaded() { // Append this script to the list of loaded scripts. CKEDITOR.loader.loadedScripts.push( scriptName ); // Load the next. CKEDITOR.loader.loadPending(); } // We must guarantee the execution order of the scripts, so we // need to load them one by one. (http://dev.ckeditor.com/ticket/4145) // The following if/else block has been taken from the scriptloader core code. if ( typeof script.onreadystatechange !== 'undefined' ) { /** @ignore */ script.onreadystatechange = function() { if ( script.readyState == 'loaded' || script.readyState == 'complete' ) { script.onreadystatechange = null; onScriptLoaded(); } }; } else { /** @ignore */ script.onload = function() { // Some browsers, such as Safari, may call the onLoad function // immediately. Which will break the loading sequence. (http://dev.ckeditor.com/ticket/3661) setTimeout( function() { onScriptLoaded( scriptName ); }, 0 ); }; } document.body.appendChild( script ); }, /** * Loads a specific script, including its dependencies. This is not a * synchronous loading, which means that the code to be loaded will * not necessarily be available after this call. * * CKEDITOR.loader.load( 'dom/element' ); * * @param {String} scriptName * @param {Boolean} [defer=false] * @todo params */ load: function( scriptName, defer ) { // Check if the script has already been loaded. if ( ( 's:' + scriptName ) in this.loadedScripts ) return; // Get the script dependencies list. var dependencies = scripts[ scriptName ]; if ( !dependencies ) throw 'The script name"' + scriptName + '" is not defined.'; // Mark the script as loaded, even before really loading it, to // avoid cross references recursion. // Prepend script name with 's:' to avoid conflict with Array's methods. this.loadedScripts[ 's:' + scriptName ] = true; // Load all dependencies first. for ( var i = 0; i < dependencies.length; i++ ) this.load( dependencies[ i ], true ); var scriptSrc = getUrl( 'core/' + scriptName + '.js' ); // Append the <script> element to the DOM. // If the page is fully loaded, we can't use document.write // but if the script is run while the body is loading then it's safe to use it // Unfortunately, Firefox <3.6 doesn't support document.readyState, so it won't get this improvement if ( document.body && ( !document.readyState || document.readyState == 'complete' ) ) { pendingLoad.push( scriptName ); if ( !defer ) this.loadPending(); } else { // Append this script to the list of loaded scripts. this.loadedScripts.push( scriptName ); document.write( '<script src="' + scriptSrc + '" type="text/javascript"><\/script>' ); } } }; } )(); } // Check if any script has been defined for autoload. if ( CKEDITOR._autoLoad ) { CKEDITOR.loader.load( CKEDITOR._autoLoad ); delete CKEDITOR._autoLoad; }
mit
raj2611/raj2611.github.io
gem/bundler/lib/bundler/cli/gem.rb
7595
# frozen_string_literal: true require "pathname" module Bundler class CLI::Gem TEST_FRAMEWORK_VERSIONS = { "rspec" => "3.0", "minitest" => "5.0" }.freeze attr_reader :options, :gem_name, :thor, :name, :target def initialize(options, gem_name, thor) @options = options @gem_name = resolve_name(gem_name) @thor = thor @name = @gem_name @target = SharedHelpers.pwd.join(gem_name) validate_ext_name if options[:ext] end def run Bundler.ui.confirm "Creating gem '#{name}'..." underscored_name = name.tr("-", "_") namespaced_path = name.tr("-", "/") constant_name = name.gsub(/-[_-]*(?![_-]|$)/) { "::" }.gsub(/([_-]+|(::)|^)(.|$)/) { $2.to_s + $3.upcase } constant_array = constant_name.split("::") git_user_name = `git config user.name`.chomp git_user_email = `git config user.email`.chomp config = { :name => name, :underscored_name => underscored_name, :namespaced_path => namespaced_path, :makefile_path => "#{underscored_name}/#{underscored_name}", :constant_name => constant_name, :constant_array => constant_array, :author => git_user_name.empty? ? "TODO: Write your name" : git_user_name, :email => git_user_email.empty? ? "TODO: Write your email address" : git_user_email, :test => options[:test], :ext => options[:ext], :exe => options[:exe], :bundler_version => bundler_dependency_version, :git_user_name => git_user_name.empty? ? "[USERNAME]" : git_user_name } ensure_safe_gem_name(name, constant_array) templates = { "Gemfile.tt" => "Gemfile", "gitignore.tt" => ".gitignore", "lib/newgem.rb.tt" => "lib/#{namespaced_path}.rb", "lib/newgem/version.rb.tt" => "lib/#{namespaced_path}/version.rb", "newgem.gemspec.tt" => "#{name}.gemspec", "Rakefile.tt" => "Rakefile", "README.md.tt" => "README.md", "bin/console.tt" => "bin/console", "bin/setup.tt" => "bin/setup" } executables = %w( bin/console bin/setup ) if test_framework = ask_and_set_test_framework config[:test] = test_framework config[:test_framework_version] = TEST_FRAMEWORK_VERSIONS[test_framework] templates.merge!(".travis.yml.tt" => ".travis.yml") case test_framework when "rspec" templates.merge!( "rspec.tt" => ".rspec", "spec/spec_helper.rb.tt" => "spec/spec_helper.rb", "spec/newgem_spec.rb.tt" => "spec/#{namespaced_path}_spec.rb" ) when "minitest" templates.merge!( "test/test_helper.rb.tt" => "test/test_helper.rb", "test/newgem_test.rb.tt" => "test/#{namespaced_path}_test.rb" ) end end config[:test_task] = config[:test] == "minitest" ? "test" : "spec" if ask_and_set(:mit, "Do you want to license your code permissively under the MIT license?", "This means that any other developer or company will be legally allowed to use your code " \ "for free as long as they admit you created it. You can read more about the MIT license " \ "at http://choosealicense.com/licenses/mit.") config[:mit] = true Bundler.ui.info "MIT License enabled in config" templates.merge!("LICENSE.txt.tt" => "LICENSE.txt") end if ask_and_set(:coc, "Do you want to include a code of conduct in gems you generate?", "Codes of conduct can increase contributions to your project by contributors who " \ "prefer collaborative, safe spaces. You can read more about the code of conduct at " \ "contributor-covenant.org. Having a code of conduct means agreeing to the responsibility " \ "of enforcing it, so be sure that you are prepared to do that. Be sure that your email " \ "address is specified as a contact in the generated code of conduct so that people know " \ "who to contact in case of a violation. For suggestions about " \ "how to enforce codes of conduct, see http://bit.ly/coc-enforcement.") config[:coc] = true Bundler.ui.info "Code of conduct enabled in config" templates.merge!("CODE_OF_CONDUCT.md.tt" => "CODE_OF_CONDUCT.md") end templates.merge!("exe/newgem.tt" => "exe/#{name}") if config[:exe] if options[:ext] templates.merge!( "ext/newgem/extconf.rb.tt" => "ext/#{name}/extconf.rb", "ext/newgem/newgem.h.tt" => "ext/#{name}/#{underscored_name}.h", "ext/newgem/newgem.c.tt" => "ext/#{name}/#{underscored_name}.c" ) end templates.each do |src, dst| thor.template("newgem/#{src}", target.join(dst), config) end executables.each do |file| path = target.join(file) executable = (path.stat.mode | 0o111) path.chmod(executable) end Bundler.ui.info "Initializing git repo in #{target}" Dir.chdir(target) do `git init` `git add .` end # Open gemspec in editor open_editor(options["edit"], target.join("#{name}.gemspec")) if options[:edit] end private def resolve_name(name) SharedHelpers.pwd.join(name).basename.to_s end def ask_and_set(key, header, message) choice = options[key] choice = Bundler.settings["gem.#{key}"] if choice.nil? if choice.nil? Bundler.ui.confirm header choice = Bundler.ui.yes? "#{message} y/(n):" Bundler.settings.set_global("gem.#{key}", choice) end choice end def validate_ext_name return unless gem_name.index("-") Bundler.ui.error "You have specified a gem name which does not conform to the \n" \ "naming guidelines for C extensions. For more information, \n" \ "see the 'Extension Naming' section at the following URL:\n" \ "http://guides.rubygems.org/gems-with-extensions/\n" exit 1 end def ask_and_set_test_framework test_framework = options[:test] || Bundler.settings["gem.test"] if test_framework.nil? Bundler.ui.confirm "Do you want to generate tests with your gem?" result = Bundler.ui.ask "Type 'rspec' or 'minitest' to generate those test files now and " \ "in the future. rspec/minitest/(none):" if result =~ /rspec|minitest/ test_framework = result else test_framework = false end end if Bundler.settings["gem.test"].nil? Bundler.settings.set_global("gem.test", test_framework) end test_framework end def bundler_dependency_version v = Gem::Version.new(Bundler::VERSION) req = v.segments[0..1] req << "a" if v.prerelease? req.join(".") end def ensure_safe_gem_name(name, constant_array) if name =~ /^\d/ Bundler.ui.error "Invalid gem name #{name} Please give a name which does not start with numbers." exit 1 elsif constant_array.inject(Object) {|c, s| (c.const_defined?(s) && c.const_get(s)) || break } Bundler.ui.error "Invalid gem name #{name} constant #{constant_array.join("::")} is already in use. Please choose another gem name." exit 1 end end def open_editor(editor, file) thor.run(%(#{editor} "#{file}")) end end end
mit
chris-rock/node-crypto-examples
sha-stream.js
452
// generate a hash from file stream var crypto = require('crypto'), fs = require('fs'), key = 'mysecret key' // open file stream var fstream = fs.createReadStream('./test/hmac.js'); var hash = crypto.createHash('sha512', key); hash.setEncoding('hex'); // once the stream is done, we read the values fstream.on('end', function () { hash.end(); // print result console.log(hash.read()); }); // pipe file to hash generator fstream.pipe(hash);
mit
l3l0/BehatExamples
vendor/vendor_full/symfony/src/Symfony/Component/HttpKernel/Bundle/Bundle.php
4829
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Bundle; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\Console\Application; use Symfony\Component\Finder\Finder; /** * An implementation of BundleInterface that adds a few conventions * for DependencyInjection extensions and Console commands. * * @author Fabien Potencier <fabien.potencier@symfony-project.com> */ abstract class Bundle extends ContainerAware implements BundleInterface { protected $name; protected $reflected; /** * Boots the Bundle. */ public function boot() { } /** * Shutdowns the Bundle. */ public function shutdown() { } /** * Builds the bundle. * * It is only ever called once when the cache is empty. * * The default implementation automatically registers a DIC extension * if its name is the same as the bundle name after replacing the * Bundle suffix by Extension (DependencyInjection\SensioBlogExtension * for a SensioBlogBundle for instance). In such a case, the alias * is forced to be the underscore version of the bundle name * (sensio_blog for a SensioBlogBundle for instance). * * This method can be overridden to register compilation passes, * other extensions, ... * * @param ContainerBuilder $container A ContainerBuilder instance */ public function build(ContainerBuilder $container) { $class = $this->getNamespace().'\\DependencyInjection\\'.str_replace('Bundle', 'Extension', $this->getName()); if (class_exists($class)) { $extension = new $class(); $alias = Container::underscore(str_replace('Bundle', '', $this->getName())); if ($alias !== $extension->getAlias()) { throw new \LogicException(sprintf('The extension alias for the default extension of a bundle must be the underscored version of the bundle name ("%s" vs "%s")', $alias, $extension->getAlias())); } $container->registerExtension($extension); } } /** * Gets the Bundle namespace. * * @return string The Bundle namespace */ public function getNamespace() { if (null === $this->reflected) { $this->reflected = new \ReflectionObject($this); } return $this->reflected->getNamespaceName(); } /** * Gets the Bundle directory path. * * @return string The Bundle absolute path */ public function getPath() { if (null === $this->reflected) { $this->reflected = new \ReflectionObject($this); } return strtr(dirname($this->reflected->getFileName()), '\\', '/'); } /** * Returns the bundle parent name. * * @return string The Bundle parent name it overrides or null if no parent */ public function getParent() { return null; } /** * Returns the bundle name (the class short name). * * @return string The Bundle name */ final public function getName() { if (null !== $this->name) { return $this->name; } $name = get_class($this); $pos = strrpos($name, '\\'); return $this->name = false === $pos ? $name : substr($name, $pos + 1); } /** * Finds and registers Commands. * * Override this method if your bundle commands do not follow the conventions: * * * Commands are in the 'Command' sub-directory * * Commands extend Symfony\Component\Console\Command\Command * * @param Application $application An Application instance */ public function registerCommands(Application $application) { if (!$dir = realpath($this->getPath().'/Command')) { return; } $finder = new Finder(); $finder->files()->name('*Command.php')->in($dir); $prefix = $this->getNamespace().'\\Command'; foreach ($finder as $file) { $ns = $prefix; if ($relativePath = $file->getRelativePath()) { $ns .= '\\'.strtr($relativePath, '/', '\\'); } $r = new \ReflectionClass($ns.'\\'.$file->getBasename('.php')); if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') && !$r->isAbstract()) { $application->add($r->newInstance()); } } } }
mit
tnasky/test
db/migrate/20110415003956_add_unique_index_to_users.rb
179
class AddUniqueIndexToUsers < ActiveRecord::Migration def self.up add_index :users, :email, :unique => true end def self.down remove_index :users, :email end end
mit
jericks/geoscript-js
src/main/resources/org/geoscript/js/lib/geoscript/style/style.js
4631
var UTIL = require("../util"); var STYLE_UTIL = require("./util"); var Symbolizer = require("./symbolizer").Symbolizer; var Filter = require("../filter").Filter; var geotools = Packages.org.geotools; /** api: (define) * module = style * class = Style */ /** api: (extends) * style/symbolizer.js */ var Style = exports.Style = UTIL.extend(Symbolizer, { /** api: constructor * .. class:: Style * * Instances of the symbolizer base class are not created directly. * See the constructor details for one of the symbolizer subclasses. */ constructor: function Style(config) { this.cache = {}; if (config) { if (config instanceof Symbolizer) { config = {parts: [config]}; } else if (UTIL.isArray(config)) { config = {parts: config}; } this.parts = config.parts || []; UTIL.applyIf(this, config); } }, /** private: property[parts] */ get parts() { if (!("parts" in this.cache)) { this.cache.parts = []; } return this.cache.parts; }, set parts(parts) { var part; var simpleParts = []; for (var i=0, ii=parts.length; i<ii; ++i) { part = parts[i]; if (part instanceof Style) { Array.prototype.push.apply(simpleParts, part.parts); } else if (part instanceof Symbolizer) { simpleParts.push(part); } else if (typeof part === "object") { simpleParts.push(STYLE_UTIL.create(part)); } else { throw new Error("Can't create symbolizer from " + part); } } this.cache.parts = simpleParts; }, /** api: method[and] * :arg symbolizer: :class:`style.Symbolizer` * :returns: :class:`style.Style` * * Generate a composite symbolizer from this symbolizer and the provided * symbolizer. */ and: function(symbolizer) { this.parts.push(symbolizer); return this; }, /** api: property[filter] * :class:`filter.Filter` * Filter that determines where this symbolizer applies. */ set filter(filter) { if (typeof filter === "string") { filter = new Filter(filter); } var symbolizer; for (var i=0, ii=this.parts.length; i<ii; ++i) { symbolizer = this.parts[i]; if (symbolizer.filter) { symbolizer.filter = filter.and(symbolizer.filter); } else { symbolizer.filter = filter; } } }, /** api: property[minScaleDenominator] * ``Number`` * Optional minimum scale denominator at which this symbolizer applies. */ set minScaleDenominator(min) { for (var i=0, ii=this.parts.length; i<ii; ++i) { this.parts[i].minScaleDenominator = min; } }, /** api: property[maxScaleDenominator] * ``Number`` * Optional maximum scale denominator at which this symbolizer applies. */ set maxScaleDenominator(min) { for (var i=0, ii=this.parts.length; i<ii; ++i) { this.parts[i].maxScaleDenominator = min; } }, /** api: property[zIndex] * ``Number`` * The zIndex determines draw order of symbolizers. Symbolizers * with higher zIndex values will be drawn over symbolizers with lower * values. By default, symbolizers have a zIndex of ``0``. */ set zIndex(index) { for (var i=0, ii=this.parts.length; i<ii; ++i) { this.parts[i].zIndex = index; } }, /** private: property[_style] * ``org.geotools.styling.Style`` */ get _style() { var zIndexes = []; var lookup = {}; this.parts.forEach(function(symbolizer) { var z = symbolizer.zIndex; if (!(z in lookup)) { zIndexes.push(z); lookup[z] = []; } lookup[z].push(symbolizer); }); var _featureTypeStyles = new java.util.ArrayList(); zIndexes.sort().forEach(function(z) { var symbolizers = lookup[z]; var _rules = java.lang.reflect.Array.newInstance(geotools.styling.Rule, symbolizers.length); symbolizers.forEach(function(symbolizer, j) { _rules[j] = symbolizer._rule; }); _featureTypeStyles.add( STYLE_UTIL._builder.createFeatureTypeStyle("Feature", _rules) ); }); var _style = STYLE_UTIL._builder.createStyle(); _style.featureTypeStyles().addAll(_featureTypeStyles); return _style; }, get config() { return { parts: this.parts.map(function(part) { return part.config; }) }; }, clone: function() { return new Style(this.config); }, /** private: method[toFullString] */ toFullString: function() { return "parts: " + this.parts.map(function(part) { return part.toString(); }).join(", "); } });
mit
storybooks/storybook
examples/angular-cli/jest-config/setup.ts
112
import 'jest-preset-angular'; import './globalMocks'; require('babel-plugin-require-context-hook/register')();
mit
n0ix/SFDL.FTP
ArxOne.FtpTest/FtpReplyCodeTest.cs
967
#region Arx One FTP // Arx One FTP // A simple FTP client // https://github.com/ArxOne/FTP // Released under MIT license http://opensource.org/licenses/MIT #endregion namespace ArxOne.FtpTest { using Ftp; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> ///This is a test class for FtpReplyCodeTest and is intended ///to contain all FtpReplyCodeTest Unit Tests ///</summary> [TestClass] public class FtpReplyCodeTest { [TestMethod] [TestCategory("Consistency")] public void ClassTest() { var code = new FtpReplyCode(450); Assert.AreEqual(FtpReplyCodeClass.Filesystem, code.Class); } [TestMethod] [TestCategory("Consistency")] public void SeverityTest() { var code = new FtpReplyCode(450); Assert.AreEqual(FtpReplyCodeSeverity.TransientNegativeCompletion, code.Severity); } } }
mit
rainlike/justshop
vendor/payum/payum/src/Payum/Paypal/ExpressCheckout/Nvp/Action/Api/CreateBillingAgreementAction.php
1371
<?php namespace Payum\Paypal\ExpressCheckout\Nvp\Action\Api; use Payum\Core\Action\ActionInterface; use Payum\Core\ApiAwareInterface; use Payum\Core\ApiAwareTrait; use Payum\Core\Bridge\Spl\ArrayObject; use Payum\Core\Exception\RequestNotSupportedException; use Payum\Core\Exception\LogicException; use Payum\Paypal\ExpressCheckout\Nvp\Api; use Payum\Paypal\ExpressCheckout\Nvp\Request\Api\CreateBillingAgreement; class CreateBillingAgreementAction implements ActionInterface, ApiAwareInterface { use ApiAwareTrait; public function __construct() { $this->apiClass = Api::class; } /** * {@inheritDoc} */ public function execute($request) { /** @var $request CreateBillingAgreement */ RequestNotSupportedException::assertSupports($this, $request); $model = ArrayObject::ensureArrayObject($request->getModel()); if (null === $model['TOKEN']) { throw new LogicException('TOKEN must be set. Have you run SetExpressCheckoutAction?'); } $model->replace( $this->api->createBillingAgreement((array) $model) ); } /** * {@inheritDoc} */ public function supports($request) { return $request instanceof CreateBillingAgreement && $request->getModel() instanceof \ArrayAccess ; } }
mit
agocke/roslyn
src/EditorFeatures/Core/Implementation/IntelliSense/Completion/OptionSetExtensions.cs
949
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion { internal static class OptionSetExtensions { public static OptionSet WithDebuggerCompletionOptions(this OptionSet options) { return options .WithChangedOption(EditorCompletionOptions.UseSuggestionMode, options.GetOption(EditorCompletionOptions.UseSuggestionMode_Debugger)) .WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, false) .WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, false); } } }
mit
pythonchelle/opencomparison
apps/package/management/commands/package_updater.py
2105
from socket import error as socket_error from sys import stdout from time import sleep, gmtime, strftime from xml.parsers.expat import ExpatError from xmlrpclib import ProtocolError from django.conf import settings from django.core.management.base import CommandError, NoArgsCommand from package.models import Package class Command(NoArgsCommand): help = "Updates all the packages in the system. Commands belongs to django-packages.apps.package" def handle(self, *args, **options): print >> stdout, "Commencing package updating now at %s " % strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) for index, package in enumerate(Package.objects.all()): try: try: package.fetch_metadata() package.fetch_commits() except socket_error, e: print >> stdout, "For '%s', threw a socket.error: %s" % (package.title, e) continue except RuntimeError, e: message = "For '%s', too many requests issued to repo threw a RuntimeError: %s" % (package.title, e) print >> stdout, message continue except UnicodeDecodeError, e: message = "For '%s', UnicodeDecodeError: %s" % (package.title, e) print >> stdout, message continue except ProtocolError, e: message = "For '%s', xmlrpc.ProtocolError: %s" % (package.title, e) print >> stdout, message continue except ExpatError, e: message = "For '%s', ExpatError: %s" % (package.title, e) print >> stdout, message continue if not hasattr(settings, "GITHUB_ACCOUNT"): sleep(5) print >> stdout, "%s. Successfully updated package '%s'" % (index+1,package.title) print >> stdout, "-" * 40 print >> stdout, "Finished at %s" % strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
mit
Nowdone/easemob-android
EaseUI/src/com/easemob/easeui/widget/photoview/VersionedGestureDetector.java
8123
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.easemob.easeui.widget.photoview; /******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.FloatMath; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.VelocityTracker; import android.view.ViewConfiguration; abstract class VersionedGestureDetector { static final String LOG_TAG = "VersionedGestureDetector"; OnGestureListener mListener; public static VersionedGestureDetector newInstance(Context context, OnGestureListener listener) { final int sdkVersion = Build.VERSION.SDK_INT; VersionedGestureDetector detector = null; if (sdkVersion < Build.VERSION_CODES.ECLAIR) { detector = new CupcakeDetector(context); } else if (sdkVersion < Build.VERSION_CODES.FROYO) { detector = new EclairDetector(context); } else { detector = new FroyoDetector(context); } detector.mListener = listener; return detector; } public abstract boolean onTouchEvent(MotionEvent ev); public abstract boolean isScaling(); public static interface OnGestureListener { public void onDrag(float dx, float dy); public void onFling(float startX, float startY, float velocityX, float velocityY); public void onScale(float scaleFactor, float focusX, float focusY); } private static class CupcakeDetector extends VersionedGestureDetector { float mLastTouchX; float mLastTouchY; final float mTouchSlop; final float mMinimumVelocity; public CupcakeDetector(Context context) { final ViewConfiguration configuration = ViewConfiguration.get(context); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mTouchSlop = configuration.getScaledTouchSlop(); } private VelocityTracker mVelocityTracker; private boolean mIsDragging; float getActiveX(MotionEvent ev) { return ev.getX(); } float getActiveY(MotionEvent ev) { return ev.getY(); } public boolean isScaling() { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); mIsDragging = false; break; } case MotionEvent.ACTION_MOVE: { final float x = getActiveX(ev); final float y = getActiveY(ev); final float dx = x - mLastTouchX, dy = y - mLastTouchY; if (!mIsDragging) { // Use Pythagoras to see if drag length is larger than // touch slop mIsDragging = Math.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop; } if (mIsDragging) { mListener.onDrag(dx, dy); mLastTouchX = x; mLastTouchY = y; if (null != mVelocityTracker) { mVelocityTracker.addMovement(ev); } } break; } case MotionEvent.ACTION_CANCEL: { // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } case MotionEvent.ACTION_UP: { if (mIsDragging) { if (null != mVelocityTracker) { mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); // Compute velocity within the last 1000ms mVelocityTracker.addMovement(ev); mVelocityTracker.computeCurrentVelocity(1000); final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker.getYVelocity(); // If the velocity is greater than minVelocity, call // listener if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) { mListener.onFling(mLastTouchX, mLastTouchY, -vX, -vY); } } } // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } } return true; } } @TargetApi(5) private static class EclairDetector extends CupcakeDetector { private static final int INVALID_POINTER_ID = -1; private int mActivePointerId = INVALID_POINTER_ID; private int mActivePointerIndex = 0; public EclairDetector(Context context) { super(context); } @Override float getActiveX(MotionEvent ev) { try { return ev.getX(mActivePointerIndex); } catch (Exception e) { return ev.getX(); } } @Override float getActiveY(MotionEvent ev) { try { return ev.getY(mActivePointerIndex); } catch (Exception e) { return ev.getY(); } } @Override public boolean onTouchEvent(MotionEvent ev) { final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mActivePointerId = ev.getPointerId(0); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mActivePointerId = INVALID_POINTER_ID; break; case MotionEvent.ACTION_POINTER_UP: final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = ev.getPointerId(newPointerIndex); mLastTouchX = ev.getX(newPointerIndex); mLastTouchY = ev.getY(newPointerIndex); } break; } mActivePointerIndex = ev.findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId : 0); return super.onTouchEvent(ev); } } @TargetApi(8) private static class FroyoDetector extends EclairDetector { private final ScaleGestureDetector mDetector; // Needs to be an inner class so that we don't hit // VerifyError's on API 4. private final OnScaleGestureListener mScaleListener = new OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { mListener.onScale(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY()); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { // NO-OP } }; public FroyoDetector(Context context) { super(context); mDetector = new ScaleGestureDetector(context, mScaleListener); } @Override public boolean isScaling() { return mDetector.isInProgress(); } @Override public boolean onTouchEvent(MotionEvent ev) { mDetector.onTouchEvent(ev); return super.onTouchEvent(ev); } } }
mit
hellorich/go-craft
craft/app/vendor/imagine/imagine/lib/Imagine/Imagick/Imagine.php
5245
<?php /* * This file is part of the Imagine package. * * (c) Bulat Shakirzyanov <mallluhuct@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Imagine\Imagick; use Imagine\Exception\NotSupportedException; use Imagine\Image\AbstractImagine; use Imagine\Image\BoxInterface; use Imagine\Image\Metadata\MetadataBag; use Imagine\Image\Palette\Color\ColorInterface; use Imagine\Exception\InvalidArgumentException; use Imagine\Exception\RuntimeException; use Imagine\Image\Palette\CMYK; use Imagine\Image\Palette\RGB; use Imagine\Image\Palette\Grayscale; /** * Imagine implementation using the Imagick PHP extension */ final class Imagine extends AbstractImagine { /** * @throws RuntimeException */ public function __construct() { if (!class_exists('Imagick')) { throw new RuntimeException('Imagick not installed'); } $version = $this->getVersion(new Imagick()); if (version_compare('6.2.9', $version) > 0) { throw new RuntimeException(sprintf('ImageMagick version 6.2.9 or higher is required, %s provided', $version)); } } /** * {@inheritdoc} */ public function open($path) { $path = $this->checkPath($path); try { $imagick = new Imagick($path); $image = new Image($imagick, $this->createPalette($imagick), $this->getMetadataReader()->readFile($path)); } catch (\Exception $e) { throw new RuntimeException(sprintf('Unable to open image %s', $path), $e->getCode(), $e); } return $image; } /** * {@inheritdoc} */ public function create(BoxInterface $size, ColorInterface $color = null) { $width = $size->getWidth(); $height = $size->getHeight(); $palette = null !== $color ? $color->getPalette() : new RGB(); $color = null !== $color ? $color : $palette->color('fff'); try { $pixel = new \ImagickPixel((string) $color); $pixel->setColorValue(Imagick::COLOR_ALPHA, $color->getAlpha() / 100); $imagick = new Imagick(); $imagick->newImage($width, $height, $pixel); $imagick->setImageMatte(true); $imagick->setImageBackgroundColor($pixel); if (version_compare('6.3.1', $this->getVersion($imagick)) < 0) { $imagick->setImageOpacity($pixel->getColorValue(Imagick::COLOR_ALPHA)); } $pixel->clear(); $pixel->destroy(); return new Image($imagick, $palette, new MetadataBag()); } catch (\ImagickException $e) { throw new RuntimeException('Could not create empty image', $e->getCode(), $e); } } /** * {@inheritdoc} */ public function load($string) { try { $imagick = new Imagick(); $imagick->readImageBlob($string); $imagick->setImageMatte(true); return new Image($imagick, $this->createPalette($imagick), $this->getMetadataReader()->readData($string)); } catch (\ImagickException $e) { throw new RuntimeException('Could not load image from string', $e->getCode(), $e); } } /** * {@inheritdoc} */ public function read($resource) { if (!is_resource($resource)) { throw new InvalidArgumentException('Variable does not contain a stream resource'); } $content = stream_get_contents($resource); try { $imagick = new Imagick(); $imagick->readImageBlob($content); } catch (\ImagickException $e) { throw new RuntimeException('Could not read image from resource', $e->getCode(), $e); } return new Image($imagick, $this->createPalette($imagick), $this->getMetadataReader()->readData($content, $resource)); } /** * {@inheritdoc} */ public function font($file, $size, ColorInterface $color) { return new Font(new Imagick(), $file, $size, $color); } /** * Returns the palette corresponding to an Imagick resource colorspace * * @param Imagick $imagick * * @return CMYK|Grayscale|RGB * * @throws NotSupportedException */ private function createPalette(Imagick $imagick) { switch ($imagick->getImageColorspace()) { case Imagick::COLORSPACE_RGB: case Imagick::COLORSPACE_SRGB: return new RGB(); case Imagick::COLORSPACE_CMYK: return new CMYK(); case Imagick::COLORSPACE_GRAY: return new Grayscale(); default: throw new NotSupportedException('Only RGB and CMYK colorspace are currently supported'); } } /** * Returns ImageMagick version * * @param Imagick $imagick * * @return string */ private function getVersion(Imagick $imagick) { $v = $imagick->getVersion(); list($version) = sscanf($v['versionString'], 'ImageMagick %s %04d-%02d-%02d %s %s'); return $version; } }
mit
luissancheza/sice
js/jqwidgets/demos/angular/app/datetimeinput/datetime/main.ts
296
import { platformBrowser } from '@angular/platform-browser'; import { enableProdMode } from '@angular/core'; import { AppModuleNgFactory } from '../../../temp/app/datetimeinput/datetime/app.module.ngfactory'; enableProdMode(); platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
mit
ArsenShnurkov/GenuineChannels
Genuine Channels/Sources/Utilities/AsyncThreadStarter.cs
2454
/* Genuine Channels product. * * Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved. * * This source code comes under and must be used and distributed according to the Genuine Channels license agreement. */ using System; using System.Collections; using System.Threading; using Belikov.GenuineChannels.Logbook; namespace Belikov.GenuineChannels.Utilities { /// <summary> /// Starts socket's asynchronous operation in the thread that never exit. /// </summary> internal class AsyncThreadStarter { private static ArrayList _workItems = new ArrayList(); private static Thread _thread; private static ManualResetEvent _manualResetEvent = new ManualResetEvent(false); /// <summary> /// Queues the asynchronous operation. /// </summary> /// <param name="iAsyncWorkItem">The asynchronous operation.</param> public static void QueueTask(IAsyncWorkItem iAsyncWorkItem) { lock (_workItems.SyncRoot) { if (_thread == null) { _thread = new Thread(new ThreadStart(ServiceWorkItems)); _thread.IsBackground = true; _thread.Name = "GC.AsyncThreadStarter"; _thread.Start(); } _workItems.Add(iAsyncWorkItem); _manualResetEvent.Set(); } } /// <summary> /// Services the work items. /// </summary> public static void ServiceWorkItems() { for ( ; ; ) { _manualResetEvent.WaitOne(); lock (_workItems.SyncRoot) { for ( int i = 0; i < _workItems.Count; i++) { IAsyncWorkItem iAsyncWorkItem = (IAsyncWorkItem)_workItems[i]; try { iAsyncWorkItem.StartAsynchronousOperation(); } catch (Exception ex) { // LOG: BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter; if ( binaryLogWriter != null ) { binaryLogWriter.WriteEvent(LogCategory.ImplementationWarning, "AsyncThreadStarter.ServiceWorkItems", LogMessageType.Error, ex, null, null, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1, 0, 0, 0, null, null, null, null, "Execution of \"{0}\" workitem has resulted in exception.", iAsyncWorkItem.GetType().FullName); } } } _workItems.Clear(); _manualResetEvent.Reset(); } } } } }
mit
teohhanhui/symfony
src/Symfony/Component/Messenger/Tests/Transport/Doctrine/DoctrineReceiverTest.php
4792
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Messenger\Tests\Transport\Doctrine; use PHPUnit\Framework\TestCase; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Exception\MessageDecodingFailedException; use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp; use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage; use Symfony\Component\Messenger\Transport\Doctrine\Connection; use Symfony\Component\Messenger\Transport\Doctrine\DoctrineReceivedStamp; use Symfony\Component\Messenger\Transport\Doctrine\DoctrineReceiver; use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer; use Symfony\Component\Messenger\Transport\Serialization\Serializer; use Symfony\Component\Serializer as SerializerComponent; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; class DoctrineReceiverTest extends TestCase { public function testItReturnsTheDecodedMessageToTheHandler() { $serializer = $this->createSerializer(); $doctrineEnvelope = $this->createDoctrineEnvelope(); $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); $connection->method('get')->willReturn($doctrineEnvelope); $receiver = new DoctrineReceiver($connection, $serializer); $actualEnvelopes = $receiver->get(); $this->assertCount(1, $actualEnvelopes); /** @var Envelope $actualEnvelope */ $actualEnvelope = $actualEnvelopes[0]; $this->assertEquals(new DummyMessage('Hi'), $actualEnvelopes[0]->getMessage()); /** @var DoctrineReceivedStamp $doctrineReceivedStamp */ $doctrineReceivedStamp = $actualEnvelope->last(DoctrineReceivedStamp::class); $this->assertNotNull($doctrineReceivedStamp); $this->assertSame('1', $doctrineReceivedStamp->getId()); /** @var TransportMessageIdStamp $transportMessageIdStamp */ $transportMessageIdStamp = $actualEnvelope->last(TransportMessageIdStamp::class); $this->assertNotNull($transportMessageIdStamp); $this->assertSame(1, $transportMessageIdStamp->getId()); } /** * @expectedException \Symfony\Component\Messenger\Exception\MessageDecodingFailedException */ public function testItRejectTheMessageIfThereIsAMessageDecodingFailedException() { $serializer = $this->createMock(PhpSerializer::class); $serializer->method('decode')->willThrowException(new MessageDecodingFailedException()); $doctrineEnvelop = $this->createDoctrineEnvelope(); $connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); $connection->method('get')->willReturn($doctrineEnvelop); $connection->expects($this->once())->method('reject'); $receiver = new DoctrineReceiver($connection, $serializer); $receiver->get(); } public function testAll() { $serializer = $this->createSerializer(); $doctrineEnvelope1 = $this->createDoctrineEnvelope(); $doctrineEnvelope2 = $this->createDoctrineEnvelope(); $connection = $this->createMock(Connection::class); $connection->method('findAll')->with(50)->willReturn([$doctrineEnvelope1, $doctrineEnvelope2]); $receiver = new DoctrineReceiver($connection, $serializer); $actualEnvelopes = iterator_to_array($receiver->all(50)); $this->assertCount(2, $actualEnvelopes); $this->assertEquals(new DummyMessage('Hi'), $actualEnvelopes[0]->getMessage()); } public function testFind() { $serializer = $this->createSerializer(); $doctrineEnvelope = $this->createDoctrineEnvelope(); $connection = $this->createMock(Connection::class); $connection->method('find')->with(10)->willReturn($doctrineEnvelope); $receiver = new DoctrineReceiver($connection, $serializer); $actualEnvelope = $receiver->find(10); $this->assertEquals(new DummyMessage('Hi'), $actualEnvelope->getMessage()); } private function createDoctrineEnvelope() { return [ 'id' => 1, 'body' => '{"message": "Hi"}', 'headers' => [ 'type' => DummyMessage::class, ], ]; } private function createSerializer(): Serializer { $serializer = new Serializer( new SerializerComponent\Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]) ); return $serializer; } }
mit
GlowstonePlusPlus/GlowstonePlusPlus
src/main/java/net/glowstone/inventory/LeveledEnchant.java
559
package net.glowstone.inventory; import net.glowstone.constants.GlowEnchantment; import net.glowstone.util.WeightedRandom.Choice; import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.EnchantmentOffer; public class LeveledEnchant extends EnchantmentOffer implements Choice { public LeveledEnchant(Enchantment enchantment, int enchantmentLevel, int cost) { super(enchantment, enchantmentLevel, cost); } @Override public int getWeight() { return ((GlowEnchantment) getEnchantment()).getWeight(); } }
mit
dinorastoder/laravel-io-development
tests/unit/Forum/UseCases/ViewThreadHandlerTest.php
1445
<?php namespace Lio\Forum\UseCases; use App; use Lio\Events\Dispatcher; use Lio\Forum\Threads\Thread; use Mockery as m; class ViewThreadHandlerTest extends \UnitTestCase { public function test_can_create_handler() { $this->assertInstanceOf('Lio\Forum\UseCases\ViewThreadHandler', $this->getHandler()); } public function test_can_get_response() { $thread = new Thread; $thread->id = 666; $threadRepository = m::mock('Lio\Forum\ThreadRepository'); $threadRepository->shouldReceive('getBySlug')->andReturn($thread); $replyRepository = m::mock('Lio\Forum\ReplyRepository'); $replyRepository->shouldReceive('getRepliesForThread')->andReturn('bar'); $request = new ViewThreadRequest('slug', 'page', 12); $response = $this->getHandler(null, $threadRepository, $replyRepository)->handle($request); $this->assertInstanceOf('Lio\Forum\UseCases\ViewThreadResponse', $response); $this->assertEquals(666, $response->thread->id); $this->assertEquals('bar', $response->replies); } private function getHandler($dispatcher = null, $threadRepository = null, $replyRepository = null) { return new ViewThreadHandler( $dispatcher ?: new Dispatcher, $threadRepository ?: m::mock('Lio\Forum\ThreadRepository'), $replyRepository ?: m::mock('Lio\Forum\ReplyRepository') ); } }
mit
bjornharrtell/ember-paper
addon/components/paper-toast.js
3806
/** * @module ember-paper */ import { inject as service } from '@ember/service'; import { or } from '@ember/object/computed'; import Component from '@ember/component'; import { computed } from '@ember/object'; import { run } from '@ember/runloop'; import { guidFor } from '@ember/object/internals'; import { getOwner } from '@ember/application'; import layout from '../templates/components/paper-toast'; import { invokeAction } from 'ember-invoke-action'; /** * @class PaperToast * @extends Ember.Component */ export default Component.extend({ layout, tagName: '', escapeToClose: false, swipeToClose: true, capsule: false, duration: 3000, position: 'bottom left', left: computed('position', function() { let [, x] = this.get('position').split(' '); return x === 'left'; }), top: computed('position', function() { let [y] = this.get('position').split(' '); return y === 'top'; }), // Calculate a default that is always valid for the parent of the backdrop. wormholeSelector: '#paper-toast-fab-wormhole', defaultedParent: or('parent', 'wormholeSelector'), // Calculate the id of the wormhole destination, setting it if need be. The // id is that of the 'parent', if provided, or 'paper-wormhole' if not. destinationId: computed('defaultedParent', function() { let config = getOwner(this).resolveRegistration('config:environment'); if (config.environment === 'test' && !this.get('parent')) { return '#ember-testing'; } let parent = this.get('defaultedParent'); let parentEle = typeof parent === 'string' ? document.querySelector(parent) : parent; // If the parent isn't found, assume that it is an id, but that the DOM doesn't // exist yet. This only happens during integration tests or if entire application // route is a dialog. if (typeof parent === 'string' && parent.charAt(0) === '#') { return `#${parent.substring(1)}`; } else { let { id } = parentEle; if (!id) { id = `${this.uniqueId}-parent`; parentEle.id = id; } return `#${id}`; } }), // Find the element referenced by destinationId destinationEl: computed('destinationId', function() { return document.querySelector(this.get('destinationId')); }), constants: service(), _destroyMessage() { if (!this.isDestroyed) { invokeAction(this, 'onClose'); } }, init() { this._super(...arguments); this.uniqueId = guidFor(this); }, willInsertElement() { this._super(...arguments); document.querySelector(this.get('destinationId')).classList.add('md-toast-animating'); }, didInsertElement() { this._super(...arguments); if (this.get('duration') !== false) { run.later(this, '_destroyMessage', this.get('duration')); } if (this.get('escapeToClose')) { // Adding Listener to body tag, FIXME this._escapeToClose = run.bind(this, (e) => { if (e.keyCode === this.get('constants.KEYCODE.ESCAPE') && this.get('onClose')) { this._destroyMessage(); } }); document.body.addEventListener('keydown', this._escapeToClose); } let y = this.get('top') ? 'top' : 'bottom'; document.querySelector(this.get('destinationId')).classList.add(`md-toast-open-${y}`); }, willDestroyElement() { this._super(...arguments); if (this.get('escapeToClose')) { document.body.removeEventListener('keydown', this._escapeToClose); this._escapeToClose = null; } let y = this.get('top') ? 'top' : 'bottom'; document.querySelector(this.get('destinationId')).classList.remove(`md-toast-open-${y}`, 'md-toast-animating'); }, swipeAction() { if (this.get('swipeToClose')) { invokeAction(this, 'onClose'); } } });
mit
ta-stott-oe/PowerBI-visuals
src/Clients/VisualsCommon/Utility/wordBreaker.ts
7799
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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. */ /// <reference path="../_references.ts"/> module jsCommon { export module WordBreaker { import TextProperties = powerbi.TextProperties; import ITextAsSVGMeasurer = powerbi.ITextAsSVGMeasurer; import ITextTruncator = powerbi.ITextTruncator; export interface WordBreakerResult { start: number; end: number; } const SPACE = ' '; const BREAKERS_REGEX = /[\s\n]+/g; function search(index: number, content: string, backward: boolean) { if (backward) { for (let i = index - 1; i > -1; i--) { if (hasBreakers(content[i])) return i + 1; } } else { for (let i = index, ilen = content.length; i < ilen; i++) { if (hasBreakers(content[i])) return i; } } return backward ? 0 : content.length; } /** * Find the word nearest the cursor specified within content * @param index - point within content to search forward/backward from * @param content - string to search */ export function find(index: number, content: string): WordBreakerResult { debug.assert(index >= 0 && index <= content.length, 'index within content string bounds'); let result = { start: 0, end: 0 }; if (content.length === 0) return result; result.start = search(index, content, true); result.end = search(index, content, false); return result; } /** * Test for presence of breakers within content * @param content - string to test */ export function hasBreakers(content: string): boolean { BREAKERS_REGEX.lastIndex = 0; return BREAKERS_REGEX.test(content); } /** * Count the number of pieces when broken by BREAKERS_REGEX * ~2.7x faster than WordBreaker.split(content).length * @param content - string to break and count */ export function wordCount(content: string): number { let count = 1; BREAKERS_REGEX.lastIndex = 0; BREAKERS_REGEX.exec(content); while (BREAKERS_REGEX.lastIndex !== 0) { count++; BREAKERS_REGEX.exec(content); } return count; } export function getMaxWordWidth(content: string, textWidthMeasurer: ITextAsSVGMeasurer, properties: TextProperties): number { var words = split(content); var maxWidth = 0; for (var w of words) { properties.text = w; maxWidth = Math.max(maxWidth, textWidthMeasurer(properties)); } return maxWidth; } function split(content: string): string[] { return content.split(BREAKERS_REGEX); } function getWidth(content: string, properties: TextProperties, textWidthMeasurer: ITextAsSVGMeasurer): number { properties.text = content; return textWidthMeasurer(properties); } function truncate(content: string, properties: TextProperties, truncator: ITextTruncator, maxWidth: number): string { properties.text = content; return truncator(properties, maxWidth); } /** * Split content by breakers (words) and greedy fit as many words * into each index in the result based on max width and number of lines * e.g. Each index in result corresponds to a line of content * when used by AxisHelper.LabelLayoutStrategy.wordBreak * @param content - string to split * @param properties - text properties to be used by @param:textWidthMeasurer * @param textWidthMeasurer - function to calculate width of given text content * @param maxWidth - maximum allowed width of text content in each result * @param maxNumLines - maximum number of results we will allow, valid values must be greater than 0 * @param truncator - (optional) if specified, used as a function to truncate content to a given width */ export function splitByWidth( content: string, properties: TextProperties, textWidthMeasurer: ITextAsSVGMeasurer, maxWidth: number, maxNumLines: number, truncator?: ITextTruncator): string[]{ // Default truncator returns string as-is truncator = truncator ? truncator : (properties: TextProperties, maxWidth: number) => properties.text; let result: string[] = []; let words = split(content); let usedWidth = 0; let wordsInLine: string[] = []; for (let word of words) { // Last line? Just add whatever is left if ((maxNumLines > 0) && (result.length >= maxNumLines - 1)) { wordsInLine.push(word); continue; } // Determine width if we add this word // Account for SPACE we will add when joining... let wordWidth = wordsInLine.length === 0 ? getWidth(word, properties, textWidthMeasurer) : getWidth(SPACE + word, properties, textWidthMeasurer); // If width would exceed max width, // then push used words and start new split result if (usedWidth + wordWidth > maxWidth) { // Word alone exceeds max width, just add it. if (wordsInLine.length === 0) { result.push(truncate(word, properties, truncator, maxWidth)); usedWidth = 0; wordsInLine = []; continue; } result.push(truncate(wordsInLine.join(SPACE), properties, truncator, maxWidth)); usedWidth = 0; wordsInLine = []; } // ...otherwise, add word and continue wordsInLine.push(word); usedWidth += wordWidth; } // Push remaining words onto result result.push(truncate(wordsInLine.join(SPACE), properties, truncator, maxWidth)); return result; } } }
mit
Jandersolutions/ionic
js/utils/platform.js
12637
(function(window, document, ionic) { function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } var IOS = 'ios'; var ANDROID = 'android'; var WINDOWS_PHONE = 'windowsphone'; /** * @ngdoc utility * @name ionic.Platform * @module ionic */ ionic.Platform = { // Put navigator on platform so it can be mocked and set // the browser does not allow window.navigator to be set navigator: window.navigator, /** * @ngdoc property * @name ionic.Platform#isReady * @returns {boolean} Whether the device is ready. */ isReady: false, /** * @ngdoc property * @name ionic.Platform#isFullScreen * @returns {boolean} Whether the device is fullscreen. */ isFullScreen: false, /** * @ngdoc property * @name ionic.Platform#platforms * @returns {Array(string)} An array of all platforms found. */ platforms: null, /** * @ngdoc property * @name ionic.Platform#grade * @returns {string} What grade the current platform is. */ grade: null, ua: navigator.userAgent, /** * @ngdoc method * @name ionic.Platform#ready * @description * Trigger a callback once the device is ready, or immediately * if the device is already ready. This method can be run from * anywhere and does not need to be wrapped by any additonal methods. * When the app is within a WebView (Cordova), it'll fire * the callback once the device is ready. If the app is within * a web browser, it'll fire the callback after `window.load`. * Please remember that Cordova features (Camera, FileSystem, etc) still * will not work in a web browser. * @param {function} callback The function to call. */ ready: function(cb) { // run through tasks to complete now that the device is ready if (this.isReady) { cb(); } else { // the platform isn't ready yet, add it to this array // which will be called once the platform is ready readyCallbacks.push(cb); } }, /** * @private */ detect: function() { ionic.Platform._checkPlatforms(); ionic.requestAnimationFrame(function() { // only add to the body class if we got platform info for (var i = 0; i < ionic.Platform.platforms.length; i++) { document.body.classList.add('platform-' + ionic.Platform.platforms[i]); } }); }, /** * @ngdoc method * @name ionic.Platform#setGrade * @description Set the grade of the device: 'a', 'b', or 'c'. 'a' is the best * (most css features enabled), 'c' is the worst. By default, sets the grade * depending on the current device. * @param {string} grade The new grade to set. */ setGrade: function(grade) { var oldGrade = this.grade; this.grade = grade; ionic.requestAnimationFrame(function() { if (oldGrade) { document.body.classList.remove('grade-' + oldGrade); } document.body.classList.add('grade-' + grade); }); }, /** * @ngdoc method * @name ionic.Platform#device * @description Return the current device (given by cordova). * @returns {object} The device object. */ device: function() { return window.device || {}; }, _checkPlatforms: function(platforms) { this.platforms = []; var grade = 'a'; if (this.isWebView()) { this.platforms.push('webview'); this.platforms.push('cordova'); } else { this.platforms.push('browser'); } if (this.isIPad()) this.platforms.push('ipad'); var platform = this.platform(); if (platform) { this.platforms.push(platform); var version = this.version(); if (version) { var v = version.toString(); if (v.indexOf('.') > 0) { v = v.replace('.', '_'); } else { v += '_0'; } this.platforms.push(platform + v.split('_')[0]); this.platforms.push(platform + v); if (this.isAndroid() && version < 4.4) { grade = (version < 4 ? 'c' : 'b'); } else if (this.isWindowsPhone()) { grade = 'b'; } } } this.setGrade(grade); }, /** * @ngdoc method * @name ionic.Platform#isWebView * @returns {boolean} Check if we are running within a WebView (such as Cordova). */ isWebView: function() { return !(!window.cordova && !window.PhoneGap && !window.phonegap); }, /** * @ngdoc method * @name ionic.Platform#isIPad * @returns {boolean} Whether we are running on iPad. */ isIPad: function() { if (/iPad/i.test(ionic.Platform.navigator.platform)) { return true; } return /iPad/i.test(this.ua); }, /** * @ngdoc method * @name ionic.Platform#isIOS * @returns {boolean} Whether we are running on iOS. */ isIOS: function() { return this.is(IOS); }, /** * @ngdoc method * @name ionic.Platform#isAndroid * @returns {boolean} Whether we are running on Android. */ isAndroid: function() { return this.is(ANDROID); }, /** * @ngdoc method * @name ionic.Platform#isWindowsPhone * @returns {boolean} Whether we are running on Windows Phone. */ isWindowsPhone: function() { return this.is(WINDOWS_PHONE); }, /** * @ngdoc method * @name ionic.Platform#platform * @returns {string} The name of the current platform. */ platform: function() { // singleton to get the platform name if (platformName === null) this.setPlatform(this.device().platform); return platformName; }, /** * @private */ setPlatform: function(n) { if (typeof n != 'undefined' && n !== null && n.length) { platformName = n.toLowerCase(); } else if(getParameterByName('ionicplatform')) { platformName = getParameterByName('ionicplatform'); } else if (this.ua.indexOf('Android') > 0) { platformName = ANDROID; } else if (this.ua.indexOf('iPhone') > -1 || this.ua.indexOf('iPad') > -1 || this.ua.indexOf('iPod') > -1) { platformName = IOS; } else if (this.ua.indexOf('Windows Phone') > -1) { platformName = WINDOWS_PHONE; } else { platformName = ionic.Platform.navigator.platform && navigator.platform.toLowerCase().split(' ')[0] || ''; } }, /** * @ngdoc method * @name ionic.Platform#version * @returns {number} The version of the current device platform. */ version: function() { // singleton to get the platform version if (platformVersion === null) this.setVersion(this.device().version); return platformVersion; }, /** * @private */ setVersion: function(v) { if (typeof v != 'undefined' && v !== null) { v = v.split('.'); v = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0)); if (!isNaN(v)) { platformVersion = v; return; } } platformVersion = 0; // fallback to user-agent checking var pName = this.platform(); var versionMatch = { 'android': /Android (\d+).(\d+)?/, 'ios': /OS (\d+)_(\d+)?/, 'windowsphone': /Windows Phone (\d+).(\d+)?/ }; if (versionMatch[pName]) { v = this.ua.match(versionMatch[pName]); if (v && v.length > 2) { platformVersion = parseFloat(v[1] + '.' + v[2]); } } }, // Check if the platform is the one detected by cordova is: function(type) { type = type.toLowerCase(); // check if it has an array of platforms if (this.platforms) { for (var x = 0; x < this.platforms.length; x++) { if (this.platforms[x] === type) return true; } } // exact match var pName = this.platform(); if (pName) { return pName === type.toLowerCase(); } // A quick hack for to check userAgent return this.ua.toLowerCase().indexOf(type) >= 0; }, /** * @ngdoc method * @name ionic.Platform#exitApp * @description Exit the app. */ exitApp: function() { this.ready(function() { navigator.app && navigator.app.exitApp && navigator.app.exitApp(); }); }, /** * @ngdoc method * @name ionic.Platform#showStatusBar * @description Shows or hides the device status bar (in Cordova). * @param {boolean} shouldShow Whether or not to show the status bar. */ showStatusBar: function(val) { // Only useful when run within cordova this._showStatusBar = val; this.ready(function() { // run this only when or if the platform (cordova) is ready ionic.requestAnimationFrame(function() { if (ionic.Platform._showStatusBar) { // they do not want it to be full screen window.StatusBar && window.StatusBar.show(); document.body.classList.remove('status-bar-hide'); } else { // it should be full screen window.StatusBar && window.StatusBar.hide(); document.body.classList.add('status-bar-hide'); } }); }); }, /** * @ngdoc method * @name ionic.Platform#fullScreen * @description * Sets whether the app is fullscreen or not (in Cordova). * @param {boolean=} showFullScreen Whether or not to set the app to fullscreen. Defaults to true. * @param {boolean=} showStatusBar Whether or not to show the device's status bar. Defaults to false. */ fullScreen: function(showFullScreen, showStatusBar) { // showFullScreen: default is true if no param provided this.isFullScreen = (showFullScreen !== false); // add/remove the fullscreen classname to the body ionic.DomUtil.ready(function() { // run this only when or if the DOM is ready ionic.requestAnimationFrame(function() { // fixing pane height before we adjust this panes = document.getElementsByClassName('pane'); for (var i = 0; i < panes.length; i++) { panes[i].style.height = panes[i].offsetHeight + "px"; } if (ionic.Platform.isFullScreen) { document.body.classList.add('fullscreen'); } else { document.body.classList.remove('fullscreen'); } }); // showStatusBar: default is false if no param provided ionic.Platform.showStatusBar((showStatusBar === true)); }); } }; var platformName = null, // just the name, like iOS or Android platformVersion = null, // a float of the major and minor, like 7.1 readyCallbacks = [], windowLoadListenderAttached; // setup listeners to know when the device is ready to go function onWindowLoad() { if (ionic.Platform.isWebView()) { // the window and scripts are fully loaded, and a cordova/phonegap // object exists then let's listen for the deviceready document.addEventListener("deviceready", onPlatformReady, false); } else { // the window and scripts are fully loaded, but the window object doesn't have the // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova onPlatformReady(); } if (windowLoadListenderAttached) { window.removeEventListener("load", onWindowLoad, false); } } if (document.readyState === 'complete') { onWindowLoad(); } else { windowLoadListenderAttached = true; window.addEventListener("load", onWindowLoad, false); } window.addEventListener("load", onWindowLoad, false); function onPlatformReady() { // the device is all set to go, init our own stuff then fire off our event ionic.Platform.isReady = true; ionic.Platform.detect(); for (var x = 0; x < readyCallbacks.length; x++) { // fire off all the callbacks that were added before the platform was ready readyCallbacks[x](); } readyCallbacks = []; ionic.trigger('platformready', { target: document }); ionic.requestAnimationFrame(function() { document.body.classList.add('platform-ready'); }); } })(this, document, ionic);
mit
systemovich/lila
modules/relation/src/main/RelationRepo.scala
1924
package lila.relation import play.api.libs.json._ import lila.common.PimpedJson._ import lila.db.api._ import lila.db.Implicits._ import tube.relationTube private[relation] object RelationRepo { def relation(id: ID): Fu[Option[Relation]] = $primitive.one($select byId id, "r")(_.asOpt[Boolean]) def relation(u1: ID, u2: ID): Fu[Option[Relation]] = relation(makeId(u1, u2)) def followers(userId: ID) = relaters(userId, Follow) def following(userId: ID) = relating(userId, Follow) def blockers(userId: ID) = relaters(userId, Block) def blocking(userId: ID) = relating(userId, Block) private def relaters(userId: ID, relation: Relation): Fu[Set[ID]] = $projection(Json.obj("u2" -> userId), Seq("u1", "r")) { obj => obj str "u1" map { _ -> ~(obj boolean "r") } } map (_.filter(_._2 == relation).map(_._1).toSet) private def relating(userId: ID, relation: Relation): Fu[Set[ID]] = $projection(Json.obj("u1" -> userId), Seq("u2", "r")) { obj => obj str "u2" map { _ -> ~(obj boolean "r") } } map (_.filter(_._2 == relation).map(_._1).toSet) def follow(u1: ID, u2: ID): Funit = save(u1, u2, Follow) def unfollow(u1: ID, u2: ID): Funit = remove(u1, u2) def block(u1: ID, u2: ID): Funit = save(u1, u2, Block) def unblock(u1: ID, u2: ID): Funit = remove(u1, u2) def unfollowAll(u1: ID): Funit = $remove(Json.obj("u1" -> u1)) private def save(u1: ID, u2: ID, relation: Relation): Funit = $save( makeId(u1, u2), Json.obj("u1" -> u1, "u2" -> u2, "r" -> relation) ) def remove(u1: ID, u2: ID): Funit = $remove byId makeId(u1, u2) def drop(userId: ID, relation: Relation, nb: Int) = $primitive( Json.obj("u1" -> userId, "r" -> relation), "_id", _ sort $sort.naturalAsc, max = nb.some )(_.asOpt[String]) flatMap { ids => $remove(Json.obj("_id" -> $in(ids))) } private def makeId(u1: String, u2: String) = u1 + "/" + u2 }
mit
segafan/wmelite_hcdaniel-repo
src/UITiledImage.cpp
12997
/* This file is part of WME Lite. http://dead-code.org/redir.php?target=wmelite Copyright (c) 2011 Jan Nedoma 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. */ #include "dcgf.h" #include "UITiledImage.h" IMPLEMENT_PERSISTENT(CUITiledImage, false); ////////////////////////////////////////////////////////////////////////// CUITiledImage::CUITiledImage(CBGame* inGame):CBObject(inGame) { m_Image = NULL; CBPlatform::SetRectEmpty(&m_UpLeft); CBPlatform::SetRectEmpty(&m_UpMiddle); CBPlatform::SetRectEmpty(&m_UpRight); CBPlatform::SetRectEmpty(&m_MiddleLeft); CBPlatform::SetRectEmpty(&m_MiddleMiddle); CBPlatform::SetRectEmpty(&m_MiddleRight); CBPlatform::SetRectEmpty(&m_DownLeft); CBPlatform::SetRectEmpty(&m_DownMiddle); CBPlatform::SetRectEmpty(&m_DownRight); } ////////////////////////////////////////////////////////////////////////// CUITiledImage::~CUITiledImage() { SAFE_DELETE(m_Image); } ////////////////////////////////////////////////////////////////////////// HRESULT CUITiledImage::Display(int X, int Y, int Width, int Height) { if(!m_Image) return E_FAIL; int tile_width = m_MiddleMiddle.right - m_MiddleMiddle.left; int tile_height = m_MiddleMiddle.bottom - m_MiddleMiddle.top; int num_columns = (Width - (m_MiddleLeft.right - m_MiddleLeft.left) - (m_MiddleRight.right - m_MiddleRight.left)) / tile_width; int num_rows = (Height - (m_UpMiddle.bottom - m_UpMiddle.top) - (m_DownMiddle.bottom - m_DownMiddle.top)) / tile_height; int col, row; Game->m_Renderer->StartSpriteBatch(); // top left/right m_Image->m_Surface->DisplayTrans(X, Y, m_UpLeft); m_Image->m_Surface->DisplayTrans(X+(m_UpLeft.right-m_UpLeft.left)+num_columns*tile_width, Y, m_UpRight); // bottom left/right m_Image->m_Surface->DisplayTrans(X, Y+(m_UpMiddle.bottom-m_UpMiddle.top) + num_rows*tile_height, m_DownLeft); m_Image->m_Surface->DisplayTrans(X+(m_UpLeft.right-m_UpLeft.left)+num_columns*tile_width, Y+(m_UpMiddle.bottom-m_UpMiddle.top) + num_rows*tile_height, m_DownRight); // left/right int yyy = Y + (m_UpMiddle.bottom-m_UpMiddle.top); for(row = 0; row<num_rows; row++) { m_Image->m_Surface->DisplayTrans(X, yyy, m_MiddleLeft); m_Image->m_Surface->DisplayTrans(X+(m_MiddleLeft.right-m_MiddleLeft.left)+num_columns*tile_width, yyy, m_MiddleRight); yyy+=tile_width; } // top/bottom int xxx = X + (m_UpLeft.right - m_UpLeft.left); for(col = 0; col<num_columns; col++) { m_Image->m_Surface->DisplayTrans(xxx, Y, m_UpMiddle); m_Image->m_Surface->DisplayTrans(xxx, Y+(m_UpMiddle.bottom-m_UpMiddle.top)+num_rows*tile_height, m_DownMiddle); xxx+=tile_width; } // tiles yyy = Y + (m_UpMiddle.bottom-m_UpMiddle.top); for(row=0; row<num_rows; row++) { xxx = X + (m_UpLeft.right - m_UpLeft.left); for(col=0; col<num_columns; col++) { m_Image->m_Surface->DisplayTrans(xxx, yyy, m_MiddleMiddle); xxx+=tile_width; } yyy+=tile_width; } Game->m_Renderer->EndSpriteBatch(); return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CUITiledImage::LoadFile(char * Filename) { BYTE* Buffer = Game->m_FileManager->ReadWholeFile(Filename); if(Buffer==NULL) { Game->LOG(0, "CUITiledImage::LoadFile failed for file '%s'", Filename); return E_FAIL; } HRESULT ret; m_Filename = new char [strlen(Filename)+1]; strcpy(m_Filename, Filename); if(FAILED(ret = LoadBuffer(Buffer, true))) Game->LOG(0, "Error parsing TILED_IMAGE file '%s'", Filename); delete [] Buffer; return ret; } TOKEN_DEF_START TOKEN_DEF (TILED_IMAGE) TOKEN_DEF (TEMPLATE) TOKEN_DEF (IMAGE) TOKEN_DEF (UP_LEFT) TOKEN_DEF (UP_RIGHT) TOKEN_DEF (UP_MIDDLE) TOKEN_DEF (DOWN_LEFT) TOKEN_DEF (DOWN_RIGHT) TOKEN_DEF (DOWN_MIDDLE) TOKEN_DEF (MIDDLE_LEFT) TOKEN_DEF (MIDDLE_RIGHT) TOKEN_DEF (MIDDLE_MIDDLE) TOKEN_DEF (VERTICAL_TILES) TOKEN_DEF (HORIZONTAL_TILES) TOKEN_DEF (EDITOR_PROPERTY) TOKEN_DEF_END ////////////////////////////////////////////////////////////////////////// HRESULT CUITiledImage::LoadBuffer(BYTE * Buffer, bool Complete) { TOKEN_TABLE_START(commands) TOKEN_TABLE (TILED_IMAGE) TOKEN_TABLE (TEMPLATE) TOKEN_TABLE (IMAGE) TOKEN_TABLE (UP_LEFT) TOKEN_TABLE (UP_RIGHT) TOKEN_TABLE (UP_MIDDLE) TOKEN_TABLE (DOWN_LEFT) TOKEN_TABLE (DOWN_RIGHT) TOKEN_TABLE (DOWN_MIDDLE) TOKEN_TABLE (MIDDLE_LEFT) TOKEN_TABLE (MIDDLE_RIGHT) TOKEN_TABLE (MIDDLE_MIDDLE) TOKEN_TABLE (VERTICAL_TILES) TOKEN_TABLE (HORIZONTAL_TILES) TOKEN_TABLE (EDITOR_PROPERTY) TOKEN_TABLE_END BYTE* params; int cmd; CBParser parser(Game); bool HTiles=false, VTiles=false; int H1=0, H2=0, H3=0; int V1=0, V2=0, V3=0; if(Complete) { if(parser.GetCommand ((char**)&Buffer, commands, (char**)&params)!=TOKEN_TILED_IMAGE) { Game->LOG(0, "'TILED_IMAGE' keyword expected."); return E_FAIL; } Buffer = params; } while ((cmd = parser.GetCommand ((char**)&Buffer, commands, (char**)&params)) > 0) { switch (cmd) { case TOKEN_TEMPLATE: if(FAILED(LoadFile((char*)params))) cmd = PARSERR_GENERIC; break; case TOKEN_IMAGE: SAFE_DELETE(m_Image); m_Image = new CBSubFrame(Game); if(!m_Image || FAILED(m_Image->SetSurface((char*)params))) { SAFE_DELETE(m_Image); cmd = PARSERR_GENERIC; } break; case TOKEN_UP_LEFT: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_UpLeft.left, &m_UpLeft.top, &m_UpLeft.right, &m_UpLeft.bottom); break; case TOKEN_UP_RIGHT: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_UpRight.left, &m_UpRight.top, &m_UpRight.right, &m_UpRight.bottom); break; case TOKEN_UP_MIDDLE: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_UpMiddle.left, &m_UpMiddle.top, &m_UpMiddle.right, &m_UpMiddle.bottom); break; case TOKEN_DOWN_LEFT: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_DownLeft.left, &m_DownLeft.top, &m_DownLeft.right, &m_DownLeft.bottom); break; case TOKEN_DOWN_RIGHT: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_DownRight.left, &m_DownRight.top, &m_DownRight.right, &m_DownRight.bottom); break; case TOKEN_DOWN_MIDDLE: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_DownMiddle.left, &m_DownMiddle.top, &m_DownMiddle.right, &m_DownMiddle.bottom); break; case TOKEN_MIDDLE_LEFT: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_MiddleLeft.left, &m_MiddleLeft.top, &m_MiddleLeft.right, &m_MiddleLeft.bottom); break; case TOKEN_MIDDLE_RIGHT: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_MiddleRight.left, &m_MiddleRight.top, &m_MiddleRight.right, &m_MiddleRight.bottom); break; case TOKEN_MIDDLE_MIDDLE: parser.ScanStr((char*)params, "%d,%d,%d,%d", &m_MiddleMiddle.left, &m_MiddleMiddle.top, &m_MiddleMiddle.right, &m_MiddleMiddle.bottom); break; case TOKEN_HORIZONTAL_TILES: parser.ScanStr((char*)params, "%d,%d,%d", &H1, &H2, &H3); HTiles = true; break; case TOKEN_VERTICAL_TILES: parser.ScanStr((char*)params, "%d,%d,%d", &V1, &V2, &V3); VTiles = true; break; case TOKEN_EDITOR_PROPERTY: ParseEditorProperty(params, false); break; } } if (cmd == PARSERR_TOKENNOTFOUND) { Game->LOG(0, "Syntax error in TILED_IMAGE definition"); return E_FAIL; } if (cmd == PARSERR_GENERIC) { Game->LOG(0, "Error loading TILED_IMAGE definition"); return E_FAIL; } if(VTiles && HTiles) { // up row CBPlatform::SetRect(&m_UpLeft, 0, 0, H1, V1); CBPlatform::SetRect(&m_UpMiddle, H1, 0, H1+H2, V1); CBPlatform::SetRect(&m_UpRight, H1+H2, 0, H1+H2+H3, V1); // middle row CBPlatform::SetRect(&m_MiddleLeft, 0, V1, H1, V1+V2); CBPlatform::SetRect(&m_MiddleMiddle, H1, V1, H1+H2, V1+V2); CBPlatform::SetRect(&m_MiddleRight, H1+H2, V1, H1+H2+H3, V1+V2); // down row CBPlatform::SetRect(&m_DownLeft, 0, V1+V2, H1, V1+V2+V3); CBPlatform::SetRect(&m_DownMiddle, H1, V1+V2, H1+H2, V1+V2+V3); CBPlatform::SetRect(&m_DownRight, H1+H2, V1+V2, H1+H2+H3, V1+V2+V3); } // default if(m_Image && m_Image->m_Surface) { int Width = m_Image->m_Surface->GetWidth()/3; int Height = m_Image->m_Surface->GetHeight()/3; if(CBPlatform::IsRectEmpty(&m_UpLeft)) CBPlatform::SetRect(&m_UpLeft, 0, 0, Width, Height); if(CBPlatform::IsRectEmpty(&m_UpMiddle)) CBPlatform::SetRect(&m_UpMiddle, Width, 0, 2*Width, Height); if(CBPlatform::IsRectEmpty(&m_UpRight)) CBPlatform::SetRect(&m_UpRight, 2*Width, 0, 3*Width, Height); if(CBPlatform::IsRectEmpty(&m_MiddleLeft)) CBPlatform::SetRect(&m_MiddleLeft, 0, Height, Width, 2*Height); if(CBPlatform::IsRectEmpty(&m_MiddleMiddle)) CBPlatform::SetRect(&m_MiddleMiddle, Width, Height, 2*Width, 2*Height); if(CBPlatform::IsRectEmpty(&m_MiddleRight)) CBPlatform::SetRect(&m_MiddleRight, 2*Width, Height, 3*Width, 2*Height); if(CBPlatform::IsRectEmpty(&m_DownLeft)) CBPlatform::SetRect(&m_DownLeft, 0, 2*Height, Width, 3*Height); if(CBPlatform::IsRectEmpty(&m_DownMiddle)) CBPlatform::SetRect(&m_DownMiddle, Width, 2*Height, 2*Width, 3*Height); if(CBPlatform::IsRectEmpty(&m_DownRight)) CBPlatform::SetRect(&m_DownRight, 2*Width, 2*Height, 3*Width, 3*Height); } return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CUITiledImage::SaveAsText(CBDynBuffer* Buffer, int Indent) { Buffer->PutTextIndent(Indent, "TILED_IMAGE\n"); Buffer->PutTextIndent(Indent, "{\n"); if(m_Image && m_Image->m_SurfaceFilename) Buffer->PutTextIndent(Indent+2, "IMAGE=\"%s\"\n", m_Image->m_SurfaceFilename); int H1, H2, H3; int V1, V2, V3; H1 = m_UpLeft.right; H2 = m_UpMiddle.right - m_UpMiddle.left; H3 = m_UpRight.right - m_UpRight.left; V1 = m_UpLeft.bottom; V2 = m_MiddleLeft.bottom - m_MiddleLeft.top; V3 = m_DownLeft.bottom - m_DownLeft.top; Buffer->PutTextIndent(Indent+2, "VERTICAL_TILES { %d, %d, %d }\n", V1, V2, V3); Buffer->PutTextIndent(Indent+2, "HORIZONTAL_TILES { %d, %d, %d }\n", H1, H2, H3); // editor properties CBBase::SaveAsText(Buffer, Indent+2); Buffer->PutTextIndent(Indent, "}\n"); return S_OK; } ////////////////////////////////////////////////////////////////////////// void CUITiledImage::CorrectSize(int* Width, int* Height) { int tile_width = m_MiddleMiddle.right - m_MiddleMiddle.left; int tile_height = m_MiddleMiddle.bottom - m_MiddleMiddle.top; int num_columns = (*Width - (m_MiddleLeft.right - m_MiddleLeft.left) - (m_MiddleRight.right - m_MiddleRight.left)) / tile_width; int num_rows = (*Height - (m_UpMiddle.bottom - m_UpMiddle.top) - (m_DownMiddle.bottom - m_DownMiddle.top)) / tile_height; *Width = (m_MiddleLeft.right - m_MiddleLeft.left) + (m_MiddleRight.right - m_MiddleRight.left) + num_columns*tile_width; *Height = (m_UpMiddle.bottom - m_UpMiddle.top) + (m_DownMiddle.bottom - m_DownMiddle.top) + num_rows*tile_height; } ////////////////////////////////////////////////////////////////////////// HRESULT CUITiledImage::Persist(CBPersistMgr* PersistMgr) { CBObject::Persist(PersistMgr); PersistMgr->Transfer(TMEMBER(m_DownLeft)); PersistMgr->Transfer(TMEMBER(m_DownMiddle)); PersistMgr->Transfer(TMEMBER(m_DownRight)); PersistMgr->Transfer(TMEMBER(m_Image)); PersistMgr->Transfer(TMEMBER(m_MiddleLeft)); PersistMgr->Transfer(TMEMBER(m_MiddleMiddle)); PersistMgr->Transfer(TMEMBER(m_MiddleRight)); PersistMgr->Transfer(TMEMBER(m_UpLeft)); PersistMgr->Transfer(TMEMBER(m_UpMiddle)); PersistMgr->Transfer(TMEMBER(m_UpRight)); return S_OK; }
mit
TillaTheHun0/ionic
angular/test/testapp/src/app/alert/alert-routing.module.ts
357
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AlertPageComponent } from './alert-page.component'; const routes: Routes = [ { path: '', component: AlertPageComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class AlertRoutingModule { }
mit
hagish/tektix
hektik/sperm/loveframes/objects/internal/modalbackground.lua
2453
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- modalbackground class local newobject = loveframes.NewObject("modalbackground", "loveframes_object_modalbackground", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(object) self.type = "modalbackground" self.width = love.graphics.getWidth() self.height = love.graphics.getHeight() self.x = 0 self.y = 0 self.internal = true self.parent = loveframes.base self.object = object table.insert(loveframes.base.children, self) if self.object.type ~= "frame" then self:Remove() end -- apply template properties to the object loveframes.templates.ApplyToObject(self) end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the element --]]--------------------------------------------------------- function newobject:update(dt) local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end local object = self.object local update = self.Update local base = loveframes.base local basechildren = base.children self:CheckHover() if #basechildren > 1 then if basechildren[#basechildren - 1] ~= self then self:Remove() table.insert(basechildren, self) end end if not object:IsActive() then self:Remove() loveframes.modalobject = false end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() if not self.visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawModalBackground or skins[defaultskin].DrawModalBackground local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end end
mit
4bic-attic/grano-ui
grano/ui/static/js/config.js
353
var config = { "APP_NAME": "{{app_name}}", "APP_VERSION": "{{app_version}}", "UI_ROOT": "{{ui_root}}", "STATIC_ROOT": "{{static_root}}", "API_ROOT": "{{api_root}}", "PLUGINS": {{plugins}}, "DATA_TYPES": {{data_types}}, "SCHEMA_OBJS": {{schema_objs}} }; angular.module('grano.config', []) .constant('config',config);
mit
intruder01/ALairWinforms
WinForms/PropertyEditing/EditorTemplates/ComboBoxEditorTemplate.cs
7849
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Drawing; using AdamsLair.WinForms.Drawing; using ButtonState = AdamsLair.WinForms.Drawing.ButtonState; namespace AdamsLair.WinForms.PropertyEditing.Templates { public class ComboBoxEditorTemplate : EditorTemplate, IPopupControlHost { private const string ClipboardDataFormat = "ComboBoxEditorTemplateData"; private object selectedObject = null; private string selectedObjStr = ""; private bool pressed = false; private DateTime mouseClosed = DateTime.MinValue; private int dropdownHeight = 100; private ComboBoxDropDown dropdown = null; private List<object> dropdownItems = new List<object>(); private PopupControl popupControl = new PopupControl(); public object SelectedObject { get { return this.selectedObject; } set { if (this.IsDropDownOpened) return; // Don't override while the user is selecting string lastObjStr = this.selectedObjStr; this.selectedObject = value; this.selectedObjStr = this.DefaultValueStringGenerator(this.selectedObject); if (this.dropdown != null) this.dropdown.SelectedItem = this.selectedObject; if (lastObjStr != this.selectedObjStr) this.EmitInvalidate(); } } public bool IsDropDownOpened { get { return this.dropdown != null; } } public object DropDownHoveredObject { get { if (this.dropdown.HoveredIndex == -1) return null; return this.dropdown.Items[this.dropdown.HoveredIndex]; } } public int DropDownHeight { get { return this.dropdownHeight; } set { this.dropdownHeight = value; } } public IEnumerable<object> DropDownItems { get { return this.dropdownItems; } set { this.dropdownItems = value.ToList(); if (this.dropdown != null) { this.dropdown.Items.Clear(); this.dropdown.Items.AddRange(this.dropdownItems.ToArray()); } } } public ComboBoxEditorTemplate(PropertyEditor parent) : base(parent) { this.popupControl.PopupControlHost = this; this.popupControl.Closed += this.popupControl_Closed; } public void OnPaint(PaintEventArgs e, bool enabled, bool multiple) { ButtonState comboState = ButtonState.Normal; if (!enabled || this.ReadOnly) comboState = ButtonState.Disabled; else if (this.pressed || this.IsDropDownOpened || (this.focused && (Control.ModifierKeys & Keys.Control) == Keys.Control)) comboState = ButtonState.Pressed; else if (this.hovered || this.focused) comboState = ButtonState.Hot; ControlRenderer.DrawComboBox(e.Graphics, this.rect, comboState, this.selectedObjStr); } public override void OnLostFocus(EventArgs e) { if (this.focused) this.EmitEditingFinished(this.selectedObject, FinishReason.LostFocus); base.OnLostFocus(e); } public override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (this.ReadOnly) this.hovered = false; } public void OnMouseDown(MouseEventArgs e) { if (this.rect.Contains(e.Location)) { if (this.hovered && (e.Button & MouseButtons.Left) != MouseButtons.None && (DateTime.Now - this.mouseClosed).TotalMilliseconds > 200) { this.pressed = true; this.EmitInvalidate(); } } } public void OnMouseUp(MouseEventArgs e) { if (this.pressed && (e.Button & MouseButtons.Left) != MouseButtons.None) { if (this.hovered) this.ShowDropDown(); this.pressed = false; this.EmitInvalidate(); } } public void OnKeyUp(KeyEventArgs e) { if (e.KeyCode == Keys.ControlKey) this.EmitInvalidate(); } public void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.ControlKey) this.EmitInvalidate(); if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Right) { this.ShowDropDown(); e.Handled = true; } else if (e.KeyCode == Keys.Down && e.Control) { this.ShowDropDown(); //int index = this.dropdownItems.IndexOf(this.selectedObject); //this.selectedObject = this.dropdownItems[(index + 1) % this.dropdownItems.Count]; //this.EmitEdited(); e.Handled = true; } else if (e.KeyCode == Keys.Up && e.Control) { this.ShowDropDown(); //int index = this.dropdownItems.IndexOf(this.selectedObject); //this.selectedObject = this.dropdownItems[(index + this.dropdownItems.Count - 1) % this.dropdownItems.Count]; //this.EmitEdited(); e.Handled = true; } else if (e.Control && e.KeyCode == Keys.C) { if (this.selectedObject != null) { DataObject data = new DataObject(); data.SetText(this.selectedObjStr); data.SetData(ClipboardDataFormat, this.selectedObject); Clipboard.SetDataObject(data); } else Clipboard.Clear(); e.Handled = true; } else if (e.Control && e.KeyCode == Keys.V) { bool success = false; if (Clipboard.ContainsData(ClipboardDataFormat) || Clipboard.ContainsText()) { object pasteObjProxy = null; if (Clipboard.ContainsData(ClipboardDataFormat)) { object pasteObj = Clipboard.GetData(ClipboardDataFormat); pasteObjProxy = this.dropdownItems.FirstOrDefault(obj => object.Equals(obj, pasteObj)); } else if (Clipboard.ContainsText()) { string pasteObj = Clipboard.GetText(); pasteObjProxy = this.dropdownItems.FirstOrDefault(obj => obj != null && obj.ToString() == pasteObj); } if (pasteObjProxy != null) { if (this.selectedObject != pasteObjProxy) { this.selectedObject = pasteObjProxy; this.selectedObjStr = this.DefaultValueStringGenerator(this.selectedObject); this.EmitInvalidate(); this.EmitEdited(this.selectedObject); } success = true; } } if (!success) System.Media.SystemSounds.Beep.Play(); e.Handled = true; } } public void ShowDropDown() { if (this.dropdown != null) return; if (this.ReadOnly) return; PropertyGrid parentGrid = this.Parent.ParentGrid; this.dropdown = new ComboBoxDropDown(this.dropdownItems); this.dropdown.SelectedItem = this.selectedObject; Size dropDownSize = new Size( this.rect.Width, Math.Min(this.dropdownHeight, this.dropdown.PreferredHeight)); Point dropDownLoc = new Point( this.rect.X + parentGrid.AutoScrollPosition.X, this.rect.Y + parentGrid.AutoScrollPosition.Y); dropDownLoc.Y += this.rect.Height + 1; this.dropdown.Location = dropDownLoc; this.dropdown.Size = dropDownSize; this.dropdown.AcceptSelection += this.dropdown_AcceptSelection; this.dropdown.RequestClose += this.dropdown_RequestClose; this.popupControl.Show(parentGrid, this.dropdown, dropDownLoc.X, dropDownLoc.Y, dropDownSize.Width, dropDownSize.Height, PopupResizeMode.None); this.EmitInvalidate(); } public void HideDropDown() { if (this.popupControl.Visible) this.popupControl.Hide(); if (this.dropdown != null) { if (!this.dropdown.Disposing && !this.dropdown.IsDisposed) this.dropdown.Dispose(); this.dropdown = null; } this.EmitInvalidate(); } private void dropdown_AcceptSelection(object sender, EventArgs e) { if (this.selectedObject != this.dropdown.SelectedItem) { this.selectedObject = this.dropdown.SelectedItem; this.selectedObjStr = this.DefaultValueStringGenerator(this.selectedObject); this.EmitInvalidate(); this.EmitEdited(this.selectedObject); } } private void dropdown_RequestClose(object sender, EventArgs e) { this.HideDropDown(); } private void popupControl_Closed(object sender, ToolStripDropDownClosedEventArgs e) { this.HideDropDown(); this.mouseClosed = DateTime.Now; } protected string DefaultValueStringGenerator(object obj) { return this.selectedObject != null ? this.selectedObject.ToString() : ""; } } }
mit
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/glanceclient/client.py
2361
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import warnings from glanceclient.common import utils def Client(version=None, endpoint=None, session=None, *args, **kwargs): """Client for the OpenStack Images API. Generic client for the OpenStack Images API. See version classes for specific details. :param string version: The version of API to use. :param session: A keystoneclient session that should be used for transport. :type session: keystoneclient.session.Session """ # FIXME(jamielennox): Add a deprecation warning if no session is passed. # Leaving it as an option until we can ensure nothing break when we switch. if session: if endpoint: kwargs.setdefault('endpoint_override', endpoint) if not version: __, version = utils.strip_version(endpoint) if not version: msg = ("You must provide a client version when using session") raise RuntimeError(msg) else: if version is not None: warnings.warn(("`version` keyword is being deprecated. Please pass" " the version as part of the URL. " "http://$HOST:$PORT/v$VERSION_NUMBER"), DeprecationWarning) endpoint, url_version = utils.strip_version(endpoint) version = version or url_version if not version: msg = ("Please provide either the version or an url with the form " "http://$HOST:$PORT/v$VERSION_NUMBER") raise RuntimeError(msg) module = utils.import_versioned_module(int(version), 'client') client_class = getattr(module, 'Client') return client_class(endpoint, *args, session=session, **kwargs)
mit
mrjive/hubzilla
Zotlabs/Module/Cards.php
5279
<?php namespace Zotlabs\Module; require_once('include/channel.php'); require_once('include/conversation.php'); require_once('include/acl_selectors.php'); class Cards extends \Zotlabs\Web\Controller { function init() { if(argc() > 1) $which = argv(1); else return; profile_load($which); } /** * {@inheritDoc} * @see \Zotlabs\Web\Controller::get() */ function get($update = 0, $load = false) { if(observer_prohibited(true)) { return login(); } if(! \App::$profile) { notice( t('Requested profile is not available.') . EOL ); \App::$error = 404; return; } if(! feature_enabled(\App::$profile_uid, 'cards')) { return; } nav_set_selected(t('Cards')); head_add_link([ 'rel' => 'alternate', 'type' => 'application/json+oembed', 'href' => z_root() . '/oep?f=&url=' . urlencode(z_root() . '/' . \App::$query_string), 'title' => 'oembed' ]); $category = (($_REQUEST['cat']) ? escape_tags(trim($_REQUEST['cat'])) : ''); if($category) { $sql_extra2 .= protect_sprintf(term_item_parent_query(\App::$profile['profile_uid'], 'item', $category, TERM_CATEGORY)); } $which = argv(1); $selected_card = ((argc() > 2) ? argv(2) : ''); $_SESSION['return_url'] = \App::$query_string; $uid = local_channel(); $owner = \App::$profile_uid; $observer = \App::get_observer(); $ob_hash = (($observer) ? $observer['xchan_hash'] : ''); if(! perm_is_allowed($owner, $ob_hash, 'view_pages')) { notice( t('Permission denied.') . EOL); return; } $is_owner = ($uid && $uid == $owner); $channel = channelx_by_n($owner); if($channel) { $channel_acl = [ 'allow_cid' => $channel['channel_allow_cid'], 'allow_gid' => $channel['channel_allow_gid'], 'deny_cid' => $channel['channel_deny_cid'], 'deny_gid' => $channel['channel_deny_gid'] ]; } else { $channel_acl = [ 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '' ]; } if(perm_is_allowed($owner, $ob_hash, 'write_pages')) { $x = [ 'webpage' => ITEM_TYPE_CARD, 'is_owner' => true, 'content_label' => t('Add Card'), 'button' => t('Create'), 'nickname' => $channel['channel_address'], 'lockstate' => (($channel['channel_allow_cid'] || $channel['channel_allow_gid'] || $channel['channel_deny_cid'] || $channel['channel_deny_gid']) ? 'lock' : 'unlock'), 'acl' => (($is_owner) ? populate_acl($channel_acl, false, \Zotlabs\Lib\PermissionDescription::fromGlobalPermission('view_pages')) : ''), 'permissions' => $channel_acl, 'showacl' => (($is_owner) ? true : false), 'visitor' => true, 'hide_location' => false, 'hide_voting' => false, 'profile_uid' => intval($owner), 'mimetype' => 'text/bbcode', 'mimeselect' => false, 'layoutselect' => false, 'expanded' => false, 'novoting' => false, 'catsenabled' => feature_enabled($owner, 'categories'), 'bbco_autocomplete' => 'bbcode', 'bbcode' => true ]; if($_REQUEST['title']) $x['title'] = $_REQUEST['title']; if($_REQUEST['body']) $x['body'] = $_REQUEST['body']; $editor = status_editor($a, $x); } else { $editor = ''; } $itemspage = get_pconfig(local_channel(),'system','itemspage'); \App::set_pager_itemspage(((intval($itemspage)) ? $itemspage : 20)); $pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval(\App::$pager['itemspage']), intval(\App::$pager['start'])); $sql_extra = item_permissions_sql($owner); $sql_item = ''; if($selected_card) { $r = q("select * from iconfig where iconfig.cat = 'system' and iconfig.k = 'CARD' and iconfig.v = '%s' limit 1", dbesc($selected_card) ); if($r) { $sql_item = "and item.id = " . intval($r[0]['iid']) . " "; } } $r = q("select * from item where uid = %d and item_type = %d $sql_extra $sql_item order by item.created desc $pager_sql", intval($owner), intval(ITEM_TYPE_CARD) ); $item_normal = " and item.item_hidden = 0 and item.item_type in (0,6) and item.item_deleted = 0 and item.item_unpublished = 0 and item.item_delayed = 0 and item.item_pending_remove = 0 and item.item_blocked = 0 "; $items_result = []; if($r) { $pager_total = count($r); $parents_str = ids_to_querystr($r, 'id'); $items = q("SELECT item.*, item.id AS item_id FROM item WHERE item.uid = %d $item_normal AND item.parent IN ( %s ) $sql_extra $sql_extra2 ", intval(\App::$profile['profile_uid']), dbesc($parents_str) ); if($items) { xchan_query($items); $items = fetch_post_tags($items, true); $items_result = conv_sort($items, 'updated'); } } $mode = 'cards'; if(get_pconfig(local_channel(),'system','articles_list_mode') && (! $selected_card)) $page_mode = 'pager_list'; else $page_mode = 'traditional'; $content = conversation($items_result, $mode, false, $page_mode); $o = replace_macros(get_markup_template('cards.tpl'), [ '$title' => t('Cards'), '$editor' => $editor, '$content' => $content, '$pager' => alt_pager($pager_total) ]); return $o; } }
mit
zweidner/hubzero-cms
core/components/com_newsletter/admin/controllers/newsletters.php
24422
<?php /** * @package hubzero-cms * @copyright Copyright 2005-2019 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ namespace Components\Newsletter\Admin\Controllers; use Components\Newsletter\Models\Newsletter; use Components\Newsletter\Models\Template; use Components\Newsletter\Models\MailingList; use Components\Newsletter\Models\Mailing; use Components\Newsletter\Models\Primary; use Components\Newsletter\Models\Secondary; use Components\Newsletter\Models\Mailing\Recipient; use Components\Members\Models\Member; use Hubzero\Component\AdminController; use Hubzero\Config\Registry; use stdClass; use Request; use Config; use Notify; use Route; use Lang; use User; use Date; use App; /** * Newsletters controller */ class Newsletters extends AdminController { /** * Execute a task * * @return void */ public function execute() { $this->registerTask('add', 'edit'); $this->registerTask('apply', 'save'); $this->registerTask('publish', 'state'); $this->registerTask('unpublish', 'state'); parent::execute(); } /** * Dependency check * * @return void */ private function dependencyCheck() { // Is the CRON component enabled? if (!\Component::isEnabled('com_cron')) { return false; } $database = App::get('db'); // Does the database table exist? if (!$database->tableExists('#__cron_jobs')) { return false; } $sql = "SELECT * FROM `#__cron_jobs` WHERE `plugin`=" . $database->quote('newsletter') . " AND `event`=" . $database->quote('processMailings'); $database->setQuery($sql); $sendMailingsCronJob = $database->loadObject(); // If we dont have an object create new cron job if (!is_object($sendMailingsCronJob)) { return false; } // Is the cron job turned off? if (is_object($sendMailingsCronJob) && $sendMailingsCronJob->state == 0) { return false; } return true; } /** * Display all newsletters task * * @return void */ public function displayTask() { // dependency check $dependency = $this->dependencyCheck(); // Filters $filters = array( 'search' => Request::getState( $this->_option . '.' . $this->_controller . '.search', 'search', '' ), 'published' => Request::getstate( $this->_option . '.' . $this->_controller . '.published', 'published', -1, 'int' ), 'type'=> Request::getstate( $this->_option . '.' . $this->controller . '.type', 'type', '' ), // Sorting 'sort' => Request::getstate( $this->_option . '.' . $this->_controller . '.sort', 'filter_order', 'name' ), 'sort_Dir' => Request::getstate( $this->_option . '.' . $this->_controller . '.sortdir', 'filter_order_Dir', 'ASC' ) ); $records = Newsletter::all() ->including(['template', function ($template){ $template->select('*'); }]) ->whereEquals('deleted', 0); if ($filters['search']) { $filters['search'] = strtolower((string)$filters['search']); $records->whereLike('name', $filters['search']); } if ($filters['published'] >= 0) { $records->whereEquals('published', $filters['published']); } if ($filters['type'] != '') { $records->whereEquals('type', $filters['type']); } $rows = $records ->order($filters['sort'], $filters['sort_Dir']) ->paginated('limitstart', 'limit') ->rows(); // Output the HTML $this->view ->setLayout('display') ->set('rows', $rows) ->set('filters', $filters) ->set('dependency', $dependency) ->display(); } /** * Edit newsletter task * * @param object $row * @return void */ public function editTask($row = null) { if (!User::authorise('core.edit', $this->_option) && !User::authorise('core.create', $this->_option)) { App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR')); } Request::setVar('hidemainmenu', 1); // Load object if (!is_object($row)) { // Incoming $id = Request::getArray('id', array(0)); $id = is_array($id) ? $id[0] : $id; $row = Newsletter::oneOrNew($id); } if ($row->isNew()) { // This is used to determine frequency // 0 - regular/disabled // 1 - daily // 2 - weekly // 3 - monthly $row->set('autogen', 0); } $templates = Template::all() ->ordered() ->rows(); // Output the HTML $this->view ->set('newsletter', $row) ->set('templates', $templates) ->set('config', $this->config) ->setLayout('edit') ->display(); } /** * Save campaign task * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); if (!User::authorise('core.edit', $this->_option) && !User::authorise('core.create', $this->_option)) { App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR')); } // Incoming data $fields = Request::getArray('newsletter', array(), 'post'); // Initiate model $row = Newsletter::oneOrNew($fields['id'])->set($fields); // did we have params $p = Request::getArray('params', array(), 'post'); if (!empty($p)) { // load previous params $params = new Registry($row->get('params')); // set from name if (isset($p['from_name'])) { $params->set('from_name', $p['from_name']); } // set from address if (isset($p['from_address'])) { $params->set('from_address', $p['from_address']); } // set reply-to name if (isset($p['replyto_name'])) { $params->set('replyto_name', $p['replyto_name']); } // set reply-to address if (isset($p['replyto_address'])) { $params->set('replyto_address', $p['replyto_address']); } //newsletter params to string $row->set('params', $params->toString()); } // Save campaign if (!$row->save()) { Notify::error($row->getError()); return $this->editTask($row); } // Set success message Notify::success(Lang::txt('COM_NEWSLETTER_SAVED_SUCCESS')); if ($this->getTask() == 'apply') { // If we just created campaign go back to edit form so we can add content return $this->editTask($row); } // Redirect back to campaigns list $this->cancelTask(); } /** * Duplicate newsletters * * @return void */ public function duplicateTask() { // Check for request forgeries Request::checkToken(['get', 'post']); if (!User::authorise('core.create', $this->_option)) { App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR')); } // Get the request vars $ids = Request::getArray('id', array()); // Make sure we have ids $success = 0; if (isset($ids) && count($ids) > 0) { // delete each newsletter foreach ($ids as $id) { // Instantiate newsletter object $newsletter = Newsletter::oneOrFail($id); if (!$newsletter->duplicate()) { Notify::error($newsletter->getError()); continue; } $success++; } } if ($success) { Notify::success(Lang::txt('COM_NEWSLETTER_DUPLICATED_SUCCESS')); } // Redirect back to campaigns list $this->cancelTask(); } /** * Delete Task * * @return void */ public function deleteTask() { // Check for request forgeries Request::checkToken(['get', 'post']); if (!User::authorise('core.delete', $this->_option)) { App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR')); } // Get the request vars $ids = Request::getArray('id', array()); // Make sure we have ids $success = 0; if (isset($ids) && count($ids) > 0) { foreach ($ids as $id) { // Instantiate newsletter object $newsletter = Newsletter::oneOrFail($id); // Mark as deleted $newsletter->set('deleted', 1); // Save changes if (!$newsletter->save()) { Notify::error(Lang::txt('COM_NEWSLETTER_DELETE_FAIL')); continue; } $success++; } } if ($success) { Notify::success(Lang::txt('COM_NEWSLETTER_DELETE_SUCCESS')); } // Redirect back to campaigns list $this->cancelTask(); } /** * Toggle published state for newsletter * * @return void */ public function stateTask() { // Check for request forgeries Request::checkToken(['get', 'post']); if (!User::authorise('core.edit.state', $this->_option)) { App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR')); } $publish = $this->getTask() == 'publish' ? Newsletter::STATE_PUBLISHED : Newsletter::STATE_UNPUBLISHED; // Get the request vars $ids = Request::getArray('id', array()); $ids = (!is_array($ids) ? array($ids) : $ids); // Make sure we have ids $success = 0; if (count($ids) > 0) { foreach ($ids as $id) { // Instantiate newsletter object $newsletter = Newsletter::oneOrFail($id); // Set state $newsletter->set('published', $publish); // Save changes if (!$newsletter->save()) { Notify::error(Lang::txt('COM_NEWSLETTER_STATE_CHANGE_FAIL')); continue; } $success++; } } if ($success) { // Set success message $msg = ($publish) ? Lang::txt('COM_NEWSLETTER_PUBLISHED_SUCCESS') : Lang::txt('COM_NEWSLETTER_UNPUBLISHED_SUCCESS'); Notify::success($msg); } // Redirect back to campaigns list $this->cancelTask(); } /** * Preview newsletter in lightbox * * @return void */ public function previewTask() { // Get the request vars $id = Request::getInt('id', 0); $no_html = Request::getInt('no_html', 0); // Get the newsletter $newsletter = Newsletter::oneOrFail($id); // Generate output if (!$no_html) { $content = '<h2 class="modal-title">' . Lang::txt('COM_NEWSLETTER_PREVIEW') . '</h2><br /><br />'; $content .= '<iframe width="100%" height="100%" src="' . Route::url('index.php?option=' . $this->_option. '&task=preview&id=' . $id . '&no_html=1') . '"></iframe>'; } else { $content = $newsletter->buildNewsletter($newsletter); } echo $content; } /** * Display send test newsletter form * * @return void */ public function sendTestTask() { // Get the request vars $ids = Request::getArray('id', array()); $id = (isset($ids[0])) ? $ids[0] : 0; // Make sure we have an id if (!$id) { Notify::warning(Lang::txt('COM_NEWSLETTER_SELECT_NEWSLETTER_FOR_MAILING')); return $this->cancelTask(); } // Get the newsletter $newsletter = Newsletter::oneOrFail($id); // Output the HTML $this->view ->setLayout('test') ->set('newsletter', $newsletter) ->display(); } /** * Send test newsletter * * @return void */ public function doSendTestTask() { //vars needed for test sending $goodEmails = array(); $badEmails = array(); // Get request vars $emails = Request::getString('emails', ''); $newsletterId = Request::getInt('nid', 0); // Parse emails $emails = array_filter(array_map("strtolower", array_map("trim", explode(",", $emails)))); // Make sure we have valid email addresses foreach ($emails as $k => $email) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { if (count($goodEmails) <= 4) { $goodEmails[] = $email; } else { $badEmails[] = $email; } } else { $badEmails[] = $email; } } // Instantiate newsletter campaign object & load campaign $newsletter = Newsletter::oneOrFail($newsletterId); // Build newsletter for sending $htmlContent = $newsletter->buildNewsletter($newsletter); $plainContent = $newsletter->buildNewsletterPlainTextPart($newsletter); // Send campaign $this->_send( $newsletter, $htmlContent, $plainContent, $goodEmails, $mailinglist = null, $sendingTest = true ); // Do we have good emails to tell user about if (count($goodEmails)) { Notify::success(Lang::txt('COM_NEWSLETTER_TEST_SEND_SUCCESS', $newsletter->name, implode('<br />', $goodEmails))); } // Do we have any bad emails to tell user about if (count($badEmails)) { Notify::error(Lang::txt('COM_NEWSLETTER_TEST_SEND_FAIL', $newsletter->name, implode('<br />', $badEmails))); } $this->cancelTask(); } /** * Display send newsletter form * * @return void */ public function sendNewsletterTask() { // get the request vars $ids = Request::getArray("id", array()); $id = (isset($ids[0])) ? $ids[0] : null; // make sure we have an id if (!$id) { Notify::error(Lang::txt('COM_NEWSLETTER_SELECT_NEWSLETTER_FOR_MAILING')); return $this->cancelTask(); } // get the newsletter $newsletter = Newsletter::oneOrFail($id); // get newsletter mailing lists $mailinglists = Mailinglist::all() ->whereEquals('deleted', 0) ->whereEquals('guest', 0) ->ordered() ->rows(); // get the mailings $mailings = Mailing::all() ->including(['recipients', function ($recipient){ $recipient ->select('id', null, true) ->whereEquals('status', 'queued'); }]) ->whereEquals('nid', $id) ->whereEquals('deleted', 0) ->rows(); // Output the HTML $this->view ->set('newsletter', $newsletter) ->set('mailinglists', $mailinglists) ->set('mailings', $mailings) ->setLayout('send') ->display(); } /** * Send Newsletter * * @return void */ public function doSendNewsletterTask() { //get request vars $newsletterId = Request::getInt('nid', 0); $mailinglistId = Request::getInt('mailinglist', -1); //instantiate newsletter campaign object & load campaign $newsletter = Newsletter::oneOrFail($newsletterId); //check to make sure we have an object if ($newsletter->name == '') { Notify::error(Lang::txt('COM_NEWSLETTER_UNABLE_TO_LOCATE')); return $this->cancelTask(); } // make sure it wasnt deleted if ($newsletter->deleted == 1) { Notify::error(Lang::txt('COM_NEWSLETTER_NEWSLETTER_SEND_DELETED')); return $this->cancelTask(); } if ($mailinglistId !== -1) { // get emails based on mailing list $mailinglist = Mailinglist::oneOrFail($mailinglistId); } // build newsletter for sending $htmlContent = $newsletter->buildNewsletter($newsletter); $plainContent = $newsletter->buildNewsletterPlainTextPart($newsletter); // send campaign // purposefully send no emails, will create later $mailing = $this->_send( $newsletter, $htmlContent, $plainContent, array(), $mailinglistId, $sendingTest = false ); // get count of emails if (isset($mailinglist)) { $count = $mailinglist ->emails() ->whereEquals('status', 'active') ->total(); $totalcount = $count; } else { $count = Member::all() ->whereEquals('sendEmail', 1) ->where('block', '!=', 1) ->where('approved', '!=', 0) ->where('activation', '>', 0) ->total(); $guestmailinglist = Mailinglist::all() ->whereEquals('guest', '1') ->row(); $count2 = $guestmailinglist ->emails() ->whereEquals('status', 'active') ->total(); $totalcount = $count + $count2; } // make sure we have emails if ($totalcount < 1) { Notify::error(Lang::txt('COM_NEWSLETTER_NEWSLETTER_SEND_MISSING_RECIPIENTS')); return $this->cancelTask(); } // add recipients at 10000 at a time // array of filters $filters = array( 'lid' => $mailinglistId, 'status' => 'active', 'limit' => 10000, 'start' => 0, 'select' => 'email' ); $left = $count; while ($left >= 0) { // get emails if (isset($mailinglist)) { $emails = $mailinglist->emails()->whereEquals('status', 'active'); } else { $emails = Member::all() ->select('email') ->whereEquals('sendEmail', 1) ->where('block', '!=', 1) ->where('activation', '>', 0) ->where('approved', '!=', 0); } $emails = $emails ->limit($filters['limit']) ->start($filters['start']) ->rows() ->toArray(); // add recipeients $this->_sendTo($mailing, $emails); // nullify vars $emails = null; unset($emails); //adjust our start $filters['start'] += $filters['limit']; // remove from what we have left to get $left -= $filters['limit']; } // handle guest users for the default list if (!isset($mailinglist)) { // array of filters $filters = array( 'lid' => $mailinglistId, 'status' => 'active', 'limit' => 10000, 'start' => 0, 'select' => 'email' ); $left = $count2; while ($left >= 0) { // get emails $emails = $guestmailinglist->emails()->whereEquals('status', 'active'); $emails = $emails ->limit($filters['limit']) ->start($filters['start']) ->rows() ->toArray(); // add recipeients $this->_sendTo($mailing, $emails); // nullify vars $emails = null; unset($emails); //adjust our start $filters['start'] += $filters['limit']; // remove from what we have left to get $left -= $filters['limit']; } } // Mark campaign as sent $newsletter->set('sent', 1); if (!$newsletter->save()) { Notify::error($newsletter->getError()); } else { Notify::success(Lang::txt('COM_NEWSLETTER_NEWSLETTER_SEND_TO', $newsletter->name, number_format($totalcount))); } $this->cancelTask(); } /** * Send Newsletter * * @param object $newsletter * @param string $newsletterHtmlContent * @param string $newsletterPlainContent * @param array $newsletterContacts * @param object $newsletterMailinglist * @param boolean $sendingTest * @return object */ private function _send($newsletter, $newsletterHtmlContent, $newsletterPlainContent, $newsletterContacts, $newsletterMailinglist, $sendingTest = false) { //set default mail from and reply-to names and addresses $defaultMailFromName = Config::get("sitename") . ' Newsletter'; $defaultMailFromAddress = 'contact@' . $_SERVER['HTTP_HOST']; $defaultMailReplytoName = Config::get("sitename") . ' Newsletter - Do Not Reply'; $defaultMailReplytoAddress = 'do-not-reply@' . $_SERVER['HTTP_HOST']; //get the config mail from and reply-to names and addresses $mailFromName = $this->config->get('newsletter_from_name', $defaultMailFromName); $mailFromAddress = $this->config->get('newsletter_from_address', $defaultMailFromAddress); $mailReplytoName = $this->config->get('newsletter_replyto_name', $defaultMailReplytoName); $mailReplytoAddress = $this->config->get('newsletter_replyto_address', $defaultMailReplytoAddress); //parse newsletter specific emails $params = new Registry($newsletter->get('params')); $mailFromName = $params->get('from_name', $mailFromName); $mailFromAddress = $params->get('from_address', $mailFromAddress); $mailReplytoName = $params->get('replyto_name', $mailReplytoName); $mailReplytoAddress = $params->get('replyto_address', $mailReplytoAddress); //set final mail from and reply-to $mailFrom = '"' . $mailFromName . '" <' . $mailFromAddress . '>'; $mailReplyTo = '"' . $mailReplytoName . '" <' . $mailReplytoAddress . '>'; //set subject and body $mailSubject = $newsletter->get('name', 'Your ' . Config::get("sitename") . '.org Newsletter'); $mailHtmlBody = $newsletterHtmlContent; $mailPlainBody = $newsletterPlainContent; //set mail headers //$mailHeaders = "MIME-Version: 1.0" . "\r\n"; //$mailHeaders .= "Content-type: text/html; charset=\"UTF-8\"" . "\r\n"; $mailHeaders = "From: {$mailFrom}" . "\r\n"; $mailHeaders .= "Reply-To: {$mailReplyTo}" . "\r\n"; //set mail priority $mailHeaders .= "X-Priority: 3" . "\r\n"; //$mailHeaders .= "X-MSMail-Priority: Normal" . "\r\n"; //$mailHeaders .= "Importance: Normal\n"; //set extra headers $mailHeaders .= "X-Mailer: PHP/" . phpversion() . "\r\n"; $mailHeaders .= "X-Component: " . $this->_option . "\r\n"; $mailHeaders .= "X-Component-Object: Campaign Mailing" . "\r\n"; $mailHeaders .= "X-Component-ObjectId: {{CAMPAIGN_MAILING_ID}}" . "\r\n"; //$mailHeaders .= "List-Unsubscribe: <mailto:{{UNSUBSCRIBE_MAILTO_LINK}}>, <{{UNSUBSCRIBE_LINK}}>"; //set mail args $mailArgs = ''; //$mailArgs = '-f hubmail-bounces@' . $_SERVER['HTTP_HOST']; //are we sending test mailing if ($sendingTest) { foreach ($newsletterContacts as $contact) { // get tracking & unsubscribe token $recipient = new stdClass; $recipient->email = $contact; $recipient->mailingid = ($newsletterMailinglist ? $newsletterMailinglist : -1); $emailToken = \Components\Newsletter\Helpers\Helper::generateMailingToken($recipient); // create unsubscribe link $unsubscribeMailtoLink = ''; $unsubscribeLink = 'https://' . $_SERVER['SERVER_NAME'] . '/newsletter/unsubscribe?e=' . urlencode($contact) . '&t=' . $emailToken; // add unsubscribe link - placeholder & in header (must do after adding tracking!!) $mailHtmlBody = str_replace("{{UNSUBSCRIBE_LINK}}", $unsubscribeLink, $mailHtmlBody); $mailPlainBody = str_replace("{{UNSUBSCRIBE_LINK}}", $unsubscribeLink, $mailPlainBody); // create new message $message = new \Hubzero\Mail\Message(); foreach (explode("\r\n", $mailHeaders) as $header) { $parts = array_map("trim", explode(':', $header)); switch ($parts[0]) { case 'From': if (preg_match("/\\\"([^\"]*)\\\"\\s<([^>]*)>/ux", $parts[1], $matches)) { $message->setFrom(array($matches[2] => $matches[1])); } break; case 'Reply-To': if (preg_match("/\\\"([^\"]*)\\\"\\s<([^>]*)>/ux", $parts[1], $matches)) { $message->setReplyTo(array($matches[2] => $matches[1])); } break; case 'Importance': case 'X-Priority': case 'X-MSMail-Priority': $priority = (isset($parts[1]) && in_array($parts[1], array(1,2,3,4,5))) ? $parts[1] : 3; $message->setPriority($priority); break; default: if (isset($parts[1])) { $message->addHeader($parts[0], $parts[1]); } } } // build message object and send $message->setSubject('[SENDING TEST] - '.$mailSubject) ->setTo($contact) ->addPart($mailHtmlBody, 'text/html') ->addPart($mailPlainBody, 'text/plain') ->send(); } return true; } // Get the scheduling $scheduler = Request::getInt('scheduler', 1); if ($scheduler == '1') { $scheduledDate = Date::toSql(); } else { $schedulerDate = Request::getString('scheduler_date', ''); $schedulerHour = Request::getString('scheduler_date_hour', '00'); $schedulerMinute = Request::getString('scheduler_date_minute', '00'); $schedulerMeridian = Request::getString('scheduler_date_meridian', 'AM'); // Make sure we have at least the date or we use now if (!$schedulerDate) { $scheduledDate = Date::toSql(); } // Break apart parts of date $schedulerDateParts = explode('/', $schedulerDate); // Make sure its in 24 time if ($schedulerMeridian == 'pm') { $schedulerHour += 12; } // Build scheduled time $scheduledTime = $schedulerDateParts[2] . '-' . $schedulerDateParts[0] . '-' . $schedulerDateParts[1]; $scheduledTime .= ' ' . $schedulerHour . ':' . $schedulerMinute . ':00'; $scheduledDate = Date::of(strtotime($scheduledTime))->toSql(); } // Create mailing object $mailing = Mailing::blank() ->set(array( 'nid' => $newsletter->id, 'lid' => $newsletterMailinglist, 'subject' => $mailSubject, 'html_body' => $mailHtmlBody, 'plain_body' => $mailPlainBody, 'headers' => $mailHeaders, 'args' => $mailArgs, 'tracking' => $newsletter->tracking, 'date' => $scheduledDate )); // Save mailing object if (!$mailing->save()) { Notify::error(Lang::txt('COM_NEWSLETTER_NEWSLETTER_SEND_FAIL')); return $this->sendNewsletterTask(); } // create recipients $this->_sendTo($mailing, $newsletterContacts); return $mailing; } /** * Create newsletter mailing recipients * * @param object $mailing * @param array $emails * @return void */ private function _sendTo($mailing, $emails) { // create date object once $date = Date::toSql(); // create new record for each email foreach ($emails as $email) { $insert = Recipient::blank() ->set(array( 'mid' => $mailing->id, 'email' => (is_array($email) ? $email['email'] : $email), 'status' => 'queued', 'date_added' => $date )); if (!$insert->save()) { Notify::error($insert->getError()); } } } }
mit
cosmy1/Urho3D
Source/Urho3D/Resource/ResourceCache.cpp
37720
// // Copyright (c) 2008-2018 the Urho3D project. // // 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. // #include "../Precompiled.h" #include "../Core/Context.h" #include "../Core/CoreEvents.h" #include "../Core/Profiler.h" #include "../Core/WorkQueue.h" #include "../IO/FileSystem.h" #include "../IO/FileWatcher.h" #include "../IO/Log.h" #include "../IO/PackageFile.h" #include "../Resource/BackgroundLoader.h" #include "../Resource/Image.h" #include "../Resource/JSONFile.h" #include "../Resource/PListFile.h" #include "../Resource/ResourceCache.h" #include "../Resource/ResourceEvents.h" #include "../Resource/XMLFile.h" #include "../DebugNew.h" #include <cstdio> namespace Urho3D { static const char* checkDirs[] = { "Fonts", "Materials", "Models", "Music", "Objects", "Particle", "PostProcess", "RenderPaths", "Scenes", "Scripts", "Sounds", "Shaders", "Techniques", "Textures", "UI", nullptr }; static const SharedPtr<Resource> noResource; ResourceCache::ResourceCache(Context* context) : Object(context), autoReloadResources_(false), returnFailedResources_(false), searchPackagesFirst_(true), isRouting_(false), finishBackgroundResourcesMs_(5) { // Register Resource library object factories RegisterResourceLibrary(context_); #ifdef URHO3D_THREADING // Create resource background loader. Its thread will start on the first background request backgroundLoader_ = new BackgroundLoader(this); #endif // Subscribe BeginFrame for handling directory watchers and background loaded resource finalization SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(ResourceCache, HandleBeginFrame)); } ResourceCache::~ResourceCache() { #ifdef URHO3D_THREADING // Shut down the background loader first backgroundLoader_.Reset(); #endif } bool ResourceCache::AddResourceDir(const String& pathName, unsigned priority) { MutexLock lock(resourceMutex_); auto* fileSystem = GetSubsystem<FileSystem>(); if (!fileSystem || !fileSystem->DirExists(pathName)) { URHO3D_LOGERROR("Could not open directory " + pathName); return false; } // Convert path to absolute String fixedPath = SanitateResourceDirName(pathName); // Check that the same path does not already exist for (unsigned i = 0; i < resourceDirs_.Size(); ++i) { if (!resourceDirs_[i].Compare(fixedPath, false)) return true; } if (priority < resourceDirs_.Size()) resourceDirs_.Insert(priority, fixedPath); else resourceDirs_.Push(fixedPath); // If resource auto-reloading active, create a file watcher for the directory if (autoReloadResources_) { SharedPtr<FileWatcher> watcher(new FileWatcher(context_)); watcher->StartWatching(fixedPath, true); fileWatchers_.Push(watcher); } URHO3D_LOGINFO("Added resource path " + fixedPath); return true; } bool ResourceCache::AddPackageFile(PackageFile* package, unsigned priority) { MutexLock lock(resourceMutex_); // Do not add packages that failed to load if (!package || !package->GetNumFiles()) { URHO3D_LOGERRORF("Could not add package file %s due to load failure", package->GetName().CString()); return false; } if (priority < packages_.Size()) packages_.Insert(priority, SharedPtr<PackageFile>(package)); else packages_.Push(SharedPtr<PackageFile>(package)); URHO3D_LOGINFO("Added resource package " + package->GetName()); return true; } bool ResourceCache::AddPackageFile(const String& fileName, unsigned priority) { SharedPtr<PackageFile> package(new PackageFile(context_)); return package->Open(fileName) && AddPackageFile(package, priority); } bool ResourceCache::AddManualResource(Resource* resource) { if (!resource) { URHO3D_LOGERROR("Null manual resource"); return false; } const String& name = resource->GetName(); if (name.Empty()) { URHO3D_LOGERROR("Manual resource with empty name, can not add"); return false; } resource->ResetUseTimer(); resourceGroups_[resource->GetType()].resources_[resource->GetNameHash()] = resource; UpdateResourceGroup(resource->GetType()); return true; } void ResourceCache::RemoveResourceDir(const String& pathName) { MutexLock lock(resourceMutex_); String fixedPath = SanitateResourceDirName(pathName); for (unsigned i = 0; i < resourceDirs_.Size(); ++i) { if (!resourceDirs_[i].Compare(fixedPath, false)) { resourceDirs_.Erase(i); // Remove the filewatcher with the matching path for (unsigned j = 0; j < fileWatchers_.Size(); ++j) { if (!fileWatchers_[j]->GetPath().Compare(fixedPath, false)) { fileWatchers_.Erase(j); break; } } URHO3D_LOGINFO("Removed resource path " + fixedPath); return; } } } void ResourceCache::RemovePackageFile(PackageFile* package, bool releaseResources, bool forceRelease) { MutexLock lock(resourceMutex_); for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i) { if (*i == package) { if (releaseResources) ReleasePackageResources(*i, forceRelease); URHO3D_LOGINFO("Removed resource package " + (*i)->GetName()); packages_.Erase(i); return; } } } void ResourceCache::RemovePackageFile(const String& fileName, bool releaseResources, bool forceRelease) { MutexLock lock(resourceMutex_); // Compare the name and extension only, not the path String fileNameNoPath = GetFileNameAndExtension(fileName); for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i) { if (!GetFileNameAndExtension((*i)->GetName()).Compare(fileNameNoPath, false)) { if (releaseResources) ReleasePackageResources(*i, forceRelease); URHO3D_LOGINFO("Removed resource package " + (*i)->GetName()); packages_.Erase(i); return; } } } void ResourceCache::ReleaseResource(StringHash type, const String& name, bool force) { StringHash nameHash(name); const SharedPtr<Resource>& existingRes = FindResource(type, nameHash); if (!existingRes) return; // If other references exist, do not release, unless forced if ((existingRes.Refs() == 1 && existingRes.WeakRefs() == 0) || force) { resourceGroups_[type].resources_.Erase(nameHash); UpdateResourceGroup(type); } } void ResourceCache::ReleaseResources(StringHash type, bool force) { bool released = false; HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type); if (i != resourceGroups_.End()) { for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin(); j != i->second_.resources_.End();) { HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++; // If other references exist, do not release, unless forced if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force) { i->second_.resources_.Erase(current); released = true; } } } if (released) UpdateResourceGroup(type); } void ResourceCache::ReleaseResources(StringHash type, const String& partialName, bool force) { bool released = false; HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type); if (i != resourceGroups_.End()) { for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin(); j != i->second_.resources_.End();) { HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++; if (current->second_->GetName().Contains(partialName)) { // If other references exist, do not release, unless forced if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force) { i->second_.resources_.Erase(current); released = true; } } } } if (released) UpdateResourceGroup(type); } void ResourceCache::ReleaseResources(const String& partialName, bool force) { // Some resources refer to others, like materials to textures. Repeat the release logic as many times as necessary to ensure // these get released. This is not necessary if forcing release bool released; do { released = false; for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i) { for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin(); j != i->second_.resources_.End();) { HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++; if (current->second_->GetName().Contains(partialName)) { // If other references exist, do not release, unless forced if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force) { i->second_.resources_.Erase(current); released = true; } } } if (released) UpdateResourceGroup(i->first_); } } while (released && !force); } void ResourceCache::ReleaseAllResources(bool force) { bool released; do { released = false; for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i) { for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin(); j != i->second_.resources_.End();) { HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++; // If other references exist, do not release, unless forced if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force) { i->second_.resources_.Erase(current); released = true; } } if (released) UpdateResourceGroup(i->first_); } } while (released && !force); } bool ResourceCache::ReloadResource(Resource* resource) { if (!resource) return false; resource->SendEvent(E_RELOADSTARTED); bool success = false; SharedPtr<File> file = GetFile(resource->GetName()); if (file) success = resource->Load(*(file.Get())); if (success) { resource->ResetUseTimer(); UpdateResourceGroup(resource->GetType()); resource->SendEvent(E_RELOADFINISHED); return true; } // If reloading failed, do not remove the resource from cache, to allow for a new live edit to // attempt loading again resource->SendEvent(E_RELOADFAILED); return false; } void ResourceCache::ReloadResourceWithDependencies(const String& fileName) { StringHash fileNameHash(fileName); // If the filename is a resource we keep track of, reload it const SharedPtr<Resource>& resource = FindResource(fileNameHash); if (resource) { URHO3D_LOGDEBUG("Reloading changed resource " + fileName); ReloadResource(resource); } // Always perform dependency resource check for resource loaded from XML file as it could be used in inheritance if (!resource || GetExtension(resource->GetName()) == ".xml") { // Check if this is a dependency resource, reload dependents HashMap<StringHash, HashSet<StringHash> >::ConstIterator j = dependentResources_.Find(fileNameHash); if (j != dependentResources_.End()) { // Reloading a resource may modify the dependency tracking structure. Therefore collect the // resources we need to reload first Vector<SharedPtr<Resource> > dependents; dependents.Reserve(j->second_.Size()); for (HashSet<StringHash>::ConstIterator k = j->second_.Begin(); k != j->second_.End(); ++k) { const SharedPtr<Resource>& dependent = FindResource(*k); if (dependent) dependents.Push(dependent); } for (unsigned k = 0; k < dependents.Size(); ++k) { URHO3D_LOGDEBUG("Reloading resource " + dependents[k]->GetName() + " depending on " + fileName); ReloadResource(dependents[k]); } } } } void ResourceCache::SetMemoryBudget(StringHash type, unsigned long long budget) { resourceGroups_[type].memoryBudget_ = budget; } void ResourceCache::SetAutoReloadResources(bool enable) { if (enable != autoReloadResources_) { if (enable) { for (unsigned i = 0; i < resourceDirs_.Size(); ++i) { SharedPtr<FileWatcher> watcher(new FileWatcher(context_)); watcher->StartWatching(resourceDirs_[i], true); fileWatchers_.Push(watcher); } } else fileWatchers_.Clear(); autoReloadResources_ = enable; } } void ResourceCache::AddResourceRouter(ResourceRouter* router, bool addAsFirst) { // Check for duplicate for (unsigned i = 0; i < resourceRouters_.Size(); ++i) { if (resourceRouters_[i] == router) return; } if (addAsFirst) resourceRouters_.Insert(0, SharedPtr<ResourceRouter>(router)); else resourceRouters_.Push(SharedPtr<ResourceRouter>(router)); } void ResourceCache::RemoveResourceRouter(ResourceRouter* router) { for (unsigned i = 0; i < resourceRouters_.Size(); ++i) { if (resourceRouters_[i] == router) { resourceRouters_.Erase(i); return; } } } SharedPtr<File> ResourceCache::GetFile(const String& name, bool sendEventOnFailure) { MutexLock lock(resourceMutex_); String sanitatedName = SanitateResourceName(name); if (!isRouting_) { isRouting_ = true; for (unsigned i = 0; i < resourceRouters_.Size(); ++i) resourceRouters_[i]->Route(sanitatedName, RESOURCE_GETFILE); isRouting_ = false; } if (sanitatedName.Length()) { File* file = nullptr; if (searchPackagesFirst_) { file = SearchPackages(sanitatedName); if (!file) file = SearchResourceDirs(sanitatedName); } else { file = SearchResourceDirs(sanitatedName); if (!file) file = SearchPackages(sanitatedName); } if (file) return SharedPtr<File>(file); } if (sendEventOnFailure) { if (resourceRouters_.Size() && sanitatedName.Empty() && !name.Empty()) URHO3D_LOGERROR("Resource request " + name + " was blocked"); else URHO3D_LOGERROR("Could not find resource " + sanitatedName); if (Thread::IsMainThread()) { using namespace ResourceNotFound; VariantMap& eventData = GetEventDataMap(); eventData[P_RESOURCENAME] = sanitatedName.Length() ? sanitatedName : name; SendEvent(E_RESOURCENOTFOUND, eventData); } } return SharedPtr<File>(); } Resource* ResourceCache::GetExistingResource(StringHash type, const String& name) { String sanitatedName = SanitateResourceName(name); if (!Thread::IsMainThread()) { URHO3D_LOGERROR("Attempted to get resource " + sanitatedName + " from outside the main thread"); return nullptr; } // If empty name, return null pointer immediately if (sanitatedName.Empty()) return nullptr; StringHash nameHash(sanitatedName); const SharedPtr<Resource>& existing = FindResource(type, nameHash); return existing; } Resource* ResourceCache::GetResource(StringHash type, const String& name, bool sendEventOnFailure) { String sanitatedName = SanitateResourceName(name); if (!Thread::IsMainThread()) { URHO3D_LOGERROR("Attempted to get resource " + sanitatedName + " from outside the main thread"); return nullptr; } // If empty name, return null pointer immediately if (sanitatedName.Empty()) return nullptr; StringHash nameHash(sanitatedName); #ifdef URHO3D_THREADING // Check if the resource is being background loaded but is now needed immediately backgroundLoader_->WaitForResource(type, nameHash); #endif const SharedPtr<Resource>& existing = FindResource(type, nameHash); if (existing) return existing; SharedPtr<Resource> resource; // Make sure the pointer is non-null and is a Resource subclass resource = DynamicCast<Resource>(context_->CreateObject(type)); if (!resource) { URHO3D_LOGERROR("Could not load unknown resource type " + String(type)); if (sendEventOnFailure) { using namespace UnknownResourceType; VariantMap& eventData = GetEventDataMap(); eventData[P_RESOURCETYPE] = type; SendEvent(E_UNKNOWNRESOURCETYPE, eventData); } return nullptr; } // Attempt to load the resource SharedPtr<File> file = GetFile(sanitatedName, sendEventOnFailure); if (!file) return nullptr; // Error is already logged URHO3D_LOGDEBUG("Loading resource " + sanitatedName); resource->SetName(sanitatedName); if (!resource->Load(*(file.Get()))) { // Error should already been logged by corresponding resource descendant class if (sendEventOnFailure) { using namespace LoadFailed; VariantMap& eventData = GetEventDataMap(); eventData[P_RESOURCENAME] = sanitatedName; SendEvent(E_LOADFAILED, eventData); } if (!returnFailedResources_) return nullptr; } // Store to cache resource->ResetUseTimer(); resourceGroups_[type].resources_[nameHash] = resource; UpdateResourceGroup(type); return resource; } bool ResourceCache::BackgroundLoadResource(StringHash type, const String& name, bool sendEventOnFailure, Resource* caller) { #ifdef URHO3D_THREADING // If empty name, fail immediately String sanitatedName = SanitateResourceName(name); if (sanitatedName.Empty()) return false; // First check if already exists as a loaded resource StringHash nameHash(sanitatedName); if (FindResource(type, nameHash) != noResource) return false; return backgroundLoader_->QueueResource(type, sanitatedName, sendEventOnFailure, caller); #else // When threading not supported, fall back to synchronous loading return GetResource(type, name, sendEventOnFailure); #endif } SharedPtr<Resource> ResourceCache::GetTempResource(StringHash type, const String& name, bool sendEventOnFailure) { String sanitatedName = SanitateResourceName(name); // If empty name, return null pointer immediately if (sanitatedName.Empty()) return SharedPtr<Resource>(); SharedPtr<Resource> resource; // Make sure the pointer is non-null and is a Resource subclass resource = DynamicCast<Resource>(context_->CreateObject(type)); if (!resource) { URHO3D_LOGERROR("Could not load unknown resource type " + String(type)); if (sendEventOnFailure) { using namespace UnknownResourceType; VariantMap& eventData = GetEventDataMap(); eventData[P_RESOURCETYPE] = type; SendEvent(E_UNKNOWNRESOURCETYPE, eventData); } return SharedPtr<Resource>(); } // Attempt to load the resource SharedPtr<File> file = GetFile(sanitatedName, sendEventOnFailure); if (!file) return SharedPtr<Resource>(); // Error is already logged URHO3D_LOGDEBUG("Loading temporary resource " + sanitatedName); resource->SetName(file->GetName()); if (!resource->Load(*(file.Get()))) { // Error should already been logged by corresponding resource descendant class if (sendEventOnFailure) { using namespace LoadFailed; VariantMap& eventData = GetEventDataMap(); eventData[P_RESOURCENAME] = sanitatedName; SendEvent(E_LOADFAILED, eventData); } return SharedPtr<Resource>(); } return resource; } unsigned ResourceCache::GetNumBackgroundLoadResources() const { #ifdef URHO3D_THREADING return backgroundLoader_->GetNumQueuedResources(); #else return 0; #endif } void ResourceCache::GetResources(PODVector<Resource*>& result, StringHash type) const { result.Clear(); HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type); if (i != resourceGroups_.End()) { for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = i->second_.resources_.Begin(); j != i->second_.resources_.End(); ++j) result.Push(j->second_); } } bool ResourceCache::Exists(const String& name) const { MutexLock lock(resourceMutex_); String sanitatedName = SanitateResourceName(name); if (!isRouting_) { isRouting_ = true; for (unsigned i = 0; i < resourceRouters_.Size(); ++i) resourceRouters_[i]->Route(sanitatedName, RESOURCE_CHECKEXISTS); isRouting_ = false; } if (sanitatedName.Empty()) return false; for (unsigned i = 0; i < packages_.Size(); ++i) { if (packages_[i]->Exists(sanitatedName)) return true; } auto* fileSystem = GetSubsystem<FileSystem>(); for (unsigned i = 0; i < resourceDirs_.Size(); ++i) { if (fileSystem->FileExists(resourceDirs_[i] + sanitatedName)) return true; } // Fallback using absolute path return fileSystem->FileExists(sanitatedName); } unsigned long long ResourceCache::GetMemoryBudget(StringHash type) const { HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type); return i != resourceGroups_.End() ? i->second_.memoryBudget_ : 0; } unsigned long long ResourceCache::GetMemoryUse(StringHash type) const { HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type); return i != resourceGroups_.End() ? i->second_.memoryUse_ : 0; } unsigned long long ResourceCache::GetTotalMemoryUse() const { unsigned long long total = 0; for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i) total += i->second_.memoryUse_; return total; } String ResourceCache::GetResourceFileName(const String& name) const { auto* fileSystem = GetSubsystem<FileSystem>(); for (unsigned i = 0; i < resourceDirs_.Size(); ++i) { if (fileSystem->FileExists(resourceDirs_[i] + name)) return resourceDirs_[i] + name; } if (IsAbsolutePath(name) && fileSystem->FileExists(name)) return name; else return String(); } ResourceRouter* ResourceCache::GetResourceRouter(unsigned index) const { return index < resourceRouters_.Size() ? resourceRouters_[index] : nullptr; } String ResourceCache::GetPreferredResourceDir(const String& path) const { String fixedPath = AddTrailingSlash(path); bool pathHasKnownDirs = false; bool parentHasKnownDirs = false; auto* fileSystem = GetSubsystem<FileSystem>(); for (unsigned i = 0; checkDirs[i] != nullptr; ++i) { if (fileSystem->DirExists(fixedPath + checkDirs[i])) { pathHasKnownDirs = true; break; } } if (!pathHasKnownDirs) { String parentPath = GetParentPath(fixedPath); for (unsigned i = 0; checkDirs[i] != nullptr; ++i) { if (fileSystem->DirExists(parentPath + checkDirs[i])) { parentHasKnownDirs = true; break; } } // If path does not have known subdirectories, but the parent path has, use the parent instead if (parentHasKnownDirs) fixedPath = parentPath; } return fixedPath; } String ResourceCache::SanitateResourceName(const String& name) const { // Sanitate unsupported constructs from the resource name String sanitatedName = GetInternalPath(name); sanitatedName.Replace("../", ""); sanitatedName.Replace("./", ""); // If the path refers to one of the resource directories, normalize the resource name auto* fileSystem = GetSubsystem<FileSystem>(); if (resourceDirs_.Size()) { String namePath = GetPath(sanitatedName); String exePath = fileSystem->GetProgramDir().Replaced("/./", "/"); for (unsigned i = 0; i < resourceDirs_.Size(); ++i) { String relativeResourcePath = resourceDirs_[i]; if (relativeResourcePath.StartsWith(exePath)) relativeResourcePath = relativeResourcePath.Substring(exePath.Length()); if (namePath.StartsWith(resourceDirs_[i], false)) namePath = namePath.Substring(resourceDirs_[i].Length()); else if (namePath.StartsWith(relativeResourcePath, false)) namePath = namePath.Substring(relativeResourcePath.Length()); } sanitatedName = namePath + GetFileNameAndExtension(sanitatedName); } return sanitatedName.Trimmed(); } String ResourceCache::SanitateResourceDirName(const String& name) const { String fixedPath = AddTrailingSlash(name); if (!IsAbsolutePath(fixedPath)) fixedPath = GetSubsystem<FileSystem>()->GetCurrentDir() + fixedPath; // Sanitate away /./ construct fixedPath.Replace("/./", "/"); return fixedPath.Trimmed(); } void ResourceCache::StoreResourceDependency(Resource* resource, const String& dependency) { if (!resource) return; MutexLock lock(resourceMutex_); StringHash nameHash(resource->GetName()); HashSet<StringHash>& dependents = dependentResources_[dependency]; dependents.Insert(nameHash); } void ResourceCache::ResetDependencies(Resource* resource) { if (!resource) return; MutexLock lock(resourceMutex_); StringHash nameHash(resource->GetName()); for (HashMap<StringHash, HashSet<StringHash> >::Iterator i = dependentResources_.Begin(); i != dependentResources_.End();) { HashSet<StringHash>& dependents = i->second_; dependents.Erase(nameHash); if (dependents.Empty()) i = dependentResources_.Erase(i); else ++i; } } String ResourceCache::PrintMemoryUsage() const { String output = "Resource Type Cnt Avg Max Budget Total\n\n"; char outputLine[256]; unsigned totalResourceCt = 0; unsigned long long totalLargest = 0; unsigned long long totalAverage = 0; unsigned long long totalUse = GetTotalMemoryUse(); for (HashMap<StringHash, ResourceGroup>::ConstIterator cit = resourceGroups_.Begin(); cit != resourceGroups_.End(); ++cit) { const unsigned resourceCt = cit->second_.resources_.Size(); unsigned long long average = 0; if (resourceCt > 0) average = cit->second_.memoryUse_ / resourceCt; else average = 0; unsigned long long largest = 0; for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator resIt = cit->second_.resources_.Begin(); resIt != cit->second_.resources_.End(); ++resIt) { if (resIt->second_->GetMemoryUse() > largest) largest = resIt->second_->GetMemoryUse(); if (largest > totalLargest) totalLargest = largest; } totalResourceCt += resourceCt; const String countString(cit->second_.resources_.Size()); const String memUseString = GetFileSizeString(average); const String memMaxString = GetFileSizeString(largest); const String memBudgetString = GetFileSizeString(cit->second_.memoryBudget_); const String memTotalString = GetFileSizeString(cit->second_.memoryUse_); const String resTypeName = context_->GetTypeName(cit->first_); memset(outputLine, ' ', 256); outputLine[255] = 0; sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", resTypeName.CString(), countString.CString(), memUseString.CString(), memMaxString.CString(), memBudgetString.CString(), memTotalString.CString()); output += ((const char*)outputLine); } if (totalResourceCt > 0) totalAverage = totalUse / totalResourceCt; const String countString(totalResourceCt); const String memUseString = GetFileSizeString(totalAverage); const String memMaxString = GetFileSizeString(totalLargest); const String memTotalString = GetFileSizeString(totalUse); memset(outputLine, ' ', 256); outputLine[255] = 0; sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", "All", countString.CString(), memUseString.CString(), memMaxString.CString(), "-", memTotalString.CString()); output += ((const char*)outputLine); return output; } const SharedPtr<Resource>& ResourceCache::FindResource(StringHash type, StringHash nameHash) { MutexLock lock(resourceMutex_); HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type); if (i == resourceGroups_.End()) return noResource; HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash); if (j == i->second_.resources_.End()) return noResource; return j->second_; } const SharedPtr<Resource>& ResourceCache::FindResource(StringHash nameHash) { MutexLock lock(resourceMutex_); for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i) { HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash); if (j != i->second_.resources_.End()) return j->second_; } return noResource; } void ResourceCache::ReleasePackageResources(PackageFile* package, bool force) { HashSet<StringHash> affectedGroups; const HashMap<String, PackageEntry>& entries = package->GetEntries(); for (HashMap<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i) { StringHash nameHash(i->first_); // We do not know the actual resource type, so search all type containers for (HashMap<StringHash, ResourceGroup>::Iterator j = resourceGroups_.Begin(); j != resourceGroups_.End(); ++j) { HashMap<StringHash, SharedPtr<Resource> >::Iterator k = j->second_.resources_.Find(nameHash); if (k != j->second_.resources_.End()) { // If other references exist, do not release, unless forced if ((k->second_.Refs() == 1 && k->second_.WeakRefs() == 0) || force) { j->second_.resources_.Erase(k); affectedGroups.Insert(j->first_); } break; } } } for (HashSet<StringHash>::Iterator i = affectedGroups.Begin(); i != affectedGroups.End(); ++i) UpdateResourceGroup(*i); } void ResourceCache::UpdateResourceGroup(StringHash type) { HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type); if (i == resourceGroups_.End()) return; for (;;) { unsigned totalSize = 0; unsigned oldestTimer = 0; HashMap<StringHash, SharedPtr<Resource> >::Iterator oldestResource = i->second_.resources_.End(); for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin(); j != i->second_.resources_.End(); ++j) { totalSize += j->second_->GetMemoryUse(); unsigned useTimer = j->second_->GetUseTimer(); if (useTimer > oldestTimer) { oldestTimer = useTimer; oldestResource = j; } } i->second_.memoryUse_ = totalSize; // If memory budget defined and is exceeded, remove the oldest resource and loop again // (resources in use always return a zero timer and can not be removed) if (i->second_.memoryBudget_ && i->second_.memoryUse_ > i->second_.memoryBudget_ && oldestResource != i->second_.resources_.End()) { URHO3D_LOGDEBUG("Resource group " + oldestResource->second_->GetTypeName() + " over memory budget, releasing resource " + oldestResource->second_->GetName()); i->second_.resources_.Erase(oldestResource); } else break; } } void ResourceCache::HandleBeginFrame(StringHash eventType, VariantMap& eventData) { for (unsigned i = 0; i < fileWatchers_.Size(); ++i) { String fileName; while (fileWatchers_[i]->GetNextChange(fileName)) { ReloadResourceWithDependencies(fileName); // Finally send a general file changed event even if the file was not a tracked resource using namespace FileChanged; VariantMap& eventData = GetEventDataMap(); eventData[P_FILENAME] = fileWatchers_[i]->GetPath() + fileName; eventData[P_RESOURCENAME] = fileName; SendEvent(E_FILECHANGED, eventData); } } // Check for background loaded resources that can be finished #ifdef URHO3D_THREADING { URHO3D_PROFILE(FinishBackgroundResources); backgroundLoader_->FinishResources(finishBackgroundResourcesMs_); } #endif } File* ResourceCache::SearchResourceDirs(const String& name) { auto* fileSystem = GetSubsystem<FileSystem>(); for (unsigned i = 0; i < resourceDirs_.Size(); ++i) { if (fileSystem->FileExists(resourceDirs_[i] + name)) { // Construct the file first with full path, then rename it to not contain the resource path, // so that the file's sanitatedName can be used in further GetFile() calls (for example over the network) File* file(new File(context_, resourceDirs_[i] + name)); file->SetName(name); return file; } } // Fallback using absolute path if (fileSystem->FileExists(name)) return new File(context_, name); return nullptr; } File* ResourceCache::SearchPackages(const String& name) { for (unsigned i = 0; i < packages_.Size(); ++i) { if (packages_[i]->Exists(name)) return new File(context_, packages_[i], name); } return nullptr; } void RegisterResourceLibrary(Context* context) { Image::RegisterObject(context); JSONFile::RegisterObject(context); PListFile::RegisterObject(context); XMLFile::RegisterObject(context); } }
mit
zamabraga/effort
Main/Source/Effort.Test/Internal/ResultSets/IResultSet.cs
1669
// -------------------------------------------------------------------------------------------- // <copyright file="IResultSet.cs" company="Effort Team"> // Copyright (C) 2011-2014 Effort Team // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // </copyright> // -------------------------------------------------------------------------------------------- namespace Effort.Test.Internal.ResultSets { using System.Collections.Generic; internal interface IResultSet { IEnumerable<IResultSetElement> Elements { get; } } }
mit
COLABORATI/centrifugo
libcentrifugo/engine.go
1151
package libcentrifugo // Engine is an interface with all methods that can be used by client or // application to publish message, handle subscriptions, save or retrieve // presence and history data type Engine interface { // getName returns a name of concrete engine implementation name() string // publish allows to send message into channel publish(chID ChannelID, message []byte) error // subscribe on channel subscribe(chID ChannelID) error // unsubscribe from channel unsubscribe(chID ChannelID) error // addPresence sets or updates presence info for connection with uid addPresence(chID ChannelID, uid ConnID, info ClientInfo) error // removePresence removes presence information for connection with uid removePresence(chID ChannelID, uid ConnID) error // getPresence returns actual presence information for channel presence(chID ChannelID) (map[ConnID]ClientInfo, error) // addHistory adds message into channel history and takes care about history size addHistory(chID ChannelID, message Message, size, lifetime int64) error // getHistory returns history messages for channel history(chID ChannelID) ([]Message, error) }
mit
TSavo/XChange
xchange-dsx/src/test/java/org/knowm/xchange/dsx/ExchangeUtils.java
1720
package org.knowm.xchange.dsx; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.ExchangeSpecification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** @author Mikhail Wall */ public class ExchangeUtils { private static final Logger logger = LoggerFactory.getLogger(ExchangeUtils.class); public static Exchange createExchangeFromJsonConfiguration( Class<? extends Exchange> exchangeClass) throws IOException { ExchangeSpecification exSpec = new ExchangeSpecification(exchangeClass); ObjectMapper mapper = new ObjectMapper(); InputStream is = ExchangeUtils.class.getClassLoader().getResourceAsStream("exchangeConfiguration.json"); if (is == null) { logger.warn("No exchangeConfiguration.json file found. Returning null exchange."); return null; } try { ExchangeConfiguration conf = mapper.readValue(is, ExchangeConfiguration.class); logger.debug(conf.toString()); if (conf.apiKey != null) { exSpec.setApiKey(conf.apiKey); } if (conf.secretKey != null) { exSpec.setSecretKey(conf.secretKey); } if (conf.sslUri != null) { exSpec.setSslUri(conf.sslUri); } } catch (Exception e) { logger.warn( "An exception occured while loading the exchangeConfiguration.json file from the classpath. " + "Returning null exchange. ", e); return null; } Exchange exchange = ExchangeFactory.INSTANCE.createExchange(exSpec); exchange.remoteInit(); return exchange; } }
mit
alvachien/aclearning
languages_and_platforms/java/thinkinjava/00_lib/enumerated/Input.java
763
//: enumerated/Input.java package enumerated; import java.util.*; public enum Input { NICKEL(5), DIME(10), QUARTER(25), DOLLAR(100), TOOTHPASTE(200), CHIPS(75), SODA(100), SOAP(50), ABORT_TRANSACTION { public int amount() { // Disallow throw new RuntimeException("ABORT.amount()"); } }, STOP { // This must be the last instance. public int amount() { // Disallow throw new RuntimeException("SHUT_DOWN.amount()"); } }; int value; // In cents Input(int value) { this.value = value; } Input() {} int amount() { return value; }; // In cents static Random rand = new Random(47); public static Input randomSelection() { // Don't include STOP: return values()[rand.nextInt(values().length - 1)]; } } ///:~
mit
allbegray/slack-api
src/main/java/allbegray/slack/type/Authentication.java
1033
package allbegray.slack.type; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Authentication { protected String url; protected String team; protected String user; protected String team_id; protected String user_id; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getTeam_id() { return team_id; } public void setTeam_id(String team_id) { this.team_id = team_id; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } @Override public String toString() { return "Authentication [url=" + url + ", team=" + team + ", user=" + user + ", team_id=" + team_id + ", user_id=" + user_id + "]"; } }
mit
roryaronson/OpenFarm
app/models/stage.rb
505
class Stage include Mongoid::Document embeds_many :pictures, cascade_callbacks: true, as: :photographic embeds_one :time_span, cascade_callbacks: true, as: :timed belongs_to :guide field :name, type: String field :stage_length, type: Integer # Length in days field :environment, type: Array field :soil, type: Array field :light, type: Array field :order, type: Integer # Inherited from the stage_option embeds_many :stage_actions accepts_nested_attributes_for :pictures end
mit