prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>jinja_helpers.py<|end_file_name|><|fim▁begin|>import collections import json as jsonlib import os import random import re from operator import attrgetter from urlparse import urljoin from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.forms import CheckboxInput from django.template import defaultfilters, loader from django.utils.encoding import smart_text from django.utils.functional import lazy from django.utils.html import format_html as django_format_html from django.utils.safestring import mark_safe from django.utils.translation import ( get_language, to_locale, trim_whitespace, ugettext) import jinja2 import waffle from babel.support import Format from django_jinja import library from rest_framework.reverse import reverse as drf_reverse from rest_framework.settings import api_settings from olympia import amo from olympia.amo import urlresolvers, utils from olympia.constants.licenses import PERSONA_LICENSES_IDS from olympia.lib.jingo_minify_helpers import ( _build_html, _get_compiled_css_url, get_css_urls, get_js_urls, get_path, is_external) from olympia.lib.cache import cache_get_or_set, make_key # Registering some utils as filters: urlparams = library.filter(utils.urlparams) library.filter(utils.epoch) library.filter(utils.isotime) library.global_function(dict) library.global_function(utils.randslice) # Mark a lazy marked instance as safe but keep # it lazy mark_safe_lazy = lazy(mark_safe, unicode) @library.global_function def switch_is_active(switch_name): return waffle.switch_is_active(switch_name) @library.filter def link(item): html = """<a href="%s">%s</a>""" % (item.get_url_path(), jinja2.escape(item.name)) return jinja2.Markup(html) @library.filter def xssafe(value): """ Like |safe but for strings with interpolation. By using |xssafe you assert that you have written tests proving an XSS can't happen here. """ return jinja2.Markup(value) @library.global_function def locale_url(url): """Take a URL and give it the locale prefix.""" prefixer = urlresolvers.get_url_prefix() script = prefixer.request.META['SCRIPT_NAME'] parts = [script, prefixer.locale, url.lstrip('/')] return '/'.join(parts) @library.global_function def url(viewname, *args, **kwargs): """Helper for Django's ``reverse`` in templates.""" add_prefix = kwargs.pop('add_prefix', True) host = kwargs.pop('host', '') src = kwargs.pop('src', '') url = '%s%s' % (host, urlresolvers.reverse(viewname, args=args, kwargs=kwargs, add_prefix=add_prefix)) if src: url = urlparams(url, src=src) return url @library.global_function @jinja2.contextfunction def drf_url(context, viewname, *args, **kwargs): """Helper for DjangoRestFramework's ``reverse`` in templates.""" request = context.get('request') if request: if not hasattr(request, 'versioning_scheme'): request.versioning_scheme = api_settings.DEFAULT_VERSIONING_CLASS() request.version = request.versioning_scheme.determine_version( request, *args, **kwargs) return drf_reverse(viewname, request=request, args=args, kwargs=kwargs) @library.global_function def services_url(viewname, *args, **kwargs): """Helper for ``url`` with host=SERVICES_URL.""" kwargs.update({'host': settings.SERVICES_URL}) return url(viewname, *args, **kwargs) @library.filter def paginator(pager): return PaginationRenderer(pager).render() @library.filter def impala_paginator(pager): t = loader.get_template('amo/impala/paginator.html') return jinja2.Markup(t.render({'pager': pager})) @library.global_function def sidebar(app): """Populates the sidebar with (categories, types).""" from olympia.addons.models import Category if app is None: return [], [] # Fetch categories... qs = Category.objects.filter(application=app.id, weight__gte=0, type=amo.ADDON_EXTENSION) # Now sort them in python according to their name property (which looks up # the translated name using gettext + our constants) categories = sorted(qs, key=attrgetter('weight', 'name')) Type = collections.namedtuple('Type', 'id name url') base = urlresolvers.reverse('home') types = [Type(99, ugettext('Collections'), base + 'collections/')] shown_types = { amo.ADDON_PERSONA: urlresolvers.reverse('browse.personas'), amo.ADDON_DICT: urlresolvers.reverse('browse.language-tools'), amo.ADDON_SEARCH: urlresolvers.reverse('browse.search-tools'), amo.ADDON_THEME: urlresolvers.reverse('browse.themes'), } titles = dict( amo.ADDON_TYPES, **{amo.ADDON_DICT: ugettext('Dictionaries & Language Packs')}) for type_, url in shown_types.items(): if type_ in app.types: types.append(Type(type_, titles[type_], url)) return categories, sorted(types, key=lambda x: x.name) class PaginationRenderer(object): def __init__(self, pager): self.pager = pager self.max = 10 self.span = (self.max - 1) / 2 self.page = pager.number self.num_pages = pager.paginator.num_pages self.count = pager.paginator.count pager.page_range = self.range() pager.dotted_upper = self.num_pages not in pager.page_range pager.dotted_lower = 1 not in pager.page_range def range(self): """Return a list of page numbers to show in the paginator.""" page, total, span = self.page, self.num_pages, self.span if total < self.max: lower, upper = 0, total elif page < span + 1: lower, upper = 0, span * 2 elif page > total - span: lower, upper = total - span * 2, total else: lower, upper = page - span, page + span - 1 return range(max(lower + 1, 1), min(total, upper) + 1) def render(self): c = {'pager': self.pager, 'num_pages': self.num_pages, 'count': self.count} t = loader.get_template('amo/paginator.html').render(c) return jinja2.Markup(t) def _get_format(): lang = get_language() return Format(utils.get_locale_from_lang(lang)) @library.filter def numberfmt(num, format=None): return _get_format().decimal(num, format) def page_name(app=None): """Determine the correct page name for the given app (or no app).""" if app: return ugettext(u'Add-ons for {0}').format(app.pretty) else: return ugettext('Add-ons') @library.global_function @jinja2.contextfunction def page_title(context, title): title = smart_text(title) base_title = page_name(context['request'].APP) # The following line doesn't use string formatting because we want to # preserve the type of `title` in case it's a jinja2 `Markup` (safe, # escaped) object. return django_format_html(u'{} :: {}', title, base_title) @library.filter def json(s): return jsonlib.dumps(s) @library.filter def absolutify(url, site=None): """Takes a URL and prepends the SITE_URL""" if url.startswith('http'): return url else: return urljoin(site or settings.SITE_URL, url) @library.filter def strip_controls(s): """ Strips control characters from a string. """ # Translation table of control characters. control_trans = dict((n, None) for n in xrange(32) if n not in [10, 13]) rv = unicode(s).translate(control_trans) return jinja2.Markup(rv) if isinstance(s, jinja2.Markup) else rv @library.filter def external_url(url): """Bounce a URL off outgoing.prod.mozaws.net.""" return urlresolvers.get_outgoing_url(unicode(url)) @library.filter def shuffle(sequence): """Shuffle a sequence.""" random.shuffle(sequence) return sequence @library.global_function def license_link(license): """Link to a code license, including icon where applicable.""" # If passed in an integer, try to look up the License. from olympia.versions.models import License if isinstance(license, (long, int)): if license in PERSONA_LICENSES_IDS: # Grab built-in license. license = PERSONA_LICENSES_IDS[license] else: # Grab custom license. license = License.objects.filter(id=license) if not license.exists(): return '' license = license[0] elif not license: return '' if not getattr(license, 'builtin', True): return ugettext('Custom License') template = loader.get_template('amo/license_link.html') return jinja2.Markup(template.render({'license': license})) @library.global_function def field(field, label=None, **attrs): if label is not None: field.label = label # HTML from Django is already escaped. return jinja2.Markup(u'%s<p>%s%s</p>' % (field.errors, field.label_tag(), field.as_widget(attrs=attrs))) @library.global_function @library.render_with('amo/category-arrow.html') @jinja2.contextfunction def category_arrow(context, key, prefix): d = dict(context.items()) d.update(key=key, prefix=prefix) return d @library.filter def timesince(time): if not time: return u'' ago = defaultfilters.timesince(time) # L10n: relative time in the past, like '4 days ago' return ugettext(u'{0} ago').format(ago) @library.global_function @library.render_with('amo/recaptcha.html') @jinja2.contextfunction def recaptcha(context, form): d = dict(context.items()) d.update(form=form) return d @library.filter def is_choice_field(value): try: return isinstance(value.field.widget, CheckboxInput) except AttributeError: pass @library.global_function @jinja2.contextfunction def cache_buster(context, url): if 'BUILD_ID' in context: build = context['BUILD_ID'] else: if url.endswith('.js'): build = context['BUILD_ID_JS'] elif url.endswith('.css'): build = context['BUILD_ID_CSS'] else: build = context['BUILD_ID_IMG'] return utils.urlparams(url, b=build) @library.global_function @jinja2.contextfunction def media(context, url): """Get a MEDIA_URL link with a cache buster querystring.""" return urljoin(settings.MEDIA_URL, cache_buster(context, url)) @library.global_function @jinja2.contextfunction def static(context, url): """Get a STATIC_URL link with a cache buster querystring.""" return urljoin(settings.STATIC_URL, cache_buster(context, url)) @library.global_function @jinja2.evalcontextfunction def attrs(ctx, *args, **kw): return jinja2.filters.do_xmlattr(ctx, dict(*args, **kw)) @library.global_function @jinja2.contextfunction def side_nav(context, addon_type, category=None): app = context['request'].APP.id cat = str(category.id) if category else 'all' cache_key = make_key( 'side-nav-%s-%s-%s' % (app, addon_type, cat), # We have potentially very long names in the cache-key, # normalize to not hit any memcached key-limits normalize=True) return cache_get_or_set( cache_key, lambda: _side_nav(context, addon_type, category)) def _side_nav(context, addon_type, cat): # Prevent helpers generating circular imports. from olympia.addons.models import Category, Addon request = context['request'] qs = Category.objects.filter(weight__gte=0) if addon_type != amo.ADDON_PERSONA: qs = qs.filter(application=request.APP.id) sort_key = attrgetter('weight', 'name') categories = sorted(qs.filter(type=addon_type), key=sort_key) if cat: base_url = cat.get_url_path() else: base_url = Addon.get_type_url(addon_type) ctx = dict(request=request, base_url=base_url, categories=categories, addon_type=addon_type, amo=amo) template = loader.get_template('amo/side_nav.html') return jinja2.Markup(template.render(ctx)) @library.global_function @jinja2.contextfunction def site_nav(context): app = context['request'].APP.id cache_key = make_key('site-nav-%s' % app, normalize=True) return cache_get_or_set(cache_key, lambda: _site_nav(context)) def _site_nav(context): # Prevent helpers from generating circular imports. from olympia.addons.models import Category request = context['request'] def sorted_cats(qs): return sorted(qs, key=attrgetter('weight', 'name')) extensions = Category.objects.filter( application=request.APP.id, weight__gte=0, type=amo.ADDON_EXTENSION) personas = Category.objects.filter(weight__gte=0, type=amo.ADDON_PERSONA) ctx = dict(request=request, amo=amo, extensions=sorted_cats(extensions), personas=sorted_cats(personas)) template = loader.get_template('amo/site_nav.html') return jinja2.Markup(template.render(ctx)) @library.global_function def loc(s): """A noop function for strings that are not ready to be localized.""" return trim_whitespace(s) @library.global_function<|fim▁hole|> @library.global_function @jinja2.contextfunction def remora_url(context, url, lang=None, app=None, prefix=''): """Wrapper for urlresolvers.remora_url""" if lang is None: _lang = context['LANG'] if _lang: lang = to_locale(_lang).replace('_', '-') if app is None: try: app = context['APP'].short except (AttributeError, KeyError): pass return urlresolvers.remora_url(url=url, lang=lang, app=app, prefix=prefix) @library.global_function @jinja2.contextfunction def hasOneToOne(context, obj, attr): try: getattr(obj, attr) return True except ObjectDoesNotExist: return False @library.global_function def no_results_amo(): # This prints a "No results found" message. That's all. Carry on. t = loader.get_template('amo/no_results.html').render() return jinja2.Markup(t) def _relative_to_absolute(url): """ Prepends relative URLs with STATIC_URL to turn those inline-able. This method is intended to be used as a ``replace`` parameter of ``re.sub``. """ url = url.group(1).strip('"\'') if not url.startswith(('data:', 'http:', 'https:', '//')): url = url.replace('../../', settings.STATIC_URL) return 'url(%s)' % url @library.global_function def inline_css(bundle, media=False, debug=None): """ If we are in debug mode, just output a single style tag for each css file. If we are not in debug mode, return a style that contains bundle-min.css. Forces a regular css() call for external URLs (no inline allowed). Extracted from jingo-minify and re-registered, see: https://github.com/jsocol/jingo-minify/pull/41 Added: turns relative links to absolute ones using STATIC_URL. """ if debug is None: debug = getattr(settings, 'DEBUG', False) if debug: items = [_get_compiled_css_url(i) for i in settings.MINIFY_BUNDLES['css'][bundle]] else: items = ['css/%s-min.css' % bundle] if not media: media = getattr(settings, 'CSS_MEDIA_DEFAULT', 'screen,projection,tv') contents = [] for css in items: if is_external(css): return _build_html([css], '<link rel="stylesheet" media="%s" ' 'href="%%s" />' % media) with open(get_path(css), 'r') as f: css_content = f.read() css_parsed = re.sub(r'url\(([^)]*?)\)', _relative_to_absolute, css_content) contents.append(css_parsed) return _build_html(contents, '<style type="text/css" media="%s">%%s' '</style>' % media) # A (temporary?) copy of this is in services/utils.py. See bug 1055654. def user_media_path(what): """Make it possible to override storage paths in settings. By default, all storage paths are in the MEDIA_ROOT. This is backwards compatible. """ default = os.path.join(settings.MEDIA_ROOT, what) key = "{0}_PATH".format(what.upper()) return getattr(settings, key, default) # A (temporary?) copy of this is in services/utils.py. See bug 1055654. def user_media_url(what): """ Generate default media url, and make possible to override it from settings. """ default = '%s%s/' % (settings.MEDIA_URL, what) key = "{0}_URL".format(what.upper().replace('-', '_')) return getattr(settings, key, default) def id_to_path(pk): """ Generate a path from an id, to distribute folders in the file system. 1 => 1/1/1 12 => 2/12/12 123456 => 6/56/123456 """ pk = unicode(pk) path = [pk[-1]] if len(pk) >= 2: path.append(pk[-2:]) else: path.append(pk) path.append(pk) return os.path.join(*path) @library.filter def hidden_field(field): return field.as_widget(attrs={'style': 'display:none'}) @library.filter def format_html(string, *args, **kwargs): """Uses ``str.format`` for string interpolation. Uses ``django.utils.html:format_html`` internally. >>> {{ "{0} arguments, {x} arguments"|format_html('args', x='kwargs') }} "positional args, kwargs arguments" Checks both, *args and **kwargs for potentially unsafe arguments ( not marked as `mark_safe`) and escapes them appropriately. """ return django_format_html(smart_text(string), *args, **kwargs) @library.global_function def js(bundle, debug=None, defer=False, async=False): """ If we are in debug mode, just output a single script tag for each js file. If we are not in debug mode, return a script that points at bundle-min.js. Copied from jingo-minify until we switch to something better... """ attrs = [] urls = get_js_urls(bundle, debug) attrs.append('src="%s"') if defer: attrs.append('defer') if async: attrs.append('async') return _build_html(urls, '<script %s></script>' % ' '.join(attrs)) @library.global_function def css(bundle, media=False, debug=None): """ If we are in debug mode, just output a single script tag for each css file. If we are not in debug mode, return a script that points at bundle-min.css. """ urls = get_css_urls(bundle, debug) if not media: media = getattr(settings, 'CSS_MEDIA_DEFAULT', 'screen,projection,tv') return _build_html(urls, '<link rel="stylesheet" media="%s" href="%%s" />' % media) @library.filter def nl2br(string): """Turn newlines into <br/>.""" if not string: return '' return jinja2.Markup('<br/>'.join(jinja2.escape(string).splitlines())) @library.filter(name='date') def format_date(value, format='DATE_FORMAT'): return defaultfilters.date(value, format) @library.filter(name='datetime') def format_datetime(value, format='DATETIME_FORMAT'): return defaultfilters.date(value, format) @library.filter def class_selected(a, b): """Return ``'class="selected"'`` if ``a == b``.""" return mark_safe('class="selected"' if a == b else '')<|fim▁end|>
def site_event_type(type): return amo.SITE_EVENT_CHOICES[type]
<|file_name|>empirical_covariance_.py<|end_file_name|><|fim▁begin|>""" Maximum likelihood covariance estimator. """ # Author: Alexandre Gramfort <[email protected]> # Gael Varoquaux <[email protected]> # Virgile Fritsch <[email protected]> # # License: BSD 3 clause # avoid division truncation import warnings import numpy as np from scipy import linalg from ..base import BaseEstimator from ..utils import check_array from ..utils.extmath import fast_logdet from ..metrics.pairwise import pairwise_distances def log_likelihood(emp_cov, precision): """Computes the sample mean of the log_likelihood under a covariance model computes the empirical expected log-likelihood (accounting for the normalization terms and scaling), allowing for universal comparison (beyond this software package) Parameters ---------- emp_cov : 2D ndarray (n_features, n_features) Maximum Likelihood Estimator of covariance precision : 2D ndarray (n_features, n_features) The precision matrix of the covariance model to be tested Returns ------- sample mean of the log-likelihood """ p = precision.shape[0] log_likelihood_ = - np.sum(emp_cov * precision) + fast_logdet(precision) log_likelihood_ -= p * np.log(2 * np.pi) log_likelihood_ /= 2. return log_likelihood_ def empirical_covariance(X, assume_centered=False): """Computes the Maximum likelihood covariance estimator Parameters ---------- X : ndarray, shape (n_samples, n_features) Data from which to compute the covariance estimate assume_centered : boolean If True, data will not be centered before computation. Useful when working with data whose mean is almost, but not exactly zero. If False, data will be centered before computation. Returns ------- covariance : 2D ndarray, shape (n_features, n_features) Empirical covariance (Maximum Likelihood Estimator). """ X = np.asarray(X) if X.ndim == 1: X = np.reshape(X, (1, -1)) if X.shape[0] == 1: warnings.warn("Only one sample available. " "You may want to reshape your data array") if assume_centered: covariance = np.dot(X.T, X) / X.shape[0] else: covariance = np.cov(X.T, bias=1) if covariance.ndim == 0: covariance = np.array([[covariance]]) return covariance class EmpiricalCovariance(BaseEstimator): """Maximum likelihood covariance estimator Read more in the :ref:`User Guide <covariance>`. Parameters ---------- store_precision : bool Specifies if the estimated precision is stored. assume_centered : bool If True, data are not centered before computation. Useful when working with data whose mean is almost, but not exactly zero. If False (default), data are centered before computation. Attributes ---------- location_ : array-like, shape (n_features,) Estimated location, i.e. the estimated mean. covariance_ : 2D ndarray, shape (n_features, n_features) Estimated covariance matrix precision_ : 2D ndarray, shape (n_features, n_features) Estimated pseudo-inverse matrix. (stored only if store_precision is True) Examples -------- >>> import numpy as np >>> from sklearn.covariance import EmpiricalCovariance >>> from sklearn.datasets import make_gaussian_quantiles >>> real_cov = np.array([[.8, .3], ... [.3, .4]]) >>> rng = np.random.RandomState(0) >>> X = rng.multivariate_normal(mean=[0, 0], ... cov=real_cov, ... size=500) >>> cov = EmpiricalCovariance().fit(X) >>> cov.covariance_ array([[0.7569..., 0.2818...], [0.2818..., 0.3928...]]) >>> cov.location_ array([0.0622..., 0.0193...]) """ def __init__(self, store_precision=True, assume_centered=False): self.store_precision = store_precision self.assume_centered = assume_centered def _set_covariance(self, covariance): """Saves the covariance and precision estimates Storage is done accordingly to `self.store_precision`. Precision stored only if invertible. Parameters ---------- covariance : 2D ndarray, shape (n_features, n_features) Estimated covariance matrix to be stored, and from which precision is computed. """ covariance = check_array(covariance) # set covariance self.covariance_ = covariance # set precision if self.store_precision: self.precision_ = linalg.pinvh(covariance) else: self.precision_ = None def get_precision(self): """Getter for the precision matrix. Returns ------- precision_ : array-like The precision matrix associated to the current covariance object. """ if self.store_precision: precision = self.precision_ else: precision = linalg.pinvh(self.covariance_) return precision def fit(self, X, y=None): """Fits the Maximum Likelihood Estimator covariance model according to the given training data and parameters. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training data, where n_samples is the number of samples and n_features is the number of features. y not used, present for API consistence purpose. Returns ------- self : object """ X = check_array(X) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: self.location_ = X.mean(0) covariance = empirical_covariance( X, assume_centered=self.assume_centered) self._set_covariance(covariance) return self <|fim▁hole|> def score(self, X_test, y=None): """Computes the log-likelihood of a Gaussian data set with `self.covariance_` as an estimator of its covariance matrix. Parameters ---------- X_test : array-like, shape = [n_samples, n_features] Test data of which we compute the likelihood, where n_samples is the number of samples and n_features is the number of features. X_test is assumed to be drawn from the same distribution than the data used in fit (including centering). y not used, present for API consistence purpose. Returns ------- res : float The likelihood of the data set with `self.covariance_` as an estimator of its covariance matrix. """ # compute empirical covariance of the test set test_cov = empirical_covariance( X_test - self.location_, assume_centered=True) # compute log likelihood res = log_likelihood(test_cov, self.get_precision()) return res def error_norm(self, comp_cov, norm='frobenius', scaling=True, squared=True): """Computes the Mean Squared Error between two covariance estimators. (In the sense of the Frobenius norm). Parameters ---------- comp_cov : array-like, shape = [n_features, n_features] The covariance to compare with. norm : str The type of norm used to compute the error. Available error types: - 'frobenius' (default): sqrt(tr(A^t.A)) - 'spectral': sqrt(max(eigenvalues(A^t.A)) where A is the error ``(comp_cov - self.covariance_)``. scaling : bool If True (default), the squared error norm is divided by n_features. If False, the squared error norm is not rescaled. squared : bool Whether to compute the squared error norm or the error norm. If True (default), the squared error norm is returned. If False, the error norm is returned. Returns ------- The Mean Squared Error (in the sense of the Frobenius norm) between `self` and `comp_cov` covariance estimators. """ # compute the error error = comp_cov - self.covariance_ # compute the error norm if norm == "frobenius": squared_norm = np.sum(error ** 2) elif norm == "spectral": squared_norm = np.amax(linalg.svdvals(np.dot(error.T, error))) else: raise NotImplementedError( "Only spectral and frobenius norms are implemented") # optionally scale the error norm if scaling: squared_norm = squared_norm / error.shape[0] # finally get either the squared norm or the norm if squared: result = squared_norm else: result = np.sqrt(squared_norm) return result def mahalanobis(self, X): """Computes the squared Mahalanobis distances of given observations. Parameters ---------- X : array-like, shape = [n_samples, n_features] The observations, the Mahalanobis distances of the which we compute. Observations are assumed to be drawn from the same distribution than the data used in fit. Returns ------- dist : array, shape = [n_samples,] Squared Mahalanobis distances of the observations. """ precision = self.get_precision() # compute mahalanobis distances dist = pairwise_distances(X, self.location_[np.newaxis, :], metric='mahalanobis', VI=precision) return np.reshape(dist, (len(X),)) ** 2<|fim▁end|>
<|file_name|>EditorWindow.py<|end_file_name|><|fim▁begin|>import sys import os import re import imp from Tkinter import * import tkSimpleDialog import tkMessageBox import webbrowser from idlelib.MultiCall import MultiCallCreator from idlelib import idlever from idlelib import WindowList from idlelib import SearchDialog from idlelib import GrepDialog from idlelib import ReplaceDialog from idlelib import PyParse from idlelib.configHandler import idleConf from idlelib import aboutDialog, textView, configDialog from idlelib import macosxSupport # The default tab setting for a Text widget, in average-width characters. TK_TABWIDTH_DEFAULT = 8 def _sphinx_version(): "Format sys.version_info to produce the Sphinx version string used to install the chm docs" major, minor, micro, level, serial = sys.version_info release = '%s%s' % (major, minor) if micro: release += '%s' % (micro,) if level == 'candidate': release += 'rc%s' % (serial,) elif level != 'final': release += '%s%s' % (level[0], serial) return release def _find_module(fullname, path=None): """Version of imp.find_module() that handles hierarchical module names""" file = None for tgt in fullname.split('.'): if file is not None: file.close() # close intermediate files (file, filename, descr) = imp.find_module(tgt, path) if descr[2] == imp.PY_SOURCE: break # find but not load the source file module = imp.load_module(tgt, file, filename, descr) try: path = module.__path__ except AttributeError: raise ImportError, 'No source for module ' + module.__name__ if descr[2] != imp.PY_SOURCE: # If all of the above fails and didn't raise an exception,fallback # to a straight import which can find __init__.py in a package. m = __import__(fullname) try: filename = m.__file__ except AttributeError: pass else: file = None base, ext = os.path.splitext(filename) if ext == '.pyc': ext = '.py' filename = base + ext descr = filename, None, imp.PY_SOURCE return file, filename, descr class HelpDialog(object): def __init__(self): self.parent = None # parent of help window self.dlg = None # the help window iteself def display(self, parent, near=None): """ Display the help dialog. parent - parent widget for the help window near - a Toplevel widget (e.g. EditorWindow or PyShell) to use as a reference for placing the help window """ if self.dlg is None: self.show_dialog(parent) if near: self.nearwindow(near) def show_dialog(self, parent): self.parent = parent fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') self.dlg = dlg = textView.view_file(parent,'Help',fn, modal=False) dlg.bind('<Destroy>', self.destroy, '+') def nearwindow(self, near): # Place the help dialog near the window specified by parent. # Note - this may not reposition the window in Metacity # if "/apps/metacity/general/disable_workarounds" is enabled dlg = self.dlg geom = (near.winfo_rootx() + 10, near.winfo_rooty() + 10) dlg.withdraw() dlg.geometry("=+%d+%d" % geom) dlg.deiconify() dlg.lift() def destroy(self, ev=None): self.dlg = None self.parent = None helpDialog = HelpDialog() # singleton instance class EditorWindow(object): from idlelib.Percolator import Percolator from idlelib.ColorDelegator import ColorDelegator from idlelib.UndoDelegator import UndoDelegator from idlelib.IOBinding import IOBinding, filesystemencoding, encoding from idlelib import Bindings from Tkinter import Toplevel from idlelib.MultiStatusBar import MultiStatusBar help_url = None def __init__(self, flist=None, filename=None, key=None, root=None): if EditorWindow.help_url is None: dochome = os.path.join(sys.prefix, 'Doc', 'index.html') if sys.platform.count('linux'): # look for html docs in a couple of standard places pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3] if os.path.isdir('/var/www/html/python/'): # "python2" rpm dochome = '/var/www/html/python/index.html' else: basepath = '/usr/share/doc/' # standard location dochome = os.path.join(basepath, pyver, 'Doc', 'index.html') elif sys.platform[:3] == 'win': chmfile = os.path.join(sys.prefix, 'Doc', 'Python%s.chm' % _sphinx_version()) if os.path.isfile(chmfile): dochome = chmfile elif macosxSupport.runningAsOSXApp(): # documentation is stored inside the python framework dochome = os.path.join(sys.prefix, 'Resources/English.lproj/Documentation/index.html') dochome = os.path.normpath(dochome) if os.path.isfile(dochome): EditorWindow.help_url = dochome if sys.platform == 'darwin': # Safari requires real file:-URLs EditorWindow.help_url = 'file://' + EditorWindow.help_url else: EditorWindow.help_url = "http://docs.python.org/%d.%d" % sys.version_info[:2] currentTheme=idleConf.CurrentTheme() self.flist = flist root = root or flist.root self.root = root try: sys.ps1 except AttributeError: sys.ps1 = '>>> ' self.menubar = Menu(root) self.top = top = WindowList.ListedToplevel(root, menu=self.menubar) if flist: self.tkinter_vars = flist.vars #self.top.instance_dict makes flist.inversedict available to #configDialog.py so it can access all EditorWindow instances self.top.instance_dict = flist.inversedict else: self.tkinter_vars = {} # keys: Tkinter event names # values: Tkinter variable instances self.top.instance_dict = {} self.recent_files_path = os.path.join(idleConf.GetUserCfgDir(), 'recent-files.lst') self.text_frame = text_frame = Frame(top) self.vbar = vbar = Scrollbar(text_frame, name='vbar') self.width = idleConf.GetOption('main','EditorWindow','width', type='int') text_options = { 'name': 'text', 'padx': 5, 'wrap': 'none', 'width': self.width, 'height': idleConf.GetOption('main', 'EditorWindow', 'height', type='int')} if TkVersion >= 8.5: # Starting with tk 8.5 we have to set the new tabstyle option # to 'wordprocessor' to achieve the same display of tabs as in # older tk versions. text_options['tabstyle'] = 'wordprocessor' self.text = text = MultiCallCreator(Text)(text_frame, **text_options) self.top.focused_widget = self.text self.createmenubar() self.apply_bindings() self.top.protocol("WM_DELETE_WINDOW", self.close) self.top.bind("<<close-window>>", self.close_event) if macosxSupport.runningAsOSXApp(): # Command-W on editorwindows doesn't work without this. text.bind('<<close-window>>', self.close_event) # Some OS X systems have only one mouse button, # so use control-click for pulldown menus there. # (Note, AquaTk defines <2> as the right button if # present and the Tk Text widget already binds <2>.) text.bind("<Control-Button-1>",self.right_menu_event) else: # Elsewhere, use right-click for pulldown menus. text.bind("<3>",self.right_menu_event) text.bind("<<cut>>", self.cut) text.bind("<<copy>>", self.copy) text.bind("<<paste>>", self.paste) text.bind("<<center-insert>>", self.center_insert_event) text.bind("<<help>>", self.help_dialog) text.bind("<<python-docs>>", self.python_docs) text.bind("<<about-idle>>", self.about_dialog) text.bind("<<open-config-dialog>>", self.config_dialog) text.bind("<<open-module>>", self.open_module) text.bind("<<do-nothing>>", lambda event: "break") text.bind("<<select-all>>", self.select_all) text.bind("<<remove-selection>>", self.remove_selection) text.bind("<<find>>", self.find_event) text.bind("<<find-again>>", self.find_again_event) text.bind("<<find-in-files>>", self.find_in_files_event) text.bind("<<find-selection>>", self.find_selection_event) text.bind("<<replace>>", self.replace_event) text.bind("<<goto-line>>", self.goto_line_event) text.bind("<<smart-backspace>>",self.smart_backspace_event) text.bind("<<newline-and-indent>>",self.newline_and_indent_event) text.bind("<<smart-indent>>",self.smart_indent_event) text.bind("<<indent-region>>",self.indent_region_event) text.bind("<<dedent-region>>",self.dedent_region_event) text.bind("<<comment-region>>",self.comment_region_event) text.bind("<<uncomment-region>>",self.uncomment_region_event) text.bind("<<tabify-region>>",self.tabify_region_event) text.bind("<<untabify-region>>",self.untabify_region_event) text.bind("<<toggle-tabs>>",self.toggle_tabs_event) text.bind("<<change-indentwidth>>",self.change_indentwidth_event) text.bind("<Left>", self.move_at_edge_if_selection(0)) text.bind("<Right>", self.move_at_edge_if_selection(1)) text.bind("<<del-word-left>>", self.del_word_left) text.bind("<<del-word-right>>", self.del_word_right) text.bind("<<beginning-of-line>>", self.home_callback) if flist: flist.inversedict[self] = key if key: flist.dict[key] = self text.bind("<<open-new-window>>", self.new_callback) text.bind("<<close-all-windows>>", self.flist.close_all_callback) text.bind("<<open-class-browser>>", self.open_class_browser) text.bind("<<open-path-browser>>", self.open_path_browser) self.set_status_bar() vbar['command'] = text.yview vbar.pack(side=RIGHT, fill=Y) text['yscrollcommand'] = vbar.set fontWeight = 'normal' if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'): fontWeight='bold' text.config(font=(idleConf.GetOption('main', 'EditorWindow', 'font'), idleConf.GetOption('main', 'EditorWindow', 'font-size', type='int'), fontWeight)) text_frame.pack(side=LEFT, fill=BOTH, expand=1) text.pack(side=TOP, fill=BOTH, expand=1) text.focus_set() # usetabs true -> literal tab characters are used by indent and # dedent cmds, possibly mixed with spaces if # indentwidth is not a multiple of tabwidth, # which will cause Tabnanny to nag! # false -> tab characters are converted to spaces by indent # and dedent cmds, and ditto TAB keystrokes # Although use-spaces=0 can be configured manually in config-main.def, # configuration of tabs v. spaces is not supported in the configuration # dialog. IDLE promotes the preferred Python indentation: use spaces! usespaces = idleConf.GetOption('main', 'Indent', 'use-spaces', type='bool') self.usetabs = not usespaces # tabwidth is the display width of a literal tab character. # CAUTION: telling Tk to use anything other than its default # tab setting causes it to use an entirely different tabbing algorithm, # treating tab stops as fixed distances from the left margin. # Nobody expects this, so for now tabwidth should never be changed. self.tabwidth = 8 # must remain 8 until Tk is fixed. # indentwidth is the number of screen characters per indent level. # The recommended Python indentation is four spaces. self.indentwidth = self.tabwidth self.set_notabs_indentwidth() # If context_use_ps1 is true, parsing searches back for a ps1 line; # else searches for a popular (if, def, ...) Python stmt. self.context_use_ps1 = False # When searching backwards for a reliable place to begin parsing, # first start num_context_lines[0] lines back, then # num_context_lines[1] lines back if that didn't work, and so on. # The last value should be huge (larger than the # of lines in a # conceivable file). # Making the initial values larger slows things down more often. self.num_context_lines = 50, 500, 5000000 self.per = per = self.Percolator(text) self.undo = undo = self.UndoDelegator() per.insertfilter(undo) text.undo_block_start = undo.undo_block_start text.undo_block_stop = undo.undo_block_stop undo.set_saved_change_hook(self.saved_change_hook) # IOBinding implements file I/O and printing functionality self.io = io = self.IOBinding(self) io.set_filename_change_hook(self.filename_change_hook) # Create the recent files submenu self.recent_files_menu = Menu(self.menubar) self.menudict['file'].insert_cascade(3, label='Recent Files', underline=0, menu=self.recent_files_menu) self.update_recent_files_list() self.color = None # initialized below in self.ResetColorizer if filename: if os.path.exists(filename) and not os.path.isdir(filename): io.loadfile(filename) else: io.set_filename(filename) self.ResetColorizer() self.saved_change_hook() self.set_indentation_params(self.ispythonsource(filename)) self.load_extensions() menu = self.menudict.get('windows') if menu: end = menu.index("end") if end is None: end = -1 if end >= 0: menu.add_separator() end = end + 1 self.wmenu_end = end WindowList.register_callback(self.postwindowsmenu) # Some abstractions so IDLE extensions are cross-IDE self.askyesno = tkMessageBox.askyesno self.askinteger = tkSimpleDialog.askinteger self.showerror = tkMessageBox.showerror self._highlight_workaround() # Fix selection tags on Windows def _highlight_workaround(self): # On Windows, Tk removes painting of the selection # tags which is different behavior than on Linux and Mac. # See issue14146 for more information. if not sys.platform.startswith('win'): return text = self.text text.event_add("<<Highlight-FocusOut>>", "<FocusOut>") text.event_add("<<Highlight-FocusIn>>", "<FocusIn>") def highlight_fix(focus): sel_range = text.tag_ranges("sel") if sel_range: if focus == 'out': HILITE_CONFIG = idleConf.GetHighlight( idleConf.CurrentTheme(), 'hilite') text.tag_config("sel_fix", HILITE_CONFIG) text.tag_raise("sel_fix") text.tag_add("sel_fix", *sel_range) elif focus == 'in': text.tag_remove("sel_fix", "1.0", "end") text.bind("<<Highlight-FocusOut>>", lambda ev: highlight_fix("out")) text.bind("<<Highlight-FocusIn>>", lambda ev: highlight_fix("in")) def _filename_to_unicode(self, filename): """convert filename to unicode in order to display it in Tk""" if isinstance(filename, unicode) or not filename: return filename else: try: return filename.decode(self.filesystemencoding) except UnicodeDecodeError: # XXX try: return filename.decode(self.encoding) except UnicodeDecodeError: # byte-to-byte conversion return filename.decode('iso8859-1') def new_callback(self, event): dirname, basename = self.io.defaultfilename() self.flist.new(dirname) return "break" def home_callback(self, event): if (event.state & 4) != 0 and event.keysym == "Home": # state&4==Control. If <Control-Home>, use the Tk binding. return if self.text.index("iomark") and \ self.text.compare("iomark", "<=", "insert lineend") and \ self.text.compare("insert linestart", "<=", "iomark"):<|fim▁hole|> for insertpt in xrange(len(line)): if line[insertpt] not in (' ','\t'): break else: insertpt=len(line) lineat = int(self.text.index("insert").split('.')[1]) if insertpt == lineat: insertpt = 0 dest = "insert linestart+"+str(insertpt)+"c" if (event.state&1) == 0: # shift was not pressed self.text.tag_remove("sel", "1.0", "end") else: if not self.text.index("sel.first"): self.text.mark_set("my_anchor", "insert") # there was no previous selection else: if self.text.compare(self.text.index("sel.first"), "<", self.text.index("insert")): self.text.mark_set("my_anchor", "sel.first") # extend back else: self.text.mark_set("my_anchor", "sel.last") # extend forward first = self.text.index(dest) last = self.text.index("my_anchor") if self.text.compare(first,">",last): first,last = last,first self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", first, last) self.text.mark_set("insert", dest) self.text.see("insert") return "break" def set_status_bar(self): self.status_bar = self.MultiStatusBar(self.top) if macosxSupport.runningAsOSXApp(): # Insert some padding to avoid obscuring some of the statusbar # by the resize widget. self.status_bar.set_label('_padding1', ' ', side=RIGHT) self.status_bar.set_label('column', 'Col: ?', side=RIGHT) self.status_bar.set_label('line', 'Ln: ?', side=RIGHT) self.status_bar.pack(side=BOTTOM, fill=X) self.text.bind("<<set-line-and-column>>", self.set_line_and_column) self.text.event_add("<<set-line-and-column>>", "<KeyRelease>", "<ButtonRelease>") self.text.after_idle(self.set_line_and_column) def set_line_and_column(self, event=None): line, column = self.text.index(INSERT).split('.') self.status_bar.set_label('column', 'Col: %s' % column) self.status_bar.set_label('line', 'Ln: %s' % line) menu_specs = [ ("file", "_File"), ("edit", "_Edit"), ("format", "F_ormat"), ("run", "_Run"), ("options", "_Options"), ("windows", "_Windows"), ("help", "_Help"), ] if macosxSupport.runningAsOSXApp(): menu_specs[-2] = ("windows", "_Window") def createmenubar(self): mbar = self.menubar self.menudict = menudict = {} for name, label in self.menu_specs: underline, label = prepstr(label) menudict[name] = menu = Menu(mbar, name=name) mbar.add_cascade(label=label, menu=menu, underline=underline) if macosxSupport.isCarbonAquaTk(self.root): # Insert the application menu menudict['application'] = menu = Menu(mbar, name='apple') mbar.add_cascade(label='IDLE', menu=menu) self.fill_menus() self.base_helpmenu_length = self.menudict['help'].index(END) self.reset_help_menu_entries() def postwindowsmenu(self): # Only called when Windows menu exists menu = self.menudict['windows'] end = menu.index("end") if end is None: end = -1 if end > self.wmenu_end: menu.delete(self.wmenu_end+1, end) WindowList.add_windows_to_menu(menu) rmenu = None def right_menu_event(self, event): self.text.mark_set("insert", "@%d,%d" % (event.x, event.y)) if not self.rmenu: self.make_rmenu() rmenu = self.rmenu self.event = event iswin = sys.platform[:3] == 'win' if iswin: self.text.config(cursor="arrow") for item in self.rmenu_specs: try: label, eventname, verify_state = item except ValueError: # see issue1207589 continue if verify_state is None: continue state = getattr(self, verify_state)() rmenu.entryconfigure(label, state=state) rmenu.tk_popup(event.x_root, event.y_root) if iswin: self.text.config(cursor="ibeam") rmenu_specs = [ # ("Label", "<<virtual-event>>", "statefuncname"), ... ("Close", "<<close-window>>", None), # Example ] def make_rmenu(self): rmenu = Menu(self.text, tearoff=0) for item in self.rmenu_specs: label, eventname = item[0], item[1] if label is not None: def command(text=self.text, eventname=eventname): text.event_generate(eventname) rmenu.add_command(label=label, command=command) else: rmenu.add_separator() self.rmenu = rmenu def rmenu_check_cut(self): return self.rmenu_check_copy() def rmenu_check_copy(self): try: indx = self.text.index('sel.first') except TclError: return 'disabled' else: return 'normal' if indx else 'disabled' def rmenu_check_paste(self): try: self.text.tk.call('tk::GetSelection', self.text, 'CLIPBOARD') except TclError: return 'disabled' else: return 'normal' def about_dialog(self, event=None): aboutDialog.AboutDialog(self.top,'About IDLE') def config_dialog(self, event=None): configDialog.ConfigDialog(self.top,'Settings') def help_dialog(self, event=None): if self.root: parent = self.root else: parent = self.top helpDialog.display(parent, near=self.top) def python_docs(self, event=None): if sys.platform[:3] == 'win': try: os.startfile(self.help_url) except WindowsError as why: tkMessageBox.showerror(title='Document Start Failure', message=str(why), parent=self.text) else: webbrowser.open(self.help_url) return "break" def cut(self,event): self.text.event_generate("<<Cut>>") return "break" def copy(self,event): if not self.text.tag_ranges("sel"): # There is no selection, so do nothing and maybe interrupt. return self.text.event_generate("<<Copy>>") return "break" def paste(self,event): self.text.event_generate("<<Paste>>") self.text.see("insert") return "break" def select_all(self, event=None): self.text.tag_add("sel", "1.0", "end-1c") self.text.mark_set("insert", "1.0") self.text.see("insert") return "break" def remove_selection(self, event=None): self.text.tag_remove("sel", "1.0", "end") self.text.see("insert") def move_at_edge_if_selection(self, edge_index): """Cursor move begins at start or end of selection When a left/right cursor key is pressed create and return to Tkinter a function which causes a cursor move from the associated edge of the selection. """ self_text_index = self.text.index self_text_mark_set = self.text.mark_set edges_table = ("sel.first+1c", "sel.last-1c") def move_at_edge(event): if (event.state & 5) == 0: # no shift(==1) or control(==4) pressed try: self_text_index("sel.first") self_text_mark_set("insert", edges_table[edge_index]) except TclError: pass return move_at_edge def del_word_left(self, event): self.text.event_generate('<Meta-Delete>') return "break" def del_word_right(self, event): self.text.event_generate('<Meta-d>') return "break" def find_event(self, event): SearchDialog.find(self.text) return "break" def find_again_event(self, event): SearchDialog.find_again(self.text) return "break" def find_selection_event(self, event): SearchDialog.find_selection(self.text) return "break" def find_in_files_event(self, event): GrepDialog.grep(self.text, self.io, self.flist) return "break" def replace_event(self, event): ReplaceDialog.replace(self.text) return "break" def goto_line_event(self, event): text = self.text lineno = tkSimpleDialog.askinteger("Goto", "Go to line number:",parent=text) if lineno is None: return "break" if lineno <= 0: text.bell() return "break" text.mark_set("insert", "%d.0" % lineno) text.see("insert") def open_module(self, event=None): # XXX Shouldn't this be in IOBinding or in FileList? try: name = self.text.get("sel.first", "sel.last") except TclError: name = "" else: name = name.strip() name = tkSimpleDialog.askstring("Module", "Enter the name of a Python module\n" "to search on sys.path and open:", parent=self.text, initialvalue=name) if name: name = name.strip() if not name: return # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = _find_module(name) except (NameError, ImportError) as msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: tkMessageBox.showerror("Unsupported type", "%s is not a source module" % name, parent=self.text) return if f: f.close() if self.flist: self.flist.open(file) else: self.io.loadfile(file) def open_class_browser(self, event=None): filename = self.io.filename if not filename: tkMessageBox.showerror( "No filename", "This buffer has no associated filename", master=self.text) self.text.focus_set() return None head, tail = os.path.split(filename) base, ext = os.path.splitext(tail) from idlelib import ClassBrowser ClassBrowser.ClassBrowser(self.flist, base, [head]) def open_path_browser(self, event=None): from idlelib import PathBrowser PathBrowser.PathBrowser(self.flist) def gotoline(self, lineno): if lineno is not None and lineno > 0: self.text.mark_set("insert", "%d.0" % lineno) self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", "insert", "insert +1l") self.center() def ispythonsource(self, filename): if not filename or os.path.isdir(filename): return True base, ext = os.path.splitext(os.path.basename(filename)) if os.path.normcase(ext) in (".py", ".pyw"): return True try: f = open(filename) line = f.readline() f.close() except IOError: return False return line.startswith('#!') and line.find('python') >= 0 def close_hook(self): if self.flist: self.flist.unregister_maybe_terminate(self) self.flist = None def set_close_hook(self, close_hook): self.close_hook = close_hook def filename_change_hook(self): if self.flist: self.flist.filename_changed_edit(self) self.saved_change_hook() self.top.update_windowlist_registry(self) self.ResetColorizer() def _addcolorizer(self): if self.color: return if self.ispythonsource(self.io.filename): self.color = self.ColorDelegator() # can add more colorizers here... if self.color: self.per.removefilter(self.undo) self.per.insertfilter(self.color) self.per.insertfilter(self.undo) def _rmcolorizer(self): if not self.color: return self.color.removecolors() self.per.removefilter(self.color) self.color = None def ResetColorizer(self): "Update the colour theme" # Called from self.filename_change_hook and from configDialog.py self._rmcolorizer() self._addcolorizer() theme = idleConf.GetOption('main','Theme','name') normal_colors = idleConf.GetHighlight(theme, 'normal') cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg') select_colors = idleConf.GetHighlight(theme, 'hilite') self.text.config( foreground=normal_colors['foreground'], background=normal_colors['background'], insertbackground=cursor_color, selectforeground=select_colors['foreground'], selectbackground=select_colors['background'], ) def ResetFont(self): "Update the text widgets' font if it is changed" # Called from configDialog.py fontWeight='normal' if idleConf.GetOption('main','EditorWindow','font-bold',type='bool'): fontWeight='bold' self.text.config(font=(idleConf.GetOption('main','EditorWindow','font'), idleConf.GetOption('main','EditorWindow','font-size', type='int'), fontWeight)) def RemoveKeybindings(self): "Remove the keybindings before they are changed." # Called from configDialog.py self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet() for event, keylist in keydefs.items(): self.text.event_delete(event, *keylist) for extensionName in self.get_standard_extension_names(): xkeydefs = idleConf.GetExtensionBindings(extensionName) if xkeydefs: for event, keylist in xkeydefs.items(): self.text.event_delete(event, *keylist) def ApplyKeybindings(self): "Update the keybindings after they are changed" # Called from configDialog.py self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet() self.apply_bindings() for extensionName in self.get_standard_extension_names(): xkeydefs = idleConf.GetExtensionBindings(extensionName) if xkeydefs: self.apply_bindings(xkeydefs) #update menu accelerators menuEventDict = {} for menu in self.Bindings.menudefs: menuEventDict[menu[0]] = {} for item in menu[1]: if item: menuEventDict[menu[0]][prepstr(item[0])[1]] = item[1] for menubarItem in self.menudict.keys(): menu = self.menudict[menubarItem] end = menu.index(END) if end is None: # Skip empty menus continue end += 1 for index in range(0, end): if menu.type(index) == 'command': accel = menu.entrycget(index, 'accelerator') if accel: itemName = menu.entrycget(index, 'label') event = '' if menubarItem in menuEventDict: if itemName in menuEventDict[menubarItem]: event = menuEventDict[menubarItem][itemName] if event: accel = get_accelerator(keydefs, event) menu.entryconfig(index, accelerator=accel) def set_notabs_indentwidth(self): "Update the indentwidth if changed and not using tabs in this window" # Called from configDialog.py if not self.usetabs: self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces', type='int') def reset_help_menu_entries(self): "Update the additional help entries on the Help menu" help_list = idleConf.GetAllExtraHelpSourcesList() helpmenu = self.menudict['help'] # first delete the extra help entries, if any helpmenu_length = helpmenu.index(END) if helpmenu_length > self.base_helpmenu_length: helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length) # then rebuild them if help_list: helpmenu.add_separator() for entry in help_list: cmd = self.__extra_help_callback(entry[1]) helpmenu.add_command(label=entry[0], command=cmd) # and update the menu dictionary self.menudict['help'] = helpmenu def __extra_help_callback(self, helpfile): "Create a callback with the helpfile value frozen at definition time" def display_extra_help(helpfile=helpfile): if not helpfile.startswith(('www', 'http')): helpfile = os.path.normpath(helpfile) if sys.platform[:3] == 'win': try: os.startfile(helpfile) except WindowsError as why: tkMessageBox.showerror(title='Document Start Failure', message=str(why), parent=self.text) else: webbrowser.open(helpfile) return display_extra_help def update_recent_files_list(self, new_file=None): "Load and update the recent files list and menus" rf_list = [] if os.path.exists(self.recent_files_path): with open(self.recent_files_path, 'r') as rf_list_file: rf_list = rf_list_file.readlines() if new_file: new_file = os.path.abspath(new_file) + '\n' if new_file in rf_list: rf_list.remove(new_file) # move to top rf_list.insert(0, new_file) # clean and save the recent files list bad_paths = [] for path in rf_list: if '\0' in path or not os.path.exists(path[0:-1]): bad_paths.append(path) rf_list = [path for path in rf_list if path not in bad_paths] ulchars = "1234567890ABCDEFGHIJK" rf_list = rf_list[0:len(ulchars)] try: with open(self.recent_files_path, 'w') as rf_file: rf_file.writelines(rf_list) except IOError as err: if not getattr(self.root, "recentfilelist_error_displayed", False): self.root.recentfilelist_error_displayed = True tkMessageBox.showerror(title='IDLE Error', message='Unable to update Recent Files list:\n%s' % str(err), parent=self.text) # for each edit window instance, construct the recent files menu for instance in self.top.instance_dict.keys(): menu = instance.recent_files_menu menu.delete(0, END) # clear, and rebuild: for i, file_name in enumerate(rf_list): file_name = file_name.rstrip() # zap \n # make unicode string to display non-ASCII chars correctly ufile_name = self._filename_to_unicode(file_name) callback = instance.__recent_file_callback(file_name) menu.add_command(label=ulchars[i] + " " + ufile_name, command=callback, underline=0) def __recent_file_callback(self, file_name): def open_recent_file(fn_closure=file_name): self.io.open(editFile=fn_closure) return open_recent_file def saved_change_hook(self): short = self.short_title() long = self.long_title() if short and long: title = short + " - " + long elif short: title = short elif long: title = long else: title = "Untitled" icon = short or long or title if not self.get_saved(): title = "*%s*" % title icon = "*%s" % icon self.top.wm_title(title) self.top.wm_iconname(icon) def get_saved(self): return self.undo.get_saved() def set_saved(self, flag): self.undo.set_saved(flag) def reset_undo(self): self.undo.reset_undo() def short_title(self): filename = self.io.filename if filename: filename = os.path.basename(filename) # return unicode string to display non-ASCII chars correctly return self._filename_to_unicode(filename) def long_title(self): # return unicode string to display non-ASCII chars correctly return self._filename_to_unicode(self.io.filename or "") def center_insert_event(self, event): self.center() def center(self, mark="insert"): text = self.text top, bot = self.getwindowlines() lineno = self.getlineno(mark) height = bot - top newtop = max(1, lineno - height//2) text.yview(float(newtop)) def getwindowlines(self): text = self.text top = self.getlineno("@0,0") bot = self.getlineno("@0,65535") if top == bot and text.winfo_height() == 1: # Geometry manager hasn't run yet height = int(text['height']) bot = top + height - 1 return top, bot def getlineno(self, mark="insert"): text = self.text return int(float(text.index(mark))) def get_geometry(self): "Return (width, height, x, y)" geom = self.top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) tuple = (map(int, m.groups())) return tuple def close_event(self, event): self.close() def maybesave(self): if self.io: if not self.get_saved(): if self.top.state()!='normal': self.top.deiconify() self.top.lower() self.top.lift() return self.io.maybesave() def close(self): reply = self.maybesave() if str(reply) != "cancel": self._close() return reply def _close(self): if self.io.filename: self.update_recent_files_list(new_file=self.io.filename) WindowList.unregister_callback(self.postwindowsmenu) self.unload_extensions() self.io.close() self.io = None self.undo = None if self.color: self.color.close(False) self.color = None self.text = None self.tkinter_vars = None self.per.close() self.per = None self.top.destroy() if self.close_hook: # unless override: unregister from flist, terminate if last window self.close_hook() def load_extensions(self): self.extensions = {} self.load_standard_extensions() def unload_extensions(self): for ins in self.extensions.values(): if hasattr(ins, "close"): ins.close() self.extensions = {} def load_standard_extensions(self): for name in self.get_standard_extension_names(): try: self.load_extension(name) except: print "Failed to load extension", repr(name) import traceback traceback.print_exc() def get_standard_extension_names(self): return idleConf.GetExtensions(editor_only=True) def load_extension(self, name): try: mod = __import__(name, globals(), locals(), []) except ImportError: print "\nFailed to import extension: ", name return cls = getattr(mod, name) keydefs = idleConf.GetExtensionBindings(name) if hasattr(cls, "menudefs"): self.fill_menus(cls.menudefs, keydefs) ins = cls(self) self.extensions[name] = ins if keydefs: self.apply_bindings(keydefs) for vevent in keydefs.keys(): methodname = vevent.replace("-", "_") while methodname[:1] == '<': methodname = methodname[1:] while methodname[-1:] == '>': methodname = methodname[:-1] methodname = methodname + "_event" if hasattr(ins, methodname): self.text.bind(vevent, getattr(ins, methodname)) def apply_bindings(self, keydefs=None): if keydefs is None: keydefs = self.Bindings.default_keydefs text = self.text text.keydefs = keydefs for event, keylist in keydefs.items(): if keylist: text.event_add(event, *keylist) def fill_menus(self, menudefs=None, keydefs=None): """Add appropriate entries to the menus and submenus Menus that are absent or None in self.menudict are ignored. """ if menudefs is None: menudefs = self.Bindings.menudefs if keydefs is None: keydefs = self.Bindings.default_keydefs menudict = self.menudict text = self.text for mname, entrylist in menudefs: menu = menudict.get(mname) if not menu: continue for entry in entrylist: if not entry: menu.add_separator() else: label, eventname = entry checkbutton = (label[:1] == '!') if checkbutton: label = label[1:] underline, label = prepstr(label) accelerator = get_accelerator(keydefs, eventname) def command(text=text, eventname=eventname): text.event_generate(eventname) if checkbutton: var = self.get_var_obj(eventname, BooleanVar) menu.add_checkbutton(label=label, underline=underline, command=command, accelerator=accelerator, variable=var) else: menu.add_command(label=label, underline=underline, command=command, accelerator=accelerator) def getvar(self, name): var = self.get_var_obj(name) if var: value = var.get() return value else: raise NameError, name def setvar(self, name, value, vartype=None): var = self.get_var_obj(name, vartype) if var: var.set(value) else: raise NameError, name def get_var_obj(self, name, vartype=None): var = self.tkinter_vars.get(name) if not var and vartype: # create a Tkinter variable object with self.text as master: self.tkinter_vars[name] = var = vartype(self.text) return var # Tk implementations of "virtual text methods" -- each platform # reusing IDLE's support code needs to define these for its GUI's # flavor of widget. # Is character at text_index in a Python string? Return 0 for # "guaranteed no", true for anything else. This info is expensive # to compute ab initio, but is probably already known by the # platform's colorizer. def is_char_in_string(self, text_index): if self.color: # Return true iff colorizer hasn't (re)gotten this far # yet, or the character is tagged as being in a string return self.text.tag_prevrange("TODO", text_index) or \ "STRING" in self.text.tag_names(text_index) else: # The colorizer is missing: assume the worst return 1 # If a selection is defined in the text widget, return (start, # end) as Tkinter text indices, otherwise return (None, None) def get_selection_indices(self): try: first = self.text.index("sel.first") last = self.text.index("sel.last") return first, last except TclError: return None, None # Return the text widget's current view of what a tab stop means # (equivalent width in spaces). def get_tabwidth(self): current = self.text['tabs'] or TK_TABWIDTH_DEFAULT return int(current) # Set the text widget's current view of what a tab stop means. def set_tabwidth(self, newtabwidth): text = self.text if self.get_tabwidth() != newtabwidth: pixels = text.tk.call("font", "measure", text["font"], "-displayof", text.master, "n" * newtabwidth) text.configure(tabs=pixels) # If ispythonsource and guess are true, guess a good value for # indentwidth based on file content (if possible), and if # indentwidth != tabwidth set usetabs false. # In any case, adjust the Text widget's view of what a tab # character means. def set_indentation_params(self, ispythonsource, guess=True): if guess and ispythonsource: i = self.guess_indent() if 2 <= i <= 8: self.indentwidth = i if self.indentwidth != self.tabwidth: self.usetabs = False self.set_tabwidth(self.tabwidth) def smart_backspace_event(self, event): text = self.text first, last = self.get_selection_indices() if first and last: text.delete(first, last) text.mark_set("insert", first) return "break" # Delete whitespace left, until hitting a real char or closest # preceding virtual tab stop. chars = text.get("insert linestart", "insert") if chars == '': if text.compare("insert", ">", "1.0"): # easy: delete preceding newline text.delete("insert-1c") else: text.bell() # at start of buffer return "break" if chars[-1] not in " \t": # easy: delete preceding real char text.delete("insert-1c") return "break" # Ick. It may require *inserting* spaces if we back up over a # tab character! This is written to be clear, not fast. tabwidth = self.tabwidth have = len(chars.expandtabs(tabwidth)) assert have > 0 want = ((have - 1) // self.indentwidth) * self.indentwidth # Debug prompt is multilined.... if self.context_use_ps1: last_line_of_prompt = sys.ps1.split('\n')[-1] else: last_line_of_prompt = '' ncharsdeleted = 0 while 1: if chars == last_line_of_prompt: break chars = chars[:-1] ncharsdeleted = ncharsdeleted + 1 have = len(chars.expandtabs(tabwidth)) if have <= want or chars[-1] not in " \t": break text.undo_block_start() text.delete("insert-%dc" % ncharsdeleted, "insert") if have < want: text.insert("insert", ' ' * (want - have)) text.undo_block_stop() return "break" def smart_indent_event(self, event): # if intraline selection: # delete it # elif multiline selection: # do indent-region # else: # indent one level text = self.text first, last = self.get_selection_indices() text.undo_block_start() try: if first and last: if index2line(first) != index2line(last): return self.indent_region_event(event) text.delete(first, last) text.mark_set("insert", first) prefix = text.get("insert linestart", "insert") raw, effective = classifyws(prefix, self.tabwidth) if raw == len(prefix): # only whitespace to the left self.reindent_to(effective + self.indentwidth) else: # tab to the next 'stop' within or to right of line's text: if self.usetabs: pad = '\t' else: effective = len(prefix.expandtabs(self.tabwidth)) n = self.indentwidth pad = ' ' * (n - effective % n) text.insert("insert", pad) text.see("insert") return "break" finally: text.undo_block_stop() def newline_and_indent_event(self, event): text = self.text first, last = self.get_selection_indices() text.undo_block_start() try: if first and last: text.delete(first, last) text.mark_set("insert", first) line = text.get("insert linestart", "insert") i, n = 0, len(line) while i < n and line[i] in " \t": i = i+1 if i == n: # the cursor is in or at leading indentation in a continuation # line; just inject an empty line at the start text.insert("insert linestart", '\n') return "break" indent = line[:i] # strip whitespace before insert point unless it's in the prompt i = 0 last_line_of_prompt = sys.ps1.split('\n')[-1] while line and line[-1] in " \t" and line != last_line_of_prompt: line = line[:-1] i = i+1 if i: text.delete("insert - %d chars" % i, "insert") # strip whitespace after insert point while text.get("insert") in " \t": text.delete("insert") # start new line text.insert("insert", '\n') # adjust indentation for continuations and block # open/close first need to find the last stmt lno = index2line(text.index('insert')) y = PyParse.Parser(self.indentwidth, self.tabwidth) if not self.context_use_ps1: for context in self.num_context_lines: startat = max(lno - context, 1) startatindex = repr(startat) + ".0" rawtext = text.get(startatindex, "insert") y.set_str(rawtext) bod = y.find_good_parse_start( self.context_use_ps1, self._build_char_in_string_func(startatindex)) if bod is not None or startat == 1: break y.set_lo(bod or 0) else: r = text.tag_prevrange("console", "insert") if r: startatindex = r[1] else: startatindex = "1.0" rawtext = text.get(startatindex, "insert") y.set_str(rawtext) y.set_lo(0) c = y.get_continuation_type() if c != PyParse.C_NONE: # The current stmt hasn't ended yet. if c == PyParse.C_STRING_FIRST_LINE: # after the first line of a string; do not indent at all pass elif c == PyParse.C_STRING_NEXT_LINES: # inside a string which started before this line; # just mimic the current indent text.insert("insert", indent) elif c == PyParse.C_BRACKET: # line up with the first (if any) element of the # last open bracket structure; else indent one # level beyond the indent of the line with the # last open bracket self.reindent_to(y.compute_bracket_indent()) elif c == PyParse.C_BACKSLASH: # if more than one line in this stmt already, just # mimic the current indent; else if initial line # has a start on an assignment stmt, indent to # beyond leftmost =; else to beyond first chunk of # non-whitespace on initial line if y.get_num_lines_in_stmt() > 1: text.insert("insert", indent) else: self.reindent_to(y.compute_backslash_indent()) else: assert 0, "bogus continuation type %r" % (c,) return "break" # This line starts a brand new stmt; indent relative to # indentation of initial line of closest preceding # interesting stmt. indent = y.get_base_indent_string() text.insert("insert", indent) if y.is_block_opener(): self.smart_indent_event(event) elif indent and y.is_block_closer(): self.smart_backspace_event(event) return "break" finally: text.see("insert") text.undo_block_stop() # Our editwin provides a is_char_in_string function that works # with a Tk text index, but PyParse only knows about offsets into # a string. This builds a function for PyParse that accepts an # offset. def _build_char_in_string_func(self, startindex): def inner(offset, _startindex=startindex, _icis=self.is_char_in_string): return _icis(_startindex + "+%dc" % offset) return inner def indent_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines)): line = lines[pos] if line: raw, effective = classifyws(line, self.tabwidth) effective = effective + self.indentwidth lines[pos] = self._make_blanks(effective) + line[raw:] self.set_region(head, tail, chars, lines) return "break" def dedent_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines)): line = lines[pos] if line: raw, effective = classifyws(line, self.tabwidth) effective = max(effective - self.indentwidth, 0) lines[pos] = self._make_blanks(effective) + line[raw:] self.set_region(head, tail, chars, lines) return "break" def comment_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines) - 1): line = lines[pos] lines[pos] = '##' + line self.set_region(head, tail, chars, lines) def uncomment_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines)): line = lines[pos] if not line: continue if line[:2] == '##': line = line[2:] elif line[:1] == '#': line = line[1:] lines[pos] = line self.set_region(head, tail, chars, lines) def tabify_region_event(self, event): head, tail, chars, lines = self.get_region() tabwidth = self._asktabwidth() if tabwidth is None: return for pos in range(len(lines)): line = lines[pos] if line: raw, effective = classifyws(line, tabwidth) ntabs, nspaces = divmod(effective, tabwidth) lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:] self.set_region(head, tail, chars, lines) def untabify_region_event(self, event): head, tail, chars, lines = self.get_region() tabwidth = self._asktabwidth() if tabwidth is None: return for pos in range(len(lines)): lines[pos] = lines[pos].expandtabs(tabwidth) self.set_region(head, tail, chars, lines) def toggle_tabs_event(self, event): if self.askyesno( "Toggle tabs", "Turn tabs " + ("on", "off")[self.usetabs] + "?\nIndent width " + ("will be", "remains at")[self.usetabs] + " 8." + "\n Note: a tab is always 8 columns", parent=self.text): self.usetabs = not self.usetabs # Try to prevent inconsistent indentation. # User must change indent width manually after using tabs. self.indentwidth = 8 return "break" # XXX this isn't bound to anything -- see tabwidth comments ## def change_tabwidth_event(self, event): ## new = self._asktabwidth() ## if new != self.tabwidth: ## self.tabwidth = new ## self.set_indentation_params(0, guess=0) ## return "break" def change_indentwidth_event(self, event): new = self.askinteger( "Indent width", "New indent width (2-16)\n(Always use 8 when using tabs)", parent=self.text, initialvalue=self.indentwidth, minvalue=2, maxvalue=16) if new and new != self.indentwidth and not self.usetabs: self.indentwidth = new return "break" def get_region(self): text = self.text first, last = self.get_selection_indices() if first and last: head = text.index(first + " linestart") tail = text.index(last + "-1c lineend +1c") else: head = text.index("insert linestart") tail = text.index("insert lineend +1c") chars = text.get(head, tail) lines = chars.split("\n") return head, tail, chars, lines def set_region(self, head, tail, chars, lines): text = self.text newchars = "\n".join(lines) if newchars == chars: text.bell() return text.tag_remove("sel", "1.0", "end") text.mark_set("insert", head) text.undo_block_start() text.delete(head, tail) text.insert(head, newchars) text.undo_block_stop() text.tag_add("sel", head, "insert") # Make string that displays as n leading blanks. def _make_blanks(self, n): if self.usetabs: ntabs, nspaces = divmod(n, self.tabwidth) return '\t' * ntabs + ' ' * nspaces else: return ' ' * n # Delete from beginning of line to insert point, then reinsert # column logical (meaning use tabs if appropriate) spaces. def reindent_to(self, column): text = self.text text.undo_block_start() if text.compare("insert linestart", "!=", "insert"): text.delete("insert linestart", "insert") if column: text.insert("insert", self._make_blanks(column)) text.undo_block_stop() def _asktabwidth(self): return self.askinteger( "Tab width", "Columns per tab? (2-16)", parent=self.text, initialvalue=self.indentwidth, minvalue=2, maxvalue=16) # Guess indentwidth from text content. # Return guessed indentwidth. This should not be believed unless # it's in a reasonable range (e.g., it will be 0 if no indented # blocks are found). def guess_indent(self): opener, indented = IndentSearcher(self.text, self.tabwidth).run() if opener and indented: raw, indentsmall = classifyws(opener, self.tabwidth) raw, indentlarge = classifyws(indented, self.tabwidth) else: indentsmall = indentlarge = 0 return indentlarge - indentsmall # "line.col" -> line, as an int def index2line(index): return int(float(index)) # Look at the leading whitespace in s. # Return pair (# of leading ws characters, # effective # of leading blanks after expanding # tabs to width tabwidth) def classifyws(s, tabwidth): raw = effective = 0 for ch in s: if ch == ' ': raw = raw + 1 effective = effective + 1 elif ch == '\t': raw = raw + 1 effective = (effective // tabwidth + 1) * tabwidth else: break return raw, effective import tokenize _tokenize = tokenize del tokenize class IndentSearcher(object): # .run() chews over the Text widget, looking for a block opener # and the stmt following it. Returns a pair, # (line containing block opener, line containing stmt) # Either or both may be None. def __init__(self, text, tabwidth): self.text = text self.tabwidth = tabwidth self.i = self.finished = 0 self.blkopenline = self.indentedline = None def readline(self): if self.finished: return "" i = self.i = self.i + 1 mark = repr(i) + ".0" if self.text.compare(mark, ">=", "end"): return "" return self.text.get(mark, mark + " lineend+1c") def tokeneater(self, type, token, start, end, line, INDENT=_tokenize.INDENT, NAME=_tokenize.NAME, OPENERS=('class', 'def', 'for', 'if', 'try', 'while')): if self.finished: pass elif type == NAME and token in OPENERS: self.blkopenline = line elif type == INDENT and self.blkopenline: self.indentedline = line self.finished = 1 def run(self): save_tabsize = _tokenize.tabsize _tokenize.tabsize = self.tabwidth try: try: _tokenize.tokenize(self.readline, self.tokeneater) except (_tokenize.TokenError, SyntaxError): # since we cut off the tokenizer early, we can trigger # spurious errors pass finally: _tokenize.tabsize = save_tabsize return self.blkopenline, self.indentedline ### end autoindent code ### def prepstr(s): # Helper to extract the underscore from a string, e.g. # prepstr("Co_py") returns (2, "Copy"). i = s.find('_') if i >= 0: s = s[:i] + s[i+1:] return i, s keynames = { 'bracketleft': '[', 'bracketright': ']', 'slash': '/', } def get_accelerator(keydefs, eventname): keylist = keydefs.get(eventname) # issue10940: temporary workaround to prevent hang with OS X Cocoa Tk 8.5 # if not keylist: if (not keylist) or (macosxSupport.runningAsOSXApp() and eventname in { "<<open-module>>", "<<goto-line>>", "<<change-indentwidth>>"}): return "" s = keylist[0] s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s) s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s) s = re.sub("Key-", "", s) s = re.sub("Cancel","Ctrl-Break",s) # [email protected] s = re.sub("Control-", "Ctrl-", s) s = re.sub("-", "+", s) s = re.sub("><", " ", s) s = re.sub("<", "", s) s = re.sub(">", "", s) return s def fixwordbreaks(root): # Make sure that Tk's double-click and next/previous word # operations use our definition of a word (i.e. an identifier) tk = root.tk tk.call('tcl_wordBreakAfter', 'a b', 0) # make sure word.tcl is loaded tk.call('set', 'tcl_wordchars', '[a-zA-Z0-9_]') tk.call('set', 'tcl_nonwordchars', '[^a-zA-Z0-9_]') def test(): root = Tk() fixwordbreaks(root) root.withdraw() if sys.argv[1:]: filename = sys.argv[1] else: filename = None edit = EditorWindow(root=root, filename=filename) edit.set_close_hook(root.quit) edit.text.bind("<<close-all-windows>>", edit.close_event) root.mainloop() root.destroy() if __name__ == '__main__': test()<|fim▁end|>
# In Shell on input line, go to just after prompt insertpt = int(self.text.index("iomark").split(".")[1]) else: line = self.text.get("insert linestart", "insert lineend")
<|file_name|>clientconn_test.go<|end_file_name|><|fim▁begin|>/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.<|fim▁hole|>package grpc import ( "net" "testing" "time" "golang.org/x/net/context" "google.golang.org/grpc/credentials" ) const tlsDir = "testdata/" func TestDialTimeout(t *testing.T) { conn, err := Dial("Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func TestTLSDialTimeout(t *testing.T) { creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds), WithTimeout(time.Millisecond), WithBlock()) if err == nil { conn.Close() } if err != context.DeadlineExceeded { t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) } } func TestTLSServerNameOverwrite(t *testing.T) { overwriteServerName := "over.write.server.name" creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", overwriteServerName) if err != nil { t.Fatalf("Failed to create credentials %v", err) } conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds)) if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } conn.Close() if conn.authority != overwriteServerName { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) } } func TestDialContextCancel(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled { t.Fatalf("DialContext(%v, _) = _, %v, want _, %v", ctx, err, context.Canceled) } } // blockingBalancer mimics the behavior of balancers whose initialization takes a long time. // In this test, reading from blockingBalancer.Notify() blocks forever. type blockingBalancer struct { ch chan []Address } func newBlockingBalancer() Balancer { return &blockingBalancer{ch: make(chan []Address)} } func (b *blockingBalancer) Start(target string, config BalancerConfig) error { return nil } func (b *blockingBalancer) Up(addr Address) func(error) { return nil } func (b *blockingBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { return Address{}, nil, nil } func (b *blockingBalancer) Notify() <-chan []Address { return b.ch } func (b *blockingBalancer) Close() error { close(b.ch) return nil } func TestDialWithBlockingBalancer(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) dialDone := make(chan struct{}) go func() { DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithBalancer(newBlockingBalancer())) close(dialDone) }() cancel() <-dialDone } // securePerRPCCredentials always requires transport security. type securePerRPCCredentials struct{} func (c securePerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil } func (c securePerRPCCredentials) RequireTransportSecurity() bool { return true } func TestCredentialsMisuse(t *testing.T) { tlsCreds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { t.Fatalf("Failed to create authenticator %v", err) } // Two conflicting credential configurations if _, err := Dial("Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errCredentialsConflict) } // security info on insecure connection if _, err := Dial("Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errTransportCredentialsMissing) } } func TestWithBackoffConfigDefault(t *testing.T) { testBackoffConfigSet(t, &DefaultBackoffConfig) } func TestWithBackoffConfig(t *testing.T) { b := BackoffConfig{MaxDelay: DefaultBackoffConfig.MaxDelay / 2} expected := b setDefaults(&expected) // defaults should be set testBackoffConfigSet(t, &expected, WithBackoffConfig(b)) } func TestWithBackoffMaxDelay(t *testing.T) { md := DefaultBackoffConfig.MaxDelay / 2 expected := BackoffConfig{MaxDelay: md} setDefaults(&expected) testBackoffConfigSet(t, &expected, WithBackoffMaxDelay(md)) } func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOption) { opts = append(opts, WithInsecure()) conn, err := Dial("foo:80", opts...) if err != nil { t.Fatalf("unexpected error dialing connection: %v", err) } if conn.dopts.bs == nil { t.Fatalf("backoff config not set") } actual, ok := conn.dopts.bs.(BackoffConfig) if !ok { t.Fatalf("unexpected type of backoff config: %#v", conn.dopts.bs) } if actual != *expected { t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected) } conn.Close() } type testErr struct { temp bool } func (e *testErr) Error() string { return "test error" } func (e *testErr) Temporary() bool { return e.temp } var nonTemporaryError = &testErr{false} func nonTemporaryErrorDialer(addr string, timeout time.Duration) (net.Conn, error) { return nil, nonTemporaryError } func TestDialWithBlockErrorOnNonTemporaryErrorDialer(t *testing.T) { ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock(), FailOnNonTempDialError(true)); err != nonTemporaryError { t.Fatalf("Dial(%q) = %v, want %v", "", err, nonTemporaryError) } // Without FailOnNonTempDialError, gRPC will retry to connect, and dial should exit with time out error. if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock()); err != context.DeadlineExceeded { t.Fatalf("Dial(%q) = %v, want %v", "", err, context.DeadlineExceeded) } }<|fim▁end|>
* */
<|file_name|>core.py<|end_file_name|><|fim▁begin|># Copyright (c) 2011 - Rui Batista <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import functools import inspect import sys import pygame def key_event(*keys): def wrap(f): f.__key_events__ = keys return f return wrap class _KeyHandlerMeta(type): def __new__(cls, name, bases, dct): if not '__key_handlers__' in dct: dct['__key_handlers__'] = {} for v in dct.values(): if hasattr(v, '__key_events__') and callable(v): for e in v.__key_events__: dct['__key_handlers__'][e] = v return type.__new__(cls, name, bases, dct) class PygameMainLoop(object): __metaclass__ = _KeyHandlerMeta def __init__(self): self._mainloop_running = False self._retval = None def run(self): self.on_run() self._mainloop_running = True while self._mainloop_running: self.run_before() for event in self.get_events(): self.dispatch_event(event) self.run_after() return self._retval def quit(self, retval=None): self._retval = retval self._mainloop_running = False def dispatch_event(self, event): if event.type == pygame.QUIT: self.on_quit_event() elif event.type == pygame.KEYDOWN and event.key in self.__key_handlers__: self.__key_handlers__[event.key](self,event) else: self.on_event_default(event) def on_quit_event(self): pygame.quit() sys.exit(0) def get_events(self): return pygame.event.get() def run_before(self): pass def run_after(self): pass<|fim▁hole|> def on_event_default(self, event): pass class VoiceDialog(PygameMainLoop): @key_event(pygame.K_ESCAPE) def escape(self, event): self.quit(None) def get_events(self): return [pygame.event.wait()]<|fim▁end|>
def on_run(self): pass
<|file_name|>MailHeader.test.tsx<|end_file_name|><|fim▁begin|>import loudRejection from 'loud-rejection'; import { fireEvent, getByTestId, getByText } from '@testing-library/dom'; import { act, screen } from '@testing-library/react'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { addApiMock, clearAll, getDropdown, getHistory, render, minimalCache, addToCache, } from '../../helpers/test/helper'; import { Breakpoints } from '../../models/utils'; import MailHeader from './MailHeader'; loudRejection(); const getProps = () => ({ labelID: 'labelID', elementID: undefined, location: getHistory().location, history: getHistory(), breakpoints: {} as Breakpoints, onSearch: jest.fn(), expanded: true, onToggleExpand: jest.fn(), onOpenShortcutsModal: jest.fn(), }); const user = { Email: 'Email', DisplayName: 'DisplayName', Name: 'Name', hasPaidMail: false, UsedSpace: 10, MaxSpace: 100, }; describe('MailHeader', () => { let props: ReturnType<typeof getProps>; const setup = async () => { minimalCache(); addToCache('User', user); addApiMock('payments/plans', () => ({})); addApiMock('contacts/v4/contacts', () => ({ Contacts: [] })); props = getProps(); const result = await render(<MailHeader {...props} />, false); const searchForm = result.getByRole('search'); const openAdvanced = async () => { const advancedDropdownButton = getByTestId(searchForm, 'dropdown-button'); fireEvent.click(advancedDropdownButton); const dropdown = await getDropdown(); const submitButton = dropdown.querySelector('button[type="submit"]') as HTMLButtonElement; const submit = () => fireEvent.click(submitButton); return { dropdown, submitButton, submit }; }; return { ...result, searchForm, openAdvanced }; }; // Not found better to test // It's hard to override sso mode constant const assertAppLink = (element: HTMLElement, href: string) => { const link = element.closest('a'); expect(link?.getAttribute('href')).toBe(href); }; afterEach(clearAll); describe('Core features', () => { it('should redirect on inbox when click on logo', async () => { const { getByText } = await setup(); const logo = getByText('ProtonMail'); fireEvent.click(logo); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/inbox'); }); it('should open app dropdown', async () => { const { getByTitle } = await setup(); const appsButton = getByTitle('Proton applications'); fireEvent.click(appsButton); const dropdown = await getDropdown(); getByText(dropdown, 'Mail'); getByText(dropdown, 'Calendar'); getByText(dropdown, 'VPN'); }); it('should open contacts widget', async () => { const { getByText: getByTextHeader } = await setup(); const contactsButton = getByTextHeader('Contacts'); fireEvent.click(contactsButton); const dropdown = await getDropdown(); getByText(dropdown, 'Contacts'); getByText(dropdown, 'Groups'); getByText(dropdown, 'Settings'); }); it('should open settings', async () => { const { getByText: getByTextHeader } = await setup(); const settingsButton = getByTextHeader('Settings'); fireEvent.click(settingsButton); const dropdown = await getDropdown(); const settingsLink = getByText(dropdown, 'settings', { exact: false }); assertAppLink(settingsLink, '/mail'); }); it('should open user dropdown', async () => { const { getByText: getByTextHeader } = await setup(); const userButton = getByTextHeader(user.DisplayName); fireEvent.click(userButton); const dropdown = await getDropdown(); const { textContent } = dropdown; expect(textContent).toContain('Proton introduction'); expect(textContent).toContain('Get help'); expect(textContent).toContain('Proton shop'); expect(textContent).toContain('Sign out'); }); it('should show upgrade button', async () => { const { getByText } = await setup(); const upgradeLabel = getByText('Upgrade'); assertAppLink(upgradeLabel, '/mail/dashboard'); }); it('should show upgrade button', async () => { const { getByText } = await setup(); <|fim▁hole|> }); }); describe('Search features', () => { it('should search with search bar', async () => { const searchTerm = 'test'; const { searchForm } = await setup(); const searchInput = searchForm.querySelector('input') as HTMLInputElement; fireEvent.change(searchInput, { target: { value: searchTerm } }); act(() => { fireEvent.submit(searchForm); }); expect(props.onSearch).toHaveBeenCalledWith(searchTerm, undefined); }); it('should search with keyword in advanced search', async () => { const searchTerm = 'test'; const { searchForm, openAdvanced, rerender } = await setup(); const { submit } = await openAdvanced(); const keywordInput = document.getElementById('search-keyword') as HTMLInputElement; fireEvent.change(keywordInput, { target: { value: searchTerm } }); submit(); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/inbox'); expect(history.location.hash).toBe(`#keyword=${searchTerm}`); await rerender(<MailHeader {...props} />); const searchInput = searchForm.querySelector('input') as HTMLInputElement; expect(searchInput.value).toBe(searchTerm); }); it('should search with keyword and location', async () => { const searchTerm = 'test'; const { openAdvanced } = await setup(); const { submit } = await openAdvanced(); const keywordInput = document.getElementById('search-keyword') as HTMLInputElement; fireEvent.change(keywordInput, { target: { value: searchTerm } }); const draftButton = screen.getByTestId(`location-${MAILBOX_LABEL_IDS.DRAFTS}`); fireEvent.click(draftButton); submit(); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/drafts'); expect(history.location.hash).toBe(`#keyword=${searchTerm}`); }); }); });<|fim▁end|>
const upgradeLabel = getByText('Upgrade'); assertAppLink(upgradeLabel, '/mail/dashboard');
<|file_name|>RaidLeader.java<|end_file_name|><|fim▁begin|>package hs.minion; import hs.CardClass; import hs.CardSet; public class RaidLeader extends Minion { static final String Name = "Raid Leader"; static final int Cost = 3; static final CardClass Class = CardClass.NEUTRAL; static final String Text = "Your other minions have +1 Attack."; static final MinionRace Race = MinionRace.NEUTRAL; static final int Attack = 2; static final int Health = 2; static CardSet Set = CardSet.BASIC; @Override public String getName() { return Name; } @Override public int getNormalCost() { return Cost; } @Override public String getText() { return Text; } @Override public CardClass getCardClass() { return Class; } @Override public int getNormalHealth() { return Health; }<|fim▁hole|> @Override public int getNormalAttack() { return Attack; } @Override public CardSet getCardSet() { return Set; } }<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover()<|fim▁hole|> url(r'^hall/(?P<slug>[-\w]+)/$', 'menu.views.halldetail', name='halldetail'), url(r'^admin/', include(admin.site.urls)), )<|fim▁end|>
urlpatterns = patterns('', url(r'^$', 'menu.views.home', name='home'),
<|file_name|>gdocs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from exceptions import KeyError import os import requests class GoogleDoc(object): """ A class for accessing a Google document as an object. Includes the bits necessary for accessing the document and auth and such. For example: doc = { "key": "123456abcdef", "file_name": "my_google_doc", "gid": "2" } g = GoogleDoc(**doc) g.get_auth() g.get_document() Will download your google doc to data/file_name.format. """ # You can update these values with kwargs. # In fact, you better pass a key or else it won't work! key = None file_format = 'xlsx' file_name = 'copy' gid = '0' # You can change these with kwargs but it's not recommended. spreadsheet_url = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%(key)s&exportFormat=%(format)s&gid=%(gid)s' new_spreadsheet_url = 'https://docs.google.com/spreadsheets/d/%(key)s/export?format=%(format)s&id=%(key)s&gid=%(gid)s' auth = None email = os.environ.get('APPS_GOOGLE_EMAIL', None) password = os.environ.get('APPS_GOOGLE_PASS', None) scope = "https://spreadsheets.google.com/feeds/" service = "wise" session = "1" def __init__(self, **kwargs): """ Because sometimes, just sometimes, you need to update the class when you instantiate it. In this case, we need, minimally, a document key. """ if kwargs: if kwargs.items(): for key, value in kwargs.items(): setattr(self, key, value) def get_auth(self): """ Gets an authorization token and adds it to the class. """ data = {} if not self.email or not self.password: raise KeyError("Error! You're missing some variables. You need to export APPS_GOOGLE_EMAIL and APPS_GOOGLE_PASS.") else: data['Email'] = self.email data['Passwd'] = self.password data['scope'] = self.scope data['service'] = self.service data['session'] = self.session r = requests.post("https://www.google.com/accounts/ClientLogin", data=data) self.auth = r.content.split('\n')[2].split('Auth=')[1] def get_document(self): """ Uses the authentication token to fetch a google doc. """<|fim▁hole|> elif not self.key: raise KeyError("Error! You forgot to pass a key to the class.") else: headers = {} headers['Authorization'] = "GoogleLogin auth=%s" % self.auth url_params = { 'key': self.key, 'format': self.file_format, 'gid': self.gid } url = self.spreadsheet_url % url_params r = requests.get(url, headers=headers) if r.status_code != 200: url = self.new_spreadsheet_url % url_params r = requests.get(url, headers=headers) if r.status_code != 200: raise KeyError("Error! Your Google Doc does not exist.") with open('data/%s.%s' % (self.file_name, self.file_format), 'wb') as writefile: writefile.write(r.content)<|fim▁end|>
# Handle basically all the things that can go wrong. if not self.auth: raise KeyError("Error! You didn't get an auth token. Something very bad happened. File a bug?")
<|file_name|>draw.rs<|end_file_name|><|fim▁begin|>use specs::{Component, VecStorage}; use specs_derive::*; #[derive(Component, Debug, Default)] #[storage(VecStorage)] pub struct RenderOrder { pub depth: usize,<|fim▁hole|><|fim▁end|>
}
<|file_name|>DLPInspectTextTest.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.extensions.ml; import static org.junit.Assert.assertThrows; <|fim▁hole|>import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.PCollectionView; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DLPInspectTextTest { @Rule public TestPipeline testPipeline = TestPipeline.create(); private static final Integer BATCH_SIZE_SMALL = 200; private static final String DELIMITER = ";"; private static final String TEMPLATE_NAME = "test_template"; private static final String PROJECT_ID = "test_id"; @Test public void throwsExceptionWhenDeidentifyConfigAndTemplatesAreEmpty() { assertThrows( "Either inspectTemplateName or inspectConfig must be supplied!", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsNullAndHeadersAreSet() { PCollectionView<List<String>> header = testPipeline.apply(Create.of("header")).apply(View.asList()); assertThrows( "Column delimiter should be set if headers are present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setHeaderColumns(header) .build()); testPipeline.run().waitUntilFinish(); } @Test public void throwsExceptionWhenBatchSizeIsTooLarge() { assertThrows( String.format( "Batch size is too large! It should be smaller or equal than %d.", DLPInspectText.DLP_PAYLOAD_LIMIT_BYTES), IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(Integer.MAX_VALUE) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } @Test public void throwsExceptionWhenDelimiterIsSetAndHeadersAreNot() { assertThrows( "Column headers should be supplied when delimiter is present.", IllegalArgumentException.class, () -> DLPInspectText.newBuilder() .setProjectId(PROJECT_ID) .setBatchSizeBytes(BATCH_SIZE_SMALL) .setInspectTemplateName(TEMPLATE_NAME) .setColumnDelimiter(DELIMITER) .build()); } }<|fim▁end|>
import java.util.List; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create;
<|file_name|>contact.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('myApp.contact', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/contact', { templateUrl: 'app/view/contact.html', controller: 'contactCtrl' }); }]) .controller('contactCtrl',['$scope','$http', function($scope, $http) { <|fim▁hole|> $scope.result = 'hidden' $scope.resultMessage; $scope.formData; //formData is an object holding the name, email, subject, and message $scope.submitButtonDisabled = false; $scope.submitted = false; //used so that form errors are shown only after the form has been submitted $scope.submit = function(contactform) { $scope.submitted = true; $scope.submitButtonDisabled = true; if (contactform.$valid) { $http({ method : 'POST', url : 'http://localhost:8000/contact-form.php', data : $.param($scope.formData), //param method from jQuery headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload) }).success(function(data){ console.log(data); if (data) { //success comes from the return json object $scope.submitButtonDisabled = true; $scope.resultMessage = data; $scope.result='bg-success'; } else { $scope.submitButtonDisabled = false; $scope.resultMessage = data; $scope.result='bg-danger'; } }); } else { $scope.submitButtonDisabled = false; $scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.'; $scope.result='bg-danger'; } }; var myCenter=new google.maps.LatLng(42.656021, -71.330044); var mapProp = { center:myCenter, zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map=new google.maps.Map(document.getElementById("map"),mapProp); var marker=new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"203 University avenue Lowell, MA, 01854" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); google.maps.event.addDomListener(window, 'load'); }]);<|fim▁end|>
<|file_name|>assets.rs<|end_file_name|><|fim▁begin|>use std::path::{Path, PathBuf}; <|fim▁hole|>}<|fim▁end|>
pub fn get(p: &str) -> PathBuf { Path::new("assets").join(p)
<|file_name|>reservation.ts<|end_file_name|><|fim▁begin|><|fim▁hole|> } } }<|fim▁end|>
namespace lodgist.controllers { export class Reservation { constructor($scope: ng.IScope) {
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig <|fim▁hole|><|fim▁end|>
class BugzConfig(AppConfig): name = 'Bugz'
<|file_name|>StringUtils.java<|end_file_name|><|fim▁begin|>package com.artfulbits.utils; import android.text.TextUtils; import java.io.UnsupportedEncodingException; import java.util.logging.Logger; /** Common string routine. */ public final class StringUtils { /* [ CONSTANTS ] ======================================================================================================================================= */ /** Our own class Logger instance. */ private final static Logger _log = LogEx.getLogger(StringUtils.class); /** Default strings encoding. */ public final static String UTF8 = "UTF-8"; /* [ CONSTRUCTORS ] ==================================================================================================================================== */ /** Hidden constructor. */ private StringUtils() { throw new AssertionError(); } <|fim▁hole|> * Convert string to utf 8 bytes. * * @param value the value to convert * @return the bytes in UTF8 encoding. */ public static byte[] toUtf8Bytes(final String value) { ValidUtils.isEmpty(value, "Expected not null value."); // try to avoid NULL values, better to return empty array byte[] buffer = new byte[]{}; if (!TextUtils.isEmpty(value)) { try { buffer = value.getBytes(StringUtils.UTF8); } catch (final UnsupportedEncodingException e) { _log.severe(LogEx.dump(e)); } } return buffer; } }<|fim▁end|>
/* [ STATIC METHODS ] ================================================================================================================================== */ /**
<|file_name|>ColumnId.ts<|end_file_name|><|fim▁begin|>import { Identifier } from "../"; export class ColumnId extends Identifier<string> { constructor(value: string = Identifier.gen()) { super(value); } public equals(obj: any): boolean { return obj instanceof ColumnId && obj.value === this.value; }<|fim▁hole|>}<|fim▁end|>
<|file_name|>podcastclient.cpp<|end_file_name|><|fim▁begin|>#include "podcastclient.h" QStringList PodcastClient::getFeedsFromSettings() { QStringList resultList = settings.value("feeds").toStringList(); if(resultList.isEmpty()) { QString string = settings.value("feeds").toString(); if(!string.isEmpty()) resultList.push_back(string); } return resultList; } PodcastClient::PodcastClient(QObject *parent) : QObject(parent) { if(settings.value("NumDownloads").isNull()) settings.setValue("NumDownloads",10); if(settings.value("Dest").isNull()) settings.setValue("Dest","."); else { if(!QDir(settings.value("Dest").toString()).exists()) { settings.setValue("Dest",","); } } downloader.setMaxConnections(settings.value("NumDownloads").toInt()); foreach(QString url, getFeedsFromSettings()) { Podcast* podcast = new Podcast(QUrl(url), &downloader, this); podcast->setTargetFolder(QDir(settings.value("Dest").toString())); podcasts.push_back(podcast); connect(podcast,&Podcast::done,this,&PodcastClient::podcastDone); connect(podcast,&Podcast::writingFailed,this,&PodcastClient::podcastWritingFailed); } } bool PodcastClient::downloadAll() { if(podcasts.isEmpty()) { out << "No podcasts in list. Done." << endl; return true; } finishedCtr = 0; foreach(Podcast* podcast, podcasts) { podcast->update(); } return false; } bool PodcastClient::addPodcast(const QUrl &url, const QString &mode) { podcasts.clear(); finishedCtr = 0; if(!url.isValid()) { out << "Invalid URL." << endl; return true; } if(mode=="last" || mode.isEmpty()) { Podcast* podcast = new Podcast(url, &downloader, this); podcasts.push_back(podcast); connect(podcast,&Podcast::done,this,&PodcastClient::podcastDone); podcast->init(true); QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.push_back(url.toString()); settings.setValue("feeds",feeds); return false; } else if(mode=="all") { QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.push_back(url.toString()); settings.setValue("feeds",feeds); return true; } else if(mode=="none") { Podcast* podcast = new Podcast(url, &downloader, this); podcasts.push_back(podcast); connect(podcast,&Podcast::done,this,&PodcastClient::podcastDone); podcast->init(false); QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.push_back(url.toString()); settings.setValue("feeds",feeds); return false; } else { out << "Invalid adding mode: " << mode << endl; out << "Modes are: last, all, none" << endl; return true; } } void PodcastClient::removePodcast(const QUrl &url) { QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.removeAll(url.toString()); if(feeds.isEmpty()) settings.remove("feeds"); else settings.setValue("feeds",feeds); } void PodcastClient::setDest(const QString &dest) { QDir dir(dest); settings.setValue("Dest",dest); settings.sync(); if(!dir.exists()) { out << "Target directory does not exist." << endl; } } QString PodcastClient::getDest() { return settings.value("Dest").toString(); }<|fim▁hole|> void PodcastClient::list() { foreach(QString url, getFeedsFromSettings()) { out << url << endl; } } void PodcastClient::setMaxDownloads(int num) { downloader.setMaxConnections(num); settings.setValue("NumDownloads",num); settings.sync(); } int PodcastClient::getMaxDownloads() { return downloader.getMaxConnections(); } void PodcastClient::podcastDone() { finishedCtr++; if(finishedCtr==podcasts.size()) { settings.sync(); QCoreApplication::exit(0); } } void PodcastClient::podcastWritingFailed() { out << "Aborting downloads..." << endl; foreach(Podcast* podcast, podcasts) { podcast->abort(); } }<|fim▁end|>
<|file_name|>decomposition.py<|end_file_name|><|fim▁begin|># This file is part of MSMTools. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # MSMTools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r"""This module provides matrix-decomposition based functions for the analysis of stochastic matrices Below are the dense implementations for functions specified in api Dense matrices are represented by numpy.ndarrays throughout this module. .. moduleauthor:: B.Trendelkamp-Schroer <benjamin DOT trendelkamp-schroer AT fu-berlin DOT de> """ import numpy as np import numbers import warnings from scipy.linalg import eig, eigh, eigvals, eigvalsh, solve from ...util.exceptions import SpectralWarning, ImaginaryEigenValueWarning from .stationary_vector import stationary_distribution from .assessment import is_reversible def eigenvalues(T, k=None, reversible=False, mu=None): r"""Compute eigenvalues of given transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T reversible : bool, optional Indicate that transition matrix is reversible mu : (d,) ndarray, optional Stationary distribution of T Returns ------- eig : (n,) ndarray, The eigenvalues of T ordered with decreasing absolute value. If k is None then n=d, if k is int then n=k otherwise n is the length of the given tuple of eigenvalue indices. Notes ----- Eigenvalues are computed using the numpy.linalg interface for the corresponding LAPACK routines. If reversible=True the the eigenvalues of the similar symmetric matrix `\sqrt(\mu_i / \mu_j) p_{ij}` will be computed. The precomputed stationary distribution will only be used if reversible=True. """ if reversible: try: evals = eigenvalues_rev(T, k=k, mu=mu) except ValueError: evals = eigvals(T).real # use fallback code but cast to real else: evals = eigvals(T) # nonreversible """Sort by decreasing absolute value""" ind = np.argsort(np.abs(evals))[::-1] evals = evals[ind] if isinstance(k, (list, set, tuple)): try: return [evals[n] for n in k] except IndexError: raise ValueError("given indices do not exist: ", k) elif k is not None: return evals[: k] else: return evals def eigenvalues_rev(T, k=None, mu=None): r"""Compute eigenvalues of reversible transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T mu : (d,) ndarray, optional Stationary distribution of T Returns ------- eig : (n,) ndarray, The eigenvalues of T ordered with decreasing absolute value. If k is None then n=d, if k is int then n=k otherwise n is the length of the given tuple of eigenvalue indices. Raises ------ ValueError If stationary distribution is nonpositive. """ """compute stationary distribution if not given""" if mu is None: mu = stationary_distribution(T) if np.any(mu <= 0): raise ValueError('Cannot symmetrize transition matrix') """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] * T / smu """ symmetric eigenvalue problem """ evals = eigvalsh(S) return evals def eigenvectors(T, k=None, right=True, reversible=False, mu=None): r"""Compute eigenvectors of transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T right : bool, optional If right=True compute right eigenvectors, left eigenvectors otherwise reversible : bool, optional Indicate that transition matrix is reversible mu : (d,) ndarray, optional Stationary distribution of T Returns ------- eigvec : (d, n) ndarray The eigenvectors of T ordered with decreasing absolute value of the corresponding eigenvalue. If k is None then n=d, if k is int then n=k otherwise n is the length of the given tuple of eigenvector indices Notes ----- Eigenvectors are computed using the numpy.linalg interface for the corresponding LAPACK routines. If reversible=True the the eigenvectors of the similar symmetric matrix `\sqrt(\mu_i / \mu_j) p_{ij}` will be used to compute the eigenvectors of T. The precomputed stationary distribution will only be used if reversible=True. """ if reversible: eigvec = eigenvectors_rev(T, right=right, mu=mu) else: eigvec = eigenvectors_nrev(T, right=right) """ Return eigenvectors """ if k is None: return eigvec elif isinstance(k, numbers.Integral): return eigvec[:, 0:k] else: ind = np.asarray(k) return eigvec[:, ind] def eigenvectors_nrev(T, right=True): r"""Compute eigenvectors of transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T right : bool, optional If right=True compute right eigenvectors, left eigenvectors otherwise Returns ------- eigvec : (d, d) ndarray The eigenvectors of T ordered with decreasing absolute value of the corresponding eigenvalue """ if right: val, R = eig(T, left=False, right=True) """ Sorted eigenvalues and left and right eigenvectors. """ perm = np.argsort(np.abs(val))[::-1] # eigval=val[perm] eigvec = R[:, perm] else: val, L = eig(T, left=True, right=False) """ Sorted eigenvalues and left and right eigenvectors. """ perm = np.argsort(np.abs(val))[::-1] # eigval=val[perm] eigvec = L[:, perm] return eigvec def eigenvectors_rev(T, right=True, mu=None): r"""Compute eigenvectors of reversible transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) right : bool, optional If right=True compute right eigenvectors, left eigenvectors otherwise mu : (d,) ndarray, optional Stationary distribution of T Returns ------- eigvec : (d, d) ndarray The eigenvectors of T ordered with decreasing absolute value of the corresponding eigenvalue """ if mu is None: mu = stationary_distribution(T) """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] * T / smu val, eigvec = eigh(S) """Sort eigenvectors""" perm = np.argsort(np.abs(val))[::-1] eigvec = eigvec[:, perm] if right: return eigvec / smu[:, np.newaxis] else: return eigvec * smu[:, np.newaxis] def rdl_decomposition(T, k=None, reversible=False, norm='standard', mu=None): r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : (M, M) ndarray Transition matrix k : int (optional) Number of eigenvector/eigenvalue pairs norm: {'standard', 'reversible', 'auto'} standard: (L'R) = Id, L[:,0] is a probability distribution, the stationary distribution mu of T. Right eigenvectors R have a 2-norm of 1. reversible: R and L are related via L=L[:,0]*R. auto: will be reversible if T is reversible, otherwise standard<|fim▁hole|> Returns ------- R : (M, M) ndarray The normalized (with respect to L) right eigenvectors, such that the column R[:,i] is the right eigenvector corresponding to the eigenvalue w[i], dot(T,R[:,i])=w[i]*R[:,i] D : (M, M) ndarray A diagonal matrix containing the eigenvalues, each repeated according to its multiplicity L : (M, M) ndarray The normalized (with respect to `R`) left eigenvectors, such that the row ``L[i, :]`` is the left eigenvector corresponding to the eigenvalue ``w[i]``, ``dot(L[i, :], T)``=``w[i]*L[i, :]`` Notes ----- If reversible=True the the eigenvalues and eigenvectors of the similar symmetric matrix `\sqrt(\mu_i / \mu_j) p_{ij}` will be used to compute the eigenvalues and eigenvectors of T. The precomputed stationary distribution will only be used if reversible=True. """ # auto-set norm if norm == 'auto': if is_reversible(T): norm = 'reversible' else: norm = 'standard' if reversible: R, D, L = rdl_decomposition_rev(T, norm=norm, mu=mu) else: R, D, L = rdl_decomposition_nrev(T, norm=norm) if reversible or norm == 'reversible': D = D.real if k is None: return R, D, L else: return R[:, 0:k], D[0:k, 0:k], L[0:k, :] def rdl_decomposition_nrev(T, norm='standard'): r"""Decomposition into left and right eigenvectors. Parameters ---------- T : (M, M) ndarray Transition matrix norm: {'standard', 'reversible'} standard: (L'R) = Id, L[:,0] is a probability distribution, the stationary distribution mu of T. Right eigenvectors R have a 2-norm of 1 reversible: R and L are related via L=L[:,0]*R Returns ------- R : (M, M) ndarray The normalized (with respect to L) right eigenvectors, such that the column R[:,i] is the right eigenvector corresponding to the eigenvalue w[i], dot(T,R[:,i])=w[i]*R[:,i] D : (M, M) ndarray A diagonal matrix containing the eigenvalues, each repeated according to its multiplicity L : (M, M) ndarray The normalized (with respect to `R`) left eigenvectors, such that the row ``L[i, :]`` is the left eigenvector corresponding to the eigenvalue ``w[i]``, ``dot(L[i, :], T)``=``w[i]*L[i, :]`` """ d = T.shape[0] w, R = eig(T) """Sort by decreasing magnitude of eigenvalue""" ind = np.argsort(np.abs(w))[::-1] w = w[ind] R = R[:, ind] """Diagonal matrix containing eigenvalues""" D = np.diag(w) # Standard norm: Euclidean norm is 1 for r and LR = I. if norm == 'standard': L = solve(np.transpose(R), np.eye(d)) """l1- normalization of L[:, 0]""" R[:, 0] = R[:, 0] * np.sum(L[:, 0]) L[:, 0] = L[:, 0] / np.sum(L[:, 0]) return R, D, np.transpose(L) # Reversible norm: elif norm == 'reversible': b = np.zeros(d) b[0] = 1.0 A = np.transpose(R) nu = solve(A, b) mu = nu / np.sum(nu) """Ensure that R[:,0] is positive""" R[:, 0] = R[:, 0] / np.sign(R[0, 0]) """Use mu to connect L and R""" L = mu[:, np.newaxis] * R """Compute overlap""" s = np.diag(np.dot(np.transpose(L), R)) """Renormalize left-and right eigenvectors to ensure L'R=Id""" R = R / np.sqrt(s[np.newaxis, :]) L = L / np.sqrt(s[np.newaxis, :]) return R, D, np.transpose(L) else: raise ValueError("Keyword 'norm' has to be either 'standard' or 'reversible'") def rdl_decomposition_rev(T, norm='reversible', mu=None): r"""Decomposition into left and right eigenvectors for reversible transition matrices. Parameters ---------- T : (M, M) ndarray Transition matrix norm: {'standard', 'reversible'} standard: (L'R) = Id, L[:,0] is a probability distribution, the stationary distribution mu of T. Right eigenvectors R have a 2-norm of 1. reversible: R and L are related via L=L[:,0]*R. mu : (M,) ndarray, optional Stationary distribution of T Returns ------- R : (M, M) ndarray The normalized (with respect to L) right eigenvectors, such that the column R[:,i] is the right eigenvector corresponding to the eigenvalue w[i], dot(T,R[:,i])=w[i]*R[:,i] D : (M, M) ndarray A diagonal matrix containing the eigenvalues, each repeated according to its multiplicity L : (M, M) ndarray The normalized (with respect to `R`) left eigenvectors, such that the row ``L[i, :]`` is the left eigenvector corresponding to the eigenvalue ``w[i]``, ``dot(L[i, :], T)``=``w[i]*L[i, :]`` Notes ----- The eigenvalues and eigenvectors of the similar symmetric matrix `\sqrt(\mu_i / \mu_j) p_{ij}` will be used to compute the eigenvalues and eigenvectors of T. The stationay distribution will be computed if no precomputed stationary distribution is given. """ if mu is None: mu = stationary_distribution(T) """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] * T / smu val, eigvec = eigh(S) """Sort eigenvalues and eigenvectors""" perm = np.argsort(np.abs(val))[::-1] val = val[perm] eigvec = eigvec[:, perm] """Diagonal matrix of eigenvalues""" D = np.diag(val) """Right and left eigenvectors""" R = eigvec / smu[:, np.newaxis] L = eigvec * smu[:, np.newaxis] """Ensure that R[:,0] is positive and unity""" tmp = R[0, 0] R[:, 0] = R[:, 0] / tmp """Ensure that L[:, 0] is probability vector""" L[:, 0] = L[:, 0] * tmp if norm == 'reversible': return R, D, L.T elif norm == 'standard': """Standard l2-norm of right eigenvectors""" w = np.diag(np.dot(R.T, R)) sw = np.sqrt(w) """Don't change normalization of eigenvectors for dominant eigenvalue""" sw[0] = 1.0 R = R / sw[np.newaxis, :] L = L * sw[np.newaxis, :] return R, D, L.T else: raise ValueError("Keyword 'norm' has to be either 'standard' or 'reversible'") def timescales(T, tau=1, k=None, reversible=False, mu=None): r"""Compute implied time scales of given transition matrix Parameters ---------- T : (M, M) ndarray Transition matrix tau : int, optional lag time k : int, optional Number of time scales reversible : bool, optional Indicate that transition matirx is reversible mu : (M,) ndarray, optional Stationary distribution of T Returns ------- ts : (N,) ndarray Implied time scales of the transition matrix. If k=None then N=M else N=k Notes ----- If reversible=True the the eigenvalues of the similar symmetric matrix `\sqrt(\mu_i / \mu_j) p_{ij}` will be computed. The precomputed stationary distribution will only be used if reversible=True. """ values = eigenvalues(T, reversible=reversible, mu=mu) """Sort by absolute value""" ind = np.argsort(np.abs(values))[::-1] values = values[ind] if k is None: values = values else: values = values[0:k] """Compute implied time scales""" return timescales_from_eigenvalues(values, tau) def timescales_from_eigenvalues(evals, tau=1): r"""Compute implied time scales from given eigenvalues Parameters ---------- evals : eigenvalues tau : lag time Returns ------- ts : ndarray The implied time scales to the given eigenvalues, in the same order. """ """Check for dominant eigenvalues with large imaginary part""" if not np.allclose(evals.imag, 0.0): warnings.warn('Using eigenvalues with non-zero imaginary part', ImaginaryEigenValueWarning) """Check for multiple eigenvalues of magnitude one""" ind_abs_one = np.isclose(np.abs(evals), 1.0, rtol=0.0, atol=1e-14) if sum(ind_abs_one) > 1: warnings.warn('Multiple eigenvalues with magnitude one.', SpectralWarning) """Compute implied time scales""" ts = np.zeros(len(evals)) """Eigenvalues of magnitude one imply infinite timescale""" ts[ind_abs_one] = np.inf """All other eigenvalues give rise to finite timescales""" ts[np.logical_not(ind_abs_one)] = \ -1.0 * tau / np.log(np.abs(evals[np.logical_not(ind_abs_one)])) return ts<|fim▁end|>
reversible : bool, optional Indicate that transition matrix is reversible mu : (d,) ndarray, optional Stationary distribution of T
<|file_name|>test_discovery.py<|end_file_name|><|fim▁begin|>"""Test config flow.""" from unittest.mock import Mock, patch from homeassistant.components.hassio.handler import HassioAPIError from homeassistant.const import EVENT_HOMEASSISTANT_START from homeassistant.setup import async_setup_component from tests.common import mock_coro async def test_hassio_discovery_startup(hass, aioclient_mock, hassio_client): """Test startup and discovery after event.""" aioclient_mock.get( "http://127.0.0.1/discovery", json={ "result": "ok", "data": { "discovery": [ { "service": "mqtt", "uuid": "test", "addon": "mosquitto", "config": { "broker": "mock-broker", "port": 1883, "username": "mock-user",<|fim▁hole|> } ] }, }, ) aioclient_mock.get( "http://127.0.0.1/addons/mosquitto/info", json={"result": "ok", "data": {"name": "Mosquitto Test"}}, ) assert aioclient_mock.call_count == 0 with patch( "homeassistant.components.mqtt." "config_flow.FlowHandler.async_step_hassio", Mock(return_value=mock_coro({"type": "abort"})), ) as mock_mqtt: hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert aioclient_mock.call_count == 2 assert mock_mqtt.called mock_mqtt.assert_called_with( { "broker": "mock-broker", "port": 1883, "username": "mock-user", "password": "mock-pass", "protocol": "3.1.1", "addon": "Mosquitto Test", } ) async def test_hassio_discovery_startup_done(hass, aioclient_mock, hassio_client): """Test startup and discovery with hass discovery.""" aioclient_mock.get( "http://127.0.0.1/discovery", json={ "result": "ok", "data": { "discovery": [ { "service": "mqtt", "uuid": "test", "addon": "mosquitto", "config": { "broker": "mock-broker", "port": 1883, "username": "mock-user", "password": "mock-pass", "protocol": "3.1.1", }, } ] }, }, ) aioclient_mock.get( "http://127.0.0.1/addons/mosquitto/info", json={"result": "ok", "data": {"name": "Mosquitto Test"}}, ) with patch( "homeassistant.components.hassio.HassIO.update_hass_api", Mock(return_value=mock_coro({"result": "ok"})), ), patch( "homeassistant.components.hassio.HassIO." "get_homeassistant_info", Mock(side_effect=HassioAPIError()), ), patch( "homeassistant.components.mqtt." "config_flow.FlowHandler.async_step_hassio", Mock(return_value=mock_coro({"type": "abort"})), ) as mock_mqtt: await hass.async_start() await async_setup_component(hass, "hassio", {}) await hass.async_block_till_done() assert aioclient_mock.call_count == 2 assert mock_mqtt.called mock_mqtt.assert_called_with( { "broker": "mock-broker", "port": 1883, "username": "mock-user", "password": "mock-pass", "protocol": "3.1.1", "addon": "Mosquitto Test", } ) async def test_hassio_discovery_webhook(hass, aioclient_mock, hassio_client): """Test discovery webhook.""" aioclient_mock.get( "http://127.0.0.1/discovery/testuuid", json={ "result": "ok", "data": { "service": "mqtt", "uuid": "test", "addon": "mosquitto", "config": { "broker": "mock-broker", "port": 1883, "username": "mock-user", "password": "mock-pass", "protocol": "3.1.1", }, }, }, ) aioclient_mock.get( "http://127.0.0.1/addons/mosquitto/info", json={"result": "ok", "data": {"name": "Mosquitto Test"}}, ) with patch( "homeassistant.components.mqtt." "config_flow.FlowHandler.async_step_hassio", Mock(return_value=mock_coro({"type": "abort"})), ) as mock_mqtt: resp = await hassio_client.post( "/api/hassio_push/discovery/testuuid", json={"addon": "mosquitto", "service": "mqtt", "uuid": "testuuid"}, ) await hass.async_block_till_done() assert resp.status == 200 assert aioclient_mock.call_count == 2 assert mock_mqtt.called mock_mqtt.assert_called_with( { "broker": "mock-broker", "port": 1883, "username": "mock-user", "password": "mock-pass", "protocol": "3.1.1", "addon": "Mosquitto Test", } )<|fim▁end|>
"password": "mock-pass", "protocol": "3.1.1", },
<|file_name|>invalid_uncompressed.js<|end_file_name|><|fim▁begin|>var hello = function() {<|fim▁hole|>};<|fim▁end|>
alert("My name is" name)
<|file_name|>admin_reset.py<|end_file_name|><|fim▁begin|>from flask_wtf import Form from wtforms import HiddenField, StringField from wtforms.validators import InputRequired, EqualTo from flask_login import current_user, abort, login_required from flask import request, flash, redirect, render_template import random import bcrypt <|fim▁hole|>class ResetForm(Form): who = HiddenField() confirm_who = StringField('Confirm Username', validators=[InputRequired(), EqualTo('who')]) @blueprint.route("/reset/<what>", methods=["POST"]) @login_required def reset(what): if not current_user.has_permission('reset.{}'.format(what)): abort(403) form = ResetForm(request.form) user = User.objects(name=form.who.data).first() if user is None: abort(401) if form.validate(): if what == 'password': password = ''.join(random.choice('0123456789abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(16)) user.hash = bcrypt.hashpw(password, bcrypt.gensalt()) user.save() return render_template('profile_reset_password_successful.html', user=user, password=password) elif what == 'tfa': user.tfa = False user.tfa_secret = '' user.save() return render_template('profile_reset_tfa_successful.html', user=user) else: abort(401) flash('Error in reset form. Make sure you are typing the confirmation token correctly.', category='alert') return redirect(user.get_profile_url()), 303<|fim▁end|>
from models.user_model import User from .. import blueprint
<|file_name|>gray.js<|end_file_name|><|fim▁begin|>document.addEventListener("DOMContentLoaded", function(event) { if (/android|blackberry|iPhone|iPad|iPod|webOS/i.test(navigator.userAgent) === false) { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { el.parentNode.addEventListener('mouseenter', animateTypeText); el.parentNode.addEventListener('mouseleave', destroyTypeText); }); } else { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { removeClass(el, 'link-descr'); }); } }); var addClass = function(elem, add_class) { elem.setAttribute("class", elem.getAttribute("class") + ' ' + add_class); }; var removeClass = function(elem, rem_class) { var origClass = elem.getAttribute("class"); var remClassRegex = new Regexp("(\\s*)"+rem_class+"(\\s*)"); var classMatch = origClass.match(remClassRegex); var replaceString = ''; if (classMatch[1].length > 0 || classMatch[2].length > 0) { replaceString = ' '; } var newClass = origClass.replace(remClassRegex, replaceString); elem.setAttribute("class", newClass);<|fim▁hole|> var typeArea = document.createElement("span"); typeArea.setAttribute("class", "link-subtext"); elem.insertBefore(typeArea, elem.querySelector("span:last-of-type")); setTimeout(addLetter(elem), 40); }; var addLetter = function(elem) { // if (elem.parentElement.querySelector(":hover") === elem) { var subtextSpan = elem.querySelector(".link-subtext"); var descrText = elem.querySelector(".link-descr").textContent; if (subtextSpan === null) { return; } var currentText = subtextSpan.textContent.slice(0,-1); var currentPos = currentText.length; subtextSpan.textContent = currentText + descrText.slice(currentPos, currentPos+1) + "\u258B"; if (currentText.length < descrText.length) { setTimeout(function(){addLetter(elem)}, 40); } // } }; var destroyTypeText = function() { var elem = this; elem.removeChild(elem.querySelector('.link-subtext')); };<|fim▁end|>
}; var animateTypeText = function() { var elem = this;
<|file_name|>trustedcoin.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # Electrum - Lightweight Bitcoin Client # Copyright (C) 2015 Thomas Voegtlin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import threading import socket import os import re import requests import json from hashlib import sha256 from urlparse import urljoin from urllib import quote from PyQt4.QtGui import * from PyQt4.QtCore import * import electrum from electrum import bitcoin from electrum.bitcoin import * from electrum.mnemonic import Mnemonic from electrum import version from electrum.wallet import Wallet_2of3 from electrum.i18n import _ from electrum.plugins import BasePlugin, run_hook, hook from electrum_gui.qt.util import * from electrum_gui.qt.qrcodewidget import QRCodeWidget from electrum_gui.qt.amountedit import AmountEdit from electrum_gui.qt.main_window import StatusBarButton from decimal import Decimal # signing_xpub is hardcoded so that the wallet can be restored from seed, without TrustedCoin's server signing_xpub = "xpub661MyMwAqRbcGnMkaTx2594P9EDuiEqMq25PM2aeG6UmwzaohgA6uDmNsvSUV8ubqwA3Wpste1hg69XHgjUuCD5HLcEp2QPzyV1HMrPppsL" billing_xpub = "xpub6DTBdtBB8qUmH5c77v8qVGVoYk7WjJNpGvutqjLasNG1mbux6KsojaLrYf2sRhXAVU4NaFuHhbD9SvVPRt1MB1MaMooRuhHcAZH1yhQ1qDU" SEED_PREFIX = version.SEED_PREFIX_2FA class TrustedCoinException(Exception): def __init__(self, message, status_code=0): Exception.__init__(self, message) self.status_code = status_code class TrustedCoinCosignerClient(object): def __init__(self, user_agent=None, base_url='https://api.trustedcoin.com/2/', debug=False): self.base_url = base_url self.debug = debug self.user_agent = user_agent def send_request(self, method, relative_url, data=None): kwargs = {'headers': {}} if self.user_agent: kwargs['headers']['user-agent'] = self.user_agent if method == 'get' and data: kwargs['params'] = data elif method == 'post' and data: kwargs['data'] = json.dumps(data) kwargs['headers']['content-type'] = 'application/json' url = urljoin(self.base_url, relative_url) if self.debug: print '%s %s %s' % (method, url, data) response = requests.request(method, url, **kwargs) if self.debug: print response.text print if response.status_code != 200: message = str(response.text) if response.headers.get('content-type') == 'application/json': r = response.json() if 'message' in r: message = r['message'] raise TrustedCoinException(message, response.status_code) if response.headers.get('content-type') == 'application/json': return response.json() else: return response.text def get_terms_of_service(self, billing_plan='electrum-per-tx-otp'): """ Returns the TOS for the given billing plan as a plain/text unicode string. :param billing_plan: the plan to return the terms for """ payload = {'billing_plan': billing_plan} return self.send_request('get', 'tos', payload) def create(self, xpubkey1, xpubkey2, email, billing_plan='electrum-per-tx-otp'): """ Creates a new cosigner resource. :param xpubkey1: a bip32 extended public key (customarily the hot key) :param xpubkey2: a bip32 extended public key (customarily the cold key) :param email: a contact email :param billing_plan: the billing plan for the cosigner """ payload = { 'email': email, 'xpubkey1': xpubkey1, 'xpubkey2': xpubkey2, 'billing_plan': billing_plan, } return self.send_request('post', 'cosigner', payload) def auth(self, id, otp): """ Attempt to authenticate for a particular cosigner. :param id: the id of the cosigner :param otp: the one time password """ payload = {'otp': otp} return self.send_request('post', 'cosigner/%s/auth' % quote(id), payload) def get(self, id): """ Attempt to authenticate for a particular cosigner. :param id: the id of the cosigner :param otp: the one time password """ return self.send_request('get', 'cosigner/%s' % quote(id)) def sign(self, id, transaction, otp): """ Attempt to authenticate for a particular cosigner. :param id: the id of the cosigner :param transaction: the hex encoded [partially signed] compact transaction to sign :param otp: the one time password """ payload = { 'otp': otp, 'transaction': transaction } return self.send_request('post', 'cosigner/%s/sign' % quote(id), payload) def transfer_credit(self, id, recipient, otp, signature_callback): """ Tranfer a cosigner's credits to another cosigner. :param id: the id of the sending cosigner :param recipient: the id of the recipient cosigner :param otp: the one time password (of the sender) :param signature_callback: a callback that signs a text message using xpubkey1/0/0 returning a compact sig """ payload = { 'otp': otp, 'recipient': recipient, 'timestamp': int(time.time()), } relative_url = 'cosigner/%s/transfer' % quote(id) full_url = urljoin(self.base_url, relative_url) headers = { 'x-signature': signature_callback(full_url + '\n' + json.dumps(payload)) } return self.send_request('post', relative_url, payload, headers) server = TrustedCoinCosignerClient(user_agent="Electrum/" + version.ELECTRUM_VERSION) class Wallet_2fa(Wallet_2of3): wallet_type = '2fa' def get_action(self): xpub1 = self.master_public_keys.get("x1/") xpub2 = self.master_public_keys.get("x2/") xpub3 = self.master_public_keys.get("x3/") if xpub2 is None and not self.storage.get('use_trustedcoin'): return 'show_disclaimer' if xpub2 is None: return 'create_extended_seed' if xpub3 is None: return 'create_remote_key' if not self.accounts: return 'create_accounts' def make_seed(self): return Mnemonic('english').make_seed(num_bits=256, prefix=SEED_PREFIX) def estimated_fee(self, tx): fee = Wallet_2of3.estimated_fee(self, tx) x = run_hook('extra_fee', tx) if x: fee += x return fee def get_tx_fee(self, tx): fee = Wallet_2of3.get_tx_fee(self, tx) x = run_hook('extra_fee', tx) if x: fee += x return fee class Plugin(BasePlugin):<|fim▁hole|> def __init__(self, x, y): BasePlugin.__init__(self, x, y) self.seed_func = lambda x: bitcoin.is_new_seed(x, SEED_PREFIX) self.billing_info = None self.is_billing = False def constructor(self, s): return Wallet_2fa(s) def is_available(self): if not self.wallet: return False if self.wallet.storage.get('wallet_type') == '2fa': return True return False def requires_settings(self): return True def set_enabled(self, enabled): self.wallet.storage.put('use_' + self.name, enabled) def is_enabled(self): if not self.is_available(): return False if self.wallet.master_private_keys.get('x2/'): return False return True def make_long_id(self, xpub_hot, xpub_cold): return bitcoin.sha256(''.join(sorted([xpub_hot, xpub_cold]))) def get_user_id(self): xpub_hot = self.wallet.master_public_keys["x1/"] xpub_cold = self.wallet.master_public_keys["x2/"] long_id = self.make_long_id(xpub_hot, xpub_cold) short_id = hashlib.sha256(long_id).hexdigest() return long_id, short_id def make_xpub(self, xpub, s): _, _, _, c, cK = deserialize_xkey(xpub) cK2, c2 = bitcoin._CKD_pub(cK, c, s) xpub2 = ("0488B21E" + "00" + "00000000" + "00000000").decode("hex") + c2 + cK2 return EncodeBase58Check(xpub2) def make_billing_address(self, num): long_id, short_id = self.get_user_id() xpub = self.make_xpub(billing_xpub, long_id) _, _, _, c, cK = deserialize_xkey(xpub) cK, c = bitcoin.CKD_pub(cK, c, num) address = public_key_to_bc_address( cK ) return address def create_extended_seed(self, wallet, window): seed = wallet.make_seed() if not window.show_seed(seed, None): return if not window.verify_seed(seed, None, self.seed_func): return password = window.password_dialog() wallet.storage.put('seed_version', wallet.seed_version, True) wallet.storage.put('use_encryption', password is not None, True) words = seed.split() n = len(words)/2 wallet.add_cosigner_seed(' '.join(words[0:n]), 'x1/', password) wallet.add_cosigner_xpub(' '.join(words[n:]), 'x2/') msg = [ _('Your wallet file is:') + " %s"%os.path.abspath(wallet.storage.path), _('You need to be online in order to complete the creation of your wallet.'), _('If you generated your seed on an offline computer, click on "%s" to close this window, move your wallet file to an online computer and reopen it with Electrum.') % _('Close'), _('If you are online, click on "%s" to continue.') % _('Next') ] return window.question('\n\n'.join(msg), no_label=_('Close'), yes_label=_('Next')) def show_disclaimer(self, wallet, window): msg = [ _("Two-factor authentication is a service provided by TrustedCoin.") + ' ', _("It uses a multi-signature wallet, where you own 2 of 3 keys.") + ' ', _("The third key is stored on a remote server that signs transactions on your behalf.") + ' ', _("To use this service, you will need a smartphone with Google Authenticator.") + '\n\n', _("A small fee will be charged on each transaction that uses the remote server.") + ' ', _("You may check and modify your billing preferences once the installation is complete.") + '\n\n', _("Note that your coins are not locked in this service.") + ' ', _("You may withdraw your funds at any time and at no cost, without the remote server, by using the 'restore wallet' option with your wallet seed.") + '\n\n', _('The next step will generate the seed of your wallet.') + ' ', _('This seed will NOT be saved in your computer, and it must be stored on paper.') + ' ', _('To be safe from malware, you may want to do this on an offline computer, and move your wallet later to an online computer.') ] icon = QPixmap(':icons/trustedcoin.png') if not window.question(''.join(msg), icon=icon): return False self.wallet = wallet self.set_enabled(True) return True def restore_third_key(self, wallet): long_user_id, short_id = self.get_user_id() xpub3 = self.make_xpub(signing_xpub, long_user_id) wallet.add_master_public_key('x3/', xpub3) @hook def do_clear(self): self.is_billing = False @hook def load_wallet(self, wallet): self.trustedcoin_button = StatusBarButton( QIcon(":icons/trustedcoin.png"), _("Network"), self.settings_dialog) self.window.statusBar().addPermanentWidget(self.trustedcoin_button) self.xpub = self.wallet.master_public_keys.get('x1/') self.user_id = self.get_user_id()[1] t = threading.Thread(target=self.request_billing_info) t.setDaemon(True) t.start() @hook def close_wallet(self): self.window.statusBar().removeWidget(self.trustedcoin_button) @hook def get_wizard_action(self, window, wallet, action): if hasattr(self, action): return getattr(self, action) @hook def installwizard_restore(self, window, storage): if storage.get('wallet_type') != '2fa': return seed = window.enter_seed_dialog("Enter your seed", None, func=self.seed_func) if not seed: return wallet = Wallet_2fa(storage) self.wallet = wallet password = window.password_dialog() wallet.add_seed(seed, password) words = seed.split() n = len(words)/2 wallet.add_cosigner_seed(' '.join(words[0:n]), 'x1/', password) wallet.add_cosigner_seed(' '.join(words[n:]), 'x2/', password) self.restore_third_key(wallet) wallet.create_main_account(password) # disable plugin self.set_enabled(False) return wallet def create_remote_key(self, wallet, window): self.wallet = wallet self.window = window if wallet.storage.get('wallet_type') != '2fa': raise return email = self.accept_terms_of_use(window) if not email: return xpub_hot = wallet.master_public_keys["x1/"] xpub_cold = wallet.master_public_keys["x2/"] # Generate third key deterministically. long_user_id, self.user_id = self.get_user_id() xpub3 = self.make_xpub(signing_xpub, long_user_id) # secret must be sent by the server try: r = server.create(xpub_hot, xpub_cold, email) except socket.error: self.window.show_message('Server not reachable, aborting') return except TrustedCoinException as e: if e.status_code == 409: r = None else: raise e if r is None: otp_secret = None else: otp_secret = r.get('otp_secret') if not otp_secret: self.window.show_message(_('Error')) return _xpub3 = r['xpubkey_cosigner'] _id = r['id'] try: assert _id == self.user_id, ("user id error", _id, self.user_id) assert xpub3 == _xpub3, ("xpub3 error", xpub3, _xpub3) except Exception as e: self.window.show_message(str(e)) return if not self.setup_google_auth(self.window, self.user_id, otp_secret): return self.wallet.add_master_public_key('x3/', xpub3) return True def need_server(self, tx): from electrum.account import BIP32_Account # Detect if the server is needed long_id, short_id = self.get_user_id() xpub3 = self.wallet.master_public_keys['x3/'] for x in tx.inputs_to_sign(): if x[0:2] == 'ff': xpub, sequence = BIP32_Account.parse_xpubkey(x) if xpub == xpub3: return True return False @hook def send_tx(self, tx): self.print_error("twofactor:send_tx") if self.wallet.storage.get('wallet_type') != '2fa': return if not self.need_server(tx): self.print_error("twofactor: xpub3 not needed") self.auth_code = None return self.auth_code = self.auth_dialog() @hook def before_send(self): # request billing info before forming the transaction self.billing_info = None self.waiting_dialog = WaitingDialog(self.window, 'please wait...', self.request_billing_info) self.waiting_dialog.start() self.waiting_dialog.wait() if self.billing_info is None: self.window.show_message('Could not contact server') return True return False @hook def extra_fee(self, tx): if self.billing_info.get('tx_remaining'): return 0 if self.is_billing: return 0 # trustedcoin won't charge if the total inputs is lower than their fee price = int(self.price_per_tx.get(1)) assert price <= 100000 if tx.input_value() < price: self.print_error("not charging for this tx") return 0 return price @hook def make_unsigned_transaction(self, tx): price = self.extra_fee(tx) if not price: return tx.outputs.append(('address', self.billing_info['billing_address'], price)) @hook def sign_transaction(self, tx, password): self.print_error("twofactor:sign") if self.wallet.storage.get('wallet_type') != '2fa': self.print_error("twofactor: aborting") return self.long_user_id, self.user_id = self.get_user_id() if not self.auth_code: return if tx.is_complete(): return tx_dict = tx.as_dict() raw_tx = tx_dict["hex"] try: r = server.sign(self.user_id, raw_tx, self.auth_code) except Exception as e: tx.error = str(e) return self.print_error( "received answer", r) if not r: return raw_tx = r.get('transaction') tx.update(raw_tx) self.print_error("twofactor: is complete", tx.is_complete()) def auth_dialog(self ): d = QDialog(self.window) d.setModal(1) vbox = QVBoxLayout(d) pw = AmountEdit(None, is_int = True) msg = _('Please enter your Google Authenticator code') vbox.addWidget(QLabel(msg)) grid = QGridLayout() grid.setSpacing(8) grid.addWidget(QLabel(_('Code')), 1, 0) grid.addWidget(pw, 1, 1) vbox.addLayout(grid) vbox.addLayout(Buttons(CancelButton(d), OkButton(d))) if not d.exec_(): return return pw.get_amount() def settings_widget(self, window): return EnterButton(_('Settings'), self.settings_dialog) def settings_dialog(self): self.waiting_dialog = WaitingDialog(self.window, 'please wait...', self.request_billing_info, self.show_settings_dialog) self.waiting_dialog.start() def show_settings_dialog(self, success): if not success: self.window.show_message(_('Server not reachable.')) return d = QDialog(self.window) d.setWindowTitle("TrustedCoin Information") d.setMinimumSize(500, 200) vbox = QVBoxLayout(d) hbox = QHBoxLayout() logo = QLabel() logo.setPixmap(QPixmap(":icons/trustedcoin.png")) msg = _('This wallet is protected by TrustedCoin\'s two-factor authentication.') + '<br/>'\ + _("For more information, visit") + " <a href=\"https://api.trustedcoin.com/#/electrum-help\">https://api.trustedcoin.com/#/electrum-help</a>" label = QLabel(msg) label.setOpenExternalLinks(1) hbox.addStretch(10) hbox.addWidget(logo) hbox.addStretch(10) hbox.addWidget(label) hbox.addStretch(10) vbox.addLayout(hbox) vbox.addStretch(10) msg = _('TrustedCoin charges a fee per co-signed transaction. You may pay on each transaction (an extra output will be added to your transaction), or you may purchase prepaid transaction using this dialog.') + '<br/>' label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addStretch(10) grid = QGridLayout() vbox.addLayout(grid) v = self.price_per_tx.get(1) grid.addWidget(QLabel(_("Price per transaction (not prepaid):")), 0, 0) grid.addWidget(QLabel(self.window.format_amount(v) + ' ' + self.window.base_unit()), 0, 1) i = 1 if 10 not in self.price_per_tx: self.price_per_tx[10] = 10 * self.price_per_tx.get(1) for k, v in sorted(self.price_per_tx.items()): if k == 1: continue grid.addWidget(QLabel("Price for %d prepaid transactions:"%k), i, 0) grid.addWidget(QLabel("%d x "%k + self.window.format_amount(v/k) + ' ' + self.window.base_unit()), i, 1) b = QPushButton(_("Buy")) b.clicked.connect(lambda b, k=k, v=v: self.on_buy(k, v, d)) grid.addWidget(b, i, 2) i += 1 n = self.billing_info.get('tx_remaining', 0) grid.addWidget(QLabel(_("Your wallet has %d prepaid transactions.")%n), i, 0) # tranfer button #def on_transfer(): # server.transfer_credit(self.user_id, recipient, otp, signature_callback) # pass #b = QPushButton(_("Transfer")) #b.clicked.connect(on_transfer) #grid.addWidget(b, 1, 2) #grid.addWidget(QLabel(_("Next Billing Address:")), i, 0) #grid.addWidget(QLabel(self.billing_info['billing_address']), i, 1) vbox.addLayout(Buttons(CloseButton(d))) d.exec_() def on_buy(self, k, v, d): d.close() if self.window.pluginsdialog: self.window.pluginsdialog.close() uri = "bitcoin:" + self.billing_info['billing_address'] + "?message=TrustedCoin %d Prepaid Transactions&amount="%k + str(Decimal(v)/100000000) self.is_billing = True self.window.pay_from_URI(uri) self.window.payto_e.setFrozen(True) self.window.message_e.setFrozen(True) self.window.amount_e.setFrozen(True) def request_billing_info(self): billing_info = server.get(self.user_id) billing_address = self.make_billing_address(billing_info['billing_index']) assert billing_address == billing_info['billing_address'] self.billing_info = billing_info self.price_per_tx = dict(self.billing_info['price_per_tx']) return True def accept_terms_of_use(self, window): vbox = QVBoxLayout() window.set_layout(vbox) vbox.addWidget(QLabel(_("Terms of Service"))) tos_e = QTextEdit() tos_e.setReadOnly(True) vbox.addWidget(tos_e) vbox.addWidget(QLabel(_("Please enter your e-mail address"))) email_e = QLineEdit() vbox.addWidget(email_e) vbox.addStretch() accept_button = OkButton(window, _('Accept')) accept_button.setEnabled(False) vbox.addLayout(Buttons(CancelButton(window), accept_button)) def request_TOS(): tos = server.get_terms_of_service() self.TOS = tos window.emit(SIGNAL('twofactor:TOS')) def on_result(): tos_e.setText(self.TOS) window.connect(window, SIGNAL('twofactor:TOS'), on_result) t = threading.Thread(target=request_TOS) t.setDaemon(True) t.start() regexp = r"[^@]+@[^@]+\.[^@]+" email_e.textChanged.connect(lambda: accept_button.setEnabled(re.match(regexp,email_e.text()) is not None)) email_e.setFocus(True) if not window.exec_(): return email = str(email_e.text()) return email def setup_google_auth(self, window, _id, otp_secret): vbox = QVBoxLayout() window.set_layout(vbox) if otp_secret is not None: uri = "otpauth://totp/%s?secret=%s"%('trustedcoin.com', otp_secret) vbox.addWidget(QLabel("Please scan this QR code in Google Authenticator.")) qrw = QRCodeWidget(uri) vbox.addWidget(qrw, 1) msg = _('Then, enter your Google Authenticator code:') else: label = QLabel("This wallet is already registered, but it was never authenticated. To finalize your registration, please enter your Google Authenticator Code. If you do not have this code, delete the wallet file and start a new registration") label.setWordWrap(1) vbox.addWidget(label) msg = _('Google Authenticator code:') hbox = QHBoxLayout() hbox.addWidget(QLabel(msg)) pw = AmountEdit(None, is_int = True) pw.setFocus(True) hbox.addWidget(pw) hbox.addStretch(1) vbox.addLayout(hbox) b = OkButton(window, _('Next')) b.setEnabled(False) vbox.addLayout(Buttons(CancelButton(window), b)) pw.textChanged.connect(lambda: b.setEnabled(len(pw.text())==6)) while True: if not window.exec_(): return False otp = pw.get_amount() try: server.auth(_id, otp) return True except: QMessageBox.information(self.window, _('Message'), _('Incorrect password'), _('OK')) pw.setText('')<|fim▁end|>
wallet = None
<|file_name|>main.js<|end_file_name|><|fim▁begin|>import Vue from 'vue'; import Electron from 'vue-electron'; import Resource from 'vue-resource'; import Router from 'vue-router'; import KeenUI from 'keen-ui'; import 'keen-ui/dist/keen-ui.css'; import App from './App'; import routes from './routes'; Vue.use(Electron); Vue.use(Resource);<|fim▁hole|>Vue.use(Router); Vue.use(KeenUI); Vue.config.debug = true; const router = new Router({ scrollBehavior: () => ({ y: 0 }), routes, }); /* eslint-disable no-new */ new Vue({ router, ...App, }).$mount('#app');<|fim▁end|>
<|file_name|>_document.tsx<|end_file_name|><|fim▁begin|>import React from 'react'; import Document, { Head, Main, NextScript } from 'next/document'; import { ServerStyleSheets } from '@material-ui/core/styles'; import theme from '../components/theme'; export default class MyDocument extends Document { render() { return ( <html lang="en"> <Head> <meta charSet="utf-8" /> <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no" /> {/* PWA primary color */}<|fim▁hole|> <meta name="theme-color" content={theme.palette.primary.main} /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito+Sans:300,300i,400,400i,600,600i,700,700i&display=swap" /> </Head> <body> <Main /> <NextScript /> </body> </html> ); } } MyDocument.getInitialProps = async ctx => { // Resolution order // // On the server: // 1. app.getInitialProps // 2. page.getInitialProps // 3. document.getInitialProps // 4. app.render // 5. page.render // 6. document.render // // On the server with error: // 1. document.getInitialProps // 2. app.render // 3. page.render // 4. document.render // // On the client // 1. app.getInitialProps // 2. page.getInitialProps // 3. app.render // 4. page.render // Render app and page and get the context of the page with collected side effects. const sheets = new ServerStyleSheets(); const originalRenderPage = ctx.renderPage; ctx.renderPage = () => originalRenderPage({ enhanceApp: App => props => sheets.collect(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, // Styles fragment is rendered after the app and page rendering finish. styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()], }; };<|fim▁end|>
<|file_name|>DESEncrypt.java<|end_file_name|><|fim▁begin|>package lm.com.framework.encrypt; import java.io.IOException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class DESEncrypt { private final static String DES = "DES"; /** * des加密 * * @param encryptString * @param key * @return * @throws Exception */ public static String encode(String encryptString, String key) throws Exception { byte[] bt = encrypt(encryptString.getBytes(), key.getBytes()); String strs = new BASE64Encoder().encode(bt); return strs; } /** * des解密 * * @param decryptString * @param key * @return * @throws IOException * @throws Exception */ public static String decode(String decryptString, String key) throws IOException, Exception { if (decryptString == null || decryptString.trim().isEmpty())<|fim▁hole|> return new String(bt); } /** * 根据键值进行加密 */ private static byte[] encrypt(byte[] data, byte[] key) throws Exception { Cipher cipher = cipherInit(data, key, Cipher.ENCRYPT_MODE); return cipher.doFinal(data); } /** * 根据键值进行解密 */ private static byte[] decrypt(byte[] data, byte[] key) throws Exception { Cipher cipher = cipherInit(data, key, Cipher.DECRYPT_MODE); return cipher.doFinal(data); } private static Cipher cipherInit(byte[] data, byte[] key, int cipherValue) throws Exception { /** 生成一个可信任的随机数源 **/ SecureRandom sr = new SecureRandom(); /** 从原始密钥数据创建DESKeySpec对象 **/ DESKeySpec dks = new DESKeySpec(key); /** 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 **/ SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); /** Cipher对象实际完成加密或解密操作 **/ Cipher cipher = Cipher.getInstance(DES); /** 用密钥初始化Cipher对象 **/ cipher.init(cipherValue, securekey, sr); return cipher; } }<|fim▁end|>
return ""; BASE64Decoder decoder = new BASE64Decoder(); byte[] buf = decoder.decodeBuffer(decryptString); byte[] bt = decrypt(buf, key.getBytes());
<|file_name|>ofxdump.cpp<|end_file_name|><|fim▁begin|>/*************************************************************************** ofxdump.cpp ------------------- copyright : (C) 2002 by Benoit Grégoire email : [email protected] ***************************************************************************/ /**@file * \brief Code for ofxdump utility. C++ example code * * ofxdump prints to stdout, in human readable form, everything the library understands about a particular ofx response file, and sends errors to stderr. To know exactly what the library understands about of a particular ofx response file, just call ofxdump on that file. * * ofxdump is meant as both a C++ code example and a developper/debuging tool. It uses every function and every structure of the LibOFX API. By default, WARNING, INFO, ERROR and STATUS messages are enabled. You can change these defaults at the top of ofxdump.cpp * * usage: ofxdump path_to_ofx_file/ofx_filename */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <iostream> #include <iomanip> #include <string> #include "libofx.h" #include <stdio.h> /* for printf() */ #include <config.h> /* Include config constants, e.g., VERSION TF */ #include <errno.h> #include "cmdline.h" /* Gengetopt generated parser */ using namespace std; int ofx_proc_security_cb(struct OfxSecurityData data, void * security_data) { char dest_string[255]; cout<<"ofx_proc_security():\n"; if(data.unique_id_valid==true){ cout<<" Unique ID of the security being traded: "<<data.unique_id<<"\n"; } if(data.unique_id_type_valid==true){ cout<<" Format of the Unique ID: "<<data.unique_id_type<<"\n"; } if(data.secname_valid==true){ cout<<" Name of the security: "<<data.secname<<"\n"; } if(data.ticker_valid==true){ cout<<" Ticker symbol: "<<data.ticker<<"\n"; } if(data.unitprice_valid==true){ cout<<" Price of each unit of the security: "<<data.unitprice<<"\n"; } if(data.date_unitprice_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_unitprice))); cout<<" Date as of which the unitprice is valid: "<<dest_string<<"\n"; } if(data.currency_valid==true){ cout<<" Currency of the unitprice: "<<data.currency<<"\n"; } if(data.memo_valid==true){ cout<<" Extra transaction information (memo): "<<data.memo<<"\n"; } cout<<"\n"; return 0; } int ofx_proc_transaction_cb(struct OfxTransactionData data, void * transaction_data) { char dest_string[255]; cout<<"ofx_proc_transaction():\n"; if(data.account_id_valid==true){ cout<<" Account ID : "<<data.account_id<<"\n"; } if(data.transactiontype_valid==true) { if(data.transactiontype==OFX_CREDIT) strncpy(dest_string, "CREDIT: Generic credit", sizeof(dest_string)); else if (data.transactiontype==OFX_DEBIT) strncpy(dest_string, "DEBIT: Generic debit", sizeof(dest_string)); else if (data.transactiontype==OFX_INT) strncpy(dest_string, "INT: Interest earned or paid (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_DIV) strncpy(dest_string, "DIV: Dividend", sizeof(dest_string)); else if (data.transactiontype==OFX_FEE) strncpy(dest_string, "FEE: FI fee", sizeof(dest_string)); else if (data.transactiontype==OFX_SRVCHG) strncpy(dest_string, "SRVCHG: Service charge", sizeof(dest_string)); else if (data.transactiontype==OFX_DEP) strncpy(dest_string, "DEP: Deposit", sizeof(dest_string)); else if (data.transactiontype==OFX_ATM) strncpy(dest_string, "ATM: ATM debit or credit (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_POS) strncpy(dest_string, "POS: Point of sale debit or credit (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_XFER) strncpy(dest_string, "XFER: Transfer", sizeof(dest_string)); else if (data.transactiontype==OFX_CHECK) strncpy(dest_string, "CHECK: Check", sizeof(dest_string)); else if (data.transactiontype==OFX_PAYMENT) strncpy(dest_string, "PAYMENT: Electronic payment", sizeof(dest_string)); else if (data.transactiontype==OFX_CASH) strncpy(dest_string, "CASH: Cash withdrawal", sizeof(dest_string)); else if (data.transactiontype==OFX_DIRECTDEP) strncpy(dest_string, "DIRECTDEP: Direct deposit", sizeof(dest_string)); else if (data.transactiontype==OFX_DIRECTDEBIT) strncpy(dest_string, "DIRECTDEBIT: Merchant initiated debit", sizeof(dest_string)); else if (data.transactiontype==OFX_REPEATPMT) strncpy(dest_string, "REPEATPMT: Repeating payment/standing order", sizeof(dest_string)); else if (data.transactiontype==OFX_OTHER) strncpy(dest_string, "OTHER: Other", sizeof(dest_string)); else strncpy(dest_string, "Unknown transaction type", sizeof(dest_string)); cout<<" Transaction type: "<<dest_string<<"\n"; } if(data.date_initiated_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_initiated))); cout<<" Date initiated: "<<dest_string<<"\n"; } if(data.date_posted_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_posted))); cout<<" Date posted: "<<dest_string<<"\n"; } if(data.date_funds_available_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_funds_available))); cout<<" Date funds are available: "<<dest_string<<"\n"; } if(data.amount_valid==true){ cout<<" Total money amount: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.amount<<"\n"; } if(data.units_valid==true){ cout<<" # of units: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.units<<"\n"; } if(data.oldunits_valid==true){ cout<<" # of units before split: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.oldunits<<"\n"; } if(data.newunits_valid==true){ cout<<" # of units after split: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.newunits<<"\n"; } if(data.unitprice_valid==true){ cout<<" Unit price: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.unitprice<<"\n"; } if(data.fees_valid==true){ cout<<" Fees: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.fees<<"\n"; } if(data.commission_valid==true){ cout<<" Commission: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.commission<<"\n"; } if(data.fi_id_valid==true){ cout<<" Financial institution's ID for this transaction: "<<data.fi_id<<"\n"; } if(data.fi_id_corrected_valid==true){ cout<<" Financial institution ID replaced or corrected by this transaction: "<<data.fi_id_corrected<<"\n"; } if(data.fi_id_correction_action_valid==true){ cout<<" Action to take on the corrected transaction: "; if (data.fi_id_correction_action==DELETE) cout<<"DELETE\n"; else if (data.fi_id_correction_action==REPLACE) cout<<"REPLACE\n";<|fim▁hole|> cout<<" Investment transaction type: "; if (data.invtransactiontype==OFX_BUYDEBT) strncpy(dest_string, "BUYDEBT (Buy debt security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYMF) strncpy(dest_string, "BUYMF (Buy mutual fund)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYOPT) strncpy(dest_string, "BUYOPT (Buy option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYOTHER) strncpy(dest_string, "BUYOTHER (Buy other security type)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYSTOCK) strncpy(dest_string, "BUYSTOCK (Buy stock))", sizeof(dest_string)); else if (data.invtransactiontype==OFX_CLOSUREOPT) strncpy(dest_string, "CLOSUREOPT (Close a position for an option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_INCOME) strncpy(dest_string, "INCOME (Investment income is realized as cash into the investment account)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_INVEXPENSE) strncpy(dest_string, "INVEXPENSE (Misc investment expense that is associated with a specific security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_JRNLFUND) strncpy(dest_string, "JRNLFUND (Journaling cash holdings between subaccounts within the same investment account)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_MARGININTEREST) strncpy(dest_string, "MARGININTEREST (Margin interest expense)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_REINVEST) strncpy(dest_string, "REINVEST (Reinvestment of income)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_RETOFCAP) strncpy(dest_string, "RETOFCAP (Return of capital)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLDEBT) strncpy(dest_string, "SELLDEBT (Sell debt security. Used when debt is sold, called, or reached maturity)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLMF) strncpy(dest_string, "SELLMF (Sell mutual fund)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLOPT) strncpy(dest_string, "SELLOPT (Sell option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLOTHER) strncpy(dest_string, "SELLOTHER (Sell other type of security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLSTOCK) strncpy(dest_string, "SELLSTOCK (Sell stock)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SPLIT) strncpy(dest_string, "SPLIT (Stock or mutial fund split)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_TRANSFER) strncpy(dest_string, "TRANSFER (Transfer holdings in and out of the investment account)", sizeof(dest_string)); else strncpy(dest_string, "ERROR, this investment transaction type is unknown. This is a bug in ofxdump", sizeof(dest_string)); cout<<dest_string<<"\n"; } if(data.unique_id_valid==true){ cout<<" Unique ID of the security being traded: "<<data.unique_id<<"\n"; } if(data.unique_id_type_valid==true){ cout<<" Format of the Unique ID: "<<data.unique_id_type<<"\n"; } if(data.security_data_valid==true){ ofx_proc_security_cb(*(data.security_data_ptr), NULL ); } if(data.server_transaction_id_valid==true){ cout<<" Server's transaction ID (confirmation number): "<<data.server_transaction_id<<"\n"; } if(data.check_number_valid==true){ cout<<" Check number: "<<data.check_number<<"\n"; } if(data.reference_number_valid==true){ cout<<" Reference number: "<<data.reference_number<<"\n"; } if(data.standard_industrial_code_valid==true){ cout<<" Standard Industrial Code: "<<data.standard_industrial_code<<"\n"; } if(data.payee_id_valid==true){ cout<<" Payee_id: "<<data.payee_id<<"\n"; } if(data.name_valid==true){ cout<<" Name of payee or transaction description: "<<data.name<<"\n"; } if(data.memo_valid==true){ cout<<" Extra transaction information (memo): "<<data.memo<<"\n"; } cout<<"\n"; return 0; }//end ofx_proc_transaction() int ofx_proc_statement_cb(struct OfxStatementData data, void * statement_data) { char dest_string[255]; cout<<"ofx_proc_statement():\n"; if(data.currency_valid==true){ cout<<" Currency: "<<data.currency<<"\n"; } if(data.account_id_valid==true){ cout<<" Account ID: "<<data.account_id<<"\n"; } if(data.date_start_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_start))); cout<<" Start date of this statement: "<<dest_string<<"\n"; } if(data.date_end_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_end))); cout<<" End date of this statement: "<<dest_string<<"\n"; } if(data.ledger_balance_valid==true){ cout<<" Ledger balance: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.ledger_balance<<"\n"; } if(data.ledger_balance_date_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.ledger_balance_date))); cout<<" Ledger balance date: "<<dest_string<<"\n"; } if(data.available_balance_valid==true){ cout<<" Available balance: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.available_balance<<"\n"; } if(data.available_balance_date_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.available_balance_date))); cout<<" Ledger balance date: "<<dest_string<<"\n"; } if(data.marketing_info_valid==true){ cout<<" Marketing information: "<<data.marketing_info<<"\n"; } cout<<"\n"; return 0; }//end ofx_proc_statement() int ofx_proc_account_cb(struct OfxAccountData data, void * account_data) { cout<<"ofx_proc_account():\n"; if(data.account_id_valid==true){ cout<<" Account ID: "<<data.account_id<<"\n"; cout<<" Account name: "<<data.account_name<<"\n"; } if(data.account_type_valid==true){ cout<<" Account type: "; switch(data.account_type){ case OfxAccountData::OFX_CHECKING : cout<<"CHECKING\n"; break; case OfxAccountData::OFX_SAVINGS : cout<<"SAVINGS\n"; break; case OfxAccountData::OFX_MONEYMRKT : cout<<"MONEYMRKT\n"; break; case OfxAccountData::OFX_CREDITLINE : cout<<"CREDITLINE\n"; break; case OfxAccountData::OFX_CMA : cout<<"CMA\n"; break; case OfxAccountData::OFX_CREDITCARD : cout<<"CREDITCARD\n"; break; case OfxAccountData::OFX_INVESTMENT : cout<<"INVESTMENT\n"; break; default: cout<<"ofx_proc_account() WRITEME: This is an unknown account type!"; } } if(data.currency_valid==true){ cout<<" Currency: "<<data.currency<<"\n"; } if (data.bank_id_valid) cout<<" Bank ID: "<<data.bank_id << endl;; if (data.branch_id_valid) cout<<" Branch ID: "<<data.branch_id << endl; if (data.account_number_valid) cout<<" Account #: "<<data.account_number << endl; cout<<"\n"; return 0; }//end ofx_proc_account() int ofx_proc_status_cb(struct OfxStatusData data, void * status_data) { cout<<"ofx_proc_status():\n"; if(data.ofx_element_name_valid==true){ cout<<" Ofx entity this status is relevent to: "<< data.ofx_element_name<<" \n"; } if(data.severity_valid==true){ cout<<" Severity: "; switch(data.severity){ case OfxStatusData::INFO : cout<<"INFO\n"; break; case OfxStatusData::WARN : cout<<"WARN\n"; break; case OfxStatusData::ERROR : cout<<"ERROR\n"; break; default: cout<<"WRITEME: Unknown status severity!\n"; } } if(data.code_valid==true){ cout<<" Code: "<<data.code<<", name: "<<data.name<<"\n Description: "<<data.description<<"\n"; } if(data.server_message_valid==true){ cout<<" Server Message: "<<data.server_message<<"\n"; } cout<<"\n"; return 0; } int main (int argc, char *argv[]) { /** Tell ofxdump what you want it to send to stderr. See messages.cpp for more details */ extern int ofx_PARSER_msg; extern int ofx_DEBUG_msg; extern int ofx_WARNING_msg; extern int ofx_ERROR_msg; extern int ofx_INFO_msg; extern int ofx_STATUS_msg; gengetopt_args_info args_info; /* let's call our cmdline parser */ if (cmdline_parser (argc, argv, &args_info) != 0) exit(1) ; // if (args_info.msg_parser_given) // cout << "The msg_parser option was given!" << endl; // cout << "The flag is " << ( args_info.msg_parser_flag ? "on" : "off" ) << // "." << endl ; args_info.msg_parser_flag ? ofx_PARSER_msg = true : ofx_PARSER_msg = false; args_info.msg_debug_flag ? ofx_DEBUG_msg = true : ofx_DEBUG_msg = false; args_info.msg_warning_flag ? ofx_WARNING_msg = true : ofx_WARNING_msg = false; args_info.msg_error_flag ? ofx_ERROR_msg = true : ofx_ERROR_msg = false; args_info.msg_info_flag ? ofx_INFO_msg = true : ofx_INFO_msg = false; args_info.msg_status_flag ? ofx_STATUS_msg = true : ofx_STATUS_msg; bool skiphelp = false; if(args_info.list_import_formats_given) { skiphelp = true; cout <<"The supported file formats for the 'input-file-format' argument are:"<<endl; for(int i=0; LibofxImportFormatList[i].format!=LAST; i++) { cout <<" "<<LibofxImportFormatList[i].description<<endl; } } LibofxContextPtr libofx_context = libofx_get_new_context(); //char **inputs ; /* unamed options */ //unsigned inputs_num ; /* unamed options number */ if (args_info.inputs_num > 0) { const char* filename = args_info.inputs[0]; ofx_set_statement_cb(libofx_context, ofx_proc_statement_cb, 0); ofx_set_account_cb(libofx_context, ofx_proc_account_cb, 0); ofx_set_transaction_cb(libofx_context, ofx_proc_transaction_cb, 0); ofx_set_security_cb(libofx_context, ofx_proc_security_cb, 0); ofx_set_status_cb(libofx_context, ofx_proc_status_cb, 0); enum LibofxFileFormat file_format = libofx_get_file_format_from_str(LibofxImportFormatList, args_info.import_format_arg); /** @todo currently, only the first file is processed as the library can't deal with more right now.*/ if(args_info.inputs_num > 1) { cout << "Sorry, currently, only the first file is processed as the library can't deal with more right now. The following files were ignored:"<<endl; for ( unsigned i = 1 ; i < args_info.inputs_num ; ++i ) { cout << "file: " << args_info.inputs[i] << endl ; } } libofx_proc_file(libofx_context, args_info.inputs[0], file_format); } else { if ( !skiphelp ) cmdline_parser_print_help(); } return 0; }<|fim▁end|>
else cout<<"ofx_proc_transaction(): This should not happen!\n"; } if(data.invtransactiontype_valid==true){
<|file_name|>metrics.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use prometheus::*; use prometheus_static_metric::*; make_static_metric! { pub label_enum MvccConflictKind { prewrite_write_conflict, rolled_back, commit_lock_not_found, rollback_committed, acquire_pessimistic_lock_conflict, pipelined_acquire_pessimistic_lock_amend_fail, pipelined_acquire_pessimistic_lock_amend_success, } pub label_enum MvccDuplicateCommandKind { prewrite, commit, rollback, acquire_pessimistic_lock, } pub label_enum MvccCheckTxnStatusKind { rollback, update_ts, get_commit_info, pessimistic_rollback, } pub struct MvccConflictCounterVec: IntCounter { "type" => MvccConflictKind, } pub struct MvccDuplicateCmdCounterVec: IntCounter { "type" => MvccDuplicateCommandKind, } pub struct MvccCheckTxnStatusCounterVec: IntCounter { "type" => MvccCheckTxnStatusKind, } } lazy_static! { pub static ref MVCC_VERSIONS_HISTOGRAM: Histogram = register_histogram!( "tikv_storage_mvcc_versions", "Histogram of versions for each key", exponential_buckets(1.0, 2.0, 30).unwrap() ) .unwrap(); pub static ref GC_DELETE_VERSIONS_HISTOGRAM: Histogram = register_histogram!( "tikv_storage_mvcc_gc_delete_versions", "Histogram of versions deleted by gc for each key", exponential_buckets(1.0, 2.0, 30).unwrap() ) .unwrap(); pub static ref CONCURRENCY_MANAGER_LOCK_DURATION_HISTOGRAM: Histogram = register_histogram!( "tikv_concurrency_manager_lock_duration", "Histogram of the duration of lock key in the concurrency manager", exponential_buckets(1e-7, 2.0, 20).unwrap() // 100ns ~ 100ms<|fim▁hole|> MvccConflictCounterVec, "tikv_storage_mvcc_conflict_counter", "Total number of conflict error", &["type"] ) .unwrap() }; pub static ref MVCC_DUPLICATE_CMD_COUNTER_VEC: MvccDuplicateCmdCounterVec = { register_static_int_counter_vec!( MvccDuplicateCmdCounterVec, "tikv_storage_mvcc_duplicate_cmd_counter", "Total number of duplicated commands", &["type"] ) .unwrap() }; pub static ref MVCC_CHECK_TXN_STATUS_COUNTER_VEC: MvccCheckTxnStatusCounterVec = { register_static_int_counter_vec!( MvccCheckTxnStatusCounterVec, "tikv_storage_mvcc_check_txn_status", "Counter of different results of check_txn_status", &["type"] ) .unwrap() }; }<|fim▁end|>
) .unwrap(); pub static ref MVCC_CONFLICT_COUNTER: MvccConflictCounterVec = { register_static_int_counter_vec!(
<|file_name|>index2.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os import mysql.connector import datetime HEADER_TEMPLATE = \ "HTTP/1.1 200 OK\r\n" \ "Server: webhttpd/2.0\r\n" \ "Cache-Control: no-cache, no-store, must-revalidate\r\n" \ "Connection: keep-alive\r\n" \ "Content-Type: text/html; charset=utf-8\r\n" \ "Date: {}\r\n" \ "\r\n" # Connection configuration for MySQL Connection SQL_CONFIG = { "host": "192.168.2.5", "user": "eamars", "password": "931105", "autocommit": True } DB_NAME = "JAV" TABLE_NAME = "GENRE_INDEX_TABLE" COL = """ <html> <head> <title>JAV Genre</title> <style> table { white-space: nowrap; font-family: 'Arial'; margin: 25px auto; border-collapse: collapse; border: 1px solid #eee; border-bottom: 2px solid #00cccc; box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1), 0px 10px 20px rgba(0, 0, 0, 0.05), 0px 20px 20px rgba(0, 0, 0, 0.05), 0px 30px 20px rgba(0, 0, 0, 0.05); } table tr:hover { background: #f4f4f4; } table tr:hover td { color: #555; } table th, table td { color: #999; border: 1px solid #eee; padding: 12px 35px; border-collapse: collapse; } table th {<|fim▁hole|> } table th.last { border-right: none; } h3 { font:1.2em normal Arial,sans-serif; color:#34495E; text-align:center; letter-spacing:-2px; font-size:2.5em; margin:20px 0; } </style> </head> <body> <h3>JAV Genre</h3> <table> <tr> <th>GENRE_ID</th> <th>GENRE_NAME_EN</th> <th>GENRE_NAME_CN</th> <th>GENRE_NAME_TW</th> <th>GENRE_NAME_JA</th> </tr> """ def main(): # Connect to server connection = mysql.connector.connect(**SQL_CONFIG) # Connect to database connection.database = DB_NAME # Create sql sql = "SELECT * FROM `{}`".format(TABLE_NAME) # Execute sql cursor = connection.cursor() cursor.execute(sql) sys.stdout.write(HEADER_TEMPLATE.format(datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"))) sys.stdout.write(COL) for result in cursor: row = "<tr><td><a href='http://www.javmoo.info/cn/genre/{}'>{}</a></td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n".format( result[0], result[0], result[1], result[2], result[3], result[4] ) sys.stdout.write(row) sys.stdout.write("</table></body></html>") sys.stdout.write("\r\n\r\n") if __name__ == "__main__": main()<|fim▁end|>
background: #00cccc; color: #fff; text-transform: uppercase; font-size: 12px;
<|file_name|>callee.go<|end_file_name|><|fim▁begin|>/* Progressive Call Results Example Callee This example demonstrates a callee client that sends data in chunks, as separate progressive call results. A callee may do this to send a large body of data in managable chunks, or to deliver some portion of the result more immediately. In this example, the progressive results are portions of a larger body of text. The final result is a sha256 sum of all the data, allowing the caller to verify that it received everything correcly. */ package main<|fim▁hole|> "context" "crypto/sha256" "encoding/base64" "log" "os" "os/signal" "github.com/gammazero/nexus/v3/client" "github.com/gammazero/nexus/v3/examples/newclient" "github.com/gammazero/nexus/v3/wamp" ) const procedureName = "example.progress.text" func main() { logger := log.New(os.Stdout, "CALLEE> ", 0) // Connect callee client with requested socket type and serialization. callee, err := newclient.NewClient(logger) if err != nil { logger.Fatal(err) } defer callee.Close() // Handler is a closure used to capture the callee, since this is not // provided as a parameter to this callback. handler := func(ctx context.Context, inv *wamp.Invocation) client.InvokeResult { return sendData(ctx, callee, inv.Arguments) } // Register procedure. if err = callee.Register(procedureName, handler, nil); err != nil { logger.Fatal("Failed to register procedure:", err) } logger.Println("Registered procedure", procedureName, "with router") // Wait for CTRL-c or client close while handling remote procedure calls. sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt) select { case <-sigChan: case <-callee.Done(): logger.Print("Router gone, exiting") return // router gone, just exit } if err = callee.Unregister(procedureName); err != nil { logger.Println("Failed to unregister procedure:", err) } } // sendData sends the body of data in chunks of the requested size. The final // result message contains the sha256 hash of the data to allow the caller to // verify that all the data was correctly received. func sendData(ctx context.Context, callee *client.Client, args wamp.List) client.InvokeResult { // Compute the base64-encoded sha256 hash of the data. h := sha256.New() h.Write([]byte(gettysburg)) hash64 := base64.StdEncoding.EncodeToString(h.Sum(nil)) // Put data in buffer to read chunks from. b := bytes.NewBuffer([]byte(gettysburg)) // Get chunksize requested by caller, use default if not set. var chunkSize int if len(args) != 0 { i, _ := wamp.AsInt64(args[0]) chunkSize = int(i) } if chunkSize == 0 { chunkSize = 64 } // Read and send chunks of data until the buffer is empty. for chunk := b.Next(chunkSize); len(chunk) != 0; chunk = b.Next(chunkSize) { // Send a chunk of data. err := callee.SendProgress(ctx, wamp.List{string(chunk)}, nil) if err != nil { // If send failed, return an error saying the call canceled. return client.InvokeResult{Err: wamp.ErrCanceled} } } // Send sha256 hash as final result. return client.InvokeResult{Args: wamp.List{hash64}} } // This is the body of data that is sent in chunks. var gettysburg = `Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.`<|fim▁end|>
import ( "bytes"
<|file_name|>blueprints.js<|end_file_name|><|fim▁begin|>/** * Blueprint API Configuration * (sails.config.blueprints) * * These settings are for the global configuration of blueprint routes and * request options (which impact the behavior of blueprint actions). * * You may also override any of these settings on a per-controller basis * by defining a '_config' key in your controller defintion, and assigning it * a configuration object with overrides for the settings in this file. * A lot of the configuration options below affect so-called "CRUD methods", * or your controllers' `find`, `create`, `update`, and `destroy` actions. * * It's important to realize that, even if you haven't defined these yourself, as long as * a model exists with the same name as the controller, Sails will respond with built-in CRUD * logic in the form of a JSON API, including support for sort, pagination, and filtering. * * For more information on the blueprint API, check out: * http://sailsjs.org/#/documentation/reference/blueprint-api * * For more information on the settings in this file, see: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html * */ module.exports.blueprints = { /*************************************************************************** * * * Action routes speed up the backend development workflow by * * eliminating the need to manually bind routes. When enabled, GET, POST, * * PUT, and DELETE routes will be generated for every one of a controller's * * actions. * * * * If an `index` action exists, additional naked routes will be created for * * it. Finally, all `actions` blueprints support an optional path * * parameter, `id`, for convenience. * * * * `actions` are enabled by default, and can be OK for production-- * * however, if you'd like to continue to use controller/action autorouting * * in a production deployment, you must take great care not to * * inadvertently expose unsafe/unintentional controller logic to GET * * requests. * * * ***************************************************************************/ actions: true, /*************************************************************************** * * * RESTful routes (`sails.config.blueprints.rest`) * * * * REST blueprints are the automatically generated routes Sails uses to * * expose a conventional REST API on top of a controller's `find`, * * `create`, `update`, and `destroy` actions. * * * * For example, a BoatController with `rest` enabled generates the * * following routes: * * ::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * GET /boat/:id? -> BoatController.find * * POST /boat -> BoatController.create * * PUT /boat/:id -> BoatController.update * * DELETE /boat/:id -> BoatController.destroy * * * * `rest` blueprint routes are enabled by default, and are suitable for use * * in a production scenario, as long you take standard security precautions * * (combine w/ policies, etc.) * * * ***************************************************************************/ rest: true, /*************************************************************************** * * * Shortcut routes are simple helpers to provide access to a * * controller's CRUD methods from your browser's URL bar. When enabled, * * GET, POST, PUT, and DELETE routes will be generated for the * * controller's`find`, `create`, `update`, and `destroy` actions. * * * * `shortcuts` are enabled by default, but should be disabled in * * production. * * * ***************************************************************************/ shortcuts: true, /*************************************************************************** * * * An optional mount path for all blueprint routes on a controller, * * including `rest`, `actions`, and `shortcuts`. This allows you to take * * advantage of blueprint routing, even if you need to namespace your API * * methods. * * * * (NOTE: This only applies to blueprint autoroutes, not manual routes from * * `sails.config.routes`) * * * ***************************************************************************/ prefix: '/api/v1.0', /*************************************************************************** * * * Whether to pluralize controller names in blueprint routes. * * * * (NOTE: This only applies to blueprint autoroutes, not manual routes from * * `sails.config.routes`) * * * * For example, REST blueprints for `FooController` with `pluralize` * * enabled: * * GET /foos/:id? *<|fim▁hole|> * * ***************************************************************************/ // pluralize: false, /*************************************************************************** * * * Whether the blueprint controllers should populate model fetches with * * data from other models which are linked by associations * * * * If you have a lot of data in one-to-many associations, leaving this on * * may result in very heavy api calls * * * ***************************************************************************/ // populate: true, /**************************************************************************** * * * Whether to run Model.watch() in the find and findOne blueprint actions. * * Can be overridden on a per-model basis. * * * ****************************************************************************/ // autoWatch: true, /**************************************************************************** * * * The default number of records to show in the response from a "find" * * action. Doubles as the default size of populated arrays if populate is * * true. * * * ****************************************************************************/ // defaultLimit: 30 };<|fim▁end|>
* POST /foos * * PUT /foos/:id? * * DELETE /foos/:id? *
<|file_name|>Worksheet.ts<|end_file_name|><|fim▁begin|>/*! s.js (C) 2019-present SheetJS -- https://sheetjs.com */<|fim▁hole|>export class Worksheet { }<|fim▁end|>
/* vim: set ts=2: */
<|file_name|>GitParentModel.py<|end_file_name|><|fim▁begin|>""" Git Parent model """ from django.db import models class GitParentEntry(models.Model): """ Git Parent """ project = models.ForeignKey('gitrepo.GitProjectEntry', related_name='git_parent_project') parent = models.ForeignKey('gitrepo.GitCommitEntry', related_name='git_parent_commit') son = models.ForeignKey('gitrepo.GitCommitEntry', related_name='git_son_commit') order = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, editable=False)<|fim▁hole|> return u'Parent:{0}, Son:{1}, order:{2}'.format(self.parent.commit_hash, self.son.commit_hash, self.order)<|fim▁end|>
updated_at = models.DateTimeField(auto_now=True, editable=False) def __unicode__(self):
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|><|fim▁hole|> * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you 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. */ /** * Defines relational expressions and rules for converting between calling * conventions. */ package org.apache.calcite.rel.convert; // End package-info.java<|fim▁end|>
/* * Licensed to the Apache Software Foundation (ASF) under one or more
<|file_name|>test_frame_split_iris.py<|end_file_name|><|fim▁begin|>import unittest, time, sys, random sys.path.extend(['.','..','py']) import h2o, h2o_cmd, h2o_glm, h2o_hosts, h2o_import as h2i, h2o_jobs, h2o_exec as h2e DO_POLL = False class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): localhost = h2o.decide_if_localhost() if (localhost): h2o.build_cloud(1,java_heap_GB=4, base_port=54323) else: h2o_hosts.build_cloud_with_hosts(base_port=54323) @classmethod def tearDownClass(cls): h2o.tear_down_cloud() <|fim▁hole|> h2o.beta_features = True csvFilename = 'iris22.csv' csvPathname = 'iris/' + csvFilename hex_key = "iris.hex" parseResult = h2i.import_parse(bucket='smalldata', path=csvPathname, hex_key=hex_key, schema='local', timeoutSecs=10) print "Just split away and see if anything blows up" splitMe = hex_key # don't split for s in range(10): fs = h2o.nodes[0].frame_split(source=splitMe, ratios=0.5) split0_key = fs['split_keys'][0] split1_key = fs['split_keys'][1] split0_rows = fs['split_rows'][0] split1_rows = fs['split_rows'][1] split0_ratio = fs['split_ratios'][0] split1_ratio = fs['split_ratios'][1] print "Iteration", s, "split0_rows:", split0_rows, "split1_rows:", split1_rows splitMe = split0_key if split0_rows<=2: break if __name__ == '__main__': h2o.unit_main()<|fim▁end|>
def test_frame_split(self):
<|file_name|>go-foreign.go<|end_file_name|><|fim▁begin|>// +build matcha package bridge // Go support functions for Objective-C. Note that this // file is copied into and compiled with the generated // bindings. /* #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include "go-foreign.h" */ import "C" import ( "bytes" "encoding/binary" "fmt" "math" "reflect" "runtime" "runtime/debug" "time" ) //export matchaTestFunc func matchaTestFunc() { count := C.MatchaForeignTrackerCount() for i := 0; i < 1000; i++ { z := Nil() a := Bool(true) b := Int64(1234) c := Float64(1.234) d := String("abc") e := Bytes([]byte("def123")) f := Interface(123 + 234i) if !z.IsNil() || a.ToBool() != true || b.ToInt64() != 1234 || c.ToFloat64() != 1.234 || d.ToString() != "abc" || !bytes.Equal(e.ToBytes(), []byte("def123")) || f.ToInterface() != 123+234i { panic("Primitive mismatch") } arr := Array(z, a, b, c, d, e, f) arr2 := arr.ToArray() z = arr2[0] a = arr2[1] b = arr2[2] c = arr2[3] d = arr2[4] e = arr2[5] f = arr2[6] if !z.IsNil() || a.ToBool() != true || b.ToInt64() != 1234 || c.ToFloat64() != 1.234 || d.ToString() != "abc" || !bytes.Equal(e.ToBytes(), []byte("def123")) || f.ToInterface() != 123+234i { panic("Array mismatch") } runtime.GC() } // bridge := Bridge("a") // fmt.Println("matchaTestFunc() - Bridge:", bridge) debug.FreeOSMemory() time.Sleep(time.Second) newCount := C.MatchaForeignTrackerCount() fmt.Println("count", count, newCount) if math.Abs(float64(count-newCount)) > 1 { // Allow some leeway cause finalizer acts weirdly... panic("Count mismatch") } } var bridgeCache = map[string]*Value{} var untrackChan = make(chan int64, 20) func init() { go func() { runtime.LockOSThread() for i := range untrackChan { C.MatchaForeignUntrack(C.FgnRef(i)) } runtime.UnlockOSThread() }() } type Value struct { ref int64 } func newValue(ref C.FgnRef) *Value { v := &Value{ref: int64(ref)} runtime.SetFinalizer(v, func(a *Value) { untrackChan <- a.ref }) return v } func (v *Value) _ref() C.FgnRef { return C.FgnRef(v.ref) } func Bridge(a string) *Value { if b, ok := bridgeCache[a]; ok { return b } cstr := cString(a) b := newValue(C.MatchaForeignBridge(cstr)) bridgeCache[a] = b return b } func Nil() *Value { return newValue(C.MatchaForeignNil()) } func (v *Value) IsNil() bool { defer runtime.KeepAlive(v) return bool(C.MatchaForeignIsNil(v._ref())) } func Bool(v bool) *Value { return newValue(C.MatchaForeignBool(C.bool(v))) } func (v *Value) ToBool() bool { defer runtime.KeepAlive(v) return bool(C.MatchaForeignToBool(v._ref())) } func Int64(v int64) *Value { return newValue(C.MatchaForeignInt64(C.int64_t(v))) } func (v *Value) ToInt64() int64 { defer runtime.KeepAlive(v) return int64(C.MatchaForeignToInt64(v._ref())) } func Float64(v float64) *Value { return newValue(C.MatchaForeignFloat64(C.double(v))) } func (v *Value) ToFloat64() float64 { defer runtime.KeepAlive(v) return float64(C.MatchaForeignToFloat64(v._ref())) } func String(v string) *Value { cstr := cString(v) return newValue(C.MatchaForeignString(cstr)) } func (v *Value) ToString() string { defer runtime.KeepAlive(v) buf := C.MatchaForeignToString(v._ref()) return goString(buf) } func Bytes(v []byte) *Value { cbytes := cBytes(v) return newValue(C.MatchaForeignBytes(cbytes)) } func (v *Value) ToBytes() []byte { defer runtime.KeepAlive(v) buf := C.MatchaForeignToBytes(v._ref()) return goBytes(buf) } func Interface(v interface{}) *Value { // Start with a go value. // Reflect on it. rv := reflect.ValueOf(v) // Track it, turning it into a goref. ref := matchaGoTrack(rv) // Wrap the goref in an foreign object, returning a foreign ref. return newValue(C.MatchaForeignGoRef(ref)) } func (v *Value) ToInterface() interface{} { defer runtime.KeepAlive(v) // Start with a foreign ref, referring to a foreign value wrapping a go ref. // Get the goref. ref := C.MatchaForeignToGoRef(v._ref()) // Get the go object, and unreflect. return matchaGoGet(ref).Interface() } func Array(a ...*Value) *Value { defer runtime.KeepAlive(a) ref := C.MatchaForeignArray(cArray2(a)) return newValue(ref) } func (v *Value) ToArray() []*Value { // TODO(KD): Untested.... defer runtime.KeepAlive(v) buf := C.MatchaForeignToArray(v._ref()) return goArray2(buf) } // Call accepts `nil` in its variadic arguments func (v *Value) Call(s string, args ...*Value) *Value { defer runtime.KeepAlive(v) defer runtime.KeepAlive(args) return newValue(C.MatchaForeignCall(v._ref(), cString(s), cArray2(args))) } func cArray(v []reflect.Value) C.CGoBuffer { var cstr C.CGoBuffer if len(v) == 0 { cstr = C.CGoBuffer{} } else { buf := new(bytes.Buffer) for _, i := range v { goref := matchaGoTrack(i) err := binary.Write(buf, binary.LittleEndian, goref) if err != nil { fmt.Println("binary.Write failed:", err) } } cstr = C.CGoBuffer{ ptr: C.CBytes(buf.Bytes()), len: C.int64_t(len(buf.Bytes())), } } return cstr } func cArray2(v []*Value) C.CGoBuffer {<|fim▁hole|> var cstr C.CGoBuffer if len(v) == 0 { cstr = C.CGoBuffer{} } else { buf := new(bytes.Buffer) for _, i := range v { foreignRef := i._ref() err := binary.Write(buf, binary.LittleEndian, foreignRef) if err != nil { fmt.Println("binary.Write failed:", err) } } cstr = C.CGoBuffer{ ptr: C.CBytes(buf.Bytes()), len: C.int64_t(len(buf.Bytes())), } } return cstr } func cBytes(v []byte) C.CGoBuffer { var cstr C.CGoBuffer if len(v) == 0 { cstr = C.CGoBuffer{} } else { cstr = C.CGoBuffer{ ptr: C.CBytes(v), len: C.int64_t(len(v)), } } return cstr } func cString(v string) C.CGoBuffer { var cstr C.CGoBuffer if len(v) == 0 { cstr = C.CGoBuffer{} } else { cstr = C.CGoBuffer{ ptr: C.CBytes([]byte(v)), len: C.int64_t(len(v)), } } return cstr } func goArray(buf C.CGoBuffer) []reflect.Value { defer C.free(buf.ptr) gorefs := make([]int64, buf.len/8) err := binary.Read(bytes.NewBuffer(C.GoBytes(buf.ptr, C.int(buf.len))), binary.LittleEndian, gorefs) if err != nil { panic(err) } rvs := []reflect.Value{} for _, i := range gorefs { rv := matchaGoGet(C.GoRef(i)) rvs = append(rvs, rv) } return rvs } func goArray2(buf C.CGoBuffer) []*Value { defer C.free(buf.ptr) fgnRef := make([]int64, buf.len/8) err := binary.Read(bytes.NewBuffer(C.GoBytes(buf.ptr, C.int(buf.len))), binary.LittleEndian, fgnRef) if err != nil { panic(err) } rvs := []*Value{} for _, i := range fgnRef { rv := newValue(C.FgnRef(i)) rvs = append(rvs, rv) } return rvs } func goString(buf C.CGoBuffer) string { defer C.free(buf.ptr) str := C.GoBytes(buf.ptr, C.int(buf.len)) return string(str) } func goBytes(buf C.CGoBuffer) []byte { defer C.free(buf.ptr) return C.GoBytes(buf.ptr, C.int(buf.len)) }<|fim▁end|>
<|file_name|>join.js<|end_file_name|><|fim▁begin|>var assert = require('assert'); var R = require('..'); describe('join', function() { it("concatenates a list's elements to a string, with an seperator string between elements", function() {<|fim▁hole|><|fim▁end|>
var list = [1, 2, 3, 4]; assert.strictEqual(R.join('~', list), '1~2~3~4'); }); });
<|file_name|>ShippingDetails.java<|end_file_name|><|fim▁begin|>package com.mmm.product.domain; import java.io.Serializable; public class ShippingDetails implements Serializable{ <|fim▁hole|> private static final long serialVersionUID = 5941389959992371612L; }<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from graph.graph_server import GraphServer<|fim▁hole|>__all__ = ['GraphServer']<|fim▁end|>
<|file_name|>ds_tc_resnet_test.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for ds_tc_resnet model in session mode.""" import numpy as np from kws_streaming.layers import test_utils from kws_streaming.layers.compat import tf from kws_streaming.layers.compat import tf1 from kws_streaming.layers.modes import Modes from kws_streaming.models import utils import kws_streaming.models.ds_tc_resnet as ds_tc_resnet from kws_streaming.train import inference class DsTcResnetTest(tf.test.TestCase): """Test ds_tc_resnet model in non streaming and streaming modes.""" def setUp(self): super(DsTcResnetTest, self).setUp() config = tf1.ConfigProto() config.gpu_options.allow_growth = True self.sess = tf1.Session(config=config) tf1.keras.backend.set_session(self.sess) tf.keras.backend.set_learning_phase(0) test_utils.set_seed(123) self.params = utils.ds_tc_resnet_model_params(True) self.model = ds_tc_resnet.model(self.params) self.model.summary() self.input_data = np.random.rand(self.params.batch_size, self.params.desired_samples) # run non streaming inference self.non_stream_out = self.model.predict(self.input_data) def test_ds_tc_resnet_stream(self): """Test for tf streaming with internal state.""" # prepare tf streaming model model_stream = utils.to_streaming_inference( self.model, self.params, Modes.STREAM_INTERNAL_STATE_INFERENCE) model_stream.summary() # run streaming inference stream_out = inference.run_stream_inference_classification( self.params, model_stream, self.input_data) self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5) def test_ds_tc_resnet_stream_tflite(self): """Test for tflite streaming with external state.""" tflite_streaming_model = utils.model_to_tflite( self.sess, self.model, self.params, Modes.STREAM_EXTERNAL_STATE_INFERENCE)<|fim▁hole|> # before processing new test sequence we reset model state inputs = [] for detail in interpreter.get_input_details(): inputs.append(np.zeros(detail['shape'], dtype=np.float32)) stream_out = inference.run_stream_inference_classification_tflite( self.params, interpreter, self.input_data, inputs) self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5) if __name__ == '__main__': tf1.disable_eager_execution() tf.test.main()<|fim▁end|>
interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model) interpreter.allocate_tensors()
<|file_name|>DBGlobals.java<|end_file_name|><|fim▁begin|>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database.parse.util; import almonds.Parse; import almonds.ParseObject; import database.parse.tables.ParsePhenomena; import database.parse.tables.ParseSensor; import java.net.URI; /** * * @author jried31 */ public class DBGlobals { static public String TABLE_PHENOMENA="tester"; static public String TABLE_SENSOR="Sensor"; public static String URL_GOOGLE_SEARCH="http://suggestqueries.google.com/complete/search?client=firefox&hl=en&q=WORD"; //http://clients1.google.com/complete/search?noLabels=t&client=web&q=WORD"; public static void InitializeParse(){ //App Ids for Connecting to the Parse DB Parse.initialize("jEciFYpTp2b1XxHuIkmAs3yaP70INpkBDg9WdTl9", //Application ID "aPEXcVv80kHwfVJK1WEKWckePkWxYNEXBovIR6d5"); //Rest API Key <|fim▁hole|><|fim▁end|>
} }
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client from django.core.urlresolvers import reverse from django.contrib.auth.models import Permission from django_webtest import WebTest from purl import URL from oscar.core.compat import get_user_model User = get_user_model() def add_permissions(user, permissions): """ Grant permissions to the passed user :param permissions: e.g. ['partner.dashboard_access'] """ for permission in permissions: app_label, __, codename = permission.partition('.') perm = Permission.objects.get(content_type__app_label=app_label, codename=codename) user.user_permissions.add(perm) class WebTestCase(WebTest): is_staff = False is_anonymous = False is_superuser = False username = 'testuser' email = '[email protected]' password = 'somefancypassword' permissions = [] def setUp(self): self.user = None if not self.is_anonymous: self.user = self.create_user( self.username, self.email, self.password) self.user.is_staff = self.is_staff add_permissions(self.user, self.permissions) self.user.save() def create_user(self, username=None, email=None, password=None): """ Create a user for use in a test. As usernames are optional in newer versions of Django, it only sets it if exists. """ kwargs = {'email': email, 'password': password} if 'username' in User._meta.get_all_field_names(): kwargs['username'] = username return User.objects.create_user(**kwargs) def get(self, url, **kwargs): kwargs.setdefault('user', self.user) return self.app.get(url, **kwargs) def post(self, url, **kwargs): kwargs.setdefault('user', self.user) return self.app.post(url, **kwargs) # Custom assertions def assertIsRedirect(self, response, expected_url=None): self.assertTrue(response.status_code in ( http_client.FOUND, http_client.MOVED_PERMANENTLY)) if expected_url: location = URL.from_string(response['Location']) self.assertEqual(expected_url, location.path()) def assertRedirectsTo(self, response, url_name): self.assertTrue(str(response.status_code).startswith('3')) location = response.headers['Location'] redirect_path = location.replace('http://localhost:80', '') self.assertEqual(reverse(url_name), redirect_path) def assertNoAccess(self, response): self.assertContext(response) self.assertTrue(response.status_code in (http_client.NOT_FOUND,<|fim▁hole|> self.assertIsRedirect(response) location = response['Location'].replace('http://testserver', '') self.assertEqual(location, reverse(name, kwargs=kwargs)) def assertIsOk(self, response): self.assertEqual(http_client.OK, response.status_code) def assertContext(self, response): self.assertTrue(response.context is not None, 'No context was returned') def assertInContext(self, response, key): self.assertContext(response) self.assertTrue(key in response.context, "Context should contain a variable '%s'" % key)<|fim▁end|>
http_client.FORBIDDEN)) def assertRedirectUrlName(self, response, name, kwargs=None):
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from distutils.core import setup setup( name = 'pydouban', version = '1.0.0',<|fim▁hole|> url = 'http://i.shiao.org/a/pydouban', packages = ['pydouban'], )<|fim▁end|>
description = 'Lightweight Python Douban API Library', author = 'Marvour', author_email = '[email protected]', license = 'BSD License',
<|file_name|>vaesenc.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vaesenc_1() { run_test(&Instruction { mnemonic: Mnemonic::VAESENC, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM2)), operand3: Some(Direct(XMM6)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 105, 220, 198], OperandSize::Dword)<|fim▁hole|>fn vaesenc_2() { run_test(&Instruction { mnemonic: Mnemonic::VAESENC, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM7)), operand3: Some(Indirect(EDI, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 65, 220, 7], OperandSize::Dword) } fn vaesenc_3() { run_test(&Instruction { mnemonic: Mnemonic::VAESENC, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: Some(Direct(XMM0)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 73, 220, 200], OperandSize::Qword) } fn vaesenc_4() { run_test(&Instruction { mnemonic: Mnemonic::VAESENC, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM4)), operand3: Some(IndirectScaledIndexedDisplaced(RDX, RAX, Two, 1425141855, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 89, 220, 188, 66, 95, 240, 241, 84], OperandSize::Qword) }<|fim▁end|>
}
<|file_name|>unit_graph.rs<|end_file_name|><|fim▁begin|>//! Tests for --unit-graph option. use cargo_test_support::project; use cargo_test_support::registry::Package; #[cargo_test] fn gated() { let p = project().file("src/lib.rs", "").build(); p.cargo("build --unit-graph") .with_status(101) .with_stderr( "\ [ERROR] the `--unit-graph` flag is unstable[..] See [..] See [..] ", ) .run(); } #[cargo_test] fn simple() { Package::new("a", "1.0.0") .dep("b", "1.0") .feature("feata", &["b/featb"]) .publish(); Package::new("b", "1.0.0") .dep("c", "1.0") .feature("featb", &["c/featc"]) .publish(); Package::new("c", "1.0.0").feature("featc", &[]).publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] a = "1.0" "#, ) .file("src/lib.rs", "") .build(); p.cargo("build --features a/feata --unit-graph -Zunstable-options") .masquerade_as_nightly_cargo() .with_json( r#"{ "version": 1, "units": [ { "pkg_id": "a 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "a", "src_path": "[..]/a-1.0.0/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev", "opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2, "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [ "feata" ], "dependencies": [ { "index": 1, "extern_crate_name": "b", "public": false, "noprelude": false } ] }, { "pkg_id": "b 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "b", "src_path": "[..]/b-1.0.0/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev", "opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2, "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [ "featb" ], "dependencies": [ { "index": 2, "extern_crate_name": "c", "public": false, "noprelude": false } ] }, { "pkg_id": "c 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "c", "src_path": "[..]/c-1.0.0/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev", "opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2, "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [ "featc" ], "dependencies": [] }, { "pkg_id": "foo 0.1.0 (path+file://[..]/foo)", "target": { "kind": [ "lib" ], "crate_types": [ "lib" ], "name": "foo", "src_path": "[..]/foo/src/lib.rs", "edition": "2015", "doctest": true }, "profile": { "name": "dev",<|fim▁hole|> "debug_assertions": true, "overflow_checks": true, "rpath": false, "incremental": false, "panic": "unwind" }, "platform": null, "mode": "build", "features": [], "dependencies": [ { "index": 0, "extern_crate_name": "a", "public": false, "noprelude": false } ] } ], "roots": [3] } "#, ) .run(); }<|fim▁end|>
"opt_level": "0", "lto": "false", "codegen_units": null, "debuginfo": 2,
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Support for MQTT vacuums. For more details about this platform, please refer to the documentation at https://www.home-assistant.io/components/vacuum.mqtt/ """ import logging import voluptuous as vol from homeassistant.components.vacuum import DOMAIN from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH from homeassistant.components.mqtt.discovery import ( MQTT_DISCOVERY_NEW, clear_discovery_hash, ) from homeassistant.helpers.dispatcher import async_dispatcher_connect from .schema import CONF_SCHEMA, LEGACY, STATE, MQTT_VACUUM_SCHEMA from .schema_legacy import PLATFORM_SCHEMA_LEGACY, async_setup_entity_legacy from .schema_state import PLATFORM_SCHEMA_STATE, async_setup_entity_state _LOGGER = logging.getLogger(__name__) def validate_mqtt_vacuum(value): """Validate MQTT vacuum schema.""" schemas = {LEGACY: PLATFORM_SCHEMA_LEGACY, STATE: PLATFORM_SCHEMA_STATE}<|fim▁hole|> PLATFORM_SCHEMA = vol.All( MQTT_VACUUM_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA), validate_mqtt_vacuum ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up MQTT vacuum through configuration.yaml.""" await _async_setup_entity(config, async_add_entities, discovery_info) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up MQTT vacuum dynamically through MQTT discovery.""" async def async_discover(discovery_payload): """Discover and add a MQTT vacuum.""" try: discovery_hash = discovery_payload.pop(ATTR_DISCOVERY_HASH) config = PLATFORM_SCHEMA(discovery_payload) await _async_setup_entity( config, async_add_entities, config_entry, discovery_hash ) except Exception: if discovery_hash: clear_discovery_hash(hass, discovery_hash) raise async_dispatcher_connect( hass, MQTT_DISCOVERY_NEW.format(DOMAIN, "mqtt"), async_discover ) async def _async_setup_entity( config, async_add_entities, config_entry, discovery_hash=None ): """Set up the MQTT vacuum.""" setup_entity = {LEGACY: async_setup_entity_legacy, STATE: async_setup_entity_state} await setup_entity[config[CONF_SCHEMA]]( config, async_add_entities, config_entry, discovery_hash )<|fim▁end|>
return schemas[value[CONF_SCHEMA]](value)
<|file_name|>.eslintrc.js<|end_file_name|><|fim▁begin|>module.exports = { "env": {<|fim▁hole|> "commonjs": true, "es6": true, "jasmine" : true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "no-mixed-spaces-and-tabs": [2, "smart-tabs"], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };<|fim▁end|>
"browser": true,
<|file_name|>MusicFile.java<|end_file_name|><|fim▁begin|>package com.mobisys.musicplayer.model; import android.os.Parcel; import android.os.Parcelable; /** * Created by Govinda P on 6/3/2016. */ public class MusicFile implements Parcelable { private String title; private String album; private String id; private String singer; private String path; public MusicFile() { } public MusicFile(String title, String album, String id, String singer, String path) { this.title = title; this.album = album; this.id = id; this.singer = singer; this.path = path; } protected MusicFile(Parcel in) { title = in.readString(); album = in.readString(); id = in.readString(); singer = in.readString(); path=in.readString(); }<|fim▁hole|> public MusicFile createFromParcel(Parcel in) { return new MusicFile(in); } @Override public MusicFile[] newArray(int size) { return new MusicFile[size]; } }; public String getTitle() { return title; } public String getAlbum() { return album; } public String getId() { return id; } public String getSinger() { return singer; } public void setTitle(String title) { this.title = title; } public void setAlbum(String album) { this.album = album; } public void setId(String id) { this.id = id; } public void setSinger(String singer) { this.singer = singer; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "MusicFile{" + "title='" + title + '\'' + ", album='" + album + '\'' + ", id='" + id + '\'' + ", singer='" + singer + '\'' + ", path='" + path + '\'' + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(album); dest.writeString(id); dest.writeString(singer); dest.writeString(path); } }<|fim▁end|>
public static final Creator<MusicFile> CREATOR = new Creator<MusicFile>() { @Override
<|file_name|>regress-373827-01.js<|end_file_name|><|fim▁begin|>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var gTestfile = 'regress-373827-01.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 373827; var summary = 'Do not assert: OBJ_GET_CLASS(cx, obj)->flags & JSCLASS_HAS_PRIVATE'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); let ([] = [{x: function(){}}]) { };<|fim▁hole|> reportCompare(expect, actual, summary); exitFunc ('test'); }<|fim▁end|>
<|file_name|>trainergui.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'trainergui.ui' # # Created: Tue May 24 14:29:31 2016 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(401, 686) MainWindow.setAutoFillBackground(False)<|fim▁hole|> self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.sliderGoal = QtGui.QSlider(self.centralwidget) self.sliderGoal.setGeometry(QtCore.QRect(340, 20, 31, 611)) self.sliderGoal.setMaximum(990000) self.sliderGoal.setSingleStep(10000) self.sliderGoal.setPageStep(100000) self.sliderGoal.setOrientation(QtCore.Qt.Vertical) self.sliderGoal.setInvertedAppearance(False) self.sliderGoal.setInvertedControls(False) self.sliderGoal.setTickPosition(QtGui.QSlider.TicksBothSides) self.sliderGoal.setTickInterval(10000) self.sliderGoal.setObjectName(_fromUtf8("sliderGoal")) self.frame = QtGui.QFrame(self.centralwidget) self.frame.setGeometry(QtCore.QRect(30, 20, 281, 611)) self.frame.setFrameShape(QtGui.QFrame.StyledPanel) self.frame.setFrameShadow(QtGui.QFrame.Raised) self.frame.setObjectName(_fromUtf8("frame")) self.txtMinPulse = QtGui.QLineEdit(self.frame) self.txtMinPulse.setGeometry(QtCore.QRect(110, 310, 141, 27)) self.txtMinPulse.setObjectName(_fromUtf8("txtMinPulse")) self.txtMaxSensor = QtGui.QLineEdit(self.frame) self.txtMaxSensor.setGeometry(QtCore.QRect(110, 400, 141, 27)) self.txtMaxSensor.setObjectName(_fromUtf8("txtMaxSensor")) self.label_3 = QtGui.QLabel(self.frame) self.label_3.setGeometry(QtCore.QRect(16, 310, 91, 21)) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(_fromUtf8("label_3")) self.label_4 = QtGui.QLabel(self.frame) self.label_4.setGeometry(QtCore.QRect(16, 340, 91, 21)) self.label_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_4.setObjectName(_fromUtf8("label_4")) self.label_5 = QtGui.QLabel(self.frame) self.label_5.setGeometry(QtCore.QRect(16, 370, 91, 21)) self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_5.setObjectName(_fromUtf8("label_5")) self.label_2 = QtGui.QLabel(self.frame) self.label_2.setGeometry(QtCore.QRect(40, 280, 67, 21)) self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_2.setObjectName(_fromUtf8("label_2")) self.txtMaxPulse = QtGui.QLineEdit(self.frame) self.txtMaxPulse.setGeometry(QtCore.QRect(110, 340, 141, 27)) self.txtMaxPulse.setObjectName(_fromUtf8("txtMaxPulse")) self.chkCalibrated = QtGui.QCheckBox(self.frame) self.chkCalibrated.setGeometry(QtCore.QRect(30, 430, 97, 22)) self.chkCalibrated.setLayoutDirection(QtCore.Qt.RightToLeft) self.chkCalibrated.setObjectName(_fromUtf8("chkCalibrated")) self.txtMaxGoal = QtGui.QLineEdit(self.frame) self.txtMaxGoal.setGeometry(QtCore.QRect(110, 280, 141, 27)) self.txtMaxGoal.setObjectName(_fromUtf8("txtMaxGoal")) self.txtMinSensor = QtGui.QLineEdit(self.frame) self.txtMinSensor.setGeometry(QtCore.QRect(110, 370, 141, 27)) self.txtMinSensor.setObjectName(_fromUtf8("txtMinSensor")) self.label = QtGui.QLabel(self.frame) self.label.setGeometry(QtCore.QRect(40, 250, 67, 21)) self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label.setObjectName(_fromUtf8("label")) self.cmbSmoothing = QtGui.QComboBox(self.frame) self.cmbSmoothing.setEnabled(False) self.cmbSmoothing.setGeometry(QtCore.QRect(110, 200, 141, 27)) self.cmbSmoothing.setObjectName(_fromUtf8("cmbSmoothing")) self.label_8 = QtGui.QLabel(self.frame) self.label_8.setEnabled(False) self.label_8.setGeometry(QtCore.QRect(16, 170, 91, 21)) self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_8.setObjectName(_fromUtf8("label_8")) self.txtMaxSpeed = QtGui.QLineEdit(self.frame) self.txtMaxSpeed.setEnabled(False) self.txtMaxSpeed.setGeometry(QtCore.QRect(110, 170, 141, 27)) self.txtMaxSpeed.setObjectName(_fromUtf8("txtMaxSpeed")) self.label_6 = QtGui.QLabel(self.frame) self.label_6.setGeometry(QtCore.QRect(16, 400, 91, 21)) self.label_6.setLayoutDirection(QtCore.Qt.LeftToRight) self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_6.setObjectName(_fromUtf8("label_6")) self.label_14 = QtGui.QLabel(self.frame) self.label_14.setEnabled(False) self.label_14.setGeometry(QtCore.QRect(10, 200, 91, 21)) self.label_14.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_14.setObjectName(_fromUtf8("label_14")) self.txtMinGoal = QtGui.QLineEdit(self.frame) self.txtMinGoal.setGeometry(QtCore.QRect(110, 250, 141, 27)) self.txtMinGoal.setObjectName(_fromUtf8("txtMinGoal")) self.label_7 = QtGui.QLabel(self.frame) self.label_7.setGeometry(QtCore.QRect(18, 560, 91, 21)) self.label_7.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_7.setObjectName(_fromUtf8("label_7")) self.txtSpeed = QtGui.QLineEdit(self.frame) self.txtSpeed.setEnabled(False) self.txtSpeed.setGeometry(QtCore.QRect(132, 520, 121, 27)) self.txtSpeed.setObjectName(_fromUtf8("txtSpeed")) self.chkPower = QtGui.QCheckBox(self.frame) self.chkPower.setEnabled(False) self.chkPower.setGeometry(QtCore.QRect(30, 500, 97, 22)) self.chkPower.setLayoutDirection(QtCore.Qt.RightToLeft) self.chkPower.setText(_fromUtf8("")) self.chkPower.setObjectName(_fromUtf8("chkPower")) self.txtPosition = QtGui.QLineEdit(self.frame) self.txtPosition.setEnabled(False) self.txtPosition.setGeometry(QtCore.QRect(110, 470, 141, 27)) self.txtPosition.setObjectName(_fromUtf8("txtPosition")) self.txtSensorRaw = QtGui.QLineEdit(self.frame) self.txtSensorRaw.setEnabled(False) self.txtSensorRaw.setGeometry(QtCore.QRect(112, 560, 141, 27)) self.txtSensorRaw.setObjectName(_fromUtf8("txtSensorRaw")) self.label_10 = QtGui.QLabel(self.frame) self.label_10.setGeometry(QtCore.QRect(40, 470, 67, 21)) self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_10.setObjectName(_fromUtf8("label_10")) self.label_11 = QtGui.QLabel(self.frame) self.label_11.setGeometry(QtCore.QRect(10, 500, 91, 17)) self.label_11.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_11.setObjectName(_fromUtf8("label_11")) self.cmbServo = QtGui.QComboBox(self.frame) self.cmbServo.setGeometry(QtCore.QRect(110, 50, 141, 27)) self.cmbServo.setObjectName(_fromUtf8("cmbServo")) self.label_12 = QtGui.QLabel(self.frame) self.label_12.setGeometry(QtCore.QRect(30, 20, 71, 21)) self.label_12.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_12.setObjectName(_fromUtf8("label_12")) self.chkEnabled = QtGui.QCheckBox(self.frame) self.chkEnabled.setGeometry(QtCore.QRect(30, 100, 97, 22)) self.chkEnabled.setLayoutDirection(QtCore.Qt.RightToLeft) self.chkEnabled.setObjectName(_fromUtf8("chkEnabled")) self.cmbBus = QtGui.QComboBox(self.frame) self.cmbBus.setGeometry(QtCore.QRect(110, 20, 141, 27)) self.cmbBus.setFrame(True) self.cmbBus.setObjectName(_fromUtf8("cmbBus")) self.label_13 = QtGui.QLabel(self.frame) self.label_13.setGeometry(QtCore.QRect(30, 50, 71, 21)) self.label_13.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_13.setObjectName(_fromUtf8("label_13")) self.label_9 = QtGui.QLabel(self.frame) self.label_9.setGeometry(QtCore.QRect(40, 130, 67, 21)) self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_9.setObjectName(_fromUtf8("label_9")) self.txtGoal = QtGui.QLineEdit(self.frame) self.txtGoal.setGeometry(QtCore.QRect(110, 130, 141, 27)) self.txtGoal.setObjectName(_fromUtf8("txtGoal")) self.chkMoving = QtGui.QCheckBox(self.frame) self.chkMoving.setEnabled(False) self.chkMoving.setGeometry(QtCore.QRect(30, 520, 97, 22)) self.chkMoving.setLayoutDirection(QtCore.Qt.RightToLeft) self.chkMoving.setText(_fromUtf8("")) self.chkMoving.setObjectName(_fromUtf8("chkMoving")) self.label_15 = QtGui.QLabel(self.frame) self.label_15.setGeometry(QtCore.QRect(10, 520, 91, 17)) self.label_15.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_15.setObjectName(_fromUtf8("label_15")) MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setSizeGripEnabled(False) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.cmbBus, self.cmbServo) MainWindow.setTabOrder(self.cmbServo, self.chkEnabled) MainWindow.setTabOrder(self.chkEnabled, self.txtGoal) MainWindow.setTabOrder(self.txtGoal, self.txtMaxSpeed) MainWindow.setTabOrder(self.txtMaxSpeed, self.cmbSmoothing) MainWindow.setTabOrder(self.cmbSmoothing, self.txtMinGoal) MainWindow.setTabOrder(self.txtMinGoal, self.txtMaxGoal) MainWindow.setTabOrder(self.txtMaxGoal, self.txtMinPulse) MainWindow.setTabOrder(self.txtMinPulse, self.txtMaxPulse) MainWindow.setTabOrder(self.txtMaxPulse, self.txtMinSensor) MainWindow.setTabOrder(self.txtMinSensor, self.txtMaxSensor) MainWindow.setTabOrder(self.txtMaxSensor, self.chkCalibrated) MainWindow.setTabOrder(self.chkCalibrated, self.txtPosition) MainWindow.setTabOrder(self.txtPosition, self.chkPower) MainWindow.setTabOrder(self.chkPower, self.chkMoving) MainWindow.setTabOrder(self.chkMoving, self.txtSpeed) MainWindow.setTabOrder(self.txtSpeed, self.txtSensorRaw) MainWindow.setTabOrder(self.txtSensorRaw, self.sliderGoal) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "ROS Servo Trainer", None)) self.label_3.setText(_translate("MainWindow", "Min Pulse", None)) self.label_4.setText(_translate("MainWindow", "Max Pulse", None)) self.label_5.setText(_translate("MainWindow", "MinSensor", None)) self.label_2.setText(_translate("MainWindow", "Max Goal", None)) self.chkCalibrated.setText(_translate("MainWindow", "Calibrated", None)) self.label.setText(_translate("MainWindow", "Min Goal", None)) self.label_8.setText(_translate("MainWindow", "MaxSpeed", None)) self.label_6.setText(_translate("MainWindow", "Max Sensor", None)) self.label_14.setText(_translate("MainWindow", "Smoothing", None)) self.label_7.setText(_translate("MainWindow", "Sensor Raw", None)) self.label_10.setText(_translate("MainWindow", "Position", None)) self.label_11.setText(_translate("MainWindow", "Power", None)) self.label_12.setText(_translate("MainWindow", "Bus", None)) self.chkEnabled.setText(_translate("MainWindow", "Enabled", None)) self.label_13.setText(_translate("MainWindow", "Servo", None)) self.label_9.setText(_translate("MainWindow", "Goal", None)) self.label_15.setText(_translate("MainWindow", "Moving", None))<|fim▁end|>
MainWindow.setDocumentMode(False)
<|file_name|>factorial.js<|end_file_name|><|fim▁begin|>'use strict'; module.exports = function (math) { var util = require('../../util/index'), BigNumber = math.type.BigNumber, collection = require('../../type/collection'), isNumber = util.number.isNumber, isBoolean = util['boolean'].isBoolean, isInteger = util.number.isInteger, isCollection = collection.isCollection; /** * Compute the factorial of a value * * Factorial only supports an integer value as argument. * For matrices, the function is evaluated element wise. * * Syntax: * * math.factorial(n) * * Examples: * * math.factorial(5); // returns 120 * math.factorial(3); // returns 6 * * See also: * * combinations, permutations * * @param {Number | BigNumber | Array | Matrix} n An integer number * @return {Number | BigNumber | Array | Matrix} The factorial of `n` */ math.factorial = function factorial (n) { var value, res; if (arguments.length != 1) { throw new math.error.ArgumentsError('factorial', arguments.length, 1); } if (isNumber(n)) { if (!isInteger(n) || n < 0) { throw new TypeError('Positive integer value expected in function factorial'); } value = n - 1; res = n; while (value > 1) { res *= value; value--; } if (res == 0) { res = 1; // 0! is per definition 1 } return res; } if (n instanceof BigNumber) { if (!(isPositiveInteger(n))) { throw new TypeError('Positive integer value expected in function factorial'); } var one = new BigNumber(1); value = n.minus(one); res = n; while (value.gt(one)) { res = res.times(value); value = value.minus(one); } if (res.equals(0)) {<|fim▁hole|> return res; } if (isBoolean(n)) { return 1; // factorial(1) = 1, factorial(0) = 1 } if (isCollection(n)) { return collection.deepMap(n, factorial); } throw new math.error.UnsupportedTypeError('factorial', math['typeof'](n)); }; /** * Test whether BigNumber n is a positive integer * @param {BigNumber} n * @returns {boolean} isPositiveInteger */ var isPositiveInteger = function(n) { return n.isInteger() && n.gte(0); }; };<|fim▁end|>
res = one; // 0! is per definition 1 }
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); #[cfg(test)] mod tests {<|fim▁hole|> fn it_works() {} }<|fim▁end|>
#[test]
<|file_name|>databasemanager.cpp<|end_file_name|><|fim▁begin|>/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2014 Mark Samman <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "configmanager.h" #include "databasemanager.h" #include "enums.h" #include "luascript.h" #include "tools.h" extern ConfigManager g_config; bool DatabaseManager::optimizeTables() { Database* db = Database::getInstance(); std::ostringstream query; query << "SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = " << db->escapeString(g_config.getString(ConfigManager::MYSQL_DB)) << " AND `DATA_FREE` > 0"; DBResult* result = db->storeQuery(query.str()); if (!result) { return false; } do { std::string tableName = result->getDataString("TABLE_NAME"); std::cout << "> Optimizing table " << tableName << "..." << std::flush; query.str(""); query << "OPTIMIZE TABLE `" << tableName << '`'; if (db->executeQuery(query.str())) { std::cout << " [success]" << std::endl; } else { std::cout << " [failed]" << std::endl; } } while (result->next()); db->freeResult(result); return true; } bool DatabaseManager::tableExists(const std::string& tableName) { Database* db = Database::getInstance(); std::ostringstream query; query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db->escapeString(g_config.getString(ConfigManager::MYSQL_DB)) << " AND `TABLE_NAME` = " << db->escapeString(tableName); DBResult* result = db->storeQuery(query.str()); if (!result) { return false; } db->freeResult(result); return true; } bool DatabaseManager::isDatabaseSetup() { Database* db = Database::getInstance(); std::ostringstream query; query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db->escapeString(g_config.getString(ConfigManager::MYSQL_DB)); DBResult* result = db->storeQuery(query.str()); if (!result) { return false; } db->freeResult(result); return true; } int32_t DatabaseManager::getDatabaseVersion() { if (!tableExists("server_config")) { Database* db = Database::getInstance(); db->executeQuery("CREATE TABLE `server_config` (`config` VARCHAR(50) NOT nullptr, `value` VARCHAR(256) NOT nullptr DEFAULT '', UNIQUE(`config`)) ENGINE = InnoDB"); db->executeQuery("INSERT INTO `server_config` VALUES ('db_version', 0)"); return 0; } int32_t version = 0; if (getDatabaseConfig("db_version", version)) { return version; } return -1; }<|fim▁hole|> void DatabaseManager::updateDatabase() { lua_State* L = luaL_newstate(); if (!L) { return; } luaL_openlibs(L); #ifndef LUAJIT_VERSION //bit operations for Lua, based on bitlib project release 24 //bit.bnot, bit.band, bit.bor, bit.bxor, bit.lshift, bit.rshift luaL_register(L, "bit", LuaScriptInterface::luaBitReg); #endif //db table luaL_register(L, "db", LuaScriptInterface::luaDatabaseTable); //result table luaL_register(L, "result", LuaScriptInterface::luaResultTable); int32_t version = getDatabaseVersion(); do { std::ostringstream ss; ss << "data/migrations/" << version << ".lua"; if (luaL_dofile(L, ss.str().c_str()) != 0) { std::cout << "[Error - DatabaseManager::updateDatabase - Version: " << version << "] " << lua_tostring(L, -1) << std::endl; break; } if (!LuaScriptInterface::reserveScriptEnv()) { break; } lua_getglobal(L, "onUpdateDatabase"); if (lua_pcall(L, 0, 1, 0) != 0) { LuaScriptInterface::resetScriptEnv(); std::cout << "[Error - DatabaseManager::updateDatabase - Version: " << version << "] " << lua_tostring(L, -1) << std::endl; break; } if (!LuaScriptInterface::popBoolean(L)) { LuaScriptInterface::resetScriptEnv(); break; } version++; std::cout << "> Database has been updated to version " << version << '.' << std::endl; registerDatabaseConfig("db_version", version); LuaScriptInterface::resetScriptEnv(); } while (true); lua_close(L); } bool DatabaseManager::getDatabaseConfig(const std::string& config, int32_t& value) { Database* db = Database::getInstance(); std::ostringstream query; query << "SELECT `value` FROM `server_config` WHERE `config` = " << db->escapeString(config); DBResult* result = db->storeQuery(query.str()); if (!result) { return false; } value = result->getDataInt("value"); db->freeResult(result); return true; } void DatabaseManager::registerDatabaseConfig(const std::string& config, int32_t value) { Database* db = Database::getInstance(); std::ostringstream query; int32_t tmp; if (!getDatabaseConfig(config, tmp)) { query << "INSERT INTO `server_config` VALUES (" << db->escapeString(config) << ", '" << value << "')"; } else { query << "UPDATE `server_config` SET `value` = '" << value << "' WHERE `config` = " << db->escapeString(config); } db->executeQuery(query.str()); }<|fim▁end|>
<|file_name|>csv_logger.py<|end_file_name|><|fim▁begin|>__author__ = 'teemu kanstren' import pypro.utils as utils import pypro.snmp.config as config class CSVFileLogger: files = {} def __init__(self): oids = config.SNMP_OIDS utils.check_dir() self.event_log = open(utils.event_log+".csv", "w", encoding="utf-8") event_header = "time;type;description" self.event_log.write(event_header + "\n") self.event_log.flush() for oid in oids: file_name = utils.log_dir + "/" + oid._name() + "_log.csv" log = open(file_name, "w", encoding="utf-8") header = "time;target;target_name;oid;oid_name;value" log.write(header + "\n") log.flush() self.files[oid.oid_id] = log <|fim▁hole|> file.close() self.event_log.close() def start(self, epoch): line = str(epoch) + ";info;session started ("+config.SESSION_NAME+")" self.event_log.write(line + "\n") self.event_log.flush() if config.PRINT_CONSOLE: print(line) def stop(self, epoch): line = str(epoch) + ";info;session stopped ("+config.SESSION_NAME+")" self.event_log.write(line + "\n") self.event_log.flush() if config.PRINT_CONSOLE: print(line) self.close() def value(self, epoch, oid, name, value): line = str(epoch) + ";" + oid.target() + ";" + oid.target_name + ";" + str(name) + ";" + str(oid._name()) + ";" + str(value) log = self.files[oid.oid_id] log.write(line + "\n") log.flush() if config.PRINT_CONSOLE: print(line) def error(self, epoch, description): line = str(epoch) + ";error;" + description self.event_log.write(line + "\n") self.event_log.flush() if config.PRINT_CONSOLE: print(line)<|fim▁end|>
def close(self): for file in self.files:
<|file_name|>opts.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Configuration options for a single run of the servo application. Created //! from command line arguments. use euclid::size::TypedSize2D; use getopts::Options; use num_cpus; use prefs::{self, PrefValue, PREFS}; use resource_files::set_resources_path; use servo_geometry::DeviceIndependentPixel; use servo_url::ServoUrl; use std::borrow::Cow; use std::cmp; use std::default::Default; use std::env; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use url::{self, Url}; /// Global flags for Servo, currently set on the command line. #[derive(Clone)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct Opts { pub is_running_problem_test: bool, /// The initial URL to load. pub url: Option<ServoUrl>, /// How many threads to use for CPU painting (`-t`). /// /// Note that painting is sequentialized when using GPU painting. pub paint_threads: usize, /// The maximum size of each tile in pixels (`-s`). pub tile_size: usize, /// The ratio of device pixels per px at the default scale. If unspecified, will use the /// platform default setting. pub device_pixels_per_px: Option<f32>, /// `None` to disable the time profiler or `Some` with an interval in seconds to enable it and /// cause it to produce output on that interval (`-p`). pub time_profiling: Option<OutputOptions>, /// When the profiler is enabled, this is an optional path to dump a self-contained HTML file /// visualizing the traces as a timeline. pub time_profiler_trace_path: Option<String>, /// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it /// and cause it to produce output on that interval (`-m`). pub mem_profiler_period: Option<f64>, pub nonincremental_layout: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded pub userscripts: Option<String>, pub user_stylesheets: Vec<(Vec<u8>, ServoUrl)>, pub output_file: Option<String>, /// Replace unpaires surrogates in DOM strings with U+FFFD. /// See https://github.com/servo/servo/issues/6564 pub replace_surrogates: bool, /// Log GC passes and their durations. pub gc_profile: bool, /// Load web fonts synchronously to avoid non-deterministic network-driven reflows. pub load_webfonts_synchronously: bool, pub headless: bool, pub hard_fail: bool, /// True if we should bubble intrinsic widths sequentially (`-b`). If this is true, then /// intrinsic widths are computed as a separate pass instead of during flow construction. You /// may wish to turn this flag on in order to benchmark style recalculation against other /// browser engines. pub bubble_inline_sizes_separately: bool, /// True if we should show borders on all layers and tiles for /// debugging purposes (`--show-debug-borders`). pub show_debug_borders: bool, /// True if we should show borders on all fragments for debugging purposes /// (`--show-debug-fragment-borders`). pub show_debug_fragment_borders: bool, /// True if we should paint tiles with overlays based on which thread painted them. pub show_debug_parallel_paint: bool, /// True if we should paint borders around flows based on which thread painted them. pub show_debug_parallel_layout: bool, /// True if we should paint tiles a random color whenever they're repainted. Useful for /// debugging invalidation. pub paint_flashing: bool, /// If set with --disable-text-aa, disable antialiasing on fonts. This is primarily useful for reftests /// where pixel perfect results are required when using fonts such as the Ahem /// font for layout tests. pub enable_text_antialiasing: bool, /// If set with --enable-subpixel, use subpixel antialiasing for glyphs. In the future /// this will likely become the default, but for now it's opt-in while we work /// out any bugs and improve the implementation. pub enable_subpixel_text_antialiasing: bool, /// If set with --disable-canvas-aa, disable antialiasing on the HTML canvas element. /// Like --disable-text-aa, this is useful for reftests where pixel perfect results are required. pub enable_canvas_antialiasing: bool, /// True if each step of layout is traced to an external JSON file /// for debugging purposes. Settings this implies sequential layout /// and paint. pub trace_layout: bool, /// Periodically print out on which events script threads spend their processing time. pub profile_script_events: bool, /// Enable all heartbeats for profiling. pub profile_heartbeats: bool, /// `None` to disable debugger or `Some` with a port number to start a server to listen to /// remote Firefox debugger connections. pub debugger_port: Option<u16>, /// `None` to disable devtools or `Some` with a port number to start a server to listen to /// remote Firefox devtools connections. pub devtools_port: Option<u16>, /// `None` to disable WebDriver or `Some` with a port number to start a server to listen to /// remote WebDriver commands. pub webdriver_port: Option<u16>, /// The initial requested size of the window. pub initial_window_size: TypedSize2D<u32, DeviceIndependentPixel>, /// An optional string allowing the user agent to be set for testing. pub user_agent: Cow<'static, str>, /// Whether we're running in multiprocess mode. pub multiprocess: bool, /// Whether we're running inside the sandbox. pub sandbox: bool, /// Probability of randomly closing a pipeline, /// used for testing the hardening of the constellation. pub random_pipeline_closure_probability: Option<f32>, /// The seed for the RNG used to randomly close pipelines, /// used for testing the hardening of the constellation. pub random_pipeline_closure_seed: Option<usize>, /// Dumps the DOM after restyle. pub dump_style_tree: bool, /// Dumps the rule tree. pub dump_rule_tree: bool, /// Dumps the flow tree after a layout. pub dump_flow_tree: bool, /// Dumps the display list after a layout. pub dump_display_list: bool, /// Dumps the display list in JSON form after a layout. pub dump_display_list_json: bool, /// Dumps the layer tree when it changes. pub dump_layer_tree: bool, /// Emits notifications when there is a relayout. pub relayout_event: bool, /// Whether Style Sharing Cache is used pub disable_share_style_cache: bool, /// Whether to show in stdout style sharing cache stats after a restyle. pub style_sharing_stats: bool, /// Translate mouse input into touch events. pub convert_mouse_to_touch: bool, /// True to exit after the page load (`-x`). pub exit_after_load: bool, /// Do not use native titlebar pub no_native_titlebar: bool, /// Enable vsync in the compositor pub enable_vsync: bool, /// True to show webrender profiling stats on screen. pub webrender_stats: bool, /// True to show webrender debug on screen. pub webrender_debug: bool, /// True if webrender recording should be enabled. pub webrender_record: bool, /// True to compile all webrender shaders at init time. This is mostly /// useful when modifying the shaders, to ensure they all compile /// after each change is made. pub precache_shaders: bool, /// True if WebRender should use multisample antialiasing. pub use_msaa: bool, /// Directory for a default config directory pub config_dir: Option<PathBuf>, // don't skip any backtraces on panic pub full_backtraces: bool, /// True to use OS native signposting facilities. This makes profiling events (script activity, /// reflow, compositing, etc.) appear in Instruments.app on macOS. pub signpost: bool, /// Print the version and exit. pub is_printing_version: bool, /// Path to SSL certificates. pub certificate_path: Option<String>, } fn print_usage(app: &str, opts: &Options) { let message = format!("Usage: {} [ options ... ] [URL]\n\twhere options include", app); println!("{}", opts.usage(&message)); } /// Debug options for Servo, currently set on the command line with -Z #[derive(Default)] pub struct DebugOptions { /// List all the debug options. pub help: bool, /// Bubble intrinsic widths separately like other engines. pub bubble_widths: bool, /// Disable antialiasing of rendered text. pub disable_text_aa: bool, /// Enable subpixel antialiasing of rendered text. pub enable_subpixel_aa: bool, /// Disable antialiasing of rendered text on the HTML canvas element. pub disable_canvas_aa: bool, /// Print the DOM after each restyle. pub dump_style_tree: bool, /// Dumps the rule tree. pub dump_rule_tree: bool, /// Print the flow tree after each layout. pub dump_flow_tree: bool, /// Print the display list after each layout. pub dump_display_list: bool, /// Print the display list in JSON form. pub dump_display_list_json: bool, /// Print the layer tree whenever it changes. pub dump_layer_tree: bool, /// Print notifications when there is a relayout. pub relayout_event: bool, /// Profile which events script threads spend their time on. pub profile_script_events: bool, /// Enable all heartbeats for profiling. pub profile_heartbeats: bool, /// Paint borders along layer and tile boundaries. pub show_compositor_borders: bool, /// Paint borders along fragment boundaries. pub show_fragment_borders: bool, /// Overlay tiles with colors showing which thread painted them. pub show_parallel_paint: bool, /// Mark which thread laid each flow out with colors. pub show_parallel_layout: bool, /// Overlay repainted areas with a random color. pub paint_flashing: bool, /// Write layout trace to an external file for debugging. pub trace_layout: bool, /// Disable the style sharing cache. pub disable_share_style_cache: bool, /// Whether to show in stdout style sharing cache stats after a restyle. pub style_sharing_stats: bool, /// Translate mouse input into touch events. pub convert_mouse_to_touch: bool, /// Replace unpaires surrogates in DOM strings with U+FFFD. /// See https://github.com/servo/servo/issues/6564 pub replace_surrogates: bool, /// Log GC passes and their durations. pub gc_profile: bool, /// Load web fonts synchronously to avoid non-deterministic network-driven reflows. pub load_webfonts_synchronously: bool, /// Disable vsync in the compositor pub disable_vsync: bool, /// Show webrender profiling stats on screen. pub webrender_stats: bool, /// Show webrender debug on screen. pub webrender_debug: bool, /// Enable webrender recording. pub webrender_record: bool, /// Use multisample antialiasing in WebRender. pub use_msaa: bool, // don't skip any backtraces on panic pub full_backtraces: bool, /// True to compile all webrender shaders at init time. This is mostly /// useful when modifying the shaders, to ensure they all compile /// after each change is made. pub precache_shaders: bool, /// True to use OS native signposting facilities. This makes profiling events (script activity, /// reflow, compositing, etc.) appear in Instruments.app on macOS. pub signpost: bool, } impl DebugOptions { pub fn extend(&mut self, debug_string: String) -> Result<(), String> { for option in debug_string.split(',') { match option { "help" => self.help = true, "bubble-widths" => self.bubble_widths = true, "disable-text-aa" => self.disable_text_aa = true, "enable-subpixel-aa" => self.enable_subpixel_aa = true, "disable-canvas-aa" => self.disable_text_aa = true, "dump-style-tree" => self.dump_style_tree = true, "dump-rule-tree" => self.dump_rule_tree = true, "dump-flow-tree" => self.dump_flow_tree = true, "dump-display-list" => self.dump_display_list = true, "dump-display-list-json" => self.dump_display_list_json = true, "dump-layer-tree" => self.dump_layer_tree = true, "relayout-event" => self.relayout_event = true, "profile-script-events" => self.profile_script_events = true, "profile-heartbeats" => self.profile_heartbeats = true, "show-compositor-borders" => self.show_compositor_borders = true, "show-fragment-borders" => self.show_fragment_borders = true, "show-parallel-paint" => self.show_parallel_paint = true, "show-parallel-layout" => self.show_parallel_layout = true, "paint-flashing" => self.paint_flashing = true, "trace-layout" => self.trace_layout = true, "disable-share-style-cache" => self.disable_share_style_cache = true, "style-sharing-stats" => self.style_sharing_stats = true, "convert-mouse-to-touch" => self.convert_mouse_to_touch = true, "replace-surrogates" => self.replace_surrogates = true, "gc-profile" => self.gc_profile = true, "load-webfonts-synchronously" => self.load_webfonts_synchronously = true, "disable-vsync" => self.disable_vsync = true, "wr-stats" => self.webrender_stats = true, "wr-debug" => self.webrender_debug = true, "wr-record" => self.webrender_record = true, "msaa" => self.use_msaa = true, "full-backtraces" => self.full_backtraces = true, "precache-shaders" => self.precache_shaders = true, "signpost" => self.signpost = true, "" => {}, _ => return Err(String::from(option)), }; }; Ok(()) } } fn print_debug_usage(app: &str) -> ! { fn print_option(name: &str, description: &str) { println!("\t{:<35} {}", name, description); } println!("Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:", app); print_option("bubble-widths", "Bubble intrinsic widths separately like other engines."); print_option("disable-text-aa", "Disable antialiasing of rendered text."); print_option("disable-canvas-aa", "Disable antialiasing on the HTML canvas element."); print_option("dump-style-tree", "Print the DOM with computed styles after each restyle."); print_option("dump-flow-tree", "Print the flow tree after each layout."); print_option("dump-display-list", "Print the display list after each layout."); print_option("dump-display-list-json", "Print the display list in JSON form."); print_option("dump-layer-tree", "Print the layer tree whenever it changes."); print_option("relayout-event", "Print notifications when there is a relayout."); print_option("profile-script-events", "Enable profiling of script-related events."); print_option("profile-heartbeats", "Enable heartbeats for all thread categories."); print_option("show-compositor-borders", "Paint borders along layer and tile boundaries."); print_option("show-fragment-borders", "Paint borders along fragment boundaries."); print_option("show-parallel-paint", "Overlay tiles with colors showing which thread painted them."); print_option("show-parallel-layout", "Mark which thread laid each flow out with colors."); print_option("paint-flashing", "Overlay repainted areas with a random color."); print_option("trace-layout", "Write layout trace to an external file for debugging."); print_option("disable-share-style-cache", "Disable the style sharing cache."); print_option("parallel-display-list-building", "Build display lists in parallel."); print_option("convert-mouse-to-touch", "Send touch events instead of mouse events"); print_option("replace-surrogates", "Replace unpaires surrogates in DOM strings with U+FFFD. \ See https://github.com/servo/servo/issues/6564"); print_option("gc-profile", "Log GC passes and their durations."); print_option("load-webfonts-synchronously", "Load web fonts synchronously to avoid non-deterministic network-driven reflows"); print_option("disable-vsync", "Disable vsync mode in the compositor to allow profiling at more than monitor refresh rate"); print_option("wr-stats", "Show WebRender profiler on screen."); print_option("msaa", "Use multisample antialiasing in WebRender."); print_option("full-backtraces", "Print full backtraces for all errors"); print_option("wr-debug", "Display webrender tile borders. Must be used with -w option."); print_option("precache-shaders", "Compile all shaders during init. Must be used with -w option."); print_option("signpost", "Emit native OS signposts for profile events (currently macOS only)"); println!(""); process::exit(0) } #[derive(Clone)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub enum OutputOptions { FileName(String), Stdout(f64) } fn args_fail(msg: &str) -> ! { writeln!(io::stderr(), "{}", msg).unwrap(); process::exit(1) } static MULTIPROCESS: AtomicBool = ATOMIC_BOOL_INIT; #[inline] pub fn multiprocess() -> bool { MULTIPROCESS.load(Ordering::Relaxed) } enum UserAgent { Desktop, Android, } fn default_user_agent_string(agent: UserAgent) -> &'static str { #[cfg(all(target_os = "linux", target_arch = "x86_64"))] const DESKTOP_UA_STRING: &'static str = "Mozilla/5.0 (X11; Linux x86_64; rv:37.0) Servo/1.0 Firefox/37.0"; #[cfg(all(target_os = "linux", not(target_arch = "x86_64")))] const DESKTOP_UA_STRING: &'static str = "Mozilla/5.0 (X11; Linux i686; rv:37.0) Servo/1.0 Firefox/37.0"; #[cfg(all(target_os = "windows", target_arch = "x86_64"))] const DESKTOP_UA_STRING: &'static str = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:37.0) Servo/1.0 Firefox/37.0"; #[cfg(all(target_os = "windows", not(target_arch = "x86_64")))] const DESKTOP_UA_STRING: &'static str = "Mozilla/5.0 (Windows NT 6.1; rv:37.0) Servo/1.0 Firefox/37.0"; #[cfg(not(any(target_os = "linux", target_os = "windows")))] // Neither Linux nor Windows, so maybe OS X, and if not then OS X is an okay fallback. const DESKTOP_UA_STRING: &'static str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Servo/1.0 Firefox/37.0"; match agent { UserAgent::Desktop => { DESKTOP_UA_STRING } UserAgent::Android => { "Mozilla/5.0 (Android; Mobile; rv:37.0) Servo/1.0 Firefox/37.0" } } } #[cfg(target_os = "android")] const DEFAULT_USER_AGENT: UserAgent = UserAgent::Android; #[cfg(not(target_os = "android"))] const DEFAULT_USER_AGENT: UserAgent = UserAgent::Desktop; pub fn default_opts() -> Opts { Opts { is_running_problem_test: false, url: Some(ServoUrl::parse("about:blank").unwrap()), paint_threads: 1, tile_size: 512, device_pixels_per_px: None, time_profiling: None, time_profiler_trace_path: None, mem_profiler_period: None, nonincremental_layout: false,<|fim▁hole|> output_file: None, replace_surrogates: false, gc_profile: false, load_webfonts_synchronously: false, headless: true, hard_fail: true, bubble_inline_sizes_separately: false, show_debug_borders: false, show_debug_fragment_borders: false, show_debug_parallel_paint: false, show_debug_parallel_layout: false, paint_flashing: false, enable_text_antialiasing: false, enable_subpixel_text_antialiasing: false, enable_canvas_antialiasing: false, trace_layout: false, debugger_port: None, devtools_port: None, webdriver_port: None, initial_window_size: TypedSize2D::new(1024, 740), user_agent: default_user_agent_string(DEFAULT_USER_AGENT).into(), multiprocess: false, random_pipeline_closure_probability: None, random_pipeline_closure_seed: None, sandbox: false, dump_style_tree: false, dump_rule_tree: false, dump_flow_tree: false, dump_display_list: false, dump_display_list_json: false, dump_layer_tree: false, relayout_event: false, profile_script_events: false, profile_heartbeats: false, disable_share_style_cache: false, style_sharing_stats: false, convert_mouse_to_touch: false, exit_after_load: false, no_native_titlebar: false, enable_vsync: true, webrender_stats: false, use_msaa: false, config_dir: None, full_backtraces: false, is_printing_version: false, webrender_debug: false, webrender_record: false, precache_shaders: false, signpost: false, certificate_path: None, } } pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { let (app_name, args) = args.split_first().unwrap(); let mut opts = Options::new(); opts.optflag("c", "cpu", "CPU painting"); opts.optflag("g", "gpu", "GPU painting"); opts.optopt("o", "output", "Output file", "output.png"); opts.optopt("s", "size", "Size of tiles", "512"); opts.optopt("", "device-pixel-ratio", "Device pixels per px", ""); opts.optopt("t", "threads", "Number of paint threads", "1"); opts.optflagopt("p", "profile", "Time profiler flag and either a TSV output filename \ OR an interval for output to Stdout (blank for Stdout with interval of 5s)", "10 \ OR time.tsv"); opts.optflagopt("", "profiler-trace-path", "Path to dump a self-contained HTML timeline of profiler traces", ""); opts.optflagopt("m", "memory-profile", "Memory profiler flag and output interval", "10"); opts.optflag("x", "exit", "Exit after load flag"); opts.optopt("y", "layout-threads", "Number of threads to use for layout", "1"); opts.optflag("i", "nonincremental-layout", "Enable to turn off incremental layout."); opts.optflagopt("", "userscripts", "Uses userscripts in resources/user-agent-js, or a specified full path", ""); opts.optmulti("", "user-stylesheet", "A user stylesheet to be added to every document", "file.css"); opts.optflag("z", "headless", "Headless mode"); opts.optflag("f", "hard-fail", "Exit on thread failure instead of displaying about:failure"); opts.optflag("F", "soft-fail", "Display about:failure on thread failure instead of exiting"); opts.optflagopt("", "remote-debugging-port", "Start remote debugger server on port", "2794"); opts.optflagopt("", "devtools", "Start remote devtools server on port", "6000"); opts.optflagopt("", "webdriver", "Start remote WebDriver server on port", "7000"); opts.optopt("", "resolution", "Set window resolution.", "1024x740"); opts.optopt("u", "user-agent", "Set custom user agent string (or android / desktop for platform default)", "NCSA Mosaic/1.0 (X11;SunOS 4.1.4 sun4m)"); opts.optflag("M", "multiprocess", "Run in multiprocess mode"); opts.optflag("S", "sandbox", "Run in a sandbox if multiprocess"); opts.optopt("", "random-pipeline-closure-probability", "Probability of randomly closing a pipeline (for testing constellation hardening).", "0.0"); opts.optopt("", "random-pipeline-closure-seed", "A fixed seed for repeatbility of random pipeline closure.", ""); opts.optmulti("Z", "debug", "A comma-separated string of debug options. Pass help to show available options.", ""); opts.optflag("h", "help", "Print this message"); opts.optopt("", "resources-path", "Path to find static resources", "/home/servo/resources"); opts.optopt("", "certificate-path", "Path to find SSL certificates", "/home/servo/resources/certs"); opts.optopt("", "content-process" , "Run as a content process and connect to the given pipe", "servo-ipc-channel.abcdefg"); opts.optmulti("", "pref", "A preference to set to enable", "dom.mozbrowser.enabled"); opts.optflag("b", "no-native-titlebar", "Do not use native titlebar"); opts.optflag("w", "webrender", "Use webrender backend"); opts.optopt("G", "graphics", "Select graphics backend (gl or es2)", "gl"); opts.optopt("", "config-dir", "config directory following xdg spec on linux platform", ""); opts.optflag("v", "version", "Display servo version information"); let opt_match = match opts.parse(args) { Ok(m) => m, Err(f) => args_fail(&f.to_string()), }; set_resources_path(opt_match.opt_str("resources-path")); if opt_match.opt_present("h") || opt_match.opt_present("help") { print_usage(app_name, &opts); process::exit(0); }; // If this is the content process, we'll receive the real options over IPC. So just fill in // some dummy options for now. if let Some(content_process) = opt_match.opt_str("content-process") { MULTIPROCESS.store(true, Ordering::SeqCst); return ArgumentParsingResult::ContentProcess(content_process); } let mut debug_options = DebugOptions::default(); for debug_string in opt_match.opt_strs("Z") { if let Err(e) = debug_options.extend(debug_string) { args_fail(&format!("error: unrecognized debug option: {}", e)); } } if debug_options.help { print_debug_usage(app_name) } let cwd = env::current_dir().unwrap(); let homepage_pref = PREFS.get("shell.homepage"); let url_opt = if !opt_match.free.is_empty() { Some(&opt_match.free[0][..]) } else { homepage_pref.as_string() }; let is_running_problem_test = url_opt .as_ref() .map_or(false, |url| url.starts_with("http://web-platform.test:8000/2dcontext/drawing-images-to-the-canvas/") || url.starts_with("http://web-platform.test:8000/_mozilla/mozilla/canvas/") || url.starts_with("http://web-platform.test:8000/_mozilla/css/canvas_over_area.html")); let url = match url_opt { Some(url_string) => { parse_url_or_filename(&cwd, url_string) .unwrap_or_else(|()| args_fail("URL parsing failed")) }, None => { print_usage(app_name, &opts); args_fail("servo asks that you provide a URL") } }; let tile_size: usize = match opt_match.opt_str("s") { Some(tile_size_str) => tile_size_str.parse() .unwrap_or_else(|err| args_fail(&format!("Error parsing option: -s ({})", err))), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| dppx_str.parse() .unwrap_or_else(|err| args_fail(&format!("Error parsing option: --device-pixel-ratio ({})", err))) ); let mut paint_threads: usize = match opt_match.opt_str("t") { Some(paint_threads_str) => paint_threads_str.parse() .unwrap_or_else(|err| args_fail(&format!("Error parsing option: -t ({})", err))), None => cmp::max(num_cpus::get() * 3 / 4, 1), }; // If only the flag is present, default to a 5 second period for both profilers let time_profiling = if opt_match.opt_present("p") { match opt_match.opt_str("p") { Some(argument) => match argument.parse::<f64>() { Ok(interval) => Some(OutputOptions::Stdout(interval)) , Err(_) => Some(OutputOptions::FileName(argument)), }, None => Some(OutputOptions::Stdout(5.0 as f64)), } } else { // if the p option doesn't exist: None }; if let Some(ref time_profiler_trace_path) = opt_match.opt_str("profiler-trace-path") { let mut path = PathBuf::from(time_profiler_trace_path); path.pop(); if let Err(why) = fs::create_dir_all(&path) { error!("Couldn't create/open {:?}: {:?}", Path::new(time_profiler_trace_path).to_string_lossy(), why); } } let mem_profiler_period = opt_match.opt_default("m", "5").map(|period| { period.parse().unwrap_or_else(|err| args_fail(&format!("Error parsing option: -m ({})", err))) }); let mut layout_threads: Option<usize> = opt_match.opt_str("y") .map(|layout_threads_str| { layout_threads_str.parse() .unwrap_or_else(|err| args_fail(&format!("Error parsing option: -y ({})", err))) }); let nonincremental_layout = opt_match.opt_present("i"); let random_pipeline_closure_probability = opt_match.opt_str("random-pipeline-closure-probability").map(|prob| prob.parse().unwrap_or_else(|err| { args_fail(&format!("Error parsing option: --random-pipeline-closure-probability ({})", err)) }) ); let random_pipeline_closure_seed = opt_match.opt_str("random-pipeline-closure-seed").map(|seed| seed.parse().unwrap_or_else(|err| { args_fail(&format!("Error parsing option: --random-pipeline-closure-seed ({})", err)) }) ); let mut bubble_inline_sizes_separately = debug_options.bubble_widths; if debug_options.trace_layout { paint_threads = 1; layout_threads = Some(1); bubble_inline_sizes_separately = true; } let debugger_port = opt_match.opt_default("remote-debugging-port", "2794").map(|port| { port.parse() .unwrap_or_else(|err| args_fail(&format!("Error parsing option: --remote-debugging-port ({})", err))) }); let devtools_port = opt_match.opt_default("devtools", "6000").map(|port| { port.parse().unwrap_or_else(|err| args_fail(&format!("Error parsing option: --devtools ({})", err))) }); let webdriver_port = opt_match.opt_default("webdriver", "7000").map(|port| { port.parse().unwrap_or_else(|err| args_fail(&format!("Error parsing option: --webdriver ({})", err))) }); let initial_window_size = match opt_match.opt_str("resolution") { Some(res_string) => { let res: Vec<u32> = res_string.split('x').map(|r| { r.parse().unwrap_or_else(|err| args_fail(&format!("Error parsing option: --resolution ({})", err))) }).collect(); TypedSize2D::new(res[0], res[1]) } None => { TypedSize2D::new(1024, 740) } }; if opt_match.opt_present("M") { MULTIPROCESS.store(true, Ordering::SeqCst) } let user_agent = match opt_match.opt_str("u") { Some(ref ua) if ua == "android" => default_user_agent_string(UserAgent::Android).into(), Some(ref ua) if ua == "desktop" => default_user_agent_string(UserAgent::Desktop).into(), Some(ua) => ua.into(), None => default_user_agent_string(DEFAULT_USER_AGENT).into(), }; let user_stylesheets = opt_match.opt_strs("user-stylesheet").iter().map(|filename| { let path = cwd.join(filename); let url = ServoUrl::from_url(Url::from_file_path(&path).unwrap()); let mut contents = Vec::new(); File::open(path) .unwrap_or_else(|err| args_fail(&format!("Couldn't open {}: {}", filename, err))) .read_to_end(&mut contents) .unwrap_or_else(|err| args_fail(&format!("Couldn't read {}: {}", filename, err))); (contents, url) }).collect(); let do_not_use_native_titlebar = opt_match.opt_present("b") || !PREFS.get("shell.native-titlebar.enabled").as_boolean().unwrap(); let is_printing_version = opt_match.opt_present("v") || opt_match.opt_present("version"); let opts = Opts { is_running_problem_test: is_running_problem_test, url: Some(url), paint_threads: paint_threads, tile_size: tile_size, device_pixels_per_px: device_pixels_per_px, time_profiling: time_profiling, time_profiler_trace_path: opt_match.opt_str("profiler-trace-path"), mem_profiler_period: mem_profiler_period, nonincremental_layout: nonincremental_layout, userscripts: opt_match.opt_default("userscripts", ""), user_stylesheets: user_stylesheets, output_file: opt_match.opt_str("o"), replace_surrogates: debug_options.replace_surrogates, gc_profile: debug_options.gc_profile, load_webfonts_synchronously: debug_options.load_webfonts_synchronously, headless: opt_match.opt_present("z"), hard_fail: opt_match.opt_present("f") && !opt_match.opt_present("F"), bubble_inline_sizes_separately: bubble_inline_sizes_separately, profile_script_events: debug_options.profile_script_events, profile_heartbeats: debug_options.profile_heartbeats, trace_layout: debug_options.trace_layout, debugger_port: debugger_port, devtools_port: devtools_port, webdriver_port: webdriver_port, initial_window_size: initial_window_size, user_agent: user_agent, multiprocess: opt_match.opt_present("M"), sandbox: opt_match.opt_present("S"), random_pipeline_closure_probability: random_pipeline_closure_probability, random_pipeline_closure_seed: random_pipeline_closure_seed, show_debug_borders: debug_options.show_compositor_borders, show_debug_fragment_borders: debug_options.show_fragment_borders, show_debug_parallel_paint: debug_options.show_parallel_paint, show_debug_parallel_layout: debug_options.show_parallel_layout, paint_flashing: debug_options.paint_flashing, enable_text_antialiasing: !debug_options.disable_text_aa, enable_subpixel_text_antialiasing: debug_options.enable_subpixel_aa, enable_canvas_antialiasing: !debug_options.disable_canvas_aa, dump_style_tree: debug_options.dump_style_tree, dump_rule_tree: debug_options.dump_rule_tree, dump_flow_tree: debug_options.dump_flow_tree, dump_display_list: debug_options.dump_display_list, dump_display_list_json: debug_options.dump_display_list_json, dump_layer_tree: debug_options.dump_layer_tree, relayout_event: debug_options.relayout_event, disable_share_style_cache: debug_options.disable_share_style_cache, style_sharing_stats: debug_options.style_sharing_stats, convert_mouse_to_touch: debug_options.convert_mouse_to_touch, exit_after_load: opt_match.opt_present("x"), no_native_titlebar: do_not_use_native_titlebar, enable_vsync: !debug_options.disable_vsync, webrender_stats: debug_options.webrender_stats, use_msaa: debug_options.use_msaa, config_dir: opt_match.opt_str("config-dir").map(Into::into), full_backtraces: debug_options.full_backtraces, is_printing_version: is_printing_version, webrender_debug: debug_options.webrender_debug, webrender_record: debug_options.webrender_record, precache_shaders: debug_options.precache_shaders, signpost: debug_options.signpost, certificate_path: opt_match.opt_str("certificate-path"), }; set_defaults(opts); // These must happen after setting the default options, since the prefs rely on // on the resource path. // Note that command line preferences have the highest precedence prefs::add_user_prefs(); for pref in opt_match.opt_strs("pref").iter() { parse_pref_from_command_line(pref); } if let Some(layout_threads) = layout_threads { PREFS.set("layout.threads", PrefValue::Number(layout_threads as f64)); } else if let Some(layout_threads) = PREFS.get("layout.threads").as_string() { PREFS.set("layout.threads", PrefValue::Number(layout_threads.parse::<f64>().unwrap())); } else if *PREFS.get("layout.threads") == PrefValue::Missing { let layout_threads = cmp::max(num_cpus::get() * 3 / 4, 1); PREFS.set("layout.threads", PrefValue::Number(layout_threads as f64)); } ArgumentParsingResult::ChromeProcess } pub enum ArgumentParsingResult { ChromeProcess, ContentProcess(String), } // Make Opts available globally. This saves having to clone and pass // opts everywhere it is used, which gets particularly cumbersome // when passing through the DOM structures. static mut DEFAULT_OPTIONS: *mut Opts = 0 as *mut Opts; const INVALID_OPTIONS: *mut Opts = 0x01 as *mut Opts; lazy_static! { static ref OPTIONS: Opts = { unsafe { let initial = if !DEFAULT_OPTIONS.is_null() { let opts = Box::from_raw(DEFAULT_OPTIONS); *opts } else { default_opts() }; DEFAULT_OPTIONS = INVALID_OPTIONS; initial } }; } pub fn set_defaults(opts: Opts) { unsafe { assert!(DEFAULT_OPTIONS.is_null()); assert!(DEFAULT_OPTIONS != INVALID_OPTIONS); let box_opts = Box::new(opts); DEFAULT_OPTIONS = Box::into_raw(box_opts); } } pub fn parse_pref_from_command_line(pref: &str) { let split: Vec<&str> = pref.splitn(2, '=').collect(); let pref_name = split[0]; let value = split.get(1); match value { Some(&"false") => PREFS.set(pref_name, PrefValue::Boolean(false)), Some(&"true") | None => PREFS.set(pref_name, PrefValue::Boolean(true)), Some(value) => match value.parse::<f64>() { Ok(v) => PREFS.set(pref_name, PrefValue::Number(v)), Err(_) => PREFS.set(pref_name, PrefValue::String(value.to_string())) } }; } #[inline] pub fn get() -> &'static Opts { &OPTIONS } pub fn parse_url_or_filename(cwd: &Path, input: &str) -> Result<ServoUrl, ()> { match ServoUrl::parse(input) { Ok(url) => Ok(url), Err(url::ParseError::RelativeUrlWithoutBase) => { Url::from_file_path(&*cwd.join(input)).map(ServoUrl::from_url) } Err(_) => Err(()), } } impl Opts { pub fn should_use_osmesa(&self) -> bool { self.headless } }<|fim▁end|>
userscripts: None, user_stylesheets: Vec::new(),
<|file_name|>decoder.py<|end_file_name|><|fim▁begin|># # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, Ilya Etingof <[email protected]> # License: http://snmplabs.com/pyasn1/license.html # from pyasn1 import debug from pyasn1 import error from pyasn1.codec.ber import eoo from pyasn1.compat.integer import from_bytes from pyasn1.compat.octets import oct2int, octs2ints, ints2octs, null from pyasn1.type import base from pyasn1.type import char from pyasn1.type import tag from pyasn1.type import tagmap from pyasn1.type import univ from pyasn1.type import useful<|fim▁hole|> LOG = debug.registerLoggee(__name__, flags=debug.DEBUG_DECODER) noValue = base.noValue class AbstractDecoder(object): protoComponent = None def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): raise error.PyAsn1Error('Decoder not implemented for %s' % (tagSet,)) def indefLenValueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): raise error.PyAsn1Error('Indefinite length mode decoder not implemented for %s' % (tagSet,)) class AbstractSimpleDecoder(AbstractDecoder): @staticmethod def substrateCollector(asn1Object, substrate, length): return substrate[:length], substrate[length:] def _createComponent(self, asn1Spec, tagSet, value, **options): if options.get('native'): return value elif asn1Spec is None: return self.protoComponent.clone(value, tagSet=tagSet) elif value is noValue: return asn1Spec else: return asn1Spec.clone(value) class ExplicitTagDecoder(AbstractSimpleDecoder): protoComponent = univ.Any('') def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if substrateFun: return substrateFun( self._createComponent(asn1Spec, tagSet, '', **options), substrate, length ) head, tail = substrate[:length], substrate[length:] value, _ = decodeFun(head, asn1Spec, tagSet, length, **options) if LOG: LOG('explicit tag container carries %d octets of trailing payload ' '(will be lost!): %s' % (len(_), debug.hexdump(_))) return value, tail def indefLenValueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if substrateFun: return substrateFun( self._createComponent(asn1Spec, tagSet, '', **options), substrate, length ) value, substrate = decodeFun(substrate, asn1Spec, tagSet, length, **options) eooMarker, substrate = decodeFun(substrate, allowEoo=True, **options) if eooMarker is eoo.endOfOctets: return value, substrate else: raise error.PyAsn1Error('Missing end-of-octets terminator') explicitTagDecoder = ExplicitTagDecoder() class IntegerDecoder(AbstractSimpleDecoder): protoComponent = univ.Integer(0) def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatSimple: raise error.PyAsn1Error('Simple tag format expected') head, tail = substrate[:length], substrate[length:] if not head: return self._createComponent(asn1Spec, tagSet, 0, **options), tail value = from_bytes(head, signed=True) return self._createComponent(asn1Spec, tagSet, value, **options), tail class BooleanDecoder(IntegerDecoder): protoComponent = univ.Boolean(0) def _createComponent(self, asn1Spec, tagSet, value, **options): return IntegerDecoder._createComponent( self, asn1Spec, tagSet, value and 1 or 0, **options) class BitStringDecoder(AbstractSimpleDecoder): protoComponent = univ.BitString(()) supportConstructedForm = True def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): head, tail = substrate[:length], substrate[length:] if substrateFun: return substrateFun(self._createComponent( asn1Spec, tagSet, noValue, **options), substrate, length) if not head: raise error.PyAsn1Error('Empty BIT STRING substrate') if tagSet[0].tagFormat == tag.tagFormatSimple: # XXX what tag to check? trailingBits = oct2int(head[0]) if trailingBits > 7: raise error.PyAsn1Error( 'Trailing bits overflow %s' % trailingBits ) value = self.protoComponent.fromOctetString( head[1:], internalFormat=True, padding=trailingBits) return self._createComponent(asn1Spec, tagSet, value, **options), tail if not self.supportConstructedForm: raise error.PyAsn1Error('Constructed encoding form prohibited ' 'at %s' % self.__class__.__name__) if LOG: LOG('assembling constructed serialization') # All inner fragments are of the same type, treat them as octet string substrateFun = self.substrateCollector bitString = self.protoComponent.fromOctetString(null, internalFormat=True) while head: component, head = decodeFun(head, self.protoComponent, substrateFun=substrateFun, **options) trailingBits = oct2int(component[0]) if trailingBits > 7: raise error.PyAsn1Error( 'Trailing bits overflow %s' % trailingBits ) bitString = self.protoComponent.fromOctetString( component[1:], internalFormat=True, prepend=bitString, padding=trailingBits ) return self._createComponent(asn1Spec, tagSet, bitString, **options), tail def indefLenValueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if substrateFun: return substrateFun(self._createComponent(asn1Spec, tagSet, noValue, **options), substrate, length) # All inner fragments are of the same type, treat them as octet string substrateFun = self.substrateCollector bitString = self.protoComponent.fromOctetString(null, internalFormat=True) while substrate: component, substrate = decodeFun(substrate, self.protoComponent, substrateFun=substrateFun, allowEoo=True, **options) if component is eoo.endOfOctets: break trailingBits = oct2int(component[0]) if trailingBits > 7: raise error.PyAsn1Error( 'Trailing bits overflow %s' % trailingBits ) bitString = self.protoComponent.fromOctetString( component[1:], internalFormat=True, prepend=bitString, padding=trailingBits ) else: raise error.SubstrateUnderrunError('No EOO seen before substrate ends') return self._createComponent(asn1Spec, tagSet, bitString, **options), substrate class OctetStringDecoder(AbstractSimpleDecoder): protoComponent = univ.OctetString('') supportConstructedForm = True def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): head, tail = substrate[:length], substrate[length:] if substrateFun: return substrateFun(self._createComponent(asn1Spec, tagSet, noValue, **options), substrate, length) if tagSet[0].tagFormat == tag.tagFormatSimple: # XXX what tag to check? return self._createComponent(asn1Spec, tagSet, head, **options), tail if not self.supportConstructedForm: raise error.PyAsn1Error('Constructed encoding form prohibited at %s' % self.__class__.__name__) if LOG: LOG('assembling constructed serialization') # All inner fragments are of the same type, treat them as octet string substrateFun = self.substrateCollector header = null while head: component, head = decodeFun(head, self.protoComponent, substrateFun=substrateFun, **options) header += component return self._createComponent(asn1Spec, tagSet, header, **options), tail def indefLenValueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if substrateFun and substrateFun is not self.substrateCollector: asn1Object = self._createComponent(asn1Spec, tagSet, noValue, **options) return substrateFun(asn1Object, substrate, length) # All inner fragments are of the same type, treat them as octet string substrateFun = self.substrateCollector header = null while substrate: component, substrate = decodeFun(substrate, self.protoComponent, substrateFun=substrateFun, allowEoo=True, **options) if component is eoo.endOfOctets: break header += component else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) return self._createComponent(asn1Spec, tagSet, header, **options), substrate class NullDecoder(AbstractSimpleDecoder): protoComponent = univ.Null('') def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatSimple: raise error.PyAsn1Error('Simple tag format expected') head, tail = substrate[:length], substrate[length:] component = self._createComponent(asn1Spec, tagSet, '', **options) if head: raise error.PyAsn1Error('Unexpected %d-octet substrate for Null' % length) return component, tail class ObjectIdentifierDecoder(AbstractSimpleDecoder): protoComponent = univ.ObjectIdentifier(()) def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatSimple: raise error.PyAsn1Error('Simple tag format expected') head, tail = substrate[:length], substrate[length:] if not head: raise error.PyAsn1Error('Empty substrate') head = octs2ints(head) oid = () index = 0 substrateLen = len(head) while index < substrateLen: subId = head[index] index += 1 if subId < 128: oid += (subId,) elif subId > 128: # Construct subid from a number of octets nextSubId = subId subId = 0 while nextSubId >= 128: subId = (subId << 7) + (nextSubId & 0x7F) if index >= substrateLen: raise error.SubstrateUnderrunError( 'Short substrate for sub-OID past %s' % (oid,) ) nextSubId = head[index] index += 1 oid += ((subId << 7) + nextSubId,) elif subId == 128: # ASN.1 spec forbids leading zeros (0x80) in OID # encoding, tolerating it opens a vulnerability. See # https://www.esat.kuleuven.be/cosic/publications/article-1432.pdf # page 7 raise error.PyAsn1Error('Invalid octet 0x80 in OID encoding') # Decode two leading arcs if 0 <= oid[0] <= 39: oid = (0,) + oid elif 40 <= oid[0] <= 79: oid = (1, oid[0] - 40) + oid[1:] elif oid[0] >= 80: oid = (2, oid[0] - 80) + oid[1:] else: raise error.PyAsn1Error('Malformed first OID octet: %s' % head[0]) return self._createComponent(asn1Spec, tagSet, oid, **options), tail class RealDecoder(AbstractSimpleDecoder): protoComponent = univ.Real() def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatSimple: raise error.PyAsn1Error('Simple tag format expected') head, tail = substrate[:length], substrate[length:] if not head: return self._createComponent(asn1Spec, tagSet, 0.0, **options), tail fo = oct2int(head[0]) head = head[1:] if fo & 0x80: # binary encoding if not head: raise error.PyAsn1Error("Incomplete floating-point value") if LOG: LOG('decoding binary encoded REAL') n = (fo & 0x03) + 1 if n == 4: n = oct2int(head[0]) head = head[1:] eo, head = head[:n], head[n:] if not eo or not head: raise error.PyAsn1Error('Real exponent screwed') e = oct2int(eo[0]) & 0x80 and -1 or 0 while eo: # exponent e <<= 8 e |= oct2int(eo[0]) eo = eo[1:] b = fo >> 4 & 0x03 # base bits if b > 2: raise error.PyAsn1Error('Illegal Real base') if b == 1: # encbase = 8 e *= 3 elif b == 2: # encbase = 16 e *= 4 p = 0 while head: # value p <<= 8 p |= oct2int(head[0]) head = head[1:] if fo & 0x40: # sign bit p = -p sf = fo >> 2 & 0x03 # scale bits p *= 2 ** sf value = (p, 2, e) elif fo & 0x40: # infinite value if LOG: LOG('decoding infinite REAL') value = fo & 0x01 and '-inf' or 'inf' elif fo & 0xc0 == 0: # character encoding if not head: raise error.PyAsn1Error("Incomplete floating-point value") if LOG: LOG('decoding character encoded REAL') try: if fo & 0x3 == 0x1: # NR1 value = (int(head), 10, 0) elif fo & 0x3 == 0x2: # NR2 value = float(head) elif fo & 0x3 == 0x3: # NR3 value = float(head) else: raise error.SubstrateUnderrunError( 'Unknown NR (tag %s)' % fo ) except ValueError: raise error.SubstrateUnderrunError( 'Bad character Real syntax' ) else: raise error.SubstrateUnderrunError( 'Unknown encoding (tag %s)' % fo ) return self._createComponent(asn1Spec, tagSet, value, **options), tail class AbstractConstructedDecoder(AbstractDecoder): protoComponent = None class UniversalConstructedTypeDecoder(AbstractConstructedDecoder): protoRecordComponent = None protoSequenceComponent = None def _getComponentTagMap(self, asn1Object, idx): raise NotImplementedError() def _getComponentPositionByType(self, asn1Object, tagSet, idx): raise NotImplementedError() def _decodeComponents(self, substrate, tagSet=None, decodeFun=None, **options): components = [] componentTypes = set() while substrate: component, substrate = decodeFun(substrate, **options) if component is eoo.endOfOctets: break components.append(component) componentTypes.add(component.tagSet) # Now we have to guess is it SEQUENCE/SET or SEQUENCE OF/SET OF # The heuristics is: # * 1+ components of different types -> likely SEQUENCE/SET # * otherwise -> likely SEQUENCE OF/SET OF if len(componentTypes) > 1: protoComponent = self.protoRecordComponent else: protoComponent = self.protoSequenceComponent asn1Object = protoComponent.clone( # construct tagSet from base tag from prototype ASN.1 object # and additional tags recovered from the substrate tagSet=tag.TagSet(protoComponent.tagSet.baseTag, *tagSet.superTags) ) if LOG: LOG('guessed %r container type (pass `asn1Spec` to guide the ' 'decoder)' % asn1Object) for idx, component in enumerate(components): asn1Object.setComponentByPosition( idx, component, verifyConstraints=False, matchTags=False, matchConstraints=False ) return asn1Object, substrate def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatConstructed: raise error.PyAsn1Error('Constructed tag format expected') head, tail = substrate[:length], substrate[length:] if substrateFun is not None: if asn1Spec is not None: asn1Object = asn1Spec.clone() elif self.protoComponent is not None: asn1Object = self.protoComponent.clone(tagSet=tagSet) else: asn1Object = self.protoRecordComponent, self.protoSequenceComponent return substrateFun(asn1Object, substrate, length) if asn1Spec is None: asn1Object, trailing = self._decodeComponents( head, tagSet=tagSet, decodeFun=decodeFun, **options ) if trailing: if LOG: LOG('Unused trailing %d octets encountered: %s' % ( len(trailing), debug.hexdump(trailing))) return asn1Object, tail asn1Object = asn1Spec.clone() asn1Object.clear() if asn1Spec.typeId in (univ.Sequence.typeId, univ.Set.typeId): namedTypes = asn1Spec.componentType isSetType = asn1Spec.typeId == univ.Set.typeId isDeterministic = not isSetType and not namedTypes.hasOptionalOrDefault if LOG: LOG('decoding %sdeterministic %s type %r chosen by type ID' % ( not isDeterministic and 'non-' or '', isSetType and 'SET' or '', asn1Spec)) seenIndices = set() idx = 0 while head: if not namedTypes: componentType = None elif isSetType: componentType = namedTypes.tagMapUnique else: try: if isDeterministic: componentType = namedTypes[idx].asn1Object elif namedTypes[idx].isOptional or namedTypes[idx].isDefaulted: componentType = namedTypes.getTagMapNearPosition(idx) else: componentType = namedTypes[idx].asn1Object except IndexError: raise error.PyAsn1Error( 'Excessive components decoded at %r' % (asn1Spec,) ) component, head = decodeFun(head, componentType, **options) if not isDeterministic and namedTypes: if isSetType: idx = namedTypes.getPositionByType(component.effectiveTagSet) elif namedTypes[idx].isOptional or namedTypes[idx].isDefaulted: idx = namedTypes.getPositionNearType(component.effectiveTagSet, idx) asn1Object.setComponentByPosition( idx, component, verifyConstraints=False, matchTags=False, matchConstraints=False ) seenIndices.add(idx) idx += 1 if LOG: LOG('seen component indices %s' % seenIndices) if namedTypes: if not namedTypes.requiredComponents.issubset(seenIndices): raise error.PyAsn1Error( 'ASN.1 object %s has uninitialized ' 'components' % asn1Object.__class__.__name__) if namedTypes.hasOpenTypes: openTypes = options.get('openTypes', {}) if LOG: LOG('using open types map: %r' % openTypes) if openTypes or options.get('decodeOpenTypes', False): for idx, namedType in enumerate(namedTypes.namedTypes): if not namedType.openType: continue if namedType.isOptional and not asn1Object.getComponentByPosition(idx).isValue: continue governingValue = asn1Object.getComponentByName( namedType.openType.name ) try: openType = openTypes[governingValue] except KeyError: try: openType = namedType.openType[governingValue] except KeyError: if LOG: LOG('failed to resolve open type by governing ' 'value %r' % (governingValue,)) continue if LOG: LOG('resolved open type %r by governing ' 'value %r' % (openType, governingValue)) containerValue = asn1Object.getComponentByPosition(idx) if containerValue.typeId in ( univ.SetOf.typeId, univ.SequenceOf.typeId): for pos, containerElement in enumerate( containerValue): component, rest = decodeFun( containerValue[pos].asOctets(), asn1Spec=openType, **options ) containerValue[pos] = component else: component, rest = decodeFun( asn1Object.getComponentByPosition(idx).asOctets(), asn1Spec=openType, **options ) asn1Object.setComponentByPosition(idx, component) else: asn1Object.verifySizeSpec() else: asn1Object = asn1Spec.clone() asn1Object.clear() componentType = asn1Spec.componentType if LOG: LOG('decoding type %r chosen by given `asn1Spec`' % componentType) idx = 0 while head: component, head = decodeFun(head, componentType, **options) asn1Object.setComponentByPosition( idx, component, verifyConstraints=False, matchTags=False, matchConstraints=False ) idx += 1 return asn1Object, tail def indefLenValueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatConstructed: raise error.PyAsn1Error('Constructed tag format expected') if substrateFun is not None: if asn1Spec is not None: asn1Object = asn1Spec.clone() elif self.protoComponent is not None: asn1Object = self.protoComponent.clone(tagSet=tagSet) else: asn1Object = self.protoRecordComponent, self.protoSequenceComponent return substrateFun(asn1Object, substrate, length) if asn1Spec is None: return self._decodeComponents( substrate, tagSet=tagSet, decodeFun=decodeFun, **dict(options, allowEoo=True) ) asn1Object = asn1Spec.clone() asn1Object.clear() if asn1Spec.typeId in (univ.Sequence.typeId, univ.Set.typeId): namedTypes = asn1Object.componentType isSetType = asn1Object.typeId == univ.Set.typeId isDeterministic = not isSetType and not namedTypes.hasOptionalOrDefault if LOG: LOG('decoding %sdeterministic %s type %r chosen by type ID' % ( not isDeterministic and 'non-' or '', isSetType and 'SET' or '', asn1Spec)) seenIndices = set() idx = 0 while substrate: if len(namedTypes) <= idx: asn1Spec = None elif isSetType: asn1Spec = namedTypes.tagMapUnique else: try: if isDeterministic: asn1Spec = namedTypes[idx].asn1Object elif namedTypes[idx].isOptional or namedTypes[idx].isDefaulted: asn1Spec = namedTypes.getTagMapNearPosition(idx) else: asn1Spec = namedTypes[idx].asn1Object except IndexError: raise error.PyAsn1Error( 'Excessive components decoded at %r' % (asn1Object,) ) component, substrate = decodeFun(substrate, asn1Spec, allowEoo=True, **options) if component is eoo.endOfOctets: break if not isDeterministic and namedTypes: if isSetType: idx = namedTypes.getPositionByType(component.effectiveTagSet) elif namedTypes[idx].isOptional or namedTypes[idx].isDefaulted: idx = namedTypes.getPositionNearType(component.effectiveTagSet, idx) asn1Object.setComponentByPosition( idx, component, verifyConstraints=False, matchTags=False, matchConstraints=False ) seenIndices.add(idx) idx += 1 else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) if LOG: LOG('seen component indices %s' % seenIndices) if namedTypes: if not namedTypes.requiredComponents.issubset(seenIndices): raise error.PyAsn1Error('ASN.1 object %s has uninitialized components' % asn1Object.__class__.__name__) if namedTypes.hasOpenTypes: openTypes = options.get('openTypes', {}) if LOG: LOG('using open types map: %r' % openTypes) if openTypes or options.get('decodeOpenTypes', False): for idx, namedType in enumerate(namedTypes.namedTypes): if not namedType.openType: continue if namedType.isOptional and not asn1Object.getComponentByPosition(idx).isValue: continue governingValue = asn1Object.getComponentByName( namedType.openType.name ) try: openType = openTypes[governingValue] except KeyError: try: openType = namedType.openType[governingValue] except KeyError: if LOG: LOG('failed to resolve open type by governing ' 'value %r' % (governingValue,)) continue if LOG: LOG('resolved open type %r by governing ' 'value %r' % (openType, governingValue)) containerValue = asn1Object.getComponentByPosition(idx) if containerValue.typeId in ( univ.SetOf.typeId, univ.SequenceOf.typeId): for pos, containerElement in enumerate( containerValue): component, rest = decodeFun( containerValue[pos].asOctets(), asn1Spec=openType, **dict(options, allowEoo=True) ) containerValue[pos] = component else: component, rest = decodeFun( asn1Object.getComponentByPosition(idx).asOctets(), asn1Spec=openType, **dict(options, allowEoo=True) ) if component is not eoo.endOfOctets: asn1Object.setComponentByPosition(idx, component) else: asn1Object.verifySizeSpec() else: asn1Object = asn1Spec.clone() asn1Object.clear() componentType = asn1Spec.componentType if LOG: LOG('decoding type %r chosen by given `asn1Spec`' % componentType) idx = 0 while substrate: component, substrate = decodeFun(substrate, componentType, allowEoo=True, **options) if component is eoo.endOfOctets: break asn1Object.setComponentByPosition( idx, component, verifyConstraints=False, matchTags=False, matchConstraints=False ) idx += 1 else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) return asn1Object, substrate class SequenceOrSequenceOfDecoder(UniversalConstructedTypeDecoder): protoRecordComponent = univ.Sequence() protoSequenceComponent = univ.SequenceOf() class SequenceDecoder(SequenceOrSequenceOfDecoder): protoComponent = univ.Sequence() class SequenceOfDecoder(SequenceOrSequenceOfDecoder): protoComponent = univ.SequenceOf() class SetOrSetOfDecoder(UniversalConstructedTypeDecoder): protoRecordComponent = univ.Set() protoSequenceComponent = univ.SetOf() class SetDecoder(SetOrSetOfDecoder): protoComponent = univ.Set() class SetOfDecoder(SetOrSetOfDecoder): protoComponent = univ.SetOf() class ChoiceDecoder(AbstractConstructedDecoder): protoComponent = univ.Choice() def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): head, tail = substrate[:length], substrate[length:] if asn1Spec is None: asn1Object = self.protoComponent.clone(tagSet=tagSet) else: asn1Object = asn1Spec.clone() if substrateFun: return substrateFun(asn1Object, substrate, length) if asn1Object.tagSet == tagSet: if LOG: LOG('decoding %s as explicitly tagged CHOICE' % (tagSet,)) component, head = decodeFun( head, asn1Object.componentTagMap, **options ) else: if LOG: LOG('decoding %s as untagged CHOICE' % (tagSet,)) component, head = decodeFun( head, asn1Object.componentTagMap, tagSet, length, state, **options ) effectiveTagSet = component.effectiveTagSet if LOG: LOG('decoded component %s, effective tag set %s' % (component, effectiveTagSet)) asn1Object.setComponentByType( effectiveTagSet, component, verifyConstraints=False, matchTags=False, matchConstraints=False, innerFlag=False ) return asn1Object, tail def indefLenValueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if asn1Spec is None: asn1Object = self.protoComponent.clone(tagSet=tagSet) else: asn1Object = asn1Spec.clone() if substrateFun: return substrateFun(asn1Object, substrate, length) if asn1Object.tagSet == tagSet: if LOG: LOG('decoding %s as explicitly tagged CHOICE' % (tagSet,)) component, substrate = decodeFun( substrate, asn1Object.componentType.tagMapUnique, **options ) # eat up EOO marker eooMarker, substrate = decodeFun( substrate, allowEoo=True, **options ) if eooMarker is not eoo.endOfOctets: raise error.PyAsn1Error('No EOO seen before substrate ends') else: if LOG: LOG('decoding %s as untagged CHOICE' % (tagSet,)) component, substrate = decodeFun( substrate, asn1Object.componentType.tagMapUnique, tagSet, length, state, **options ) effectiveTagSet = component.effectiveTagSet if LOG: LOG('decoded component %s, effective tag set %s' % (component, effectiveTagSet)) asn1Object.setComponentByType( effectiveTagSet, component, verifyConstraints=False, matchTags=False, matchConstraints=False, innerFlag=False ) return asn1Object, substrate class AnyDecoder(AbstractSimpleDecoder): protoComponent = univ.Any() def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if asn1Spec is None: isUntagged = True elif asn1Spec.__class__ is tagmap.TagMap: isUntagged = tagSet not in asn1Spec.tagMap else: isUntagged = tagSet != asn1Spec.tagSet if isUntagged: fullSubstrate = options['fullSubstrate'] # untagged Any container, recover inner header substrate length += len(fullSubstrate) - len(substrate) substrate = fullSubstrate if LOG: LOG('decoding as untagged ANY, substrate %s' % debug.hexdump(substrate)) if substrateFun: return substrateFun(self._createComponent(asn1Spec, tagSet, noValue, **options), substrate, length) head, tail = substrate[:length], substrate[length:] return self._createComponent(asn1Spec, tagSet, head, **options), tail def indefLenValueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if asn1Spec is None: isTagged = False elif asn1Spec.__class__ is tagmap.TagMap: isTagged = tagSet in asn1Spec.tagMap else: isTagged = tagSet == asn1Spec.tagSet if isTagged: # tagged Any type -- consume header substrate header = null if LOG: LOG('decoding as tagged ANY') else: fullSubstrate = options['fullSubstrate'] # untagged Any, recover header substrate header = fullSubstrate[:-len(substrate)] if LOG: LOG('decoding as untagged ANY, header substrate %s' % debug.hexdump(header)) # Any components do not inherit initial tag asn1Spec = self.protoComponent if substrateFun and substrateFun is not self.substrateCollector: asn1Object = self._createComponent(asn1Spec, tagSet, noValue, **options) return substrateFun(asn1Object, header + substrate, length + len(header)) if LOG: LOG('assembling constructed serialization') # All inner fragments are of the same type, treat them as octet string substrateFun = self.substrateCollector while substrate: component, substrate = decodeFun(substrate, asn1Spec, substrateFun=substrateFun, allowEoo=True, **options) if component is eoo.endOfOctets: break header += component else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) if substrateFun: return header, substrate else: return self._createComponent(asn1Spec, tagSet, header, **options), substrate # character string types class UTF8StringDecoder(OctetStringDecoder): protoComponent = char.UTF8String() class NumericStringDecoder(OctetStringDecoder): protoComponent = char.NumericString() class PrintableStringDecoder(OctetStringDecoder): protoComponent = char.PrintableString() class TeletexStringDecoder(OctetStringDecoder): protoComponent = char.TeletexString() class VideotexStringDecoder(OctetStringDecoder): protoComponent = char.VideotexString() class IA5StringDecoder(OctetStringDecoder): protoComponent = char.IA5String() class GraphicStringDecoder(OctetStringDecoder): protoComponent = char.GraphicString() class VisibleStringDecoder(OctetStringDecoder): protoComponent = char.VisibleString() class GeneralStringDecoder(OctetStringDecoder): protoComponent = char.GeneralString() class UniversalStringDecoder(OctetStringDecoder): protoComponent = char.UniversalString() class BMPStringDecoder(OctetStringDecoder): protoComponent = char.BMPString() # "useful" types class ObjectDescriptorDecoder(OctetStringDecoder): protoComponent = useful.ObjectDescriptor() class GeneralizedTimeDecoder(OctetStringDecoder): protoComponent = useful.GeneralizedTime() class UTCTimeDecoder(OctetStringDecoder): protoComponent = useful.UTCTime() tagMap = { univ.Integer.tagSet: IntegerDecoder(), univ.Boolean.tagSet: BooleanDecoder(), univ.BitString.tagSet: BitStringDecoder(), univ.OctetString.tagSet: OctetStringDecoder(), univ.Null.tagSet: NullDecoder(), univ.ObjectIdentifier.tagSet: ObjectIdentifierDecoder(), univ.Enumerated.tagSet: IntegerDecoder(), univ.Real.tagSet: RealDecoder(), univ.Sequence.tagSet: SequenceOrSequenceOfDecoder(), # conflicts with SequenceOf univ.Set.tagSet: SetOrSetOfDecoder(), # conflicts with SetOf univ.Choice.tagSet: ChoiceDecoder(), # conflicts with Any # character string types char.UTF8String.tagSet: UTF8StringDecoder(), char.NumericString.tagSet: NumericStringDecoder(), char.PrintableString.tagSet: PrintableStringDecoder(), char.TeletexString.tagSet: TeletexStringDecoder(), char.VideotexString.tagSet: VideotexStringDecoder(), char.IA5String.tagSet: IA5StringDecoder(), char.GraphicString.tagSet: GraphicStringDecoder(), char.VisibleString.tagSet: VisibleStringDecoder(), char.GeneralString.tagSet: GeneralStringDecoder(), char.UniversalString.tagSet: UniversalStringDecoder(), char.BMPString.tagSet: BMPStringDecoder(), # useful types useful.ObjectDescriptor.tagSet: ObjectDescriptorDecoder(), useful.GeneralizedTime.tagSet: GeneralizedTimeDecoder(), useful.UTCTime.tagSet: UTCTimeDecoder() } # Type-to-codec map for ambiguous ASN.1 types typeMap = { univ.Set.typeId: SetDecoder(), univ.SetOf.typeId: SetOfDecoder(), univ.Sequence.typeId: SequenceDecoder(), univ.SequenceOf.typeId: SequenceOfDecoder(), univ.Choice.typeId: ChoiceDecoder(), univ.Any.typeId: AnyDecoder() } # Put in non-ambiguous types for faster codec lookup for typeDecoder in tagMap.values(): if typeDecoder.protoComponent is not None: typeId = typeDecoder.protoComponent.__class__.typeId if typeId is not None and typeId not in typeMap: typeMap[typeId] = typeDecoder (stDecodeTag, stDecodeLength, stGetValueDecoder, stGetValueDecoderByAsn1Spec, stGetValueDecoderByTag, stTryAsExplicitTag, stDecodeValue, stDumpRawValue, stErrorCondition, stStop) = [x for x in range(10)] class Decoder(object): defaultErrorState = stErrorCondition #defaultErrorState = stDumpRawValue defaultRawDecoder = AnyDecoder() supportIndefLength = True # noinspection PyDefaultArgument def __init__(self, tagMap, typeMap={}): self.__tagMap = tagMap self.__typeMap = typeMap # Tag & TagSet objects caches self.__tagCache = {} self.__tagSetCache = {} self.__eooSentinel = ints2octs((0, 0)) def __call__(self, substrate, asn1Spec=None, tagSet=None, length=None, state=stDecodeTag, decodeFun=None, substrateFun=None, **options): if LOG: LOG('decoder called at scope %s with state %d, working with up to %d octets of substrate: %s' % (debug.scope, state, len(substrate), debug.hexdump(substrate))) allowEoo = options.pop('allowEoo', False) # Look for end-of-octets sentinel if allowEoo and self.supportIndefLength: if substrate[:2] == self.__eooSentinel: if LOG: LOG('end-of-octets sentinel found') return eoo.endOfOctets, substrate[2:] value = noValue tagMap = self.__tagMap typeMap = self.__typeMap tagCache = self.__tagCache tagSetCache = self.__tagSetCache fullSubstrate = substrate while state is not stStop: if state is stDecodeTag: if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on tag decoding' ) # Decode tag isShortTag = True firstOctet = substrate[0] substrate = substrate[1:] try: lastTag = tagCache[firstOctet] except KeyError: integerTag = oct2int(firstOctet) tagClass = integerTag & 0xC0 tagFormat = integerTag & 0x20 tagId = integerTag & 0x1F if tagId == 0x1F: isShortTag = False lengthOctetIdx = 0 tagId = 0 try: while True: integerTag = oct2int(substrate[lengthOctetIdx]) lengthOctetIdx += 1 tagId <<= 7 tagId |= (integerTag & 0x7F) if not integerTag & 0x80: break substrate = substrate[lengthOctetIdx:] except IndexError: raise error.SubstrateUnderrunError( 'Short octet stream on long tag decoding' ) lastTag = tag.Tag( tagClass=tagClass, tagFormat=tagFormat, tagId=tagId ) if isShortTag: # cache short tags tagCache[firstOctet] = lastTag if tagSet is None: if isShortTag: try: tagSet = tagSetCache[firstOctet] except KeyError: # base tag not recovered tagSet = tag.TagSet((), lastTag) tagSetCache[firstOctet] = tagSet else: tagSet = tag.TagSet((), lastTag) else: tagSet = lastTag + tagSet state = stDecodeLength if LOG: LOG('tag decoded into %s, decoding length' % tagSet) if state is stDecodeLength: # Decode length if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on length decoding' ) firstOctet = oct2int(substrate[0]) if firstOctet < 128: size = 1 length = firstOctet elif firstOctet > 128: size = firstOctet & 0x7F # encoded in size bytes encodedLength = octs2ints(substrate[1:size + 1]) # missing check on maximum size, which shouldn't be a # problem, we can handle more than is possible if len(encodedLength) != size: raise error.SubstrateUnderrunError( '%s<%s at %s' % (size, len(encodedLength), tagSet) ) length = 0 for lengthOctet in encodedLength: length <<= 8 length |= lengthOctet size += 1 else: size = 1 length = -1 substrate = substrate[size:] if length == -1: if not self.supportIndefLength: raise error.PyAsn1Error('Indefinite length encoding not supported by this codec') else: if len(substrate) < length: raise error.SubstrateUnderrunError('%d-octet short' % (length - len(substrate))) state = stGetValueDecoder if LOG: LOG('value length decoded into %d, payload substrate is: %s' % (length, debug.hexdump(length == -1 and substrate or substrate[:length]))) if state is stGetValueDecoder: if asn1Spec is None: state = stGetValueDecoderByTag else: state = stGetValueDecoderByAsn1Spec # # There're two ways of creating subtypes in ASN.1 what influences # decoder operation. These methods are: # 1) Either base types used in or no IMPLICIT tagging has been # applied on subtyping. # 2) Subtype syntax drops base type information (by means of # IMPLICIT tagging. # The first case allows for complete tag recovery from substrate # while the second one requires original ASN.1 type spec for # decoding. # # In either case a set of tags (tagSet) is coming from substrate # in an incremental, tag-by-tag fashion (this is the case of # EXPLICIT tag which is most basic). Outermost tag comes first # from the wire. # if state is stGetValueDecoderByTag: try: concreteDecoder = tagMap[tagSet] except KeyError: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: try: concreteDecoder = tagMap[tagSet[:1]] except KeyError: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: state = stTryAsExplicitTag if LOG: LOG('codec %s chosen by a built-in type, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state is stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push(concreteDecoder is None and '?' or concreteDecoder.protoComponent.__class__.__name__) if state is stGetValueDecoderByAsn1Spec: if asn1Spec.__class__ is tagmap.TagMap: try: chosenSpec = asn1Spec[tagSet] except KeyError: chosenSpec = None if LOG: LOG('candidate ASN.1 spec is a map of:') for firstOctet, v in asn1Spec.presentTypes.items(): LOG(' %s -> %s' % (firstOctet, v.__class__.__name__)) if asn1Spec.skipTypes: LOG('but neither of: ') for firstOctet, v in asn1Spec.skipTypes.items(): LOG(' %s -> %s' % (firstOctet, v.__class__.__name__)) LOG('new candidate ASN.1 spec is %s, chosen by %s' % (chosenSpec is None and '<none>' or chosenSpec.prettyPrintType(), tagSet)) elif tagSet == asn1Spec.tagSet or tagSet in asn1Spec.tagMap: chosenSpec = asn1Spec if LOG: LOG('candidate ASN.1 spec is %s' % asn1Spec.__class__.__name__) else: chosenSpec = None if chosenSpec is not None: try: # ambiguous type or just faster codec lookup concreteDecoder = typeMap[chosenSpec.typeId] if LOG: LOG('value decoder chosen for an ambiguous type by type ID %s' % (chosenSpec.typeId,)) except KeyError: # use base type for codec lookup to recover untagged types baseTagSet = tag.TagSet(chosenSpec.tagSet.baseTag, chosenSpec.tagSet.baseTag) try: # base type or tagged subtype concreteDecoder = tagMap[baseTagSet] if LOG: LOG('value decoder chosen by base %s' % (baseTagSet,)) except KeyError: concreteDecoder = None if concreteDecoder: asn1Spec = chosenSpec state = stDecodeValue else: state = stTryAsExplicitTag else: concreteDecoder = None state = stTryAsExplicitTag if LOG: LOG('codec %s chosen by ASN.1 spec, decoding %s' % (state is stDecodeValue and concreteDecoder.__class__.__name__ or "<none>", state is stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push(chosenSpec is None and '?' or chosenSpec.__class__.__name__) if state is stDecodeValue: if not options.get('recursiveFlag', True) and not substrateFun: # deprecate this substrateFun = lambda a, b, c: (a, b[:c]) options.update(fullSubstrate=fullSubstrate) if length == -1: # indef length value, substrate = concreteDecoder.indefLenValueDecoder( substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun, **options ) else: value, substrate = concreteDecoder.valueDecoder( substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun, **options ) if LOG: LOG('codec %s yields type %s, value:\n%s\n...remaining substrate is: %s' % (concreteDecoder.__class__.__name__, value.__class__.__name__, isinstance(value, base.Asn1Item) and value.prettyPrint() or value, substrate and debug.hexdump(substrate) or '<none>')) state = stStop break if state is stTryAsExplicitTag: if (tagSet and tagSet[0].tagFormat == tag.tagFormatConstructed and tagSet[0].tagClass != tag.tagClassUniversal): # Assume explicit tagging concreteDecoder = explicitTagDecoder state = stDecodeValue else: concreteDecoder = None state = self.defaultErrorState if LOG: LOG('codec %s chosen, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state is stDecodeValue and 'value' or 'as failure')) if state is stDumpRawValue: concreteDecoder = self.defaultRawDecoder if LOG: LOG('codec %s chosen, decoding value' % concreteDecoder.__class__.__name__) state = stDecodeValue if state is stErrorCondition: raise error.PyAsn1Error( '%s not in asn1Spec: %r' % (tagSet, asn1Spec) ) if LOG: debug.scope.pop() LOG('decoder left scope %s, call completed' % debug.scope) return value, substrate #: Turns BER octet stream into an ASN.1 object. #: #: Takes BER octet-stream and decode it into an ASN.1 object #: (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) which #: may be a scalar or an arbitrary nested structure. #: #: Parameters #: ---------- #: substrate: :py:class:`bytes` (Python 3) or :py:class:`str` (Python 2) #: BER octet-stream #: #: Keyword Args #: ------------ #: asn1Spec: any pyasn1 type object e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative #: A pyasn1 type object to act as a template guiding the decoder. Depending on the ASN.1 structure #: being decoded, *asn1Spec* may or may not be required. Most common reason for #: it to require is that ASN.1 structure is encoded in *IMPLICIT* tagging mode. #: #: Returns #: ------- #: : :py:class:`tuple` #: A tuple of pyasn1 object recovered from BER substrate (:py:class:`~pyasn1.type.base.PyAsn1Item` derivative) #: and the unprocessed trailing portion of the *substrate* (may be empty) #: #: Raises #: ------ #: ~pyasn1.error.PyAsn1Error, ~pyasn1.error.SubstrateUnderrunError #: On decoding errors #: #: Examples #: -------- #: Decode BER serialisation without ASN.1 schema #: #: .. code-block:: pycon #: #: >>> s, _ = decode(b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03') #: >>> str(s) #: SequenceOf: #: 1 2 3 #: #: Decode BER serialisation with ASN.1 schema #: #: .. code-block:: pycon #: #: >>> seq = SequenceOf(componentType=Integer()) #: >>> s, _ = decode(b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03', asn1Spec=seq) #: >>> str(s) #: SequenceOf: #: 1 2 3 #: decode = Decoder(tagMap, typeMap) # XXX # non-recursive decoding; return position rather than substrate<|fim▁end|>
__all__ = ['decode']
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from .main import main, zdkb<|fim▁end|>
<|file_name|>SILGenBridging.cpp<|end_file_name|><|fim▁begin|>//===--- SILGenBridging.cpp - SILGen for bridging to Clang ASTs -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "ArgumentScope.h" #include "Callee.h" #include "RValue.h" #include "ResultPlan.h" #include "SILGenFunction.h" #include "Scope.h" #include "swift/AST/DiagnosticsSIL.h" #include "swift/AST/ExistentialLayout.h" #include "swift/AST/ForeignErrorConvention.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/ParameterList.h" #include "swift/AST/ProtocolConformance.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILUndef.h" #include "swift/SIL/TypeLowering.h" using namespace swift; using namespace Lowering; /// Convert to the given formal type, assuming that the lowered type of /// the source type is the same as its formal type. This is a reasonable /// assumption for a wide variety of types. static ManagedValue emitUnabstractedCast(SILGenFunction &SGF, SILLocation loc, ManagedValue value, CanType sourceFormalType, CanType targetFormalType) { if (value.getType() == SGF.getLoweredType(targetFormalType)) return value; return SGF.emitTransformedValue(loc, value, AbstractionPattern(sourceFormalType), sourceFormalType, AbstractionPattern(targetFormalType), targetFormalType); } static bool shouldBridgeThroughError(SILGenModule &SGM, CanType type, CanType targetType) { // Never use this logic if the target type is AnyObject. if (targetType->isEqual(SGM.getASTContext().getAnyObjectType())) return false; auto errorProtocol = SGM.getASTContext().getErrorDecl(); if (!errorProtocol) return false; // Existential types are convertible to Error if they are, or imply, Error. if (type.isExistentialType()) { auto layout = type->getExistentialLayout(); for (auto proto : layout.getProtocols()) { if (proto->getDecl() == errorProtocol || proto->getDecl()->inheritsFrom(errorProtocol)) { return true; } } // They're also convertible to Error if they have a class bound that // conforms to Error. if (auto cls = layout.superclass) { type = cls->getCanonicalType(); // Otherwise, they are not convertible to Error. } else { return false; } } auto optConf = SGM.SwiftModule->lookupConformance(type, errorProtocol); return optConf.hasValue(); } /// Bridge the given Swift value to its corresponding Objective-C /// object, using the appropriate witness for the /// _ObjectiveCBridgeable._bridgeToObjectiveC requirement. static Optional<ManagedValue> emitBridgeNativeToObjectiveC(SILGenFunction &SGF, SILLocation loc, ManagedValue swiftValue, CanType swiftValueType, CanType bridgedType, ProtocolConformance *conformance) { // Find the _bridgeToObjectiveC requirement. auto requirement = SGF.SGM.getBridgeToObjectiveCRequirement(loc); if (!requirement) return None; // Retrieve the _bridgeToObjectiveC witness. auto witness = conformance->getWitnessDecl(requirement, nullptr); assert(witness); // Determine the type we're bridging to. auto objcTypeReq = SGF.SGM.getBridgedObjectiveCTypeRequirement(loc); if (!objcTypeReq) return None; Type objcType = conformance->getTypeWitness(objcTypeReq, nullptr); assert(objcType); // Create a reference to the witness. SILDeclRef witnessConstant(witness); auto witnessRef = SGF.emitGlobalFunctionRef(loc, witnessConstant); // Determine the substitutions. auto witnessFnTy = witnessRef->getType(); // Compute the substitutions. // FIXME: Figure out the right SubstitutionMap stuff if the witness // has generic parameters of its own. assert(!cast<FuncDecl>(witness)->isGeneric() && "Generic witnesses not supported"); auto *dc = cast<FuncDecl>(witness)->getDeclContext(); auto *genericSig = dc->getGenericSignatureOfContext(); auto typeSubMap = swiftValueType->getContextSubstitutionMap( SGF.SGM.SwiftModule, dc); // Substitute into the witness function type. witnessFnTy = witnessFnTy.substGenericArgs(SGF.SGM.M, typeSubMap); // The witness may be more abstract than the concrete value we're bridging, // for instance, if the value is a concrete instantiation of a generic type. // // Note that we assume that we don't ever have to reabstract the parameter. // This is safe for now, since only nominal types currently can conform to // protocols. SILFunctionConventions witnessConv(witnessFnTy.castTo<SILFunctionType>(), SGF.SGM.M); if (witnessConv.isSILIndirect(witnessConv.getParameters()[0]) && !swiftValue.getType().isAddress()) { auto tmp = SGF.emitTemporaryAllocation(loc, swiftValue.getType()); SGF.B.createStoreBorrowOrTrivial(loc, swiftValue.borrow(SGF, loc), tmp); swiftValue = ManagedValue::forUnmanaged(tmp); } SmallVector<Substitution, 4> subs; if (genericSig) genericSig->getSubstitutions(typeSubMap, subs); // Call the witness. SILType resultTy = SGF.getLoweredType(objcType); SILValue bridgedValue = SGF.B.createApply(loc, witnessRef, witnessFnTy, resultTy, subs, swiftValue.borrow(SGF, loc).getValue()); auto bridgedMV = SGF.emitManagedRValueWithCleanup(bridgedValue); // The Objective-C value doesn't necessarily match the desired type. bridgedMV = emitUnabstractedCast(SGF, loc, bridgedMV, objcType->getCanonicalType(), bridgedType); return bridgedMV; } /// Bridge the given Objective-C object to its corresponding Swift /// value, using the appropriate witness for the /// _ObjectiveCBridgeable._unconditionallyBridgeFromObjectiveC requirement. static Optional<ManagedValue> emitBridgeObjectiveCToNative(SILGenFunction &SGF, SILLocation loc, ManagedValue objcValue, CanType bridgedType, ProtocolConformance *conformance) { // Find the _unconditionallyBridgeFromObjectiveC requirement. auto requirement = SGF.SGM.getUnconditionallyBridgeFromObjectiveCRequirement(loc); if (!requirement) return None; // Find the _ObjectiveCType requirement. auto objcTypeRequirement = SGF.SGM.getBridgedObjectiveCTypeRequirement(loc); if (!objcTypeRequirement) return None; // Retrieve the _unconditionallyBridgeFromObjectiveC witness. auto witness = conformance->getWitnessDeclRef(requirement, nullptr); assert(witness); // Retrieve the _ObjectiveCType witness. auto objcType = conformance->getTypeWitness(objcTypeRequirement, nullptr); assert(objcType); // Create a reference to the witness. SILDeclRef witnessConstant(witness.getDecl()); auto witnessRef = SGF.emitGlobalFunctionRef(loc, witnessConstant); // Determine the substitutions. auto witnessFnTy = witnessRef->getType().castTo<SILFunctionType>(); CanType swiftValueType = conformance->getType()->getCanonicalType(); auto genericSig = witnessFnTy->getGenericSignature(); SubstitutionMap typeSubMap; if (genericSig) typeSubMap = genericSig->getSubstitutionMap(witness.getSubstitutions()); // Substitute into the witness function type. witnessFnTy = witnessFnTy->substGenericArgs(SGF.SGM.M, typeSubMap); // The witness takes an _ObjectiveCType?, so convert to that type. CanType desiredValueType = OptionalType::get(objcType)->getCanonicalType(); objcValue = emitUnabstractedCast(SGF, loc, objcValue, bridgedType, desiredValueType); // Call the witness. auto metatypeParam = witnessFnTy->getParameters()[1]; assert(isa<MetatypeType>(metatypeParam.getType()) && cast<MetatypeType>(metatypeParam.getType()).getInstanceType() == swiftValueType); SILValue metatypeValue = SGF.B.createMetatype(loc, metatypeParam.getSILStorageType()); auto witnessCI = SGF.getConstantInfo(witnessConstant); CanType formalResultTy = witnessCI.LoweredType.getResult(); auto subs = witness.getSubstitutions(); // Set up the generic signature, since formalResultTy is an interface type. GenericContextScope genericContextScope(SGF.SGM.Types, genericSig); CalleeTypeInfo calleeTypeInfo( witnessFnTy, AbstractionPattern(genericSig, formalResultTy), swiftValueType); SGFContext context; ResultPlanPtr resultPlan = ResultPlanBuilder::computeResultPlan(SGF, calleeTypeInfo, loc, context); ArgumentScope argScope(SGF, loc); RValue result = SGF.emitApply(std::move(resultPlan), std::move(argScope), loc, ManagedValue::forUnmanaged(witnessRef), subs, {objcValue, ManagedValue::forUnmanaged(metatypeValue)}, calleeTypeInfo, ApplyOptions::None, context); return std::move(result).getAsSingleValue(SGF, loc); } static ManagedValue emitBridgeBoolToObjCBool(SILGenFunction &SGF, SILLocation loc, ManagedValue swiftBool) { // func _convertBoolToObjCBool(Bool) -> ObjCBool SILValue boolToObjCBoolFn = SGF.emitGlobalFunctionRef(loc, SGF.SGM.getBoolToObjCBoolFn()); SILType resultTy =SGF.getLoweredLoadableType(SGF.SGM.Types.getObjCBoolType()); SILValue result = SGF.B.createApply(loc, boolToObjCBoolFn, boolToObjCBoolFn->getType(), resultTy, {}, swiftBool.forward(SGF)); return SGF.emitManagedRValueWithCleanup(result); } static ManagedValue emitBridgeBoolToDarwinBoolean(SILGenFunction &SGF, SILLocation loc, ManagedValue swiftBool) { // func _convertBoolToDarwinBoolean(Bool) -> DarwinBoolean SILValue boolToDarwinBooleanFn = SGF.emitGlobalFunctionRef(loc, SGF.SGM.getBoolToDarwinBooleanFn()); SILType resultTy = SGF.getLoweredLoadableType(SGF.SGM.Types.getDarwinBooleanType()); SILValue result = SGF.B.createApply(loc, boolToDarwinBooleanFn, boolToDarwinBooleanFn->getType(), resultTy, {}, swiftBool.forward(SGF)); return SGF.emitManagedRValueWithCleanup(result); } static ManagedValue emitBridgeForeignBoolToBool(SILGenFunction &SGF, SILLocation loc, ManagedValue foreignBool, SILDeclRef bridgingFnRef) { // func _convertObjCBoolToBool(ObjCBool) -> Bool SILValue bridgingFn = SGF.emitGlobalFunctionRef(loc, bridgingFnRef); SILType resultTy = SGF.getLoweredLoadableType(SGF.SGM.Types.getBoolType()); SILValue result = SGF.B.createApply(loc, bridgingFn, bridgingFn->getType(), resultTy, {}, foreignBool.forward(SGF)); return SGF.emitManagedRValueWithCleanup(result); } static ManagedValue emitManagedParameter(SILGenFunction &SGF, SILLocation loc, SILParameterInfo param, SILValue value) { const TypeLowering &valueTL = SGF.getTypeLowering(value->getType()); switch (param.getConvention()) { case ParameterConvention::Direct_Owned: // Consume owned parameters at +1. return SGF.emitManagedRValueWithCleanup(value, valueTL); case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Direct_Unowned: // We need to independently retain the value. return SGF.emitManagedRetain(loc, value, valueTL); case ParameterConvention::Indirect_Inout: return ManagedValue::forLValue(value); case ParameterConvention::Indirect_In_Guaranteed: case ParameterConvention::Indirect_In_Constant: if (valueTL.isLoadable()) { return SGF.emitLoad(loc, value, valueTL, SGFContext(), IsNotTake); } else { return SGF.emitManagedRetain(loc, value, valueTL); } case ParameterConvention::Indirect_In: if (valueTL.isLoadable()) { return SGF.emitLoad(loc, value, valueTL, SGFContext(), IsTake); } else { return SGF.emitManagedRValueWithCleanup(value, valueTL); } case ParameterConvention::Indirect_InoutAliasable: llvm_unreachable("unexpected inout_aliasable argument"); } llvm_unreachable("bad convention"); } static void expandTupleTypes(CanType type, SmallVectorImpl<CanType> &results) { if (auto tuple = dyn_cast<TupleType>(type)) { for (auto eltType : tuple.getElementTypes()) expandTupleTypes(eltType, results); } else { results.push_back(type); } } /// Recursively expand all the tuples in the given parameter list. /// Callers assume that the resulting array will line up with the /// SILFunctionType's parameter list, which is true as along as there /// aren't any indirectly-passed tuples; we should be safe from that /// here in the bridging code. static SmallVector<CanType, 8> expandTupleTypes(AnyFunctionType::CanParamArrayRef params) { SmallVector<CanType, 8> results; for (auto param : params) expandTupleTypes(param.getType(), results); return results; } static void buildFuncToBlockInvokeBody(SILGenFunction &SGF, SILLocation loc, CanAnyFunctionType formalFuncType, CanAnyFunctionType formalBlockType, CanSILFunctionType funcTy, CanSILFunctionType blockTy, CanSILBlockStorageType blockStorageTy) { Scope scope(SGF.Cleanups, CleanupLocation::get(loc)); SILBasicBlock *entry = &*SGF.F.begin(); SILFunctionConventions blockConv(blockTy, SGF.SGM.M); SILFunctionConventions funcConv(funcTy, SGF.SGM.M); // Make sure we lower the component types of the formal block type. formalBlockType = SGF.SGM.Types.getBridgedFunctionType(AbstractionPattern(formalBlockType), formalBlockType, formalBlockType->getExtInfo()); // Set up the indirect result. SILType blockResultTy = blockTy->getAllResultsType(); SILValue indirectResult; if (blockTy->getNumResults() != 0) { auto result = blockTy->getSingleResult(); if (result.getConvention() == ResultConvention::Indirect) { indirectResult = entry->createFunctionArgument(blockResultTy); } } // Get the captured native function value out of the block. auto storageAddrTy = SILType::getPrimitiveAddressType(blockStorageTy); auto storage = entry->createFunctionArgument(storageAddrTy); auto capture = SGF.B.createProjectBlockStorage(loc, storage); auto &funcTL = SGF.getTypeLowering(funcTy); auto fn = SGF.emitLoad(loc, capture, funcTL, SGFContext(), IsNotTake); // Collect the block arguments, which may have nonstandard conventions. assert(blockTy->getParameters().size() == funcTy->getParameters().size() && "block and function types don't match"); auto nativeParamTypes = expandTupleTypes(formalFuncType.getParams()); auto bridgedParamTypes = expandTupleTypes(formalBlockType.getParams()); SmallVector<ManagedValue, 4> args; for (unsigned i : indices(funcTy->getParameters())) { auto &param = blockTy->getParameters()[i]; SILType paramTy = blockConv.getSILType(param); SILValue v = entry->createFunctionArgument(paramTy); ManagedValue mv; // If the parameter is a block, we need to copy it to ensure it lives on // the heap. The adapted closure value might outlive the block's original // scope. if (SGF.getSILType(param).isBlockPointerCompatible()) { // We still need to consume the original block if it was owned. switch (param.getConvention()) { case ParameterConvention::Direct_Owned: SGF.emitManagedRValueWithCleanup(v); break; case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Direct_Unowned: break; case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: case ParameterConvention::Indirect_In_Guaranteed: case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: llvm_unreachable("indirect params to blocks not supported"); } SILValue blockCopy = SGF.B.createCopyBlock(loc, v); mv = SGF.emitManagedRValueWithCleanup(blockCopy); } else { mv = emitManagedParameter(SGF, loc, param, v); } CanType formalBridgedType = bridgedParamTypes[i]; CanType formalNativeType = nativeParamTypes[i]; SILType loweredNativeTy = funcTy->getParameters()[i].getSILStorageType(); args.push_back(SGF.emitBridgedToNativeValue(loc, mv, formalBridgedType, formalNativeType, loweredNativeTy)); } auto init = indirectResult ? SGF.useBufferAsTemporary(indirectResult, SGF.getTypeLowering(indirectResult->getType())) : nullptr; CanType formalNativeResultType = formalFuncType.getResult(); CanType formalBridgedResultType = formalBlockType.getResult(); bool canEmitIntoInit = (indirectResult && indirectResult->getType() == SGF.getLoweredType(formalNativeResultType).getAddressType()); // Call the native function. SGFContext C(canEmitIntoInit ? init.get() : nullptr); ManagedValue result = SGF.emitMonomorphicApply(loc, fn, args, formalNativeResultType, formalNativeResultType, ApplyOptions::None, None, None, C) .getAsSingleValue(SGF, loc); // Bridge the result back to ObjC. if (!canEmitIntoInit) { result = SGF.emitNativeToBridgedValue(loc, result, formalNativeResultType, formalBridgedResultType, blockResultTy, SGFContext(init.get())); } SILValue resultVal; // If we have an indirect result, make sure the result is there. if (indirectResult) { if (!result.isInContext()) { init->copyOrInitValueInto(SGF, loc, result, /*isInit*/ true); init->finishInitialization(SGF); } init->getManagedAddress().forward(SGF); resultVal = SGF.B.createTuple(loc, {}); // Otherwise, return the result at +1. } else { resultVal = result.forward(SGF); } scope.pop(); SGF.B.createReturn(loc, resultVal); } /// Bridge a native function to a block with a thunk. ManagedValue SILGenFunction::emitFuncToBlock(SILLocation loc, ManagedValue fn, CanAnyFunctionType funcType, CanAnyFunctionType blockType, CanSILFunctionType loweredBlockTy){ auto loweredFuncTy = fn.getType().castTo<SILFunctionType>(); // Build the invoke function signature. The block will capture the original // function value. auto fnInterfaceTy = cast<SILFunctionType>( F.mapTypeOutOfContext(loweredFuncTy)->getCanonicalType()); auto blockInterfaceTy = cast<SILFunctionType>( F.mapTypeOutOfContext(loweredBlockTy)->getCanonicalType()); auto storageTy = SILBlockStorageType::get(loweredFuncTy); auto storageInterfaceTy = SILBlockStorageType::get(fnInterfaceTy); // Build the invoke function type. SmallVector<SILParameterInfo, 4> params; params.push_back(SILParameterInfo(storageInterfaceTy, ParameterConvention::Indirect_InoutAliasable)); std::copy(blockInterfaceTy->getParameters().begin(), blockInterfaceTy->getParameters().end(), std::back_inserter(params)); auto extInfo = SILFunctionType::ExtInfo() .withRepresentation(SILFunctionType::Representation::CFunctionPointer); CanGenericSignature genericSig; GenericEnvironment *genericEnv = nullptr; SubstitutionList subs; if (funcType->hasArchetype() || blockType->hasArchetype()) { genericSig = F.getLoweredFunctionType()->getGenericSignature(); genericEnv = F.getGenericEnvironment(); subs = F.getForwardingSubstitutions(); // The block invoke function must be pseudogeneric. This should be OK for now // since a bridgeable function's parameters and returns should all be // trivially representable in ObjC so not need to exercise the type metadata. // // Ultimately we may need to capture generic parameters in block storage, but // that will require a redesign of the interface to support dependent-layout // context. Currently we don't capture anything directly into a block but a // Swift closure, but that's totally dumb. if (genericSig) extInfo = extInfo.withIsPseudogeneric(); } auto invokeTy = SILFunctionType::get( genericSig, extInfo, ParameterConvention::Direct_Unowned, params, blockInterfaceTy->getResults(), blockInterfaceTy->getOptionalErrorResult(), getASTContext()); // Create the invoke function. Borrow the mangling scheme from reabstraction // thunks, which is what we are in spirit. auto thunk = SGM.getOrCreateReabstractionThunk(genericEnv, invokeTy, loweredFuncTy, loweredBlockTy, F.isSerialized()); // Build it if necessary. if (thunk->empty()) { thunk->setGenericEnvironment(genericEnv); SILGenFunction thunkSGF(SGM, *thunk); auto loc = RegularLocation::getAutoGeneratedLocation(); buildFuncToBlockInvokeBody(thunkSGF, loc, funcType, blockType, loweredFuncTy, loweredBlockTy, storageTy); } // Form the block on the stack. auto storageAddrTy = SILType::getPrimitiveAddressType(storageTy); auto storage = emitTemporaryAllocation(loc, storageAddrTy); auto capture = B.createProjectBlockStorage(loc, storage); B.createStore(loc, fn, capture, StoreOwnershipQualifier::Init); auto invokeFn = B.createFunctionRef(loc, thunk); auto stackBlock = B.createInitBlockStorageHeader(loc, storage, invokeFn, SILType::getPrimitiveObjectType(loweredBlockTy), subs); // Copy the block so we have an independent heap object we can hand off. auto heapBlock = B.createCopyBlock(loc, stackBlock); return emitManagedRValueWithCleanup(heapBlock); } static ManagedValue emitNativeToCBridgedNonoptionalValue(SILGenFunction &SGF, SILLocation loc, ManagedValue v, CanType nativeType, CanType bridgedType, SILType loweredBridgedTy, SGFContext C) { assert(loweredBridgedTy.isObject()); if (v.getType().getObjectType() == loweredBridgedTy) return v; // If the input is a native type with a bridged mapping, convert it. #define BRIDGE_TYPE(BridgedModule,BridgedType, NativeModule,NativeType,Opt) \ if (nativeType == SGF.SGM.Types.get##NativeType##Type() \ && bridgedType == SGF.SGM.Types.get##BridgedType##Type()) { \ return emitBridge##NativeType##To##BridgedType(SGF, loc, v); \ } #include "swift/SIL/BridgedTypes.def" // Bridge thick to Objective-C metatypes. if (auto bridgedMetaTy = dyn_cast<AnyMetatypeType>(bridgedType)) { if (bridgedMetaTy->hasRepresentation() && bridgedMetaTy->getRepresentation() == MetatypeRepresentation::ObjC) { SILValue native = SGF.B.emitThickToObjCMetatype(loc, v.getValue(), loweredBridgedTy); // *NOTE*: ObjCMetatypes are trivial types. They only gain ARC semantics // when they are converted to an object via objc_metatype_to_object. assert(!v.hasCleanup() && "Metatypes are trivial and thus should not have cleanups"); return ManagedValue::forUnmanaged(native); } } // Bridge native functions to blocks. auto bridgedFTy = dyn_cast<AnyFunctionType>(bridgedType); if (bridgedFTy && bridgedFTy->getRepresentation() == AnyFunctionType::Representation::Block) { auto nativeFTy = cast<AnyFunctionType>(nativeType); if (nativeFTy->getRepresentation() != AnyFunctionType::Representation::Block) return SGF.emitFuncToBlock(loc, v, nativeFTy, bridgedFTy, loweredBridgedTy.castTo<SILFunctionType>()); } // If the native type conforms to _ObjectiveCBridgeable, use its // _bridgeToObjectiveC witness. if (auto conformance = SGF.SGM.getConformanceToObjectiveCBridgeable(loc, nativeType)) { if (auto result = emitBridgeNativeToObjectiveC(SGF, loc, v, nativeType, bridgedType, conformance)) return *result; assert(SGF.SGM.getASTContext().Diags.hadAnyError() && "Bridging code should have complained"); return SGF.emitUndef(loc, bridgedType); } // Bridge Error, or types that conform to it, to NSError. if (shouldBridgeThroughError(SGF.SGM, nativeType, bridgedType)) { auto errorTy = SGF.SGM.Types.getNSErrorType(); auto error = SGF.emitNativeToBridgedError(loc, v, nativeType, errorTy); if (errorTy != bridgedType) { error = emitUnabstractedCast(SGF, loc, error, errorTy, bridgedType); } return error; } // Fall back to dynamic Any-to-id bridging. // The destination type should be AnyObject in this case. assert(bridgedType->isEqual(SGF.getASTContext().getAnyObjectType())); // If the input argument is known to be an existential, save the runtime // some work by opening it. if (nativeType->isExistentialType()) { auto openedType = ArchetypeType::getOpened(nativeType); auto openedExistential = SGF.emitOpenExistential( loc, v, openedType, SGF.getLoweredType(openedType), AccessKind::Read); v = SGF.manageOpaqueValue(openedExistential, loc, SGFContext()); nativeType = openedType; } // Call into the stdlib intrinsic. if (auto bridgeAnything = SGF.getASTContext().getBridgeAnythingToObjectiveC(nullptr)) { auto *genericSig = bridgeAnything->getGenericSignature(); auto subMap = genericSig->getSubstitutionMap( [&](SubstitutableType *t) -> Type { return nativeType; }, MakeAbstractConformanceForGenericType()); // The intrinsic takes a T; reabstract to the generic abstraction // pattern. v = SGF.emitSubstToOrigValue(loc, v, AbstractionPattern::getOpaque(), nativeType); // Put the value into memory if necessary. assert(v.getType().isTrivial(SGF.SGM.M) || v.hasCleanup()); SILModuleConventions silConv(SGF.SGM.M); // bridgeAnything always takes an indirect argument as @in. // Since we don't have the SIL type here, check the current SIL stage/mode // to determine the convention. if (v.getType().isObject() && silConv.useLoweredAddresses()) { auto tmp = SGF.emitTemporaryAllocation(loc, v.getType()); v.forwardInto(SGF, loc, tmp); v = SGF.emitManagedBufferWithCleanup(tmp); } return SGF.emitApplyOfLibraryIntrinsic(loc, bridgeAnything, subMap, v, C) .getAsSingleValue(SGF, loc); } // Shouldn't get here unless the standard library is busted. return SGF.emitUndef(loc, loweredBridgedTy); } static ManagedValue emitNativeToCBridgedValue(SILGenFunction &SGF, SILLocation loc, ManagedValue v, CanType nativeType, CanType bridgedType, SILType loweredBridgedTy, SGFContext C = SGFContext()) { SILType loweredNativeTy = v.getType(); if (loweredNativeTy.getObjectType() == loweredBridgedTy.getObjectType()) return v; CanType bridgedObjectType = bridgedType.getAnyOptionalObjectType(); CanType nativeObjectType = nativeType.getAnyOptionalObjectType(); // Check for optional-to-optional conversions. if (bridgedObjectType && nativeObjectType) { auto helper = [&](SILGenFunction &SGF, SILLocation loc, ManagedValue v, SILType loweredBridgedObjectTy, SGFContext C) { return emitNativeToCBridgedValue(SGF, loc, v, nativeObjectType, bridgedObjectType, loweredBridgedObjectTy, C); }; return SGF.emitOptionalToOptional(loc, v, loweredBridgedTy, helper, C); } // Check if we need to wrap the bridged result in an optional. if (bridgedObjectType) { auto helper = [&](SILGenFunction &SGF, SILLocation loc, SGFContext C) { auto loweredBridgedObjectTy = loweredBridgedTy.getAnyOptionalObjectType(); return emitNativeToCBridgedValue(SGF, loc, v, nativeType, bridgedObjectType, loweredBridgedObjectTy, C); }; return SGF.emitOptionalSome(loc, loweredBridgedTy, helper, C); } return emitNativeToCBridgedNonoptionalValue(SGF, loc, v, nativeType, bridgedType, loweredBridgedTy, C); } ManagedValue SILGenFunction::emitNativeToBridgedValue(SILLocation loc, ManagedValue v, CanType nativeTy, CanType bridgedTy, SILType loweredBridgedTy, SGFContext C) { loweredBridgedTy = loweredBridgedTy.getObjectType(); return emitNativeToCBridgedValue(*this, loc, v, nativeTy, bridgedTy, loweredBridgedTy, C); } static void buildBlockToFuncThunkBody(SILGenFunction &SGF, SILLocation loc, CanAnyFunctionType formalBlockTy, CanAnyFunctionType formalFuncTy, CanSILFunctionType blockTy, CanSILFunctionType funcTy) { // Collect the native arguments, which should all be +1. Scope scope(SGF.Cleanups, CleanupLocation::get(loc)); assert(blockTy->getNumParameters() == funcTy->getNumParameters() && "block and function types don't match"); SmallVector<ManagedValue, 4> args; SILBasicBlock *entry = &*SGF.F.begin(); SILFunctionConventions fnConv(funcTy, SGF.SGM.M); // Set up the indirect result slot. SILValue indirectResult; if (funcTy->getNumResults() != 0) { auto result = funcTy->getSingleResult(); if (result.getConvention() == ResultConvention::Indirect) { SILType resultTy = fnConv.getSILType(result); indirectResult = entry->createFunctionArgument(resultTy); } } auto formalBlockParams = expandTupleTypes(formalBlockTy.getParams()); auto formalFuncParams = expandTupleTypes(formalFuncTy.getParams()); assert(formalBlockParams.size() == blockTy->getNumParameters()); assert(formalFuncParams.size() == funcTy->getNumParameters()); for (unsigned i : indices(funcTy->getParameters())) { auto &param = funcTy->getParameters()[i]; CanType formalBlockParamTy = formalBlockParams[i]; CanType formalFuncParamTy = formalFuncParams[i]; auto paramTy = fnConv.getSILType(param); SILValue v = entry->createFunctionArgument(paramTy); auto mv = emitManagedParameter(SGF, loc, param, v); SILType loweredBlockArgTy = blockTy->getParameters()[i].getSILStorageType(); args.push_back(SGF.emitNativeToBridgedValue(loc, mv, formalFuncParamTy, formalBlockParamTy, loweredBlockArgTy)); } // Add the block argument. SILValue blockV = entry->createFunctionArgument(SILType::getPrimitiveObjectType(blockTy)); ManagedValue block = SGF.emitManagedRValueWithCleanup(blockV); CanType formalResultType = formalFuncTy.getResult(); auto init = indirectResult ? SGF.useBufferAsTemporary(indirectResult, SGF.getTypeLowering(indirectResult->getType())) : nullptr; // Call the block. ManagedValue result = SGF.emitMonomorphicApply(loc, block, args, formalBlockTy.getResult(), formalResultType, ApplyOptions::None, /*override CC*/ SILFunctionTypeRepresentation::Block, /*foreign error*/ None, SGFContext(init.get())) .getAsSingleValue(SGF, loc); SILValue r; // If we have an indirect result, make sure the result is there. if (indirectResult) { if (!result.isInContext()) { init->copyOrInitValueInto(SGF, loc, result, /*isInit*/ true); init->finishInitialization(SGF); } init->getManagedAddress().forward(SGF); r = SGF.B.createTuple(loc, fnConv.getSILResultType(), {}); // Otherwise, return the result at +1. } else { r = result.forward(SGF); } scope.pop(); SGF.B.createReturn(loc, r); } /// Bridge a native function to a block with a thunk. ManagedValue SILGenFunction::emitBlockToFunc(SILLocation loc, ManagedValue block, CanAnyFunctionType blockType, CanAnyFunctionType funcType, CanSILFunctionType loweredFuncTy) { // Declare the thunk. auto loweredBlockTy = block.getType().castTo<SILFunctionType>(); SubstitutionMap contextSubs, interfaceSubs; GenericEnvironment *genericEnv = nullptr; // These two are not used here -- but really, bridging thunks // should be emitted using the formal AST type, not the lowered // type CanType inputSubstType, outputSubstType; auto thunkTy = buildThunkType(loweredBlockTy, loweredFuncTy, inputSubstType, outputSubstType, genericEnv, interfaceSubs); auto thunk = SGM.getOrCreateReabstractionThunk(genericEnv, thunkTy, loweredBlockTy, loweredFuncTy, F.isSerialized()); // Build it if necessary. if (thunk->empty()) { SILGenFunction thunkSGF(SGM, *thunk); thunk->setGenericEnvironment(genericEnv); auto loc = RegularLocation::getAutoGeneratedLocation(); buildBlockToFuncThunkBody(thunkSGF, loc, blockType, funcType, loweredBlockTy, loweredFuncTy); } CanSILFunctionType substFnTy = thunkTy; SmallVector<Substitution, 4> subs; if (auto genericSig = thunkTy->getGenericSignature()) { genericSig->getSubstitutions(interfaceSubs, subs); substFnTy = thunkTy->substGenericArgs(F.getModule(), interfaceSubs); } // Create it in the current function. auto thunkValue = B.createFunctionRef(loc, thunk); SingleValueInstruction *thunkedFn = B.createPartialApply( loc, thunkValue, SILType::getPrimitiveObjectType(substFnTy), subs, block.forward(*this), SILType::getPrimitiveObjectType(loweredFuncTy)); if (loweredFuncTy->isNoEscape()) { auto &funcTL = getTypeLowering(loweredFuncTy); thunkedFn = B.createConvertFunction(loc, thunkedFn, funcTL.getLoweredType()); } return emitManagedRValueWithCleanup(thunkedFn); } static ManagedValue emitCBridgedToNativeValue(SILGenFunction &SGF, SILLocation loc, ManagedValue v, CanType bridgedType, CanType nativeType, SILType loweredNativeTy, bool isCallResult, SGFContext C) { assert(loweredNativeTy.isObject()); SILType loweredBridgedTy = v.getType(); if (loweredNativeTy == loweredBridgedTy.getObjectType()) return v; if (auto nativeObjectType = nativeType.getAnyOptionalObjectType()) { auto bridgedObjectType = bridgedType.getAnyOptionalObjectType(); // Optional injection. if (!bridgedObjectType) { auto helper = [&](SILGenFunction &SGF, SILLocation loc, SGFContext C) { auto loweredNativeObjectTy = loweredNativeTy.getAnyOptionalObjectType(); return emitCBridgedToNativeValue(SGF, loc, v, bridgedType, nativeObjectType, loweredNativeObjectTy, isCallResult, C); }; return SGF.emitOptionalSome(loc, loweredNativeTy, helper, C); } // Optional-to-optional. auto helper = [=](SILGenFunction &SGF, SILLocation loc, ManagedValue v, SILType loweredNativeObjectTy, SGFContext C) { return emitCBridgedToNativeValue(SGF, loc, v, bridgedObjectType, nativeObjectType, loweredNativeObjectTy, isCallResult, C); }; return SGF.emitOptionalToOptional(loc, v, loweredNativeTy, helper, C); } // Bridge Bool to ObjCBool or DarwinBoolean when requested. if (nativeType == SGF.SGM.Types.getBoolType()) { if (bridgedType == SGF.SGM.Types.getObjCBoolType()) { return emitBridgeForeignBoolToBool(SGF, loc, v, SGF.SGM.getObjCBoolToBoolFn()); } if (bridgedType == SGF.SGM.Types.getDarwinBooleanType()) { return emitBridgeForeignBoolToBool(SGF, loc, v, SGF.SGM.getDarwinBooleanToBoolFn()); } } // Bridge Objective-C to thick metatypes. if (isa<AnyMetatypeType>(nativeType)) { auto bridgedMetaTy = cast<AnyMetatypeType>(bridgedType); if (bridgedMetaTy->hasRepresentation() && bridgedMetaTy->getRepresentation() == MetatypeRepresentation::ObjC) { SILValue native = SGF.B.emitObjCToThickMetatype(loc, v.getValue(), loweredNativeTy); // *NOTE*: ObjCMetatypes are trivial types. They only gain ARC semantics // when they are converted to an object via objc_metatype_to_object. assert(!v.hasCleanup() && "Metatypes are trivial and should not have " "cleanups"); return ManagedValue::forUnmanaged(native); } } // Bridge blocks back into native function types. if (auto nativeFTy = dyn_cast<AnyFunctionType>(nativeType)) { auto bridgedFTy = cast<AnyFunctionType>(bridgedType); if (bridgedFTy->getRepresentation() == AnyFunctionType::Representation::Block && nativeFTy->getRepresentation() != AnyFunctionType::Representation::Block) { return SGF.emitBlockToFunc(loc, v, bridgedFTy, nativeFTy, loweredNativeTy.castTo<SILFunctionType>()); } } // Bridge via _ObjectiveCBridgeable. if (auto conformance = SGF.SGM.getConformanceToObjectiveCBridgeable(loc, nativeType)) { if (auto result = emitBridgeObjectiveCToNative(SGF, loc, v, bridgedType, conformance)) return *result; assert(SGF.SGM.getASTContext().Diags.hadAnyError() && "Bridging code should have complained"); return SGF.emitUndef(loc, nativeType); } // id-to-Any bridging. if (nativeType->isAny()) { // If this is not a call result, use the normal erasure logic. if (!isCallResult) { return SGF.emitTransformedValue(loc, v, bridgedType, nativeType, C); } // Otherwise, we use more complicated logic that handles results that // were unexpetedly null. assert(bridgedType.isAnyClassReferenceType()); // Convert to AnyObject if necessary. CanType anyObjectTy = SGF.getASTContext().getAnyObjectType()->getCanonicalType(); if (bridgedType != anyObjectTy) { v = SGF.emitTransformedValue(loc, v, bridgedType, anyObjectTy); } // TODO: Ever need to handle +0 values here? assert(v.hasCleanup()); // Use a runtime call to bridge the AnyObject to Any. We do this instead of // a simple AnyObject-to-Any upcast because the ObjC API may have returned // a null object in spite of its annotation. // Bitcast to Optional. This provides a barrier to the optimizer to prevent // it from attempting to eliminate null checks. auto optionalBridgedTy = SILType::getOptionalType(loweredBridgedTy); auto optionalV = SGF.B.createUncheckedBitCast(loc, v.getValue(), optionalBridgedTy); auto optionalMV = ManagedValue(optionalV, v.getCleanup()); return SGF.emitApplyOfLibraryIntrinsic(loc, SGF.getASTContext().getBridgeAnyObjectToAny(nullptr), SubstitutionMap(), optionalMV, C) .getAsSingleValue(SGF, loc); } // Bridge NSError to Error. if (bridgedType == SGF.SGM.Types.getNSErrorType()) return SGF.emitBridgedToNativeError(loc, v); return v; } ManagedValue SILGenFunction::emitBridgedToNativeValue(SILLocation loc, ManagedValue v, CanType bridgedType, CanType nativeType, SILType loweredNativeTy, SGFContext C, bool isCallResult) { loweredNativeTy = loweredNativeTy.getObjectType(); return emitCBridgedToNativeValue(*this, loc, v, bridgedType, nativeType, loweredNativeTy, isCallResult, C); } /// Bridge a possibly-optional foreign error type to Error. ManagedValue SILGenFunction::emitBridgedToNativeError(SILLocation loc, ManagedValue bridgedError) { // If the incoming error is non-optional, just do an existential erasure. CanType bridgedErrorTy = bridgedError.getType().getSwiftRValueType(); if (!bridgedErrorTy.getAnyOptionalObjectType()) { auto nativeErrorTy = SILType::getExceptionType(getASTContext()); auto conformance = SGM.getNSErrorConformanceToError(); if (!conformance) return emitUndef(loc, nativeErrorTy); ProtocolConformanceRef conformanceArray[] = { ProtocolConformanceRef(conformance) }; auto conformances = getASTContext().AllocateCopy(conformanceArray); SILValue nativeError = B.createInitExistentialRef(loc, nativeErrorTy, bridgedErrorTy, bridgedError.forward(*this), conformances); return emitManagedRValueWithCleanup(nativeError); } // Otherwise, we need to call a runtime function to potential substitute // a standard error for a nil NSError. auto bridgeFn = emitGlobalFunctionRef(loc, SGM.getNSErrorToErrorFn()); auto bridgeFnType = bridgeFn->getType().castTo<SILFunctionType>(); SILFunctionConventions bridgeFnConv(bridgeFnType, SGM.M); assert(bridgeFnType->getNumResults() == 1); assert(bridgeFnType->getResults()[0].getConvention() == ResultConvention::Owned); auto nativeErrorType = bridgeFnConv.getSILType(bridgeFnType->getResults()[0]); assert(bridgeFnType->getParameters()[0].getConvention() == ParameterConvention::Direct_Owned); SILValue nativeError = B.createApply(loc, bridgeFn, bridgeFn->getType(), nativeErrorType, {}, bridgedError.forward(*this)); return emitManagedRValueWithCleanup(nativeError); } /// Bridge Error to a foreign error type. ManagedValue SILGenFunction::emitNativeToBridgedError(SILLocation loc, ManagedValue nativeError, CanType nativeType, CanType bridgedErrorType){ // Handle injections into optional. if (auto bridgedObjectType = bridgedErrorType.getAnyOptionalObjectType()) { auto loweredBridgedOptionalTy = SILType::getPrimitiveObjectType(bridgedErrorType); return emitOptionalSome(loc, loweredBridgedOptionalTy, [&](SILGenFunction &SGF, SILLocation loc, SGFContext C) { SILType loweredBridgedObjectTy = loweredBridgedOptionalTy.getAnyOptionalObjectType(); return emitNativeToBridgedValue(loc, nativeError, nativeType, bridgedObjectType, loweredBridgedObjectTy); }); } assert(bridgedErrorType == SGM.Types.getNSErrorType() && "only handling NSError for now"); // The native error might just be a value of a type that conforms to // Error. This should be a subtyping or erasure conversion of the sort // that we can do automatically. // FIXME: maybe we should use a different entrypoint for this case, to // avoid the code size and performance overhead of forming the box? nativeError = emitUnabstractedCast(*this, loc, nativeError, nativeType, getASTContext().getExceptionType()); auto bridgeFn = emitGlobalFunctionRef(loc, SGM.getErrorToNSErrorFn()); auto bridgeFnType = bridgeFn->getType().castTo<SILFunctionType>(); SILFunctionConventions bridgeFnConv(bridgeFnType, SGM.M); assert(bridgeFnType->getNumResults() == 1); assert(bridgeFnType->getResults()[0].getConvention() == ResultConvention::Owned); auto loweredBridgedErrorType = bridgeFnConv.getSILType(bridgeFnType->getResults()[0]); assert(bridgeFnType->getParameters()[0].getConvention() == ParameterConvention::Direct_Owned); SILValue bridgedError = B.createApply(loc, bridgeFn, bridgeFn->getType(), loweredBridgedErrorType, {}, nativeError.forward(*this)); return emitManagedRValueWithCleanup(bridgedError); } //===----------------------------------------------------------------------===// // ObjC method thunks //===----------------------------------------------------------------------===// static SILValue emitBridgeReturnValue(SILGenFunction &SGF, SILLocation loc, SILValue result, CanType formalNativeTy, CanType formalBridgedTy, SILType loweredBridgedTy) { Scope scope(SGF.Cleanups, CleanupLocation::get(loc)); ManagedValue native = SGF.emitManagedRValueWithCleanup(result); ManagedValue bridged = SGF.emitNativeToBridgedValue(loc, native, formalNativeTy, formalBridgedTy, loweredBridgedTy); return bridged.forward(SGF); } /// Take an argument at +0 and bring it to +1. static SILValue emitObjCUnconsumedArgument(SILGenFunction &SGF, SILLocation loc, SILValue arg) { auto &lowering = SGF.getTypeLowering(arg->getType()); // If address-only, make a +1 copy and operate on that. if (lowering.isAddressOnly()) { auto tmp = SGF.emitTemporaryAllocation(loc, arg->getType().getObjectType()); SGF.B.createCopyAddr(loc, arg, tmp, IsNotTake, IsInitialization); return tmp; } return lowering.emitCopyValue(SGF.B, loc, arg); } static CanAnyFunctionType substGenericArgs(CanAnyFunctionType fnType, const SubstitutionList &subs) { if (auto genericFnType = dyn_cast<GenericFunctionType>(fnType)) { return cast<FunctionType>(genericFnType->substGenericArgs(subs) ->getCanonicalType()); } return fnType; } /// Bridge argument types and adjust retain count conventions for an ObjC thunk. static SILFunctionType *emitObjCThunkArguments(SILGenFunction &SGF, SILLocation loc, SILDeclRef thunk, SmallVectorImpl<SILValue> &args, SILValue &foreignErrorSlot, Optional<ForeignErrorConvention> &foreignError, CanType &nativeFormalResultTy, CanType &bridgedFormalResultTy) { SILDeclRef native = thunk.asForeign(false); auto subs = SGF.F.getForwardingSubstitutions(); auto objcInfo = SGF.SGM.Types.getConstantInfo(thunk); auto objcFnTy = objcInfo.SILFnType->substGenericArgs(SGF.SGM.M, subs); auto objcFormalFnTy = substGenericArgs(objcInfo.LoweredType, subs); auto swiftInfo = SGF.SGM.Types.getConstantInfo(native); auto swiftFnTy = swiftInfo.SILFnType->substGenericArgs(SGF.SGM.M, subs); auto swiftFormalFnTy = substGenericArgs(swiftInfo.LoweredType, subs); SILFunctionConventions swiftConv(swiftFnTy, SGF.SGM.M); // We must have the same context archetypes as the unthunked function. assert(objcInfo.GenericEnv == swiftInfo.GenericEnv); SmallVector<ManagedValue, 8> bridgedArgs; bridgedArgs.reserve(objcFnTy->getParameters().size()); SILFunction *orig = SGF.SGM.getFunction(native, NotForDefinition); // Find the foreign error convention if we have one. if (orig->getLoweredFunctionType()->hasErrorResult()) { auto func = cast<AbstractFunctionDecl>(thunk.getDecl()); foreignError = func->getForeignErrorConvention(); assert(foreignError && "couldn't find foreign error convention!"); } // We don't know what to do with indirect results from the Objective-C side. assert(objcFnTy->getNumIndirectFormalResults() == 0 && "Objective-C methods cannot have indirect results"); auto bridgedFormalTypes = expandTupleTypes(objcFormalFnTy.getParams()); bridgedFormalResultTy = objcFormalFnTy.getResult(); auto nativeFormalTypes = expandTupleTypes(swiftFormalFnTy.getParams()); nativeFormalResultTy = swiftFormalFnTy.getResult(); // Emit the other arguments, taking ownership of arguments if necessary. auto inputs = objcFnTy->getParameters(); auto nativeInputs = swiftFnTy->getParameters(); assert(nativeInputs.size() == bridgedFormalTypes.size()); assert(nativeInputs.size() == nativeFormalTypes.size()); assert(inputs.size() == nativeInputs.size() + unsigned(foreignError.hasValue())); for (unsigned i = 0, e = inputs.size(); i < e; ++i) { SILType argTy = SGF.getSILType(inputs[i]); SILValue arg = SGF.F.begin()->createFunctionArgument(argTy); // If this parameter is the foreign error slot, pull it out. // It does not correspond to a native argument. if (foreignError && i == foreignError->getErrorParameterIndex()) { foreignErrorSlot = arg; continue; } // If the argument is a block, copy it. if (argTy.isBlockPointerCompatible()) { auto copy = SGF.B.createCopyBlock(loc, arg); // If the argument is consumed, we're still responsible for releasing the // original. if (inputs[i].isConsumed()) SGF.emitManagedRValueWithCleanup(arg); arg = copy; } // Convert the argument to +1 if necessary. else if (!inputs[i].isConsumed()) { arg = emitObjCUnconsumedArgument(SGF, loc, arg); } auto managedArg = SGF.emitManagedRValueWithCleanup(arg); bridgedArgs.push_back(managedArg); } assert(bridgedArgs.size() + unsigned(foreignError.hasValue()) == objcFnTy->getParameters().size() && "objc inputs don't match number of arguments?!"); assert(bridgedArgs.size() == swiftFnTy->getParameters().size() && "swift inputs don't match number of arguments?!"); assert((foreignErrorSlot || !foreignError) && "didn't find foreign error slot"); // Bridge the input types. // FIXME: We really want alloc_stacks to outlive this scope, because // bridging id-to-Any requires allocating an Any which gets passed to // the native entry point. // Scope scope(gen.Cleanups, CleanupLocation::get(loc)); assert(bridgedArgs.size() == nativeInputs.size()); for (unsigned i = 0, size = bridgedArgs.size(); i < size; ++i) { ManagedValue native = SGF.emitBridgedToNativeValue(loc, bridgedArgs[i], bridgedFormalTypes[i], nativeFormalTypes[i], swiftFnTy->getParameters()[i].getSILStorageType()); SILValue argValue; if (nativeInputs[i].isConsumed()) { argValue = native.forward(SGF); } else if (nativeInputs[i].isGuaranteed()) { argValue = native.borrow(SGF, loc).getUnmanagedValue(); } else { argValue = native.getValue(); } args.push_back(argValue); } return objcFnTy; } void SILGenFunction::emitNativeToForeignThunk(SILDeclRef thunk) { assert(thunk.isForeign); SILDeclRef native = thunk.asForeign(false); auto nativeInfo = getConstantInfo(native); auto subs = F.getForwardingSubstitutions(); auto substTy = nativeInfo.SILFnType->substGenericArgs(SGM.M, subs); SILType substSILTy = SILType::getPrimitiveObjectType(substTy); SILFunctionConventions substConv(substTy, SGM.M); // Use the same generic environment as the native entry point. F.setGenericEnvironment(nativeInfo.GenericEnv); auto loc = thunk.getAsRegularLocation(); loc.markAutoGenerated(); Scope scope(Cleanups, CleanupLocation::get(loc)); // If we are bridging a Swift method with an Any return value, create a // stack allocation to hold the result, since Any is address-only. SmallVector<SILValue, 4> args; if (substConv.hasIndirectSILResults()) { args.push_back( emitTemporaryAllocation(loc, substConv.getSingleSILResultType())); } // If the '@objc' was inferred due to deprecated rules, // emit a Builtin.swift3ImplicitObjCEntrypoint(). // // However, don't do so for 'dynamic' members, which must use Objective-C // dispatch and therefore create many false positives. if (thunk.hasDecl()) { auto decl = thunk.getDecl(); // For an accessor, look at the storage declaration's attributes. if (auto func = dyn_cast<FuncDecl>(decl)) { if (func->isAccessor()) decl = func->getAccessorStorageDecl(); } if (auto attr = decl->getAttrs().getAttribute<ObjCAttr>()) { // If @objc was inferred based on the Swift 3 @objc inference rules, but // we aren't compiling in Swift 3 compatibility mode, emit a call to // Builtin.swift3ImplicitObjCEntrypoint() to enable runtime logging of // the uses of such entrypoints. if (attr->isSwift3Inferred() && !decl->getAttrs().hasAttribute<DynamicAttr>() && !getASTContext().LangOpts.isSwiftVersion3()) { // Get the starting source location of the declaration so we can say // exactly where to stick '@objc'. SourceLoc objcInsertionLoc = decl->getAttributeInsertionLoc(/*modifier*/ false); auto objcInsertionLocArgs = emitSourceLocationArgs(objcInsertionLoc, loc); B.createBuiltin(loc, getASTContext().getIdentifier("swift3ImplicitObjCEntrypoint"), getModule().Types.getEmptyTupleType(), { }, { objcInsertionLocArgs.filenameStartPointer.forward(*this), objcInsertionLocArgs.filenameLength.forward(*this), objcInsertionLocArgs.line.forward(*this), objcInsertionLocArgs.column.forward(*this) }); } } } // Now, enter a cleanup used for bridging the arguments. Note that if we // have an indirect result, it must be outside of this scope, otherwise // we will deallocate it too early. Scope argScope(Cleanups, CleanupLocation::get(loc)); // Bridge the arguments. Optional<ForeignErrorConvention> foreignError; SILValue foreignErrorSlot; CanType nativeFormalResultType, bridgedFormalResultType; auto objcFnTy = emitObjCThunkArguments(*this, loc, thunk, args, foreignErrorSlot, foreignError, nativeFormalResultType, bridgedFormalResultType); SILFunctionConventions objcConv(CanSILFunctionType(objcFnTy), SGM.M); SILFunctionConventions nativeConv(CanSILFunctionType(nativeInfo.SILFnType), SGM.M); auto swiftResultTy = F.mapTypeIntoContext(nativeConv.getSILResultType()); auto objcResultTy = objcConv.getSILResultType(); // Call the native entry point. SILValue nativeFn = emitGlobalFunctionRef(loc, native, nativeInfo); SILValue result; assert(foreignError.hasValue() == substTy->hasErrorResult()); if (!substTy->hasErrorResult()) { // Create the apply. result = B.createApply(loc, nativeFn, substSILTy, swiftResultTy, subs, args); if (substConv.hasIndirectSILResults()) { assert(substTy->getNumResults() == 1); result = args[0]; } // Leave the argument cleanup scope immediately. This isn't really // necessary; it just limits lifetimes a little bit more. argScope.pop(); // Now bridge the return value. result = emitBridgeReturnValue(*this, loc, result, nativeFormalResultType, bridgedFormalResultType, objcResultTy); } else { SILBasicBlock *contBB = createBasicBlock(); SILBasicBlock *errorBB = createBasicBlock(); SILBasicBlock *normalBB = createBasicBlock(); B.createTryApply(loc, nativeFn, substSILTy, subs, args, normalBB, errorBB); // Emit the non-error destination. { B.emitBlock(normalBB); SILValue nativeResult = normalBB->createPHIArgument(swiftResultTy, ValueOwnershipKind::Owned); if (substConv.hasIndirectSILResults()) { assert(substTy->getNumResults() == 1); nativeResult = args[0]; } // In this branch, the eventual return value is mostly created // by bridging the native return value, but we may need to // adjust it slightly. SILValue bridgedResult = emitBridgeReturnValueForForeignError(loc, nativeResult, nativeFormalResultType, bridgedFormalResultType, objcResultTy, foreignErrorSlot, *foreignError); B.createBranch(loc, contBB, bridgedResult); } // Emit the error destination. { B.emitBlock(errorBB); SILValue nativeError = errorBB->createPHIArgument( substConv.getSILErrorType(), ValueOwnershipKind::Owned); // In this branch, the eventual return value is mostly invented. // Store the native error in the appropriate location and return. SILValue bridgedResult = emitBridgeErrorForForeignError(loc, nativeError, objcResultTy, foreignErrorSlot, *foreignError); B.createBranch(loc, contBB, bridgedResult); } // Emit the join block. B.emitBlock(contBB); result = contBB->createPHIArgument(objcResultTy, ValueOwnershipKind::Owned); // Leave the scope now. argScope.pop(); } scope.pop(); B.createReturn(loc, result); } static SILValue getThunkedForeignFunctionRef(SILGenFunction &SGF, SILLocation loc, SILDeclRef foreign, ArrayRef<ManagedValue> args, SubstitutionList subs, const SILConstantInfo &foreignCI) { assert(!foreign.isCurried && "should not thunk calling convention when curried"); // Produce a witness_method when thunking ObjC protocol methods. auto dc = foreign.getDecl()->getDeclContext(); if (isa<ProtocolDecl>(dc) && cast<ProtocolDecl>(dc)->isObjC()) { assert(subs.size() == 1); auto thisType = subs[0].getReplacement()->getCanonicalType(); assert(isa<ArchetypeType>(thisType) && "no archetype for witness?!"); SILValue thisArg = args.back().getValue(); SILValue OpenedExistential; if (!cast<ArchetypeType>(thisType)->getOpenedExistentialType().isNull()) OpenedExistential = thisArg; auto conformance = ProtocolConformanceRef(cast<ProtocolDecl>(dc)); return SGF.B.createWitnessMethod(loc, thisType, conformance, foreign, foreignCI.getSILType(), OpenedExistential); // Produce a class_method when thunking imported ObjC methods. } else if (foreignCI.SILFnType->getRepresentation() == SILFunctionTypeRepresentation::ObjCMethod) { SILValue thisArg = args.back().getValue(); return SGF.B.createObjCMethod(loc, thisArg, foreign, SILType::getPrimitiveObjectType(foreignCI.SILFnType)); } // Otherwise, emit a function_ref. return SGF.emitGlobalFunctionRef(loc, foreign); } /// Generate code to emit a thunk with native conventions that calls a /// function with foreign conventions. void SILGenFunction::emitForeignToNativeThunk(SILDeclRef thunk) { assert(!thunk.isForeign && "foreign-to-native thunks only"); // Wrap the function in its original form. auto fd = cast<AbstractFunctionDecl>(thunk.getDecl()); auto nativeCI = getConstantInfo(thunk); auto nativeFnTy = F.getLoweredFunctionType(); assert(nativeFnTy == nativeCI.SILFnType); // Use the same generic environment as the native entry point. F.setGenericEnvironment(nativeCI.GenericEnv); SILDeclRef foreignDeclRef = thunk.asForeign(true); SILConstantInfo foreignCI = getConstantInfo(foreignDeclRef); auto foreignFnTy = foreignCI.SILFnType; // Find the foreign error convention and 'self' parameter index. Optional<ForeignErrorConvention> foreignError; if (nativeFnTy->hasErrorResult()) { foreignError = fd->getForeignErrorConvention(); assert(foreignError && "couldn't find foreign error convention!"); } ImportAsMemberStatus memberStatus = fd->getImportAsMemberStatus(); // Forward the arguments. auto forwardedParameters = fd->getParameterLists(); // For allocating constructors, 'self' is a metatype, not the 'self' value // formally present in the constructor body. Type allocatorSelfType; if (thunk.kind == SILDeclRef::Kind::Allocator) { allocatorSelfType = forwardedParameters[0] ->getInterfaceType(getASTContext()) ->getWithoutSpecifierType(); if (F.getGenericEnvironment()) allocatorSelfType = F.getGenericEnvironment() ->mapTypeIntoContext(allocatorSelfType); forwardedParameters = forwardedParameters.slice(1); } SmallVector<SILValue, 8> params; // Introduce indirect returns if necessary. // TODO: Handle exploded results? We don't currently need to since the only // bridged indirect type is Any. SILValue indirectResult; SILFunctionConventions nativeConv(nativeFnTy, SGM.M); if (nativeConv.hasIndirectSILResults()) { assert(nativeConv.getNumIndirectSILResults() == 1 && "bridged exploded result?!"); indirectResult = F.begin()->createFunctionArgument(nativeConv.getSingleSILResultType()); } for (auto *paramList : reversed(forwardedParameters)) bindParametersForForwarding(paramList, params); if (allocatorSelfType) { auto selfMetatype = CanMetatypeType::get(allocatorSelfType->getCanonicalType()); auto selfArg = F.begin()->createFunctionArgument( getLoweredLoadableType(selfMetatype), fd->getImplicitSelfDecl()); params.push_back(selfArg); } // Set up the throw destination if necessary. CleanupLocation cleanupLoc(fd); if (foreignError) { prepareRethrowEpilog(cleanupLoc); } SILValue result; { Scope scope(Cleanups, fd); // Bridge all the arguments. SmallVector<ManagedValue, 8> args; unsigned foreignArgIndex = 0; // A helper function to add a function error argument in the // appropriate position. auto maybeAddForeignErrorArg = [&] { if (foreignError && foreignArgIndex == foreignError->getErrorParameterIndex()) { args.push_back(ManagedValue()); foreignArgIndex++; } }; { auto foreignFormalParams = expandTupleTypes(foreignCI.LoweredType.getParams()); auto nativeFormalParams = expandTupleTypes(nativeCI.LoweredType.getParams()); for (unsigned nativeParamIndex : indices(params)) { // Bring the parameter to +1. auto paramValue = params[nativeParamIndex]; auto thunkParam = nativeFnTy->getParameters()[nativeParamIndex]; // TODO: Could avoid a retain if the bridged parameter is also +0 and // doesn't require a bridging conversion. ManagedValue param; switch (thunkParam.getConvention()) { case ParameterConvention::Direct_Owned: param = emitManagedRValueWithCleanup(paramValue); break; case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Direct_Unowned: param = emitManagedRetain(fd, paramValue); break; case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: param = ManagedValue::forLValue(paramValue); break; case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: param = emitManagedRValueWithCleanup(paramValue); break; case ParameterConvention::Indirect_In_Guaranteed: auto tmp = emitTemporaryAllocation(fd, paramValue->getType()); B.createCopyAddr(fd, paramValue, tmp, IsNotTake, IsInitialization); param = emitManagedRValueWithCleanup(tmp); break; } maybeAddForeignErrorArg(); bool isSelf = nativeParamIndex == params.size() - 1; if (memberStatus.isInstance()) { // Leave space for `self` to be filled in later. if (foreignArgIndex == memberStatus.getSelfIndex()) { args.push_back({}); foreignArgIndex++; } // Use the `self` space we skipped earlier if it's time. if (isSelf) { foreignArgIndex = memberStatus.getSelfIndex(); } } else if (memberStatus.isStatic() && isSelf) { // Lose a static `self` parameter. break; } CanType nativeFormalType = F.mapTypeIntoContext(nativeFormalParams[nativeParamIndex]) ->getCanonicalType(); CanType foreignFormalType = F.mapTypeIntoContext(foreignFormalParams[nativeParamIndex]) ->getCanonicalType(); auto foreignParam = foreignFnTy->getParameters()[foreignArgIndex++]; SILType foreignLoweredTy = F.mapTypeIntoContext(foreignParam.getSILStorageType()); auto bridged = emitNativeToBridgedValue(fd, param, nativeFormalType, foreignFormalType, foreignLoweredTy); // Handle C pointer arguments imported as indirect `self` arguments. if (foreignParam.getConvention() == ParameterConvention::Indirect_In) { auto temp = emitTemporaryAllocation(fd, bridged.getType()); bridged.forwardInto(*this, fd, temp); bridged = emitManagedBufferWithCleanup(temp); } if (memberStatus.isInstance() && isSelf) { // Fill in the `self` space. args[memberStatus.getSelfIndex()] = bridged; } else { args.push_back(bridged); } } } maybeAddForeignErrorArg(); // Call the original. auto subs = getForwardingSubstitutions(); auto fn = getThunkedForeignFunctionRef(*this, fd, foreignDeclRef, args, subs, foreignCI); auto fnType = fn->getType().castTo<SILFunctionType>(); fnType = fnType->substGenericArgs(SGM.M, subs); CanType nativeFormalResultType = fd->mapTypeIntoContext(nativeCI.LoweredType.getResult()) ->getCanonicalType(); CanType bridgedFormalResultType = fd->mapTypeIntoContext(foreignCI.LoweredType.getResult()) ->getCanonicalType(); CalleeTypeInfo calleeTypeInfo( fnType, AbstractionPattern(nativeFnTy->getGenericSignature(), bridgedFormalResultType), nativeFormalResultType, foreignError, ImportAsMemberStatus()); auto init = indirectResult ? useBufferAsTemporary(indirectResult, getTypeLowering(indirectResult->getType())) : nullptr; SGFContext context(init.get()); ResultPlanPtr resultPlan = ResultPlanBuilder::computeResultPlan( *this, calleeTypeInfo, fd, context); ArgumentScope argScope(*this, fd); ManagedValue resultMV = emitApply(std::move(resultPlan), std::move(argScope), fd,<|fim▁hole|> ApplyOptions::None, context) .getAsSingleValue(*this, fd); if (indirectResult) { if (!resultMV.isInContext()) { init->copyOrInitValueInto(*this, fd, resultMV, /*isInit*/ true); init->finishInitialization(*this); } init->getManagedAddress().forward(*this); result = emitEmptyTuple(fd); } else { result = resultMV.forward(*this); } } B.createReturn(ImplicitReturnLocation::getImplicitReturnLoc(fd), result); // Emit the throw destination. emitRethrowEpilog(fd); }<|fim▁end|>
ManagedValue::forUnmanaged(fn), subs, args, calleeTypeInfo,
<|file_name|>func.go<|end_file_name|><|fim▁begin|>package main func main() { fn := func() { println("Hello, World!") } fn() fns := [](func(x int) int){ func(x int) int { return x + 1 }, func(x int) int { return x + 2 }, } println(fns[1](100)) d := struct { fn func() string }{ fn: func() string { return "Hello, World!" }, } println(d.fn())<|fim▁hole|>}<|fim▁end|>
fc := make(chan func() string, 2) fc <- func() string { return "Hello, World!" } println((<-fc)())
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>""" Django settings for figexample project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pp&p7ex-&+#n4waijg96v&txz$=y*rh=t$u-!hri@(-s@6^51=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',<|fim▁hole|> 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'figexample.urls' WSGI_APPLICATION = 'figexample.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db_1', 'PORT': 5432, } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/'<|fim▁end|>
<|file_name|>parameter_test.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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 datetime from helpers import unittest from datetime import timedelta import luigi import luigi.date_interval import luigi.interface import luigi.notifications from helpers import with_config from luigi.mock import MockTarget, MockFileSystem from luigi.parameter import ParameterException from worker_test import email_patch luigi.notifications.DEBUG = True class A(luigi.Task): p = luigi.IntParameter() class WithDefault(luigi.Task): x = luigi.Parameter(default='xyz') class Foo(luigi.Task): bar = luigi.Parameter() p2 = luigi.IntParameter() multi = luigi.Parameter(is_list=True) not_a_param = "lol" class Bar(luigi.Task): multibool = luigi.BoolParameter(is_list=True) def run(self): Bar._val = self.multibool class Baz(luigi.Task): bool = luigi.BoolParameter() def run(self): Baz._val = self.bool class ForgotParam(luigi.Task): param = luigi.Parameter() def run(self): pass class ForgotParamDep(luigi.Task): def requires(self): return ForgotParam() def run(self): pass class HasGlobalParam(luigi.Task): x = luigi.Parameter() global_param = luigi.IntParameter(is_global=True, default=123) # global parameters need default values global_bool_param = luigi.BoolParameter(is_global=True, default=False) def run(self): self.complete = lambda: True def complete(self): return False class HasGlobalParamDep(luigi.Task): x = luigi.Parameter() def requires(self): return HasGlobalParam(self.x) _shared_global_param = luigi.Parameter(is_global=True, default='123') class SharedGlobalParamA(luigi.Task): shared_global_param = _shared_global_param class SharedGlobalParamB(luigi.Task): shared_global_param = _shared_global_param class BananaDep(luigi.Task): x = luigi.Parameter() y = luigi.Parameter(default='def') def output(self): return MockTarget('banana-dep-%s-%s' % (self.x, self.y)) def run(self): self.output().open('w').close() class Banana(luigi.Task): x = luigi.Parameter() y = luigi.Parameter() style = luigi.Parameter(default=None) def requires(self): if self.style is None: return BananaDep() # will fail elif self.style == 'x-arg': return BananaDep(self.x) elif self.style == 'y-kwarg': return BananaDep(y=self.y) elif self.style == 'x-arg-y-arg': return BananaDep(self.x, self.y) else: raise Exception('unknown style') def output(self): return MockTarget('banana-%s-%s' % (self.x, self.y)) def run(self): self.output().open('w').close() class MyConfig(luigi.Config): mc_p = luigi.IntParameter() mc_q = luigi.IntParameter(default=73) class MyConfigWithoutSection(luigi.Config): use_cmdline_section = False mc_r = luigi.IntParameter() mc_s = luigi.IntParameter(default=99) class NoopTask(luigi.Task): pass class ParameterTest(unittest.TestCase): def setUp(self): super(ParameterTest, self).setUp() # Need to restore some defaults for the global params since they are overriden HasGlobalParam.global_param.set_global(123) HasGlobalParam.global_bool_param.set_global(False) def test_default_param(self): self.assertEqual(WithDefault().x, 'xyz') def test_missing_param(self): def create_a(): return A() self.assertRaises(luigi.parameter.MissingParameterException, create_a) def test_unknown_param(self): def create_a(): return A(p=5, q=4) self.assertRaises(luigi.parameter.UnknownParameterException, create_a) def test_unknown_param_2(self): def create_a(): return A(1, 2, 3) self.assertRaises(luigi.parameter.UnknownParameterException, create_a) def test_duplicated_param(self): def create_a(): return A(5, p=7) self.assertRaises(luigi.parameter.DuplicateParameterException, create_a) def test_parameter_registration(self): self.assertEqual(len(Foo.get_params()), 3) def test_task_creation(self): f = Foo("barval", p2=5, multi=('m1', 'm2')) self.assertEqual(len(f.get_params()), 3) self.assertEqual(f.bar, "barval") self.assertEqual(f.p2, 5) self.assertEqual(f.multi, ('m1', 'm2')) self.assertEqual(f.not_a_param, "lol") def test_multibool(self): luigi.run(['--local-scheduler', '--no-lock', 'Bar', '--multibool', 'true', '--multibool', 'false']) self.assertEqual(Bar._val, (True, False)) def test_multibool_empty(self): luigi.run(['--local-scheduler', '--no-lock', 'Bar']) self.assertEqual(Bar._val, tuple()) def test_bool_false(self): luigi.run(['--local-scheduler', '--no-lock', 'Baz']) self.assertEqual(Baz._val, False) def test_bool_true(self): luigi.run(['--local-scheduler', '--no-lock', 'Baz', '--bool']) self.assertEqual(Baz._val, True) def test_forgot_param(self): self.assertRaises(luigi.parameter.MissingParameterException, luigi.run, ['--local-scheduler', '--no-lock', 'ForgotParam'],) @email_patch def test_forgot_param_in_dep(self, emails): # A programmatic missing parameter will cause an error email to be sent luigi.run(['--local-scheduler', '--no-lock', 'ForgotParamDep']) self.assertNotEquals(emails, []) def test_default_param_cmdline(self): luigi.run(['--local-scheduler', '--no-lock', 'WithDefault']) self.assertEqual(WithDefault().x, 'xyz') def test_global_param_defaults(self): h = HasGlobalParam(x='xyz') self.assertEqual(h.global_param, 123) self.assertEqual(h.global_bool_param, False) def test_global_param_cmdline(self): luigi.run(['--local-scheduler', '--no-lock', 'HasGlobalParam', '--x', 'xyz', '--global-param', '124']) h = HasGlobalParam(x='xyz') self.assertEqual(h.global_param, 124) self.assertEqual(h.global_bool_param, False) def test_global_param_cmdline_flipped(self): luigi.run(['--local-scheduler', '--no-lock', '--global-param', '125', 'HasGlobalParam', '--x', 'xyz']) h = HasGlobalParam(x='xyz') self.assertEqual(h.global_param, 125) self.assertEqual(h.global_bool_param, False) def test_global_param_override(self): h1 = HasGlobalParam(x='xyz', global_param=124) h2 = HasGlobalParam(x='xyz') self.assertEquals(h1.global_param, 124) self.assertEquals(h2.global_param, 123) def test_global_param_dep_cmdline(self): luigi.run(['--local-scheduler', '--no-lock', 'HasGlobalParamDep', '--x', 'xyz', '--global-param', '124']) h = HasGlobalParam(x='xyz') self.assertEqual(h.global_param, 124) self.assertEqual(h.global_bool_param, False) def test_global_param_dep_cmdline_optparse(self): luigi.run(['--local-scheduler', '--no-lock', '--task', 'HasGlobalParamDep', '--x', 'xyz', '--global-param', '124'], use_optparse=True) h = HasGlobalParam(x='xyz') self.assertEqual(h.global_param, 124) self.assertEqual(h.global_bool_param, False) def test_global_param_dep_cmdline_bool(self): luigi.run(['--local-scheduler', '--no-lock', 'HasGlobalParamDep', '--x', 'xyz', '--global-bool-param']) h = HasGlobalParam(x='xyz') self.assertEqual(h.global_param, 123) self.assertEqual(h.global_bool_param, True) def test_global_param_shared(self): luigi.run(['--local-scheduler', '--no-lock', 'SharedGlobalParamA', '--shared-global-param', 'abc']) b = SharedGlobalParamB() self.assertEqual(b.shared_global_param, 'abc') def test_insignificant_parameter(self): class InsignificantParameterTask(luigi.Task): foo = luigi.Parameter(significant=False, default='foo_default') bar = luigi.Parameter() t1 = InsignificantParameterTask(foo='x', bar='y') self.assertEqual(t1.task_id, 'InsignificantParameterTask(bar=y)') t2 = InsignificantParameterTask('u', 'z') self.assertEqual(t2.foo, 'u') self.assertEqual(t2.bar, 'z') self.assertEqual(t2.task_id, 'InsignificantParameterTask(bar=z)') def test_local_significant_param(self): """ Obviously, if anything should be positional, so should local significant parameters """ class MyTask(luigi.Task): # This could typically be "--label-company=disney" x = luigi.Parameter(significant=True) MyTask('arg') self.assertRaises(luigi.parameter.MissingParameterException, lambda: MyTask()) def test_local_insignificant_param(self): """ Ensure we have the same behavior as in before a78338c """ class MyTask(luigi.Task): # This could typically be "--num-threads=True" x = luigi.Parameter(significant=False) MyTask('arg') self.assertRaises(luigi.parameter.MissingParameterException, lambda: MyTask()) class TestNewStyleGlobalParameters(unittest.TestCase): def setUp(self): super(TestNewStyleGlobalParameters, self).setUp() MockTarget.fs.clear() BananaDep.y.reset_global() def expect_keys(self, expected): self.assertEquals(set(MockTarget.fs.get_all_data().keys()), set(expected)) def test_x_arg(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'x-arg']) self.expect_keys(['banana-foo-bar', 'banana-dep-foo-def']) def test_x_arg_override(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'x-arg', '--BananaDep-y', 'xyz']) self.expect_keys(['banana-foo-bar', 'banana-dep-foo-xyz']) def test_x_arg_override_stupid(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'x-arg', '--BananaDep-x', 'blabla']) self.expect_keys(['banana-foo-bar', 'banana-dep-foo-def']) def test_x_arg_y_arg(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'x-arg-y-arg']) self.expect_keys(['banana-foo-bar', 'banana-dep-foo-bar']) def test_x_arg_y_arg_override(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'x-arg-y-arg', '--BananaDep-y', 'xyz']) self.expect_keys(['banana-foo-bar', 'banana-dep-foo-bar']) def test_x_arg_y_arg_override_all(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'x-arg-y-arg', '--BananaDep-y', 'xyz', '--BananaDep-x', 'blabla']) self.expect_keys(['banana-foo-bar', 'banana-dep-foo-bar']) def test_y_arg_override(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'y-kwarg', '--BananaDep-x', 'xyz']) self.expect_keys(['banana-foo-bar', 'banana-dep-xyz-bar']) def test_y_arg_override_both(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--x', 'foo', '--y', 'bar', '--style', 'y-kwarg', '--BananaDep-x', 'xyz', '--BananaDep-y', 'blah']) self.expect_keys(['banana-foo-bar', 'banana-dep-xyz-bar']) def test_y_arg_override_banana(self): luigi.run(['--local-scheduler', '--no-lock', 'Banana', '--y', 'bar', '--style', 'y-kwarg', '--BananaDep-x', 'xyz', '--Banana-x', 'baz']) self.expect_keys(['banana-baz-bar', 'banana-dep-xyz-bar']) class TestRemoveGlobalParameters(unittest.TestCase): def setUp(self): super(TestRemoveGlobalParameters, self).setUp() MyConfig.mc_p.reset_global() MyConfig.mc_q.reset_global() MyConfigWithoutSection.mc_r.reset_global() MyConfigWithoutSection.mc_s.reset_global() def run_and_check(self, args): run_exit_status = luigi.run(['--local-scheduler', '--no-lock'] + args) self.assertTrue(run_exit_status) return run_exit_status def test_use_config_class_1(self): self.run_and_check(['--MyConfig-mc-p', '99', '--mc-r', '55', 'NoopTask']) self.assertEqual(MyConfig().mc_p, 99) self.assertEqual(MyConfig().mc_q, 73) self.assertEqual(MyConfigWithoutSection().mc_r, 55) self.assertEqual(MyConfigWithoutSection().mc_s, 99) def test_use_config_class_2(self): self.run_and_check(['NoopTask', '--MyConfig-mc-p', '99', '--mc-r', '55']) self.assertEqual(MyConfig().mc_p, 99) self.assertEqual(MyConfig().mc_q, 73) self.assertEqual(MyConfigWithoutSection().mc_r, 55) self.assertEqual(MyConfigWithoutSection().mc_s, 99) def test_use_config_class_more_args(self): self.run_and_check(['--MyConfig-mc-p', '99', '--mc-r', '55', 'NoopTask', '--mc-s', '123', '--MyConfig-mc-q', '42']) self.assertEqual(MyConfig().mc_p, 99) self.assertEqual(MyConfig().mc_q, 42) self.assertEqual(MyConfigWithoutSection().mc_r, 55) self.assertEqual(MyConfigWithoutSection().mc_s, 123) @with_config({"MyConfig": {"mc_p": "666", "mc_q": "777"}}) def test_use_config_class_with_configuration(self): self.run_and_check(['--mc-r', '555', 'NoopTask']) self.assertEqual(MyConfig().mc_p, 666) self.assertEqual(MyConfig().mc_q, 777) self.assertEqual(MyConfigWithoutSection().mc_r, 555) self.assertEqual(MyConfigWithoutSection().mc_s, 99) @with_config({"MyConfigWithoutSection": {"mc_r": "999", "mc_s": "888"}}) def test_use_config_class_with_configuration_2(self): self.run_and_check(['NoopTask', '--MyConfig-mc-p', '222', '--mc-r', '555']) self.assertEqual(MyConfig().mc_p, 222) self.assertEqual(MyConfig().mc_q, 73) self.assertEqual(MyConfigWithoutSection().mc_r, 555) self.assertEqual(MyConfigWithoutSection().mc_s, 888) def test_misc_1(self): class Dogs(luigi.Config): n_dogs = luigi.IntParameter() class CatsWithoutSection(luigi.Config): use_cmdline_section = False n_cats = luigi.IntParameter() self.run_and_check(['--n-cats', '123', '--Dogs-n-dogs', '456', 'WithDefault']) self.assertEqual(Dogs().n_dogs, 456) self.assertEqual(CatsWithoutSection().n_cats, 123) self.run_and_check(['WithDefault', '--n-cats', '321', '--Dogs-n-dogs', '654']) self.assertEqual(Dogs().n_dogs, 654) self.assertEqual(CatsWithoutSection().n_cats, 321) def test_global_significant_param(self): """ We don't want any kind of global param to be positional """ class MyTask(luigi.Task): # This could typically be called "--test-dry-run" x_g1 = luigi.Parameter(default='y', is_global=True, significant=True) self.assertRaises(luigi.parameter.UnknownParameterException, lambda: MyTask('arg')) def test_global_insignificant_param(self): """ We don't want any kind of global param to be positional """ class MyTask(luigi.Task): # This could typically be "--yarn-pool=development" x_g2 = luigi.Parameter(default='y', is_global=True, significant=False) self.assertRaises(luigi.parameter.UnknownParameterException, lambda: MyTask('arg')) def test_mixed_params(self): """ Essentially for what broke in a78338c and was reported in #738 """ class MyTask(luigi.Task): # This could typically be "--num-threads=True" x_g3 = luigi.Parameter(default='y', is_global=True) local_param = luigi.Parameter() MyTask('setting_local_param') def test_mixed_params_inheritence(self): """ A slightly more real-world like test case """ class TaskWithOneGlobalParam(luigi.Task): non_positional_param = luigi.Parameter(default='y', is_global=True) class TaskWithOnePositionalParam(TaskWithOneGlobalParam): """ Try to mess with positional parameters by subclassing """ only_positional_param = luigi.Parameter() def complete(self): return True class PositionalParamsRequirer(luigi.Task): def requires(self): return TaskWithOnePositionalParam('only_positional_value') def run(self): pass self.run_and_check(['PositionalParamsRequirer']) self.run_and_check(['PositionalParamsRequirer', '--non-positional-param', 'z']) class TestParamWithDefaultFromConfig(unittest.TestCase): def testNoSection(self): self.assertRaises(ParameterException, lambda: luigi.Parameter(config_path=dict(section="foo", name="bar")).value) @with_config({"foo": {}}) def testNoValue(self): self.assertRaises(ParameterException, lambda: luigi.Parameter(config_path=dict(section="foo", name="bar")).value) @with_config({"foo": {"bar": "baz"}}) def testDefault(self): class A(luigi.Task): p = luigi.Parameter(config_path=dict(section="foo", name="bar")) self.assertEqual("baz", A().p) self.assertEqual("boo", A(p="boo").p) @with_config({"foo": {"bar": "2001-02-03T04"}}) def testDateHour(self): p = luigi.DateHourParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(datetime.datetime(2001, 2, 3, 4, 0, 0), p.value) @with_config({"foo": {"bar": "2001-02-03"}}) def testDate(self): p = luigi.DateParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(datetime.date(2001, 2, 3), p.value) @with_config({"foo": {"bar": "123"}}) def testInt(self): p = luigi.IntParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(123, p.value) @with_config({"foo": {"bar": "true"}}) def testBool(self): p = luigi.BoolParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(True, p.value) @with_config({"foo": {"bar": "2001-02-03-2001-02-28"}}) def testDateInterval(self): p = luigi.DateIntervalParameter(config_path=dict(section="foo", name="bar")) expected = luigi.date_interval.Custom.parse("2001-02-03-2001-02-28") self.assertEqual(expected, p.value) @with_config({"foo": {"bar": "1 day"}}) def testTimeDelta(self): p = luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(timedelta(days=1), p.value) @with_config({"foo": {"bar": "2 seconds"}}) def testTimeDeltaPlural(self): p = luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(timedelta(seconds=2), p.value) @with_config({"foo": {"bar": "3w 4h 5m"}}) def testTimeDeltaMultiple(self): p = luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(timedelta(weeks=3, hours=4, minutes=5), p.value) @with_config({"foo": {"bar": "P4DT12H30M5S"}}) def testTimeDelta8601(self): p = luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(timedelta(days=4, hours=12, minutes=30, seconds=5), p.value) @with_config({"foo": {"bar": "P5D"}}) def testTimeDelta8601NoTimeComponent(self): p = luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(timedelta(days=5), p.value) @with_config({"foo": {"bar": "P5W"}}) def testTimeDelta8601Weeks(self): p = luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(timedelta(weeks=5), p.value) @with_config({"foo": {"bar": "P3Y6M4DT12H30M5S"}}) def testTimeDelta8601YearMonthNotSupported(self): def f(): return luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")).value self.assertRaises(luigi.parameter.ParameterException, f) # ISO 8601 durations with years or months are not supported @with_config({"foo": {"bar": "PT6M"}}) def testTimeDelta8601MAfterT(self): p = luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")) self.assertEqual(timedelta(minutes=6), p.value) @with_config({"foo": {"bar": "P6M"}}) def testTimeDelta8601MBeforeT(self): def f(): return luigi.TimeDeltaParameter(config_path=dict(section="foo", name="bar")).value self.assertRaises(luigi.parameter.ParameterException, f) # ISO 8601 durations with months are not supported def testHasDefaultNoSection(self): luigi.Parameter(config_path=dict(section="foo", name="bar")).has_value self.assertFalse(luigi.Parameter(config_path=dict(section="foo", name="bar")).has_value) @with_config({"foo": {}}) def testHasDefaultNoValue(self): self.assertFalse(luigi.Parameter(config_path=dict(section="foo", name="bar")).has_value) @with_config({"foo": {"bar": "baz"}}) def testHasDefaultWithBoth(self): self.assertTrue(luigi.Parameter(config_path=dict(section="foo", name="bar")).has_value) @with_config({"foo": {"bar": "one\n\ttwo\n\tthree\n"}}) def testDefaultList(self): p = luigi.Parameter(is_list=True, config_path=dict(section="foo", name="bar")) self.assertEqual(('one', 'two', 'three'), p.value) @with_config({"foo": {"bar": "1\n2\n3"}}) def testDefaultIntList(self): p = luigi.IntParameter(is_list=True, config_path=dict(section="foo", name="bar")) self.assertEqual((1, 2, 3), p.value) @with_config({"foo": {"bar": "baz"}}) def testWithDefault(self): p = luigi.Parameter(config_path=dict(section="foo", name="bar"), default='blah') self.assertEqual('baz', p.value) # config overrides default def testWithDefaultAndMissing(self): p = luigi.Parameter(config_path=dict(section="foo", name="bar"), default='blah') self.assertEqual('blah', p.value) @with_config({"foo": {"bar": "baz"}}) def testGlobal(self): p = luigi.Parameter(config_path=dict(section="foo", name="bar"), is_global=True, default='blah') self.assertEqual('baz', p.value) p.set_global('meh') self.assertEqual('meh', p.value) def testGlobalAndMissing(self): p = luigi.Parameter(config_path=dict(section="foo", name="bar"), is_global=True, default='blah') self.assertEqual('blah', p.value) p.set_global('meh') self.assertEqual('meh', p.value)<|fim▁hole|> class A(luigi.Task): p = luigi.Parameter() self.assertEqual("p_default", A().p) self.assertEqual("boo", A(p="boo").p) @with_config({"A": {"p": "999"}}) def testDefaultFromTaskNameInt(self): class A(luigi.Task): p = luigi.IntParameter() self.assertEqual(999, A().p) self.assertEqual(777, A(p=777).p) @with_config({"A": {"p": "p_default"}, "foo": {"bar": "baz"}}) def testDefaultFromConfigWithTaskNameToo(self): class A(luigi.Task): p = luigi.Parameter(config_path=dict(section="foo", name="bar")) self.assertEqual("p_default", A().p) self.assertEqual("boo", A(p="boo").p) @with_config({"A": {"p": "p_default_2"}}) def testDefaultFromTaskNameWithDefault(self): class A(luigi.Task): p = luigi.Parameter(default="banana") self.assertEqual("p_default_2", A().p) self.assertEqual("boo_2", A(p="boo_2").p) @with_config({"MyClass": {"p_wohoo": "p_default_3"}}) def testWithLongParameterName(self): class MyClass(luigi.Task): p_wohoo = luigi.Parameter(default="banana") self.assertEqual("p_default_3", MyClass().p_wohoo) self.assertEqual("boo_2", MyClass(p_wohoo="boo_2").p_wohoo) @with_config({"RangeDaily": {"days_back": "123"}}) def testSettingOtherMember(self): class A(luigi.Task): pass self.assertEqual(123, luigi.tools.range.RangeDaily(of=A).days_back) self.assertEqual(70, luigi.tools.range.RangeDaily(of=A, days_back=70).days_back) class OverrideEnvStuff(unittest.TestCase): def setUp(self): env_params_cls = luigi.interface.core env_params_cls.scheduler_port.reset_global() @with_config({"core": {"default-scheduler-port": '6543'}}) def testOverrideSchedulerPort(self): env_params = luigi.interface.core() self.assertEqual(env_params.scheduler_port, 6543) @with_config({"core": {"scheduler-port": '6544'}}) def testOverrideSchedulerPort2(self): env_params = luigi.interface.core() self.assertEqual(env_params.scheduler_port, 6544) @with_config({"core": {"scheduler_port": '6545'}}) def testOverrideSchedulerPort3(self): env_params = luigi.interface.core() self.assertEqual(env_params.scheduler_port, 6545) if __name__ == '__main__': luigi.run(use_optparse=True)<|fim▁end|>
@with_config({"A": {"p": "p_default"}}) def testDefaultFromTaskName(self):
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event //! notification, and other useful utilities for building high performance IO //! apps. //! //! # Goals //! //! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...) //! * Zero allocations //! * A scalable readiness-based API, similar to epoll on Linux //! * Design to allow for stack allocated buffers when possible (avoid double buffering). //! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab. //! //! # Usage //! //! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which //! handles receiving events from the OS and dispatching them to a supplied //! [Handler](handler/trait.Handler.html). //! //! # Example //! //! ``` //! use mio::*; //! use mio::tcp::{TcpListener, TcpStream}; //! //! // Setup some tokens to allow us to identify which event is //! // for which socket.<|fim▁hole|>//! # //! # // level() isn't implemented on windows yet //! # if cfg!(windows) { return } //! //! let addr = "127.0.0.1:13265".parse().unwrap(); //! //! // Setup the server socket //! let server = TcpListener::bind(&addr).unwrap(); //! //! // Create an event loop //! let mut event_loop = EventLoop::new().unwrap(); //! //! // Start listening for incoming connections //! event_loop.register(&server, SERVER, EventSet::readable(), //! PollOpt::edge()).unwrap(); //! //! // Setup the client socket //! let sock = TcpStream::connect(&addr).unwrap(); //! //! // Register the socket //! event_loop.register(&sock, CLIENT, EventSet::readable(), //! PollOpt::edge()).unwrap(); //! //! // Define a handler to process the events //! struct MyHandler(TcpListener); //! //! impl Handler for MyHandler { //! type Timeout = (); //! type Message = (); //! //! fn ready(&mut self, event_loop: &mut EventLoop<MyHandler>, token: Token, _: EventSet) { //! match token { //! SERVER => { //! let MyHandler(ref mut server) = *self; //! // Accept and drop the socket immediately, this will close //! // the socket and notify the client of the EOF. //! let _ = server.accept(); //! } //! CLIENT => { //! // The server just shuts down the socket, let's just //! // shutdown the event loop //! event_loop.shutdown(); //! } //! _ => panic!("unexpected token"), //! } //! } //! } //! //! // Start handling events //! event_loop.run(&mut MyHandler(server)).unwrap(); //! //! ``` #![crate_name = "mio"] #![cfg_attr(unix, deny(warnings))] extern crate bytes; extern crate time; extern crate slab; extern crate libc; #[cfg(unix)] extern crate nix; extern crate winapi; extern crate miow; extern crate net2; #[macro_use] extern crate log; #[cfg(test)] extern crate env_logger; pub mod util; mod event; mod event_loop; mod handler; mod io; mod net; mod notify; mod poll; mod sys; mod timer; mod token; pub use event::{ PollOpt, EventSet, }; pub use event_loop::{ EventLoop, EventLoopConfig, Sender, }; pub use handler::{ Handler, }; pub use io::{ TryRead, TryWrite, Evented, TryAccept, }; pub use net::{ tcp, udp, IpAddr, Ipv4Addr, Ipv6Addr, }; #[cfg(unix)] pub mod unix { pub use net::unix::{ pipe, PipeReader, PipeWriter, UnixListener, UnixSocket, UnixStream, }; pub use sys::{ EventedFd, }; } pub use notify::{ NotifyError, }; pub use poll::{ Poll }; pub use timer::{ Timeout, TimerError, TimerResult }; pub use token::{ Token, }; #[cfg(unix)] pub use sys::Io; pub use sys::Selector; pub mod prelude { pub use super::{ EventLoop, TryRead, TryWrite, }; }<|fim▁end|>
//! const SERVER: Token = Token(0); //! const CLIENT: Token = Token(1);
<|file_name|>app.js<|end_file_name|><|fim▁begin|>var RoonApi = require("node-roon-api"), RoonApiStatus = require("node-roon-api-status"), RoonApiSettings = require("node-roon-api-settings"), RoonApiSourceControl = require("node-roon-api-source-control"), RoonApiVolumeControl = require("node-roon-api-volume-control"), Yamaha = require("node-yamaha-avr"); var roon = new RoonApi({ extension_id: 'com.statesofpop.roon-yamaha', display_name: "Yamaha Control", display_version: "0.0.7", publisher: 'states of pop', email: '[email protected]', website: 'https://github.com/statesofpop/roon-yamaha' }); var yamaha = { "default_device_name": "Yamaha", "default_input": "HDMI1", "volume": -50 }; var svc_status = new RoonApiStatus(roon); var svc_volume = new RoonApiVolumeControl(roon); var svc_source = new RoonApiSourceControl(roon); var svc_settings = new RoonApiSettings(roon); var volTimeout = null; var mysettings = roon.load_config("settings") || { receiver_url: "", input: yamaha.default_input, device_name: yamaha.default_device_name, input_list: [ { title: "HDMI 1", value: "HDMI1" }, { title: "HDMI 2", value: "HDMI2" }, { title: "HDMI 3", value: "HDMI3" }, { title: "HDMI 4", value: "HDMI4" }, { title: "HDMI 5", value: "HDMI5" }, { title: "HDMI 6", value: "HDMI6" } ] }; function makelayout(settings) { var l = { values: settings, layout: [], has_error: false }; l.layout.push({ type: "string", title: "Device name", subtitle: "Changing this might take some time to take effect.", setting: "device_name" }); l.layout.push({ type: "dropdown", title: "Input", values: mysettings.input_list, setting: "input" }); let v = { type: "string", title: "Receiver IP", subtitle: "Your device should be recognized automatically. If not, please configure your receiver to use a fixed IP-address.", setting: "receiver_url" };<|fim▁hole|> l.has_error = true; } l.layout.push(v); return l; } var svc_settings = new RoonApiSettings(roon, { get_settings: function(cb) { cb(makelayout(mysettings)); }, save_settings: function(req, isdryrun, settings) { let l = makelayout(settings.values); req.send_complete(l.has_error ? "NotValid" : "Success", { settings: l }); if (!isdryrun && !l.has_error) { mysettings = l.values; svc_settings.update_settings(l); roon.save_config("settings", mysettings); } } }); svc_status.set_status("Initialising", false); function update_status() { if (yamaha.hid && yamaha.device_name) { svc_status.set_status("Found Yamaha " + yamaha.device_name + " at " + yamaha.ip, false); } else if (yamaha.hid && yamaha.ip) { svc_status.set_status("Found Yamaha device at " + yamaha.ip, false); } else if (yamaha.hid) { svc_status.set_status("Found Yamaha device. Discovering…", false); } else { svc_status.set_status("Could not find Yamaha device.", true) } } function check_status() { if (yamaha.hid) { yamaha.hid.getStatus() .then( (result) => { // exit if a change through roon is in progress if (volTimeout) return; // this seems to only get called on success let vol_status = result["YAMAHA_AV"]["Main_Zone"][0]["Basic_Status"][0]["Volume"][0]; // should get current state first, to see if update is necessary yamaha.svc_volume.update_state({ volume_value: vol_status["Lvl"][0]["Val"] / 10, is_muted: (vol_status["Mute"] == "On") }); update_status() }) .catch( (error) => { // this seems not to get called when device is offline yamaha.hid == ""; svc_status.set_status("Could not find Yamaha device.", true); }); } } function setup_yamaha() { if (yamaha.hid) { yamaha.hid = undefined; } if (yamaha.source_control) { yamaha.source_control.destroy(); delete(yamaha.source_control); } if (yamaha.svc_volume) { yamaha.svc_volume.destroy(); delete(yamaha.svc_volume); } yamaha.hid = new Yamaha(mysettings.receiver_url); // should check whether the device is behind the given url // only then start to discover. yamaha.hid.discover() .then( (ip) => { yamaha.ip = ip; update_status(); }) .catch( (error) => { yamaha.hid = undefined; svc_status.set_status("Could not find Yamaha device.", true) }); try { yamaha.hid.getSystemConfig().then(function(config) { if (mysettings.device_name == yamaha.default_device_name) { mysettings.device_name = config["YAMAHA_AV"]["System"][0]["Config"][0]["Model_Name"][0]; } let inputs = config["YAMAHA_AV"]["System"][0]["Config"][0]["Name"][0]["Input"][0]; mysettings.input_list = []; for (let key in inputs) { mysettings.input_list.push({ "title": inputs[key][0].trim(), "value": key.replace("_", "") }) } update_status(); }) } catch(e) { // getting the device name is not critical, so let's continue } yamaha.svc_volume = svc_volume.new_device({ state: { display_name: mysettings.device_name, volume_type: "db", volume_min: -87.5, volume_max: -20, volume_value: -50, volume_step: 0.5, is_muted: 0 }, set_volume: function (req, mode, value) { let newvol = mode == "absolute" ? value : (yamaha.volume + value); if (newvol < this.state.volume_min) newvol = this.state.volume_min; else if (newvol > this.state.volume_max) newvol = this.state.volume_max; yamaha.svc_volume.update_state({ volume_value: newvol }); clearTimeout(volTimeout); volTimeout = setTimeout(() => { // node-yamaha-avr sends full ints yamaha.hid.setVolume( value * 10 ); clearTimeout(volTimeout); volTimeout = null; }, 500) req.send_complete("Success"); }, set_mute: function (req, action) { let is_muted = !this.state.is_muted; yamaha.hid.setMute( (is_muted)? "on": "off" ) yamaha.svc_volume.update_state({ is_muted: is_muted }); req.send_complete("Success"); } }); yamaha.source_control = svc_source.new_device({ state: { display_name: mysettings.device_name, supports_standby: true, status: "selected", }, convenience_switch: function (req) { yamaha.hid.setInput(mysettings.input); req.send_complete("Success"); }, standby: function (req) { let state = this.state.status; this.state.status = (state == "selected")? "standby": "selected"; yamaha.hid.setPower((state == "selected")? "off": "on"); req.send_complete("Success"); } }); } roon.init_services({ provided_services: [ svc_status, svc_settings, svc_volume, svc_source ] }); setInterval(() => { if (!yamaha.hid) setup_yamaha(); }, 1000); setInterval(() => { if (yamaha.hid) check_status(); }, 5000); roon.start_discovery();<|fim▁end|>
if (settings.receiver_url != "" && settings.receiver_url.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/) === null) { v.error = "Please enter a valid IP-address";
<|file_name|>Person.java<|end_file_name|><|fim▁begin|>package com.baeldung.reflect; public class Person { private String fullName; public Person(String fullName) { this.fullName = fullName; } <|fim▁hole|> public String getFullName() { return fullName; } }<|fim▁end|>
public void setFullName(String fullName) { this.fullName = fullName; }
<|file_name|>util.rs<|end_file_name|><|fim▁begin|>/* * Copyright 2015-2016 Ben Ashford * * 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. */ //! Miscellaneous code used in numerous places use std::iter::Iterator; /// A custom String-join trait as the stdlib one is currently marked as unstable. pub trait StrJoin { /// Join an iterator of things that can be referenced as strings into a /// single owned-string by the given joining string /// /// # Example /// /// ``` /// use rs_es::util::StrJoin; /// /// let data = vec!["a", "b", "c", "d"]; /// assert_eq!("a-b-c-d", data.iter().join("-")); /// ``` /// /// This will print: `a-b-c-d` /// fn join(self, join: &str) -> String; } impl<I, S> StrJoin for I where S: AsRef<str>, I: Iterator<Item = S>, { fn join(self, join: &str) -> String { let mut s = String::new(); for f in self { s.push_str(f.as_ref()); s.push_str(join); } s.pop(); s } } /// Useful macro for adding a function to supply a value to an optional field macro_rules! add_field { ($n:ident, $f:ident, $t:ty) => ( pub fn $n<T: Into<$t>>(mut self, val: T) -> Self { self.$f = Some(val.into()); self } ); } /// Useful macros for implementing `From` traits /// /// TODO: this may only be useful for Query DSL, in which case should be moved /// to that module macro_rules! from_exp { ($ft:ty, $dt:ident, $pi:ident, $ex:expr) => { impl From<$ft> for $dt { fn from($pi: $ft) -> $dt { $ex } } }; } macro_rules! from { ($ft:ty, $dt:ident, $ev:ident, $pi:ident) => { from_exp!($ft, $dt, $pi, $dt::$ev($pi)); }; ($ft:ty, $dt:ident, $ev:ident) => {<|fim▁hole|> from!($ft, $dt, $ev, from); }; }<|fim▁end|>
<|file_name|>mp3gen.py<|end_file_name|><|fim▁begin|><|fim▁hole|>#!/usr/bin/python # -*- coding: utf-8 -*- # # This would be a lot easier with a shellscript. # Will probably just do this in bash, once I make this work. # In this case we're doing it for educational purposes. # Expect future revisions to be faster and more efficient. # Started with working code, broke it to fit my needs. # Makes me very sad, and way more work to figure out than ls *.mp3 # but at least it's not full on regex? :p # by steakwipe with way too much help from beatsteak #importing old soup for good luck import os #yt variable needed later yt=https://youtu.be/ mp3list = '/home/steakwipe/git/ytdl-namer' #i'd like this to be a runtime option later # let's look around here for some mp3s def mp3gen(): for root, dirs, files in os.walk('.'): for filename in files: if os.path.splitext(filename)[1] == ".mp3": yield os.path.join(root, filename) # next we are attempting to process all.mp3 files in the dir # to isolate the part of teh filename that is for YT. # pretty much dies right away, but i basically did this # in a python console with a single file. # splitext, grab the first piece, then trim off the last # 11 characters. Should result in NVEzFqKGrXY or something. # broke as fuck. hopefully i've at least got the right idea. # this'll need to chew thru hundreds of mp3s at a time # and pushing the output youtube url's back in as id3 tags. for mp3file in mp3gen(): fn = os.path.splitext(os.path.basename('mp3file')), text=print([fn[0]]), url = text[-11::], print(yt+url)<|fim▁end|>
<|file_name|>DefaultSelectStrategy.java<|end_file_name|><|fim▁begin|>/* * Copyright 2016 The Netty Project * * The Netty Project licenses this file to you 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<|fim▁hole|> * 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 io.netty.channel; import io.netty.util.IntSupplier; /** * Default select strategy. */ final class DefaultSelectStrategy implements SelectStrategy { static final SelectStrategy INSTANCE = new DefaultSelectStrategy(); private DefaultSelectStrategy() { } @Override public int calculateStrategy(IntSupplier selectSupplier, boolean hasTasks) throws Exception { return hasTasks ? selectSupplier.get() : SelectStrategy.SELECT; } }<|fim▁end|>
* * Unless required by applicable law or agreed to in writing, software
<|file_name|>ControllerServlet.java<|end_file_name|><|fim▁begin|>package org.se.lab; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; @WebServlet("/controller") public class ControllerServlet extends HttpServlet { private final Logger LOG = Logger.getLogger(ControllerServlet.class); private static final long serialVersionUID = 1L; public ControllerServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Controller String message = ""; String state = ""; String action = request.getParameter("action"); if(action == null) { // do nothing } else if(action.equals("Login")) { LOG.info("> login"); state = listToString(new ArrayList<Product>()); message = "You logged in successfully!"; } else if(action.equals("Logout")) { LOG.info("> logout"); state = ""; message = "You logged out successfully!"; } else if(action.equals("Add")) { String name = request.getParameter("name"); String quantity = request.getParameter("quantity"); ArrayList<Product> cart = listFromString(request.getParameter("state")); Product product = new Product(name, quantity); LOG.info("> add " + product); cart.add(product); state = listToString(cart); message = "added: " + product.getQuantity() + " " + product.getName() + " to the cart"; LOG.info("> cart: " + cart); } // generate response page response.setContentType("text/html"); PrintWriter out = response.getWriter(); String html = generateWebPage(state, message); out.println(html); out.close(); } private String generateWebPage(String state, String message) { StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"); html.append("<html>\n"); html.append(" <head>\n"); html.append(" <title>Simple Shopping Cart</title>\n"); html.append(" </head>\n"); html.append(" <body>\n"); html.append(" <h2>Session Management</h2>\n"); html.append(" <form method=\"post\" action=\"controller\">"); html.append(" <input type=\"hidden\" name=\"state\" value=\"" + state + "\"/>\n"); html.append(" <table border=\"0\" cellspacing=\"1\" cellpadding=\"5\">"); html.append(" <colgroup>"); html.append(" <col width=\"150\"> <col width=\"150\"> <col width=\"100\">"); html.append(" </colgroup>"); html.append(" <tr>"); html.append(" <th>"); html.append(" <input type=\"submit\" name=\"action\" value=\"Login\">"); html.append(" </th>"); html.append(" <th>"); html.append(" </th>"); html.append(" <th>"); html.append(" <input type=\"submit\" name=\"action\" value=\"Logout\">"); html.append(" </th>"); html.append(" </tr>"); html.append(" </table>"); html.append(" </form>"); html.append(" <p/>"); html.append(" <h2>Your Shopping Cart:</h2>\n"); html.append(" <form method=\"post\" action=\"controller\">"); html.append(" <input type=\"hidden\" name=\"state\" value=\"" + state + "\"/>\n"); html.append(" <table border=\"0\" cellspacing=\"1\" cellpadding=\"5\">"); html.append(" <colgroup>"); html.append(" <col width=\"150\"> <col width=\"150\"> <col width=\"100\">"); html.append(" </colgroup>"); html.append(" <tr>"); html.append(" <th>Product</th>"); html.append(" <th>Quantity</th>"); html.append(" <th></th>"); html.append(" </tr>"); html.append(" <tr>"); html.append(" <td><input type = \"text\" name = \"name\" /></td>"); html.append(" <td><input type = \"text\" name = \"quantity\" /></td>"); html.append(" <td><input type = \"submit\" name = \"action\" value = \"Add\" /></td>"); html.append(" </tr>"); html.append(" </table>"); html.append(" </form>"); html.append(" <p/>"); html.append(" <p style=\"color:blue\"><i>" + message + "</i></p>"); html.append(" <p/>"); Date now = new Date(); html.append(" <h6>" + now + "</h6>"); return html.toString(); } private String listToString(ArrayList<Product> list) { LOG.debug("listToString() " + list); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos= new ObjectOutputStream(bout); oos.writeObject(list); oos.close(); byte[] bytes = bout.toByteArray(); // TODO: Encryption return Base64.encodeBase64String(bytes);<|fim▁hole|> return ""; } } @SuppressWarnings("unchecked") private ArrayList<Product> listFromString(String base64String) { LOG.debug("listFromString() " + base64String); try { byte[] bytes = Base64.decodeBase64(base64String); // Decrypt data ArrayList<Product> list = new ArrayList<Product>(); ByteArrayInputStream bin = new ByteArrayInputStream(bytes); ObjectInputStream ois; ois = new ObjectInputStream(bin); list = (ArrayList<Product>) ois.readObject(); ois.close(); return list; } catch (IOException | ClassNotFoundException e) { return new ArrayList<Product>(); } } }<|fim▁end|>
} catch (IOException e) {
<|file_name|>Reference.java<|end_file_name|><|fim▁begin|>package com.fnacmod.fnac; //This code is copyright SoggyMustache, Link1234Gamer and Andrew_Playz public class Reference { public static final String MOD_ID = "fnac"; <|fim▁hole|> public static final String CLIENT_PROXY_CLASS = "com.fnacmod.fnac.proxy.ClientProxy"; public static final String SERVER_PROXY_CLASS = "com.fnacmod.fnac.proxy.ServerProxy"; }<|fim▁end|>
public static final String MOD_NAME = "Five Nights at Candy's Mod"; public static final String VERSION = "1.0";
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>extern crate syntex; extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() { let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/lib.rs.in"); let dst = Path::new(&out_dir).join("lib.rs"); let mut registry = syntex::Registry::new();<|fim▁hole|><|fim▁end|>
serde_codegen::register(&mut registry); registry.expand("google-doubleclickbidmanager1", &src, &dst).unwrap(); }
<|file_name|>RandomizedQueue.java<|end_file_name|><|fim▁begin|>package com.linbo.algs.examples.queues; import java.util.Iterator; import com.linbo.algs.util.StdRandom; /** * Created by @linbojin on 13/1/17. * Ref: http://coursera.cs.princeton.edu/algs4/assignments/queues.html * RandomizedQueue: a double-ended queue or deque (pronounced "deck") is a * generalization of a stack and a queue that supports adding and removing * items from either the front or the back of the data structure. */ public class RandomizedQueue<Item> implements Iterable<Item> { // Memory: 16 + 8 + 4 + 4 + 4 + 4 + 24 + N * 4 * 2 // = 64 + 8N private Item[] q; // queue elements private int size; // number of elements on queue private int first; // index of first element of queue private int last; // index of next available slot // construct an empty randomized queue public RandomizedQueue() { q = (Item[]) new Object[2]; size = 0; first = 0; last = 0; } // is the queue empty? public boolean isEmpty() { return size == 0; } // return the number of items on the queue public int size() { return size; } // resize the underlying array private void resize(int capacity) { assert capacity >= size; Item[] temp = (Item[]) new Object[capacity]; for (int i = 0; i < size; i++) { temp[i] = q[(first + i) % q.length]; } q = temp; first = 0; last = size; } // add the item public void enqueue(Item item) { if (item == null) { throw new java.lang.NullPointerException("Input item can not be null!"); } // double size of array if necessary and recopy to front of array<|fim▁hole|> size++; } // remove and return a random item public Item dequeue() { if (isEmpty()) { throw new java.util.NoSuchElementException("Queue is empty!"); } int index = StdRandom.uniform(size) + first; int i = index % q.length; Item item = q[i]; last = (last + q.length - 1) % q.length; if (i != last) { q[i] = q[last]; } q[last] = null; size--; // shrink size of array if necessary if (size > 0 && size == q.length / 4) resize(q.length / 2); return item; } // return (but do not remove) a random item public Item sample() { if (isEmpty()) { throw new java.util.NoSuchElementException("Queue is empty!"); } int index = StdRandom.uniform(size) + first; return q[index % q.length]; } // an independent iterator over items in random order public Iterator<Item> iterator() { return new ArrayIterator(); } // an iterator, doesn't implement remove() since it's optional private class ArrayIterator implements Iterator<Item> { private int i = 0; private int[] inxArr; public ArrayIterator() { inxArr = StdRandom.permutation(size); } public boolean hasNext() { return i < size; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if (!hasNext()) throw new java.util.NoSuchElementException(); Item item = q[(inxArr[i] + first) % q.length]; i++; return item; } } // unit testing (optional) public static void main(String[] args) { RandomizedQueue<Integer> rq = new RandomizedQueue<Integer>(); System.out.println(rq.isEmpty()); rq.enqueue(1); rq.enqueue(2); rq.enqueue(3); rq.enqueue(4); rq.enqueue(5); for (int i : rq) { System.out.print(i); System.out.print(" "); } System.out.println("\n*******"); System.out.println(rq.sample()); System.out.println(rq.size()); // 5 System.out.println("*******"); System.out.println(rq.isEmpty()); System.out.println(rq.dequeue()); System.out.println(rq.dequeue()); System.out.println(rq.sample()); System.out.println(rq.size()); // 3 System.out.println("*******"); System.out.println(rq.dequeue()); System.out.println(rq.dequeue()); System.out.println(rq.size()); // 1 System.out.println("*******"); System.out.println(rq.sample()); System.out.println(rq.dequeue()); System.out.println(rq.size()); // 0 System.out.println("*******"); RandomizedQueue<Integer> rqOne = new RandomizedQueue<Integer>(); System.out.println(rq.size()); rq.enqueue(4); System.out.println(rq.size()); rq.enqueue(5); System.out.println(rq.dequeue()); } }<|fim▁end|>
if (size == q.length) resize(2 * q.length); // double size of array if necessary q[last++] = item; // add item if (last == q.length) last = 0; // wrap-around
<|file_name|>Ipkg.py<|end_file_name|><|fim▁begin|>import os from enigma import eConsoleAppContainer from Components.Harddisk import harddiskmanager opkgDestinations = [] opkgStatusPath = '' def opkgExtraDestinations(): global opkgDestinations return ''.join([" --dest %s:%s" % (i,i) for i in opkgDestinations]) def opkgAddDestination(mountpoint): pass #global opkgDestinations #if mountpoint not in opkgDestinations: #opkgDestinations.append(mountpoint) #print "[Ipkg] Added to OPKG destinations:", mountpoint def onPartitionChange(why, part): global opkgDestinations global opkgStatusPath mountpoint = os.path.normpath(part.mountpoint) if mountpoint and mountpoint != '/': if why == 'add': if opkgStatusPath == '': # older opkg versions opkgStatusPath = 'usr/lib/opkg/status' if not os.path.exists(os.path.join('/', opkgStatusPath)): # recent opkg versions opkgStatusPath = 'var/lib/opkg/status' if os.path.exists(os.path.join(mountpoint, opkgStatusPath)): opkgAddDestination(mountpoint) elif why == 'remove': try: opkgDestinations.remove(mountpoint) print "[Ipkg] Removed from OPKG destinations:", mountpoint except: pass harddiskmanager.on_partition_list_change.append(onPartitionChange) for part in harddiskmanager.getMountedPartitions(): onPartitionChange('add', part) class IpkgComponent: EVENT_INSTALL = 0 EVENT_DOWNLOAD = 1 EVENT_INFLATING = 2 EVENT_CONFIGURING = 3 EVENT_REMOVE = 4 EVENT_UPGRADE = 5 EVENT_LISTITEM = 9 EVENT_DONE = 10 EVENT_ERROR = 11 EVENT_MODIFIED = 12 CMD_INSTALL = 0 CMD_LIST = 1 CMD_REMOVE = 2 CMD_UPDATE = 3 CMD_UPGRADE = 4 CMD_UPGRADE_LIST = 5 def __init__(self, ipkg = 'opkg'): self.ipkg = ipkg self.cmd = eConsoleAppContainer() self.cache = None self.callbackList = [] self.setCurrentCommand() def setCurrentCommand(self, command = None): self.currentCommand = command def runCmdEx(self, cmd): self.runCmd(opkgExtraDestinations() + ' ' + cmd) def runCmd(self, cmd): print "executing", self.ipkg, cmd self.cmd.appClosed.append(self.cmdFinished) self.cmd.dataAvail.append(self.cmdData) if self.cmd.execute(self.ipkg + " " + cmd): self.cmdFinished(-1) def startCmd(self, cmd, args = None): if cmd is self.CMD_UPDATE: self.runCmdEx("update") elif cmd is self.CMD_UPGRADE: append = "" if args["test_only"]: append = " -test" self.runCmdEx("upgrade" + append) elif cmd is self.CMD_LIST: self.fetchedList = [] if args['installed_only']: self.runCmdEx("list_installed") else: self.runCmd("list") elif cmd is self.CMD_INSTALL: self.runCmd("install " + args['package']) elif cmd is self.CMD_REMOVE: self.runCmd("remove " + args['package']) elif cmd is self.CMD_UPGRADE_LIST: self.fetchedList = [] self.runCmdEx("list_upgradable") self.setCurrentCommand(cmd) def cmdFinished(self, retval): self.callCallbacks(self.EVENT_DONE) self.cmd.appClosed.remove(self.cmdFinished) self.cmd.dataAvail.remove(self.cmdData) def cmdData(self, data): print "data:", data if self.cache is None:<|fim▁hole|> self.cache += data if '\n' in data: splitcache = self.cache.split('\n') if self.cache[-1] == '\n': iteration = splitcache self.cache = None else: iteration = splitcache[:-1] self.cache = splitcache[-1] for mydata in iteration: if mydata != '': self.parseLine(mydata) def parseLine(self, data): if self.currentCommand in (self.CMD_LIST, self.CMD_UPGRADE_LIST): item = data.split(' - ', 2) if len(item) < 3: self.callCallbacks(self.EVENT_ERROR, None) return self.fetchedList.append(item) self.callCallbacks(self.EVENT_LISTITEM, item) return try: if data[:11] == 'Downloading': self.callCallbacks(self.EVENT_DOWNLOAD, data.split(' ', 5)[1].strip()) elif data[:9] == 'Upgrading': self.callCallbacks(self.EVENT_UPGRADE, data.split(' ', 2)[1]) elif data[:10] == 'Installing': self.callCallbacks(self.EVENT_INSTALL, data.split(' ', 2)[1]) elif data[:8] == 'Removing': self.callCallbacks(self.EVENT_REMOVE, data.split(' ', 3)[2]) elif data[:11] == 'Configuring': self.callCallbacks(self.EVENT_CONFIGURING, data.split(' ', 2)[1]) elif data[:17] == 'An error occurred': self.callCallbacks(self.EVENT_ERROR, None) elif data[:18] == 'Failed to download': self.callCallbacks(self.EVENT_ERROR, None) elif data[:21] == 'ipkg_download: ERROR:': self.callCallbacks(self.EVENT_ERROR, None) elif 'Configuration file \'' in data: # Note: the config file update question doesn't end with a newline, so # if we get multiple config file update questions, the next ones # don't necessarily start at the beginning of a line self.callCallbacks(self.EVENT_MODIFIED, data.split(' \'', 3)[1][:-1]) except Exception, ex: print "[Ipkg] Failed to parse: '%s'" % data print "[Ipkg]", ex def callCallbacks(self, event, param = None): for callback in self.callbackList: callback(event, param) def addCallback(self, callback): self.callbackList.append(callback) def removeCallback(self, callback): self.callbackList.remove(callback) def getFetchedList(self): return self.fetchedList def stop(self): self.cmd.kill() def isRunning(self): return self.cmd.running() def write(self, what): if what: # We except unterminated commands what += "\n" self.cmd.write(what, len(what))<|fim▁end|>
self.cache = data else:
<|file_name|>mount.rs<|end_file_name|><|fim▁begin|>use libc::{c_ulong, c_int}; use libc; use {Errno, Result, NixPath}; bitflags!( pub struct MsFlags: c_ulong { const MS_RDONLY = libc::MS_RDONLY; // Mount read-only const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Writes are synced at once const MS_REMOUNT = libc::MS_REMOUNT; // Alter flags of a mounted FS const MS_MANDLOCK = libc::MS_MANDLOCK; // Allow mandatory locks on a FS const MS_DIRSYNC = libc::MS_DIRSYNC; // Directory modifications are synchronous const MS_NOATIME = libc::MS_NOATIME; // Do not update access times const MS_NODIRATIME = libc::MS_NODIRATIME; // Do not update directory access times const MS_BIND = libc::MS_BIND; // Linux 2.4.0 - Bind directory at different place const MS_MOVE = libc::MS_MOVE; const MS_REC = libc::MS_REC; const MS_VERBOSE = 1 << 15; // Deprecated const MS_SILENT = libc::MS_SILENT; const MS_POSIXACL = libc::MS_POSIXACL; const MS_UNBINDABLE = libc::MS_UNBINDABLE; const MS_PRIVATE = libc::MS_PRIVATE; const MS_SLAVE = libc::MS_SLAVE; const MS_SHARED = libc::MS_SHARED; const MS_RELATIME = libc::MS_RELATIME; const MS_KERNMOUNT = libc::MS_KERNMOUNT; const MS_I_VERSION = libc::MS_I_VERSION; const MS_STRICTATIME = libc::MS_STRICTATIME; const MS_NOSEC = 1 << 28; const MS_BORN = 1 << 29; const MS_ACTIVE = libc::MS_ACTIVE; const MS_NOUSER = libc::MS_NOUSER; const MS_RMT_MASK = libc::MS_RMT_MASK; const MS_MGC_VAL = libc::MS_MGC_VAL; const MS_MGC_MSK = libc::MS_MGC_MSK;<|fim▁hole|>libc_bitflags!( pub flags MntFlags: c_int { MNT_FORCE, MNT_DETACH, MNT_EXPIRE, } ); pub fn mount<P1: ?Sized + NixPath, P2: ?Sized + NixPath, P3: ?Sized + NixPath, P4: ?Sized + NixPath>( source: Option<&P1>, target: &P2, fstype: Option<&P3>, flags: MsFlags, data: Option<&P4>) -> Result<()> { use libc; let res = try!(try!(try!(try!( source.with_nix_path(|source| { target.with_nix_path(|target| { fstype.with_nix_path(|fstype| { data.with_nix_path(|data| { unsafe { libc::mount(source.as_ptr(), target.as_ptr(), fstype.as_ptr(), flags.bits, data.as_ptr() as *const libc::c_void) } }) }) }) }))))); Errno::result(res).map(drop) } pub fn umount<P: ?Sized + NixPath>(target: &P) -> Result<()> { let res = try!(target.with_nix_path(|cstr| { unsafe { libc::umount(cstr.as_ptr()) } })); Errno::result(res).map(drop) } pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> { let res = try!(target.with_nix_path(|cstr| { unsafe { libc::umount2(cstr.as_ptr(), flags.bits) } })); Errno::result(res).map(drop) }<|fim▁end|>
} );
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>try: from ttag.args import Arg, BasicArg, BooleanArg, ConstantArg, DateArg, \ DateTimeArg, IntegerArg, IsInstanceArg, KeywordsArg, \ ModelInstanceArg, StringArg, TimeArg, MultiArg from ttag.core import Tag from ttag.exceptions import TagArgumentMissing, TagValidationError from ttag import helpers except ImportError: # This allows setup.py to skip import errors which may occur if ttag is # being installed at the same time as Django. pass VERSION = (3, 0) <|fim▁hole|> if not isinstance(bit, int): if number_only: break number = False version.append(number and '.' or '-') version.append(str(bit)) return ''.join(version)<|fim▁end|>
def get_version(number_only=False): version = [str(VERSION[0])] number = True for bit in VERSION[1:]:
<|file_name|>Ui_ExportData.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Ui_ExportData.ui' # # Created: Sat May 28 00:16:57 2011 # by: PyQt4 UI code generator 4.8.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_ExportData(object): def setupUi(self, ExportData): ExportData.setObjectName(_fromUtf8("ExportData")) ExportData.resize(354, 527) self.verticalLayout_5 = QtGui.QVBoxLayout(ExportData) self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) self.groupBox_2 = QtGui.QGroupBox(ExportData) self.groupBox_2.setObjectName(_fromUtf8("groupBox_2")) self.gridLayout = QtGui.QGridLayout(self.groupBox_2) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.label = QtGui.QLabel(self.groupBox_2) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.fileName = QtGui.QLineEdit(self.groupBox_2) self.fileName.setObjectName(_fromUtf8("fileName")) self.gridLayout.addWidget(self.fileName, 0, 1, 1, 1) self.label_2 = QtGui.QLabel(self.groupBox_2) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) self.outputType = QtGui.QComboBox(self.groupBox_2) self.outputType.setObjectName(_fromUtf8("outputType")) self.outputType.addItem(_fromUtf8("")) self.gridLayout.addWidget(self.outputType, 1, 1, 1, 2) self.stackedWidget = QtGui.QStackedWidget(self.groupBox_2) self.stackedWidget.setObjectName(_fromUtf8("stackedWidget")) self.delimitedStackedWidget = QtGui.QWidget() self.delimitedStackedWidget.setObjectName(_fromUtf8("delimitedStackedWidget")) self.gridLayout_2 = QtGui.QGridLayout(self.delimitedStackedWidget) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.label_3 = QtGui.QLabel(self.delimitedStackedWidget) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout_2.addWidget(self.label_3, 0, 0, 1, 1) self.delimitedDelimiterGroupBox = QtGui.QGroupBox(self.delimitedStackedWidget) self.delimitedDelimiterGroupBox.setTitle(_fromUtf8("")) self.delimitedDelimiterGroupBox.setObjectName(_fromUtf8("delimitedDelimiterGroupBox")) self.horizontalLayout = QtGui.QHBoxLayout(self.delimitedDelimiterGroupBox) self.horizontalLayout.setContentsMargins(2, 0, 0, 0) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.delimitedCommaRadio = QtGui.QRadioButton(self.delimitedDelimiterGroupBox) self.delimitedCommaRadio.setChecked(True) self.delimitedCommaRadio.setObjectName(_fromUtf8("delimitedCommaRadio")) self.delimiterButtonGroup = QtGui.QButtonGroup(ExportData) self.delimiterButtonGroup.setObjectName(_fromUtf8("delimiterButtonGroup")) self.delimiterButtonGroup.addButton(self.delimitedCommaRadio) self.horizontalLayout.addWidget(self.delimitedCommaRadio) self.delimitedTabRadio = QtGui.QRadioButton(self.delimitedDelimiterGroupBox) self.delimitedTabRadio.setObjectName(_fromUtf8("delimitedTabRadio")) self.delimiterButtonGroup.addButton(self.delimitedTabRadio) self.horizontalLayout.addWidget(self.delimitedTabRadio) self.delimitedOtherRadio = QtGui.QRadioButton(self.delimitedDelimiterGroupBox) self.delimitedOtherRadio.setObjectName(_fromUtf8("delimitedOtherRadio")) self.delimiterButtonGroup.addButton(self.delimitedOtherRadio) self.horizontalLayout.addWidget(self.delimitedOtherRadio) self.delimitedOtherDelimiter = QtGui.QLineEdit(self.delimitedDelimiterGroupBox) self.delimitedOtherDelimiter.setEnabled(False) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.delimitedOtherDelimiter.sizePolicy().hasHeightForWidth()) self.delimitedOtherDelimiter.setSizePolicy(sizePolicy) self.delimitedOtherDelimiter.setMaximumSize(QtCore.QSize(20, 16777215)) self.delimitedOtherDelimiter.setBaseSize(QtCore.QSize(0, 0)) font = QtGui.QFont() font.setPointSize(12) self.delimitedOtherDelimiter.setFont(font) self.delimitedOtherDelimiter.setMaxLength(1) self.delimitedOtherDelimiter.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.delimitedOtherDelimiter.setObjectName(_fromUtf8("delimitedOtherDelimiter")) self.horizontalLayout.addWidget(self.delimitedOtherDelimiter) self.horizontalLayout.setStretch(0, 5) self.horizontalLayout.setStretch(1, 5) self.gridLayout_2.addWidget(self.delimitedDelimiterGroupBox, 0, 1, 1, 1) self.label_4 = QtGui.QLabel(self.delimitedStackedWidget) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout_2.addWidget(self.label_4, 1, 0, 1, 1) self.delimitedDataDirectionGroupBox = QtGui.QGroupBox(self.delimitedStackedWidget) self.delimitedDataDirectionGroupBox.setTitle(_fromUtf8("")) self.delimitedDataDirectionGroupBox.setObjectName(_fromUtf8("delimitedDataDirectionGroupBox")) self.horizontalLayout_3 = QtGui.QHBoxLayout(self.delimitedDataDirectionGroupBox) self.horizontalLayout_3.setContentsMargins(2, 0, 0, 0) self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) self.dataDirectionColumns = QtGui.QRadioButton(self.delimitedDataDirectionGroupBox) self.dataDirectionColumns.setChecked(True) self.dataDirectionColumns.setObjectName(_fromUtf8("dataDirectionColumns")) self.dataDirectionButtonGroup = QtGui.QButtonGroup(ExportData) self.dataDirectionButtonGroup.setObjectName(_fromUtf8("dataDirectionButtonGroup")) self.dataDirectionButtonGroup.addButton(self.dataDirectionColumns) self.horizontalLayout_3.addWidget(self.dataDirectionColumns) self.dataDirectionRows = QtGui.QRadioButton(self.delimitedDataDirectionGroupBox) self.dataDirectionRows.setChecked(False) self.dataDirectionRows.setObjectName(_fromUtf8("dataDirectionRows")) self.dataDirectionButtonGroup.addButton(self.dataDirectionRows) self.horizontalLayout_3.addWidget(self.dataDirectionRows) self.gridLayout_2.addWidget(self.delimitedDataDirectionGroupBox, 1, 1, 1, 1) self.stackedWidget.addWidget(self.delimitedStackedWidget) self.page_2 = QtGui.QWidget() self.page_2.setObjectName(_fromUtf8("page_2")) self.stackedWidget.addWidget(self.page_2) self.gridLayout.addWidget(self.stackedWidget, 2, 0, 1, 3) self.fileNameButton = QtGui.QPushButton(self.groupBox_2) self.fileNameButton.setObjectName(_fromUtf8("fileNameButton")) self.gridLayout.addWidget(self.fileNameButton, 0, 2, 1, 1) self.verticalLayout_5.addWidget(self.groupBox_2) self.groupBox_3 = QtGui.QGroupBox(ExportData) self.groupBox_3.setObjectName(_fromUtf8("groupBox_3")) self.horizontalLayout_2 = QtGui.QHBoxLayout(self.groupBox_3) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.label_6 = QtGui.QLabel(self.groupBox_3) self.label_6.setObjectName(_fromUtf8("label_6")) self.verticalLayout.addWidget(self.label_6) self.allWavesListView = QtGui.QListView(self.groupBox_3) self.allWavesListView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.allWavesListView.setObjectName(_fromUtf8("allWavesListView")) self.verticalLayout.addWidget(self.allWavesListView) self.horizontalLayout_2.addLayout(self.verticalLayout) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem) self.addWaveButton = QtGui.QPushButton(self.groupBox_3) self.addWaveButton.setObjectName(_fromUtf8("addWaveButton")) self.verticalLayout_2.addWidget(self.addWaveButton) self.removeWaveButton = QtGui.QPushButton(self.groupBox_3) self.removeWaveButton.setObjectName(_fromUtf8("removeWaveButton")) self.verticalLayout_2.addWidget(self.removeWaveButton) spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem1) self.horizontalLayout_2.addLayout(self.verticalLayout_2) self.verticalLayout_3 = QtGui.QVBoxLayout() self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.label_5 = QtGui.QLabel(self.groupBox_3) self.label_5.setObjectName(_fromUtf8("label_5")) self.verticalLayout_3.addWidget(self.label_5) self.fileWavesListView = QtGui.QListView(self.groupBox_3) self.fileWavesListView.setDragEnabled(True) self.fileWavesListView.setDragDropMode(QtGui.QAbstractItemView.InternalMove) self.fileWavesListView.setDefaultDropAction(QtCore.Qt.MoveAction) self.fileWavesListView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.fileWavesListView.setObjectName(_fromUtf8("fileWavesListView")) self.verticalLayout_3.addWidget(self.fileWavesListView) self.horizontalLayout_2.addLayout(self.verticalLayout_3) self.verticalLayout_5.addWidget(self.groupBox_3) self.groupBox_5 = QtGui.QGroupBox(ExportData)<|fim▁hole|> self.exportDataButton = QtGui.QPushButton(self.groupBox_5) self.exportDataButton.setObjectName(_fromUtf8("exportDataButton")) self.verticalLayout_4.addWidget(self.exportDataButton) self.verticalLayout_5.addWidget(self.groupBox_5) self.retranslateUi(ExportData) self.stackedWidget.setCurrentIndex(0) QtCore.QObject.connect(self.delimitedOtherRadio, QtCore.SIGNAL(_fromUtf8("toggled(bool)")), self.delimitedOtherDelimiter.setEnabled) QtCore.QObject.connect(self.outputType, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.stackedWidget.setCurrentIndex) def retranslateUi(self, ExportData): ExportData.setWindowTitle(QtGui.QApplication.translate("ExportData", "Export Data", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_2.setTitle(QtGui.QApplication.translate("ExportData", "Step 1 - File Options", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("ExportData", "File", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("ExportData", "Type", None, QtGui.QApplication.UnicodeUTF8)) self.outputType.setItemText(0, QtGui.QApplication.translate("ExportData", "Delimited", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("ExportData", "Delimiter", None, QtGui.QApplication.UnicodeUTF8)) self.delimitedCommaRadio.setText(QtGui.QApplication.translate("ExportData", "Comma", None, QtGui.QApplication.UnicodeUTF8)) self.delimitedTabRadio.setText(QtGui.QApplication.translate("ExportData", "Tab", None, QtGui.QApplication.UnicodeUTF8)) self.delimitedOtherRadio.setText(QtGui.QApplication.translate("ExportData", "Other", None, QtGui.QApplication.UnicodeUTF8)) self.delimitedOtherDelimiter.setText(QtGui.QApplication.translate("ExportData", ",", None, QtGui.QApplication.UnicodeUTF8)) self.label_4.setText(QtGui.QApplication.translate("ExportData", "Data as", None, QtGui.QApplication.UnicodeUTF8)) self.dataDirectionColumns.setText(QtGui.QApplication.translate("ExportData", "Columns", None, QtGui.QApplication.UnicodeUTF8)) self.dataDirectionRows.setText(QtGui.QApplication.translate("ExportData", "Rows", None, QtGui.QApplication.UnicodeUTF8)) self.fileNameButton.setText(QtGui.QApplication.translate("ExportData", "Select...", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_3.setTitle(QtGui.QApplication.translate("ExportData", "Step 2 - Select Data", None, QtGui.QApplication.UnicodeUTF8)) self.label_6.setText(QtGui.QApplication.translate("ExportData", "All Waves", None, QtGui.QApplication.UnicodeUTF8)) self.addWaveButton.setText(QtGui.QApplication.translate("ExportData", "Add -->", None, QtGui.QApplication.UnicodeUTF8)) self.removeWaveButton.setText(QtGui.QApplication.translate("ExportData", "<-- Remove", None, QtGui.QApplication.UnicodeUTF8)) self.label_5.setText(QtGui.QApplication.translate("ExportData", "Waves to Export", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_5.setTitle(QtGui.QApplication.translate("ExportData", "Step 3 - Export", None, QtGui.QApplication.UnicodeUTF8)) self.exportDataButton.setText(QtGui.QApplication.translate("ExportData", "Export Data", None, QtGui.QApplication.UnicodeUTF8))<|fim▁end|>
self.groupBox_5.setObjectName(_fromUtf8("groupBox_5")) self.verticalLayout_4 = QtGui.QVBoxLayout(self.groupBox_5) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
<|file_name|>factor.rs<|end_file_name|><|fim▁begin|>// * This file is part of the uutils coreutils package. // *<|fim▁hole|>// * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. use smallvec::SmallVec; use std::cell::RefCell; use std::fmt; use crate::numeric::{Arithmetic, Montgomery}; use crate::{miller_rabin, rho, table}; type Exponent = u8; #[derive(Clone, Debug, Default)] struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>); // spell-checker:ignore (names) Erdős–Kac * Erdős Kac // The number of factors to inline directly into a `Decomposition` object. // As a consequence of the Erdős–Kac theorem, the average number of prime factors // of integers < 10²⁵ ≃ 2⁸³ is 4, so we can use a slightly higher value. const NUM_FACTORS_INLINE: usize = 5; impl Decomposition { fn one() -> Self { Self::default() } fn add(&mut self, factor: u64, exp: Exponent) { debug_assert!(exp > 0); if let Some((_, e)) = self.0.iter_mut().find(|(f, _)| *f == factor) { *e += exp; } else { self.0.push((factor, exp)); } } #[cfg(test)] fn product(&self) -> u64 { self.0 .iter() .fold(1, |acc, (p, exp)| acc * p.pow(*exp as u32)) } fn get(&self, p: u64) -> Option<&(u64, u8)> { self.0.iter().find(|(q, _)| *q == p) } } impl PartialEq for Decomposition { fn eq(&self, other: &Self) -> bool { for p in &self.0 { if other.get(p.0) != Some(p) { return false; } } for p in &other.0 { if self.get(p.0) != Some(p) { return false; } } true } } impl Eq for Decomposition {} #[derive(Clone, Debug, Eq, PartialEq)] pub struct Factors(RefCell<Decomposition>); impl Factors { pub fn one() -> Self { Self(RefCell::new(Decomposition::one())) } pub fn add(&mut self, prime: u64, exp: Exponent) { debug_assert!(miller_rabin::is_prime(prime)); self.0.borrow_mut().add(prime, exp); } pub fn push(&mut self, prime: u64) { self.add(prime, 1); } #[cfg(test)] fn product(&self) -> u64 { self.0.borrow().product() } } impl fmt::Display for Factors { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let v = &mut (self.0).borrow_mut().0; v.sort_unstable(); for (p, exp) in v.iter() { for _ in 0..*exp { write!(f, " {}", p)?; } } Ok(()) } } fn _factor<A: Arithmetic + miller_rabin::Basis>(num: u64, f: Factors) -> Factors { use miller_rabin::Result::*; // Shadow the name, so the recursion automatically goes from “Big” arithmetic to small. let _factor = |n, f| { if n < (1 << 32) { _factor::<Montgomery<u32>>(n, f) } else { _factor::<A>(n, f) } }; if num == 1 { return f; } let n = A::new(num); let divisor = match miller_rabin::test::<A>(n) { Prime => { #[cfg(feature = "coz")] coz::progress!("factor found"); let mut r = f; r.push(num); return r; } Composite(d) => d, Pseudoprime => rho::find_divisor::<A>(n), }; let f = _factor(divisor, f); _factor(num / divisor, f) } pub fn factor(mut n: u64) -> Factors { #[cfg(feature = "coz")] coz::begin!("factorization"); let mut factors = Factors::one(); if n < 2 { return factors; } let n_zeros = n.trailing_zeros(); if n_zeros > 0 { factors.add(2, n_zeros as Exponent); n >>= n_zeros; } if n == 1 { #[cfg(feature = "coz")] coz::end!("factorization"); return factors; } table::factor(&mut n, &mut factors); #[allow(clippy::let_and_return)] let r = if n < (1 << 32) { _factor::<Montgomery<u32>>(n, factors) } else { _factor::<Montgomery<u64>>(n, factors) }; #[cfg(feature = "coz")] coz::end!("factorization"); r } #[cfg(test)] mod tests { use super::{factor, Decomposition, Exponent, Factors}; use quickcheck::quickcheck; use smallvec::smallvec; use std::cell::RefCell; #[test] fn factor_2044854919485649() { let f = Factors(RefCell::new(Decomposition(smallvec![ (503, 1), (2423, 1), (40961, 2) ]))); assert_eq!(factor(f.product()), f); } #[test] fn factor_recombines_small() { assert!((1..10_000) .map(|i| 2 * i + 1) .all(|i| factor(i).product() == i)); } #[test] fn factor_recombines_overflowing() { assert!((0..250) .map(|i| 2 * i + 2u64.pow(32) + 1) .all(|i| factor(i).product() == i)); } #[test] fn factor_recombines_strong_pseudoprime() { // This is a strong pseudoprime (wrt. miller_rabin::BASIS) // and triggered a bug in rho::factor's code path handling // miller_rabbin::Result::Composite let pseudoprime = 17179869183; for _ in 0..20 { // Repeat the test 20 times, as it only fails some fraction // of the time. assert!(factor(pseudoprime).product() == pseudoprime); } } quickcheck! { fn factor_recombines(i: u64) -> bool { i == 0 || factor(i).product() == i } fn recombines_factors(f: Factors) -> () { assert_eq!(factor(f.product()), f); } fn exponentiate_factors(f: Factors, e: Exponent) -> () { if e == 0 { return; } if let Some(fe) = f.product().checked_pow(e.into()) { assert_eq!(factor(fe), f ^ e); } } } } #[cfg(test)] use rand::{ distributions::{Distribution, Standard}, Rng, }; #[cfg(test)] impl Distribution<Factors> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Factors { let mut f = Factors::one(); let mut g = 1u64; let mut n = u64::MAX; // spell-checker:ignore (names) Adam Kalai * Kalai's // Adam Kalai's algorithm for generating uniformly-distributed // integers and their factorization. // // See Generating Random Factored Numbers, Easily, J. Cryptology (2003) 'attempt: loop { while n > 1 { n = rng.gen_range(1..n); if miller_rabin::is_prime(n) { if let Some(h) = g.checked_mul(n) { f.push(n); g = h; } else { // We are overflowing u64, retry continue 'attempt; } } } return f; } } } #[cfg(test)] impl quickcheck::Arbitrary for Factors { fn arbitrary(g: &mut quickcheck::Gen) -> Self { factor(u64::arbitrary(g)) } } #[cfg(test)] impl std::ops::BitXor<Exponent> for Factors { type Output = Self; fn bitxor(self, rhs: Exponent) -> Self { debug_assert_ne!(rhs, 0); let mut r = Self::one(); for (p, e) in self.0.borrow().0.iter() { r.add(*p, rhs * e); } debug_assert_eq!(r.product(), self.product().pow(rhs.into())); r } }<|fim▁end|>
// * (c) 2020 nicoo <[email protected]>
<|file_name|>cash register.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
#cash register #Samuel Armstrong
<|file_name|>test_version.py<|end_file_name|><|fim▁begin|># Copyright 2017,2018 IBM Corp. # # 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 json import mock import unittest from zvmsdk.sdkwsgi.handlers import version from zvmsdk import version as sdk_version class HandlersRootTest(unittest.TestCase): def setUp(self): pass def test_version(self): req = mock.Mock() ver_str = {"rc": 0, "overallRC": 0, "errmsg": "", "modID": None, "output": {"api_version": version.APIVERSION, "min_version": version.APIVERSION, "version": sdk_version.__version__, "max_version": version.APIVERSION, }, "rs": 0}<|fim▁hole|> # version_json = json.dumps(ver_res) # version_str = utils.to_utf8(version_json) ver_res = json.loads(req.response.body.decode('utf-8')) self.assertEqual(ver_str, ver_res) self.assertEqual('application/json', res.content_type)<|fim▁end|>
res = version.version(req) self.assertEqual('application/json', req.response.content_type)
<|file_name|>clean_test.go<|end_file_name|><|fim▁begin|>// Copyright 2020 The Knative Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package service import ( "testing" "gotest.tools/v3/assert" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8sfake "k8s.io/client-go/kubernetes/fake" "knative.dev/kperf/pkg" "knative.dev/kperf/pkg/testutil" servingv1client "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1" servingv1fake "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/fake" ) func TestCleanServicesFunc(t *testing.T) { tests := []struct { name string cleanArgs pkg.CleanArgs }{ { name: "should clean services in namespace", cleanArgs: pkg.CleanArgs{ Namespace: "test-kperf-1", }, }, { name: "should clean services in namespace range", cleanArgs: pkg.CleanArgs{ NamespacePrefix: "test-kperf", NamespaceRange: "1,2", }, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "test-kperf-1", }, } client := k8sfake.NewSimpleClientset(ns) fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake} servingClient := func() (servingv1client.ServingV1Interface, error) { return fakeServing, nil } p := &pkg.PerfParams{ ClientSet: client, NewServingClient: servingClient, } err := CleanServices(p, tc.cleanArgs) assert.NilError(t, err) }) } } func TestNewServiceCleanCommand(t *testing.T) {<|fim▁hole|> fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake} servingClient := func() (servingv1client.ServingV1Interface, error) { return fakeServing, nil } p := &pkg.PerfParams{ ClientSet: client, NewServingClient: servingClient, } cmd := NewServiceCleanCommand(p) _, err := testutil.ExecuteCommand(cmd) assert.ErrorContains(t, err, "both namespace and namespace-prefix are empty") _, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "2,1") assert.ErrorContains(t, err, "failed to parse namespace range 2,1") _, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "x,y") assert.ErrorContains(t, err, "strconv.Atoi: parsing \"x\": invalid syntax") _, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1,y") assert.ErrorContains(t, err, "strconv.Atoi: parsing \"y\": invalid syntax") _, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1") assert.ErrorContains(t, err, "expected range like 1,500, given 1") _, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "1,2") assert.ErrorContains(t, err, "no namespace found with prefix test-kperf-1") }) t.Run("clean service as expected", func(t *testing.T) { ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "test-kperf-1", }, } client := k8sfake.NewSimpleClientset(ns) fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake} servingClient := func() (servingv1client.ServingV1Interface, error) { return fakeServing, nil } p := &pkg.PerfParams{ ClientSet: client, NewServingClient: servingClient, } cmd := NewServiceCleanCommand(p) _, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-1") assert.NilError(t, err) _, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1,2") assert.NilError(t, err) }) t.Run("failed to clean services", func(t *testing.T) { ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "test-kperf-2", }, } client := k8sfake.NewSimpleClientset(ns) fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake} servingClient := func() (servingv1client.ServingV1Interface, error) { return fakeServing, nil } p := &pkg.PerfParams{ ClientSet: client, NewServingClient: servingClient, } cmd := NewServiceCleanCommand(p) _, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-1") assert.ErrorContains(t, err, "namespaces \"test-kperf-1\" not found") cmd = NewServiceCleanCommand(p) _, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "1,2") assert.ErrorContains(t, err, "no namespace found with prefix test-kperf-1") }) t.Run("clean generated ksvc with namespace flag", func(t *testing.T) { ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "test-kperf-prefix-1", }, } client := k8sfake.NewSimpleClientset(ns) fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake} servingClient := func() (servingv1client.ServingV1Interface, error) { return fakeServing, nil } p := &pkg.PerfParams{ ClientSet: client, NewServingClient: servingClient, } cmd := NewServiceCleanCommand(p) _, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-prefix-1", "--svc-prefix", "test-ksvc") assert.NilError(t, err) }) }<|fim▁end|>
t.Run("incompleted or wrong args for service clean", func(t *testing.T) { client := k8sfake.NewSimpleClientset()
<|file_name|>printTileConfigCoords.py<|end_file_name|><|fim▁begin|>import os, sys sys.path = [os.path.join(os.getcwd(), "..") ] + sys.path sys.path = [os.path.join(os.getcwd(), "..", "..") ] + sys.path from flTile.amConfig import CreateAMConfig def run(): tileConfig = CreateAMConfig() #hostname = gethostname() #machineDesc = tileConfig.getMachineDescByHostname(hostname) print "Machine, local rects, absolute rects" for machineDesc in tileConfig.machines: localRects = [] absoluteRects = [] for tile in machineDesc.tiles: localRects.append(tileConfig.getLocalDrawRect(tile.uid)) absoluteRects.append(tileConfig.getAbsoluteFullDisplayRect(tile.uid)) print machineDesc.hostname, localRects, absoluteRects fullRect = tileConfig.getMainDisplayRect() print "FULL DISPLAY:", fullRect.width, fullRect.height <|fim▁hole|><|fim▁end|>
if __name__ == "__main__": run()
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if a slice is sorted properly. pub fn check_sorted<E>(candidate: &[E]) where E: Ord + Clone + Debug { let sorted = { let mut copy = candidate.iter().cloned().collect::<Vec<_>>(); copy.sort(); copy }; assert_eq!(sorted.as_slice(), candidate); } #[test] fn test_check_sorted() { let sorted = vec![1, 2, 3, 4, 5]; check_sorted(&sorted); } #[test] #[should_panic] fn test_check_unsorted() { let unsorted = vec![1, 3, 2]; check_sorted(&unsorted); } #[cfg(test)] mod tests { use regex::Regex; use std::collections::HashSet; use std::io::{BufReader, BufRead}; use std::fs::{self, File}; use std::path::Path; /// A test to check if all source files are covered by `Cargo.toml` #[test] fn check_sources_covered() { let sources = get_source_files(); let bins = get_toml_paths(); let not_covered = get_not_covered(&sources, &bins); if !not_covered.is_empty() { println!("Error, the following source files are not covered by Cargo.toml:"); for source in &not_covered { println!("{}", source); } panic!("Please add the previous source files to Cargo.toml"); } } /// Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::read_dir("./src").unwrap(); paths.map(|p| { p.unwrap() .path() .file_name() .unwrap() .to_os_string() .into_string() .unwrap()<|fim▁hole|> } /// Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open("./Cargo.toml").unwrap(); let reader = BufReader::new(c_toml); let regex = Regex::new("path = \"(.*)\"").unwrap(); reader.lines() .filter_map(|l| { let l = l.unwrap(); regex.captures(&l).map(|c| { c.at(1) .map(|s| Path::new(s)) .unwrap() .file_name() .unwrap() .to_string_lossy() .into_owned() }) }) .collect() } /// Returns the filenames of the source files which are not covered by Cargo.toml fn get_not_covered<'a>(sources: &'a HashSet<String>, paths: &'a HashSet<String>) -> HashSet<&'a String> { sources.difference(paths).collect() } }<|fim▁end|>
}) .filter(|s| s[..].ends_with(".rs")) .collect()
<|file_name|>util.py<|end_file_name|><|fim▁begin|>from collections import Counter import sys import numpy as np import scipy as sp from lexical_structure import WordEmbeddingDict import dense_feature_functions as df def _get_word2vec_ff(embedding_path, projection): word2vec = df.EmbeddingFeaturizer(embedding_path) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _get_zh_word2vec_ff(num_units, vec_type, projection, cdtb): prefix = 'zh_gigaword3' if cdtb: file_name = '/data/word_embeddings/%s-%s%s-cdtb_vocab.txt' \ % (prefix, vec_type, num_units) else: file_name = '/data/word_embeddings/%s-%s%s.txt' \ % (prefix, vec_type, num_units) word2vec = df.EmbeddingFeaturizer(file_name) if projection == 'mean_pool': return word2vec.mean_args elif projection == 'sum_pool': return word2vec.additive_args elif projection == 'max_pool': return word2vec.max_args elif projection == 'top': return word2vec.top_args else: raise ValueError('projection must be one of {mean_pool, sum_pool, max_pool, top}. Got %s ' % projection) def _sparse_featurize_relation_list(relation_list, ff_list, alphabet=None): if alphabet is None: alphabet = {} grow_alphabet = True else: grow_alphabet = False feature_vectors = [] print 'Applying feature functions...' for relation in relation_list: feature_vector_indices = [] for ff in ff_list: feature_vector = ff(relation) for f in feature_vector: if grow_alphabet and f not in alphabet: alphabet[f] = len(alphabet) if f in alphabet: feature_vector_indices.append(alphabet[f]) feature_vectors.append(feature_vector_indices) print 'Creating feature sparse matrix...'<|fim▁hole|> for i, fv in enumerate(feature_vectors): feature_matrix[i, fv] = 1 return feature_matrix.tocsr(), alphabet def sparse_featurize(relation_list_list, ff_list): print 'Featurizing...' data_list = [] alphabet = None for relation_list in relation_list_list: data, alphabet = _sparse_featurize_relation_list(relation_list, ff_list, alphabet) data_list.append(data) return (data_list, alphabet) def convert_seconds_to_hours(num_seconds): m, s = divmod(num_seconds, 60) h, m = divmod(m, 60) return (h, m, s) def compute_mi(feature_matrix, label_vector): """Compute mutual information of each feature """ num_labels = np.max(label_vector) + 1 num_features = feature_matrix.shape[1] num_rows = feature_matrix.shape[0] total = num_rows + num_labels c_y = np.zeros(num_labels) for l in label_vector: c_y[l] += 1.0 c_y += 1.0 c_x_y = np.zeros((num_features, num_labels)) c_x = np.zeros(num_features) for i in range(num_rows): c_x_y[:, label_vector[i]] += feature_matrix[i, :] c_x += feature_matrix[i, :] c_x_y += 1.0 c_x += 1.0 c_x_c_y = np.outer(c_x, c_y) c_not_x_c_y = np.outer((total - c_x), c_y) c_not_x_y = c_y - c_x_y inner = c_x_y / total * np.log(c_x_y * total / c_x_c_y) + \ c_not_x_y / total * np.log(c_not_x_y * total / c_not_x_c_y) mi_x = inner.sum(1) return mi_x def prune_feature_matrices(feature_matrices, mi, num_features): sorted_indices = mi.argsort()[-num_features:] return [x[:, sorted_indices] for x in feature_matrices] class BrownDictionary(object): def __init__(self): self.word_to_brown_mapping = {} self.num_clusters = 0 brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c3200-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c320-freq1.txt' #brown_cluster_file_name = 'brown-rcv1.clean.tokenized-CoNLL03.txt-c100-freq1.txt' self._load_brown_clusters('resources/%s' % brown_cluster_file_name) def _load_brown_clusters(self, path): try: lexicon_file = open(path) except: print 'fail to load brown cluster data' cluster_set = set() for line in lexicon_file: cluster_assn, word, _ = line.split('\t') if cluster_assn not in cluster_set: cluster_set.add(cluster_assn) self.word_to_brown_mapping[word] = len(cluster_set) - 1 self.num_clusters = len(cluster_set) def _get_brown_cluster_bag(self, tokens): bag = set() for token in tokens: if token in self.word_to_brown_mapping: cluster_assn = self.word_to_brown_mapping[token] if cluster_assn not in bag: bag.add(cluster_assn) return bag def get_brown_sparse_matrices_relations(self, relations): X1 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) X2 = sp.sparse.csr_matrix((len(relations), self.num_clusters),dtype=float) for i, relation in enumerate(relations): bag1 = self._get_brown_cluster_bag(relation.arg_tokens(1)) for cluster in bag1: X1[i, cluster] = 1.0 bag2 = self._get_brown_cluster_bag(relation.arg_tokens(2)) for cluster in bag2: X2[i, cluster] = 1.0 return (X1, X2) def get_brown_matrices_data(self, relation_list_list, use_sparse): """Extract sparse For each directory, returns (X1, X2, Y) X1 and X2 are sparse matrices from arg1 and arg2 respectively. Y is an integer vector of type int32 """ data = [] alphabet = None # load the data for relation_list in relation_list_list: # turn them into a data matrix print 'Making matrices' X1, X2 = self.get_brown_sparse_matrices_relations(relation_list) if not use_sparse: X1 = X1.toarray() X2 = X2.toarray() Y, alphabet = level2_labels(relation_list, alphabet) data.append((X1, X2, Y)) return (data, alphabet) def label_vectorize(relation_list_list, lf): alphabet = {} for i, valid_label in enumerate(lf.valid_labels()): alphabet[valid_label] = i label_vectors = [] for relation_list in relation_list_list: label_vector = [alphabet[lf.label(x)] for x in relation_list] label_vectors.append(np.array(label_vector, np.int64)) return label_vectors, alphabet def compute_baseline_acc(label_vector): label_counter = Counter() for label in label_vector: label_counter[label] += 1.0 _, freq = label_counter.most_common(1)[0] return round(freq / len(label_vector), 4) def convert_level2_labels(relations): # TODO: this is not enough because we have to exclude some tinay classes new_relation_list = [] for relation in relations: split_sense = relation.senses[0].split('.') if len(split_sense) >= 2: relation.relation_dict['Sense']= ['.'.join(split_sense[0:2])] new_relation_list.append(relation) return new_relation_list def level2_labels(relations, alphabet=None): if alphabet is None: alphabet = {} label_set = set() for relation in relations: label_set.add(relation.senses[0]) print label_set sorted_label = sorted(list(label_set)) for i, label in enumerate(sorted_label): alphabet[label] = i label_vector = [] for relation in relations: if relation.senses[0] not in alphabet: alphabet[relation.senses[0]] = len(alphabet) label_vector.append(alphabet[relation.senses[0]]) return np.array(label_vector, np.int64), alphabet def get_wbm(num_units): if num_units == 50: dict_file = '/data/word_embeddings/wsj-skipgram50.npy' vocab_file = '/data/word_embeddings/wsj-skipgram50_vocab.txt' elif num_units == 100: dict_file = '/data/word_embeddings/wsj-skipgram100.npy' vocab_file = '/data/word_embeddings/wsj-skipgram100_vocab.txt' elif num_units == 300: #dict_file = '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300.npy' dict_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors-negative300-wsj_vocab.npy' vocab_file = \ '/home/j/llc/tet/nlp/lib/lexicon/google_word_vector/GoogleNews-vectors.negative300-wsj_vocab-vocab.txt' else: # this will crash the next step and te's too lazy to make it throw an exception. dict_file = None vocab_file = None wbm = WordEmbeddingDict(dict_file, vocab_file) return wbm def get_zh_wbm(num_units): dict_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab.npy' % num_units vocab_file = '/data/word_embeddings/zh_gigaword3-skipgram%s-cdtb_vocab-vocab.txt' % num_units return WordEmbeddingDict(dict_file, vocab_file) def set_logger(file_name, dry_mode=False): if not dry_mode: sys.stdout = open('%s.log' % file_name, 'w', 1) json_file = open('%s.json' % file_name, 'w', 1) return json_file import base_label_functions as l from nets.learning import DataTriplet from data_reader import extract_implicit_relations from lstm import prep_serrated_matrix_relations def get_data_srm(dir_list, wbm, max_length=75): sense_lf = l.SecondLevelLabel() relation_list_list = [extract_implicit_relations(dir, sense_lf) for dir in dir_list] data_list = [] for relation_list in relation_list_list: data = prep_serrated_matrix_relations(relation_list, wbm, max_length) data_list.append(data) label_vectors, label_alphabet = \ label_vectorize(relation_list_list, sense_lf) data_triplet = DataTriplet( data_list, [[x] for x in label_vectors], [label_alphabet]) return data_triplet def make_givens_srm(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 mask1 X2 mask2] X1 and X2 are TxNxd serrated matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][:,start_idx:end_idx, :] givens[input_vec[1]] = T_training_data[1][:,start_idx:end_idx] # second arg embedding and mask givens[input_vec[2]] = T_training_data[2][:,start_idx:end_idx, :] givens[input_vec[3]] = T_training_data[3][:,start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] def make_givens(givens, input_vec, T_training_data, output_vec, T_training_data_label, start_idx, end_idx): """Make the 'given' dict for SGD training for discourse the input vecs should be [X1 X2] X1 and X2 are Nxd matrices. """ # first arg embedding and mask givens[input_vec[0]] = T_training_data[0][start_idx:end_idx] givens[input_vec[1]] = T_training_data[1][start_idx:end_idx] for i, output_var in enumerate(output_vec): givens[output_var] = T_training_data_label[i][start_idx:end_idx] if __name__ == '__main__': fm = np.array([ [1, 0, 1], [1, 0, 0], [0, 0, 0], [0, 1, 1], [0, 1, 0], [0, 0, 0]]) lv = np.array([0,0,0,1,1,1]) compute_mi(fm, lv)<|fim▁end|>
feature_matrix = sp.sparse.lil_matrix((len(relation_list), len(alphabet)))
<|file_name|>screenshot_flow.cc<|end_file_name|><|fim▁begin|>// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/image_editor/screenshot_flow.h" #include <memory> #include "base/logging.h" #include "build/build_config.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h"<|fim▁hole|>#include "content/public/browser/web_contents_observer.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/compositor/paint_recorder.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/render_text.h" #include "ui/snapshot/snapshot.h" #include "ui/views/background.h" #if defined(OS_MAC) #include "chrome/browser/image_editor/event_capture_mac.h" #include "components/lens/lens_features.h" #include "content/public/browser/render_view_host.h" #include "ui/views/widget/widget.h" #endif #if defined(USE_AURA) #include "ui/aura/window.h" #include "ui/wm/core/window_util.h" #endif namespace image_editor { // Colors for semitransparent overlay. static constexpr SkColor kColorSemitransparentOverlayMask = SkColorSetARGB(0x7F, 0x00, 0x00, 0x00); static constexpr SkColor kColorSemitransparentOverlayVisible = SkColorSetARGB(0x00, 0x00, 0x00, 0x00); static constexpr SkColor kColorSelectionRect = SkColorSetRGB(0xEE, 0xEE, 0xEE); // Minimum selection rect edge size to treat as a valid capture region. static constexpr int kMinimumValidSelectionEdgePixels = 30; ScreenshotFlow::ScreenshotFlow(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), web_contents_(web_contents->GetWeakPtr()) { weak_this_ = weak_factory_.GetWeakPtr(); } ScreenshotFlow::~ScreenshotFlow() { RemoveUIOverlay(); } void ScreenshotFlow::CreateAndAddUIOverlay() { if (screen_capture_layer_) return; web_contents_observer_ = std::make_unique<UnderlyingWebContentsObserver>( web_contents_.get(), this); screen_capture_layer_ = std::make_unique<ui::Layer>(ui::LayerType::LAYER_TEXTURED); screen_capture_layer_->SetName("ScreenshotRegionSelectionLayer"); screen_capture_layer_->SetFillsBoundsOpaquely(false); screen_capture_layer_->set_delegate(this); #if defined(OS_MAC) gfx::Rect bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_->GetContentNativeView(); views::Widget* widget = views::Widget::GetWidgetForNativeView(web_contents_view); ui::Layer* content_layer = widget->GetLayer(); const gfx::Rect offset_bounds = widget->GetWindowBoundsInScreen(); bounds.Offset(-offset_bounds.x(), -offset_bounds.y()); event_capture_mac_ = std::make_unique<EventCaptureMac>( this, web_contents_->GetTopLevelNativeWindow()); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::Layer* content_layer = native_window->layer(); const gfx::Rect bounds = native_window->bounds(); // Capture mouse down and drag events on our window. native_window->AddPreTargetHandler(this); #endif content_layer->Add(screen_capture_layer_.get()); content_layer->StackAtTop(screen_capture_layer_.get()); screen_capture_layer_->SetBounds(bounds); screen_capture_layer_->SetVisible(true); SetCursor(ui::mojom::CursorType::kCross); // After setup is done, we should set the capture mode to active. capture_mode_ = CaptureMode::SELECTION_RECTANGLE; } void ScreenshotFlow::RemoveUIOverlay() { if (capture_mode_ == CaptureMode::NOT_CAPTURING) return; capture_mode_ = CaptureMode::NOT_CAPTURING; if (!web_contents_ || !screen_capture_layer_) return; #if defined(OS_MAC) views::Widget* widget = views::Widget::GetWidgetForNativeView( web_contents_->GetContentNativeView()); if (!widget) return; ui::Layer* content_layer = widget->GetLayer(); event_capture_mac_.reset(); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); native_window->RemovePreTargetHandler(this); ui::Layer* content_layer = native_window->layer(); #endif content_layer->Remove(screen_capture_layer_.get()); screen_capture_layer_->set_delegate(nullptr); screen_capture_layer_.reset(); // Restore the cursor to pointer; there's no corresponding GetCursor() // to store the pre-capture-mode cursor, and the pointer will have moved // in the meantime. SetCursor(ui::mojom::CursorType::kPointer); } void ScreenshotFlow::Start(ScreenshotCaptureCallback flow_callback) { flow_callback_ = std::move(flow_callback); CreateAndAddUIOverlay(); RequestRepaint(gfx::Rect()); } void ScreenshotFlow::StartFullscreenCapture( ScreenshotCaptureCallback flow_callback) { // Start and finish the capture process by screenshotting the full window. // There is no region selection step in this mode. flow_callback_ = std::move(flow_callback); CaptureAndRunScreenshotCompleteCallback(ScreenshotCaptureResultCode::SUCCESS, gfx::Rect(web_contents_->GetSize())); } void ScreenshotFlow::CaptureAndRunScreenshotCompleteCallback( ScreenshotCaptureResultCode result_code, gfx::Rect region) { if (region.IsEmpty()) { RunScreenshotCompleteCallback(result_code, gfx::Rect(), gfx::Image()); return; } gfx::Rect bounds = web_contents_->GetViewBounds(); #if defined(OS_MAC) const gfx::NativeView& native_view = web_contents_->GetContentNativeView(); gfx::Image img; bool rval = ui::GrabViewSnapshot(native_view, region, &img); // If |img| is empty, clients should treat it as a canceled action, but // we have a DCHECK for development as we expected this call to succeed. DCHECK(rval); RunScreenshotCompleteCallback(result_code, bounds, img); #else ui::GrabWindowSnapshotAsyncCallback screenshot_callback = base::BindOnce(&ScreenshotFlow::RunScreenshotCompleteCallback, weak_this_, result_code, bounds); const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::GrabWindowSnapshotAsync(native_window, region, std::move(screenshot_callback)); #endif } void ScreenshotFlow::CancelCapture() { RemoveUIOverlay(); } void ScreenshotFlow::OnKeyEvent(ui::KeyEvent* event) { if (event->type() == ui::ET_KEY_PRESSED && event->key_code() == ui::VKEY_ESCAPE) { event->StopPropagation(); CompleteCapture(ScreenshotCaptureResultCode::USER_ESCAPE_EXIT, gfx::Rect()); } } void ScreenshotFlow::OnMouseEvent(ui::MouseEvent* event) { if (!event->IsLocatedEvent()) return; const ui::LocatedEvent* located_event = ui::LocatedEvent::FromIfValid(event); if (!located_event) return; gfx::Point location = located_event->location(); #if defined(OS_MAC) // Offset |location| be relative to the WebContents widget, vs the parent // window, recomputed rather than cached in case e.g. user disables // bookmarks bar from another window. gfx::Rect web_contents_bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_->GetContentNativeView(); views::Widget* widget = views::Widget::GetWidgetForNativeView(web_contents_view); const gfx::Rect widget_bounds = widget->GetWindowBoundsInScreen(); location.set_x(location.x() + (widget_bounds.x() - web_contents_bounds.x())); location.set_y(location.y() + (widget_bounds.y() - web_contents_bounds.y())); // Don't capture clicks on browser ui outside the webcontents. if (location.x() < 0 || location.y() < 0 || location.x() > web_contents_bounds.width() || location.y() > web_contents_bounds.height()) { return; } #endif switch (event->type()) { case ui::ET_MOUSE_MOVED: SetCursor(ui::mojom::CursorType::kCross); event->SetHandled(); break; case ui::ET_MOUSE_PRESSED: if (event->IsLeftMouseButton()) { drag_start_ = location; drag_end_ = location; event->SetHandled(); } break; case ui::ET_MOUSE_DRAGGED: if (event->IsLeftMouseButton()) { drag_end_ = location; RequestRepaint(gfx::Rect()); event->SetHandled(); } break; case ui::ET_MOUSE_RELEASED: if (capture_mode_ == CaptureMode::SELECTION_RECTANGLE || capture_mode_ == CaptureMode::SELECTION_ELEMENT) { event->SetHandled(); gfx::Rect selection = gfx::BoundingRect(drag_start_, drag_end_); drag_start_.SetPoint(0, 0); drag_end_.SetPoint(0, 0); if (selection.width() >= kMinimumValidSelectionEdgePixels && selection.height() >= kMinimumValidSelectionEdgePixels) { CompleteCapture(ScreenshotCaptureResultCode::SUCCESS, selection); } else { RequestRepaint(gfx::Rect()); } } break; default: break; } } void ScreenshotFlow::CompleteCapture(ScreenshotCaptureResultCode result_code, const gfx::Rect& region) { RemoveUIOverlay(); CaptureAndRunScreenshotCompleteCallback(result_code, region); } void ScreenshotFlow::RunScreenshotCompleteCallback( ScreenshotCaptureResultCode result_code, gfx::Rect bounds, gfx::Image image) { ScreenshotCaptureResult result; result.result_code = result_code; result.image = image; result.screen_bounds = bounds; std::move(flow_callback_).Run(result); } void ScreenshotFlow::OnPaintLayer(const ui::PaintContext& context) { if (!screen_capture_layer_) return; const gfx::Rect& screen_bounds(screen_capture_layer_->bounds()); ui::PaintRecorder recorder(context, screen_bounds.size()); gfx::Canvas* canvas = recorder.canvas(); auto selection_rect = gfx::BoundingRect(drag_start_, drag_end_); PaintSelectionLayer(canvas, selection_rect, gfx::Rect()); paint_invalidation_ = gfx::Rect(); } void ScreenshotFlow::RequestRepaint(gfx::Rect region) { if (!screen_capture_layer_) return; if (region.IsEmpty()) { const gfx::Size& layer_size = screen_capture_layer_->size(); region = gfx::Rect(0, 0, layer_size.width(), layer_size.height()); } paint_invalidation_.Union(region); screen_capture_layer_->SchedulePaint(region); } void ScreenshotFlow::PaintSelectionLayer(gfx::Canvas* canvas, const gfx::Rect& selection, const gfx::Rect& invalidation_region) { // Adjust for hidpi and lodpi support. canvas->UndoDeviceScaleFactor(); // Clear the canvas with our mask color. canvas->DrawColor(kColorSemitransparentOverlayMask); // Allow the user's selection to show through, and add a border around it. if (!selection.IsEmpty()) { float scale_factor = screen_capture_layer_->device_scale_factor(); gfx::Rect selection_scaled = gfx::ScaleToEnclosingRect(selection, scale_factor); canvas->FillRect(selection_scaled, kColorSemitransparentOverlayVisible, SkBlendMode::kClear); canvas->DrawRect(gfx::RectF(selection_scaled), kColorSelectionRect); } } void ScreenshotFlow::SetCursor(ui::mojom::CursorType cursor_type) { if (!web_contents_) { return; } #if defined(OS_MAC) if (cursor_type == ui::mojom::CursorType::kCross && lens::features::kRegionSearchMacCursorFix.Get()) { EventCaptureMac::SetCrossCursor(); return; } #endif content::RenderWidgetHost* host = web_contents_->GetMainFrame()->GetRenderWidgetHost(); if (host) { ui::Cursor cursor(cursor_type); host->SetCursor(cursor); } } bool ScreenshotFlow::IsCaptureModeActive() { return capture_mode_ != CaptureMode::NOT_CAPTURING; } void ScreenshotFlow::WebContentsDestroyed() { if (IsCaptureModeActive()) { CancelCapture(); } } void ScreenshotFlow::OnVisibilityChanged(content::Visibility visibility) { if (IsCaptureModeActive()) { CancelCapture(); } } // UnderlyingWebContentsObserver monitors the WebContents and exits screen // capture mode if a navigation occurs. class ScreenshotFlow::UnderlyingWebContentsObserver : public content::WebContentsObserver { public: UnderlyingWebContentsObserver(content::WebContents* web_contents, ScreenshotFlow* screenshot_flow) : content::WebContentsObserver(web_contents), screenshot_flow_(screenshot_flow) {} ~UnderlyingWebContentsObserver() override = default; UnderlyingWebContentsObserver(const UnderlyingWebContentsObserver&) = delete; UnderlyingWebContentsObserver& operator=( const UnderlyingWebContentsObserver&) = delete; // content::WebContentsObserver void PrimaryPageChanged(content::Page& page) override { // We only care to complete/cancel a capture if the capture mode is // currently active. if (screenshot_flow_->IsCaptureModeActive()) screenshot_flow_->CompleteCapture( ScreenshotCaptureResultCode::USER_NAVIGATED_EXIT, gfx::Rect()); } private: ScreenshotFlow* screenshot_flow_; }; } // namespace image_editor<|fim▁end|>
<|file_name|>foundation-sites-tests.ts<|end_file_name|><|fim▁begin|>// Tests for type definitions for Foundation Sites v6.0.4 // Project: http://foundation.zurb.com/ // Definitions by: Sam Vloeberghs <https://github.com/samvloeberghs/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../jquery/jquery.d.ts" /> /// <reference path="foundation-sites.d.ts" /> $(document).foundation(); $(document).foundation('method5'); $(document).foundation(['method', 'method2']); Foundation.Abide($('.selector')); Foundation.Abide($('.selector'), {}); Foundation.Accordion($('.selector')); Foundation.Accordion($('.selector'), {}); Foundation.AccordionMenu($('.selector')); Foundation.AccordionMenu($('.selector'), {}); Foundation.DrillDown($('.selector')); Foundation.DrillDown($('.selector'), {}); Foundation.Dropdown($('.selector')); Foundation.Dropdown($('.selector'), {}); Foundation.DropdownMenu($('.selector')); Foundation.DropdownMenu($('.selector'), {}); Foundation.Equalizer($('.selector')); Foundation.Equalizer($('.selector'), {}); Foundation.Interchange($('.selector')); Foundation.Interchange($('.selector'), {}); Foundation.Magellan($('.selector')); Foundation.Magellan($('.selector'), {}); Foundation.OffCanvas($('.selector')); Foundation.OffCanvas($('.selector'), {}); Foundation.Orbit($('.selector')); Foundation.Orbit($('.selector'), {}); Foundation.Reveal($('.selector')); Foundation.Reveal($('.selector'), {}); Foundation.Slider($('.selector')); Foundation.Slider($('.selector'), {}); <|fim▁hole|>Foundation.Sticky($('.selector'), {}); Foundation.Tabs($('.selector')); Foundation.Tabs($('.selector'), {}); Foundation.Toggler($('.selector')); Foundation.Toggler($('.selector'), {}); Foundation.Tooltip($('.selector')); Foundation.Tooltip($('.selector'), {}); /* TODO: fix this: error TS7017: Index signature of object type implicitly has an 'any' type. function pluginList() { 'use strict'; return [ 'Abide', 'Accordion', 'AccordionMenu', 'DrillDown', 'Dropdown', 'DropdownMenu', 'Equalizer', 'Interchange', 'Magellan', 'OffCanvas', 'Orbit', 'Reveal', 'Slider', 'Sticky', 'Tabs', 'Toggler', 'Tooltip' ]; } pluginList().forEach((value:string) => { Foundation[value]($('.selector')); Foundation[value]($('.selector'), {}); }); */<|fim▁end|>
Foundation.Sticky($('.selector'));
<|file_name|>CWE190_Integer_Overflow__int_fgets_multiply_72b.cpp<|end_file_name|><|fim▁begin|>/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_fgets_multiply_72b.cpp Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-72b.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: fgets Read data from the console using fgets() * GoodSource: Set data to a small, non-zero number (two) * Sinks: multiply * GoodSink: Ensure there will not be an overflow before multiplying data by 2 * BadSink : If data is positive, multiply by 2, which can cause an overflow * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files * * */ #include "std_testcase.h" #include <vector> using namespace std; namespace CWE190_Integer_Overflow__int_fgets_multiply_72 { #ifndef OMITBAD void badSink(vector<int> dataVector) { /* copy data out of dataVector */ int data = dataVector[2]; if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > INT_MAX, this will overflow */ int result = data * 2; printIntLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(vector<int> dataVector) { <|fim▁hole|> if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > INT_MAX, this will overflow */ int result = data * 2; printIntLine(result); } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(vector<int> dataVector) { int data = dataVector[2]; if(data > 0) /* ensure we won't have an underflow */ { /* FIX: Add a check to prevent an overflow from occurring */ if (data < (INT_MAX/2)) { int result = data * 2; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } #endif /* OMITGOOD */ } /* close namespace */<|fim▁end|>
int data = dataVector[2];
<|file_name|>networks.py<|end_file_name|><|fim▁begin|># Main network and testnet3 definitions params = { 'bitcoin_main': { 'pubkey_address': 50, 'script_address': 9, 'genesis_hash': '00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5c6e238c60c'<|fim▁hole|> 'script_address': 188, 'genesis_hash': '000003ae7f631de18a457fa4fa078e6fa8aff38e258458f8189810de5d62cede' } }<|fim▁end|>
}, 'bitcoin_test': { 'pubkey_address': 88,
<|file_name|>remote.rs<|end_file_name|><|fim▁begin|>use std::cell::{RefCell, Ref, Cell}; use std::io::SeekFrom; use std::io::prelude::*; use std::mem; use std::path::Path; use curl::easy::{Easy, List}; use git2; use hex::ToHex; use serde_json; use url::Url; use core::{PackageId, SourceId}; use ops; use sources::git; use sources::registry::{RegistryData, RegistryConfig, INDEX_LOCK}; use util::network; use util::{FileLock, Filesystem, LazyCell}; use util::{Config, Sha256, ToUrl}; use util::errors::{CargoErrorKind, CargoResult, CargoResultExt}; pub struct RemoteRegistry<'cfg> { index_path: Filesystem, cache_path: Filesystem, source_id: SourceId, config: &'cfg Config, handle: LazyCell<RefCell<Easy>>, tree: RefCell<Option<git2::Tree<'static>>>, repo: LazyCell<git2::Repository>, head: Cell<Option<git2::Oid>>, } impl<'cfg> RemoteRegistry<'cfg> { pub fn new(source_id: &SourceId, config: &'cfg Config, name: &str) -> RemoteRegistry<'cfg> { RemoteRegistry { index_path: config.registry_index_path().join(name), cache_path: config.registry_cache_path().join(name), source_id: source_id.clone(), config: config, tree: RefCell::new(None), handle: LazyCell::new(), repo: LazyCell::new(), head: Cell::new(None), } } fn easy(&self) -> CargoResult<&RefCell<Easy>> { self.handle.get_or_try_init(|| { ops::http_handle(self.config).map(RefCell::new) }) } fn repo(&self) -> CargoResult<&git2::Repository> { self.repo.get_or_try_init(|| { let path = self.index_path.clone().into_path_unlocked(); // Fast path without a lock if let Ok(repo) = git2::Repository::open(&path) { return Ok(repo) } // Ok, now we need to lock and try the whole thing over again. let lock = self.index_path.open_rw(Path::new(INDEX_LOCK), self.config, "the registry index")?; match git2::Repository::open(&path) { Ok(repo) => Ok(repo), Err(_) => { let _ = lock.remove_siblings(); // Note that we'd actually prefer to use a bare repository // here as we're not actually going to check anything out. // All versions of Cargo, though, share the same CARGO_HOME, // so for compatibility with older Cargo which *does* do // checkouts we make sure to initialize a new full // repository (not a bare one). // // We should change this to `init_bare` whenever we feel // like enough time has passed or if we change the directory // that the folder is located in, such as by changing the // hash at the end of the directory. Ok(git2::Repository::init(&path)?) } } }) } fn head(&self) -> CargoResult<git2::Oid> { if self.head.get().is_none() { let oid = self.repo()?.refname_to_id("refs/remotes/origin/master")?; self.head.set(Some(oid)); } Ok(self.head.get().unwrap()) } fn tree(&self) -> CargoResult<Ref<git2::Tree>> { { let tree = self.tree.borrow(); if tree.is_some() { return Ok(Ref::map(tree, |s| s.as_ref().unwrap())) } } let repo = self.repo()?; let commit = repo.find_commit(self.head()?)?; let tree = commit.tree()?; // Unfortunately in libgit2 the tree objects look like they've got a // reference to the repository object which means that a tree cannot // outlive the repository that it came from. Here we want to cache this // tree, though, so to accomplish this we transmute it to a static // lifetime. // // Note that we don't actually hand out the static lifetime, instead we // only return a scoped one from this function. Additionally the repo // we loaded from (above) lives as long as this object // (`RemoteRegistry`) so we then just need to ensure that the tree is // destroyed first in the destructor, hence the destructor on // `RemoteRegistry` below. let tree = unsafe { mem::transmute::<git2::Tree, git2::Tree<'static>>(tree) }; *self.tree.borrow_mut() = Some(tree); Ok(Ref::map(self.tree.borrow(), |s| s.as_ref().unwrap())) } } impl<'cfg> RegistryData for RemoteRegistry<'cfg> { fn index_path(&self) -> &Filesystem { &self.index_path } fn load(&self, _root: &Path, path: &Path, data: &mut FnMut(&[u8]) -> CargoResult<()>) -> CargoResult<()> { // Note that the index calls this method and the filesystem is locked // in the index, so we don't need to worry about an `update_index` // happening in a different process. let repo = self.repo()?; let tree = self.tree()?; let entry = tree.get_path(path)?; let object = entry.to_object(&repo)?; let blob = match object.as_blob() { Some(blob) => blob, None => bail!("path `{}` is not a blob in the git repo", path.display()), }; data(blob.content()) } fn config(&mut self) -> CargoResult<Option<RegistryConfig>> { self.repo()?; // create intermediate dirs and initialize the repo let _lock = self.index_path.open_ro(Path::new(INDEX_LOCK), self.config, "the registry index")?; let mut config = None; self.load(Path::new(""), Path::new("config.json"), &mut |json| { config = Some(serde_json::from_slice(&json)?); Ok(()) })?; Ok(config) } fn update_index(&mut self) -> CargoResult<()> { // Ensure that we'll actually be able to acquire an HTTP handle later on // once we start trying to download crates. This will weed out any // problems with `.cargo/config` configuration related to HTTP. // // This way if there's a problem the error gets printed before we even // hit the index, which may not actually read this configuration. ops::http_handle(self.config)?; let repo = self.repo()?; let _lock = self.index_path.open_rw(Path::new(INDEX_LOCK), self.config, "the registry index")?;<|fim▁hole|> self.config.shell().status("Updating", format!("registry `{}`", self.source_id.url()))?; let mut needs_fetch = true; if self.source_id.url().host_str() == Some("github.com") { if let Ok(oid) = self.head() { let mut handle = self.easy()?.borrow_mut(); debug!("attempting github fast path for {}", self.source_id.url()); if github_up_to_date(&mut handle, self.source_id.url(), &oid) { needs_fetch = false; } else { debug!("fast path failed, falling back to a git fetch"); } } } if needs_fetch { // git fetch origin master let url = self.source_id.url().to_string(); let refspec = "refs/heads/master:refs/remotes/origin/master"; git::fetch(&repo, &url, refspec, self.config).chain_err(|| { format!("failed to fetch `{}`", url) })?; } self.head.set(None); *self.tree.borrow_mut() = None; Ok(()) } fn download(&mut self, pkg: &PackageId, checksum: &str) -> CargoResult<FileLock> { let filename = format!("{}-{}.crate", pkg.name(), pkg.version()); let path = Path::new(&filename); // Attempt to open an read-only copy first to avoid an exclusive write // lock and also work with read-only filesystems. Note that we check the // length of the file like below to handle interrupted downloads. // // If this fails then we fall through to the exclusive path where we may // have to redownload the file. if let Ok(dst) = self.cache_path.open_ro(path, self.config, &filename) { let meta = dst.file().metadata()?; if meta.len() > 0 { return Ok(dst) } } let mut dst = self.cache_path.open_rw(path, self.config, &filename)?; let meta = dst.file().metadata()?; if meta.len() > 0 { return Ok(dst) } self.config.shell().status("Downloading", pkg)?; let config = self.config()?.unwrap(); let mut url = config.dl.to_url()?; url.path_segments_mut().unwrap() .push(pkg.name()) .push(&pkg.version().to_string()) .push("download"); // TODO: don't download into memory, but ensure that if we ctrl-c a // download we should resume either from the start or the middle // on the next time let url = url.to_string(); let mut handle = self.easy()?.borrow_mut(); handle.get(true)?; handle.url(&url)?; handle.follow_location(true)?; let mut state = Sha256::new(); let mut body = Vec::new(); network::with_retry(self.config, || { state = Sha256::new(); body = Vec::new(); { let mut handle = handle.transfer(); handle.write_function(|buf| { state.update(buf); body.extend_from_slice(buf); Ok(buf.len()) })?; handle.perform()?; } let code = handle.response_code()?; if code != 200 && code != 0 { let url = handle.effective_url()?.unwrap_or(&url); Err(CargoErrorKind::HttpNot200(code, url.to_string()).into()) } else { Ok(()) } })?; // Verify what we just downloaded if state.finish().to_hex() != checksum { bail!("failed to verify the checksum of `{}`", pkg) } dst.write_all(&body)?; dst.seek(SeekFrom::Start(0))?; Ok(dst) } } impl<'cfg> Drop for RemoteRegistry<'cfg> { fn drop(&mut self) { // Just be sure to drop this before our other fields self.tree.borrow_mut().take(); } } /// Updating the index is done pretty regularly so we want it to be as fast as /// possible. For registries hosted on github (like the crates.io index) there's /// a fast path available to use [1] to tell us that there's no updates to be /// made. /// /// This function will attempt to hit that fast path and verify that the `oid` /// is actually the current `master` branch of the repository. If `true` is /// returned then no update needs to be performed, but if `false` is returned /// then the standard update logic still needs to happen. /// /// [1]: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference /// /// Note that this function should never cause an actual failure because it's /// just a fast path. As a result all errors are ignored in this function and we /// just return a `bool`. Any real errors will be reported through the normal /// update path above. fn github_up_to_date(handle: &mut Easy, url: &Url, oid: &git2::Oid) -> bool { macro_rules! try { ($e:expr) => (match $e { Some(e) => e, None => return false, }) } // This expects github urls in the form `github.com/user/repo` and nothing // else let mut pieces = try!(url.path_segments()); let username = try!(pieces.next()); let repo = try!(pieces.next()); if pieces.next().is_some() { return false } let url = format!("https://api.github.com/repos/{}/{}/commits/master", username, repo); try!(handle.get(true).ok()); try!(handle.url(&url).ok()); try!(handle.useragent("cargo").ok()); let mut headers = List::new(); try!(headers.append("Accept: application/vnd.github.3.sha").ok()); try!(headers.append(&format!("If-None-Match: \"{}\"", oid)).ok()); try!(handle.http_headers(headers).ok()); try!(handle.perform().ok()); try!(handle.response_code().ok()) == 304 }<|fim▁end|>
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for Melnor RainCloud sprinkler water timer.""" from __future__ import annotations import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_MONITORED_CONDITIONS from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.icon import icon_for_battery_level from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import ( DATA_RAINCLOUD, ICON_MAP, SENSORS, UNIT_OF_MEASUREMENT_MAP, RainCloudEntity, ) _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)): vol.All(<|fim▁hole|> } ) def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up a sensor for a raincloud device.""" raincloud = hass.data[DATA_RAINCLOUD].data sensors = [] for sensor_type in config[CONF_MONITORED_CONDITIONS]: if sensor_type == "battery": sensors.append(RainCloudSensor(raincloud.controller.faucet, sensor_type)) else: # create a sensor for each zone managed by a faucet for zone in raincloud.controller.faucet.zones: sensors.append(RainCloudSensor(zone, sensor_type)) add_entities(sensors, True) class RainCloudSensor(RainCloudEntity, SensorEntity): """A sensor implementation for raincloud device.""" @property def native_value(self): """Return the state of the sensor.""" return self._state @property def native_unit_of_measurement(self): """Return the units of measurement.""" return UNIT_OF_MEASUREMENT_MAP.get(self._sensor_type) def update(self): """Get the latest data and updates the states.""" _LOGGER.debug("Updating RainCloud sensor: %s", self._name) if self._sensor_type == "battery": self._state = self.data.battery else: self._state = getattr(self.data, self._sensor_type) @property def icon(self): """Icon to use in the frontend, if any.""" if self._sensor_type == "battery" and self._state is not None: return icon_for_battery_level( battery_level=int(self._state), charging=False ) return ICON_MAP.get(self._sensor_type)<|fim▁end|>
cv.ensure_list, [vol.In(SENSORS)] )
<|file_name|>bitcoin_zh_CN.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_CN" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="14"/> <source>About PACCoin</source> <translation>关于比特币</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="53"/> <source>&lt;b&gt;PACCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;比特币&lt;/b&gt;版本</translation> </message> <message> <location filename="../forms/aboutdialog.ui" line="85"/> <source>Copyright © 2011-2013 PACCoin Developers This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file license.txt 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 ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation>版权归比特币开发者所有 © 2011-2013 PACCoin Developers 这是一个实验性软件。 Distributed under the MIT/X11 software license, see the accompanying file license.txt 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 ([email protected]) and UPnP software written by Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="14"/> <source>Address Book</source> <translation>地址薄</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="20"/> <source>These are your PACCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>这些是你接受支付的比特币地址。当支付时你可以给出不同的地址,以便追踪不同的支付者。</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="33"/> <source>Double-click to edit address or label</source> <translation>双击以编辑地址或标签</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="57"/> <source>Create a new address</source> <translation>创建新地址</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="60"/> <source>&amp;New Address...</source> <translation>&amp;新地址...</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="71"/> <source>Copy the currently selected address to the system clipboard</source> <translation>复制当前选中地址到系统剪贴板</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="74"/> <source>&amp;Copy to Clipboard</source> <translation>&amp;复制到剪贴板</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="85"/> <source>Show &amp;QR Code</source> <translation>显示二维码</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="96"/> <source>Sign a message to prove you own this address</source> <translation>发送签名消息以证明您是该比特币地址的拥有者</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="99"/> <source>&amp;Sign Message</source> <translation>&amp;发送签名消息</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="110"/> <source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source> <translation>从列表中删除当前选中地址。只有发送地址可以被删除。</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="113"/> <source>&amp;Delete</source> <translation>&amp;删除</translation> </message> <message> <location filename="../addressbookpage.cpp" line="61"/> <source>Copy address</source> <translation>复制地址</translation> </message> <message> <location filename="../addressbookpage.cpp" line="62"/> <source>Copy label</source> <translation>复制标签</translation> </message> <message> <location filename="../addressbookpage.cpp" line="63"/> <source>Edit</source> <translation>编辑</translation> </message> <message> <location filename="../addressbookpage.cpp" line="64"/> <source>Delete</source> <translation>删除</translation> </message> <message> <location filename="../addressbookpage.cpp" line="281"/> <source>Export Address Book Data</source> <translation>导出地址薄数据</translation> </message> <message> <location filename="../addressbookpage.cpp" line="282"/> <source>Comma separated file (*.csv)</source> <translation>逗号分隔文件 (*.csv)</translation> </message> <message> <location filename="../addressbookpage.cpp" line="295"/> <source>Error exporting</source> <translation>导出错误</translation> </message> <message> <location filename="../addressbookpage.cpp" line="295"/> <source>Could not write to file %1.</source> <translation>无法写入文件 %1。</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Label</source> <translation>标签</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="77"/> <source>Address</source> <translation>地址</translation> </message> <message> <location filename="../addresstablemodel.cpp" line="113"/> <source>(no label)</source> <translation>(没有标签)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="26"/> <source>Dialog</source> <translation>会话</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="32"/> <location filename="../forms/askpassphrasedialog.ui" line="97"/> <source>TextLabel</source> <translation>文本标签</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="50"/> <source>Enter passphrase</source> <translation>输入口令</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="64"/> <source>New passphrase</source> <translation>新口令</translation> </message> <message> <location filename="../forms/askpassphrasedialog.ui" line="78"/> <source>Repeat new passphrase</source> <translation>重复新口令</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="34"/> <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>输入钱包的新口令。&lt;br/&gt;使用的口令请至少包含&lt;b&gt;10个以上随机字符&lt;/&gt;,或者是&lt;b&gt;8个以上的单词&lt;/b&gt;。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="35"/> <source>Encrypt wallet</source> <translation>加密钱包</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="38"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>该操作需要您首先使用口令解锁钱包。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="43"/> <source>Unlock wallet</source> <translation>解锁钱包</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="46"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>该操作需要您首先使用口令解密钱包。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="51"/> <source>Decrypt wallet</source> <translation>解密钱包</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="54"/> <source>Change passphrase</source> <translation>修改口令</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="55"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>请输入钱包的旧口令与新口令。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="101"/> <source>Confirm wallet encryption</source> <translation>确认加密钱包</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="102"/> <source>WARNING: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR PACCoinS&lt;/b&gt;! Are you sure you wish to encrypt your wallet?</source> <translation>警告:如果您加密了您的钱包之后忘记了口令,您将会&lt;b&gt;失去所有的比特币&lt;/b&gt;! 确定要加密钱包吗?</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="111"/> <location filename="../askpassphrasedialog.cpp" line="160"/> <source>Wallet encrypted</source> <translation>钱包已加密</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="112"/> <source>PACCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your PACCoins from being stolen by malware infecting your computer.</source> <translation>将关闭软件以完成加密过程。 请您谨记:钱包加密并不是万能的,电脑中毒,您的比特币还是有可能丢失。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="208"/> <location filename="../askpassphrasedialog.cpp" line="232"/> <source>Warning: The Caps Lock key is on.</source> <translation>警告:大写锁定键CapsLock开启</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="117"/> <location filename="../askpassphrasedialog.cpp" line="124"/> <location filename="../askpassphrasedialog.cpp" line="166"/> <location filename="../askpassphrasedialog.cpp" line="172"/> <source>Wallet encryption failed</source> <translation>钱包加密失败</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="118"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>由于一个本地错误,加密钱包操作已经失败。您的钱包没有被加密。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="125"/> <location filename="../askpassphrasedialog.cpp" line="173"/> <source>The supplied passphrases do not match.</source> <translation>口令不匹配。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="136"/> <source>Wallet unlock failed</source> <translation>钱包解锁失败</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="137"/> <location filename="../askpassphrasedialog.cpp" line="148"/> <location filename="../askpassphrasedialog.cpp" line="167"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>用于解密钱包的口令不正确。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="147"/> <source>Wallet decryption failed</source> <translation>钱包解密失败。</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="161"/> <source>Wallet passphrase was succesfully changed.</source> <translation>钱包口令修改成功</translation> </message> </context> <context> <name>PACCoinGUI</name> <message> <location filename="../paccoingui.cpp" line="69"/> <source>PACCoin Wallet</source> <translation>比特币钱包</translation> </message> <message> <location filename="../paccoingui.cpp" line="142"/> <location filename="../paccoingui.cpp" line="464"/> <source>Synchronizing with network...</source> <translation>正在与网络同步...</translation> </message> <message> <location filename="../paccoingui.cpp" line="145"/> <source>Block chain synchronization in progress</source> <translation>正在同步区域锁链</translation> </message> <message> <location filename="../paccoingui.cpp" line="176"/> <source>&amp;Overview</source> <translation>&amp;概况</translation> </message> <message> <location filename="../paccoingui.cpp" line="177"/> <source>Show general overview of wallet</source> <translation>显示钱包概况</translation> </message> <message> <location filename="../paccoingui.cpp" line="182"/> <source>&amp;Transactions</source> <translation>&amp;交易</translation> </message> <message> <location filename="../paccoingui.cpp" line="183"/> <source>Browse transaction history</source> <translation>查看交易历史</translation> </message> <message> <location filename="../paccoingui.cpp" line="188"/> <source>&amp;Address Book</source> <translation>&amp;地址薄</translation> </message> <message> <location filename="../paccoingui.cpp" line="189"/> <source>Edit the list of stored addresses and labels</source> <translation>修改存储的地址和标签列表</translation> </message> <message> <location filename="../paccoingui.cpp" line="194"/> <source>&amp;Receive coins</source> <translation>&amp;接收货币</translation> </message> <message> <location filename="../paccoingui.cpp" line="195"/> <source>Show the list of addresses for receiving payments</source> <translation>显示接收支付的地址列表</translation> </message> <message> <location filename="../paccoingui.cpp" line="200"/> <source>&amp;Send coins</source> <translation>&amp;发送货币</translation> </message> <message> <location filename="../paccoingui.cpp" line="201"/> <source>Send coins to a PACCoin address</source> <translation>将货币发送到一个比特币地址</translation> </message> <message> <location filename="../paccoingui.cpp" line="206"/> <source>Sign &amp;message</source> <translation>发送签名 &amp;消息</translation> </message> <message> <location filename="../paccoingui.cpp" line="207"/> <source>Prove you control an address</source> <translation>证明您拥有某个比特币地址</translation> </message> <message> <location filename="../paccoingui.cpp" line="226"/> <source>E&amp;xit</source> <translation>退出</translation> </message> <message> <location filename="../paccoingui.cpp" line="227"/> <source>Quit application</source> <translation>退出程序</translation> </message> <message> <location filename="../paccoingui.cpp" line="230"/> <source>&amp;About %1</source> <translation>&amp;关于 %1</translation> </message> <message> <location filename="../paccoingui.cpp" line="231"/> <source>Show information about PACCoin</source> <translation>显示比特币的相关信息</translation> </message> <message> <location filename="../paccoingui.cpp" line="233"/> <source>About &amp;Qt</source> <translation>关于 &amp;Qt</translation> </message> <message> <location filename="../paccoingui.cpp" line="234"/> <source>Show information about Qt</source> <translation>显示Qt相关信息</translation> </message> <message> <location filename="../paccoingui.cpp" line="236"/> <source>&amp;Options...</source> <translation>&amp;选项...</translation> </message> <message> <location filename="../paccoingui.cpp" line="237"/> <source>Modify configuration options for PACCoin</source> <translation>修改比特币配置选项</translation> </message> <message> <location filename="../paccoingui.cpp" line="239"/> <source>Open &amp;PACCoin</source> <translation>打开 &amp;比特币</translation> </message> <message> <location filename="../paccoingui.cpp" line="240"/> <source>Show the PACCoin window</source> <translation>显示比特币窗口</translation> </message> <message> <location filename="../paccoingui.cpp" line="241"/> <source>&amp;Export...</source> <translation>&amp;导出...</translation> </message> <message> <location filename="../paccoingui.cpp" line="242"/> <source>Export the data in the current tab to a file</source> <translation>导出当前数据到文件</translation> </message> <message> <location filename="../paccoingui.cpp" line="243"/> <source>&amp;Encrypt Wallet</source> <translation>&amp;加密钱包</translation> </message> <message> <location filename="../paccoingui.cpp" line="244"/> <source>Encrypt or decrypt wallet</source> <translation>加密或解密钱包</translation> </message> <message> <location filename="../paccoingui.cpp" line="246"/> <source>&amp;Backup Wallet</source> <translation>&amp;备份钱包</translation> </message> <message> <location filename="../paccoingui.cpp" line="247"/> <source>Backup wallet to another location</source> <translation>备份钱包到其它文件夹</translation> </message> <message> <location filename="../paccoingui.cpp" line="248"/> <source>&amp;Change Passphrase</source> <translation>&amp;修改口令</translation> </message> <message> <location filename="../paccoingui.cpp" line="249"/> <source>Change the passphrase used for wallet encryption</source> <translation>修改钱包加密口令</translation> </message> <message> <location filename="../paccoingui.cpp" line="272"/> <source>&amp;File</source> <translation>&amp;文件</translation> </message> <message> <location filename="../paccoingui.cpp" line="281"/> <source>&amp;Settings</source> <translation>&amp;设置</translation> </message> <message> <location filename="../paccoingui.cpp" line="287"/> <source>&amp;Help</source> <translation>&amp;帮助</translation> </message> <message> <location filename="../paccoingui.cpp" line="294"/> <source>Tabs toolbar</source> <translation>分页工具栏</translation> </message> <message> <location filename="../paccoingui.cpp" line="305"/> <source>Actions toolbar</source> <translation>动作工具栏</translation> </message> <message> <location filename="../paccoingui.cpp" line="317"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location filename="../paccoingui.cpp" line="407"/> <source>PACCoin-qt</source> <translation>PACCoin-qt</translation> </message> <message numerus="yes"> <location filename="../paccoingui.cpp" line="449"/> <source>%n active connection(s) to PACCoin network</source> <translation><numerusform>%n 个到比特币网络的活动连接</numerusform></translation> </message> <message> <location filename="../paccoingui.cpp" line="475"/> <source>Downloaded %1 of %2 blocks of transaction history.</source> <translation>%1 / %2 个交易历史的区块已下载</translation> </message> <message> <location filename="../paccoingui.cpp" line="487"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>%1 个交易历史的区块已下载</translation> </message> <message numerus="yes"> <location filename="../paccoingui.cpp" line="502"/> <source>%n second(s) ago</source> <translation><numerusform>%n 秒前</numerusform></translation> </message> <message numerus="yes"> <location filename="../paccoingui.cpp" line="506"/> <source>%n minute(s) ago</source> <translation><numerusform>%n 分种前</numerusform></translation> </message> <message numerus="yes"> <location filename="../paccoingui.cpp" line="510"/> <source>%n hour(s) ago</source> <translation><numerusform>%n 小时前</numerusform></translation> </message> <message numerus="yes"> <location filename="../paccoingui.cpp" line="514"/> <source>%n day(s) ago</source> <translation><numerusform>%n 天前</numerusform></translation> </message> <message> <location filename="../paccoingui.cpp" line="520"/> <source>Up to date</source> <translation>最新状态</translation> </message> <message> <location filename="../paccoingui.cpp" line="525"/> <source>Catching up...</source> <translation>更新中...</translation> </message> <message> <location filename="../paccoingui.cpp" line="533"/> <source>Last received block was generated %1.</source> <translation>最新收到的区块产生于 %1。</translation> </message> <message> <location filename="../paccoingui.cpp" line="597"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>该笔交易的数据量超限.您可以选择支付 %1 交易费, 交易费将支付给处理该笔交易的网络节点,有助于维持比特币网络的运行. 您愿意支付交易费用吗?</translation> </message> <message> <location filename="../paccoingui.cpp" line="602"/> <source>Sending...</source> <translation>发送中</translation> </message> <message> <location filename="../paccoingui.cpp" line="629"/> <source>Sent transaction</source> <translation>已发送交易</translation> </message> <message> <location filename="../paccoingui.cpp" line="630"/> <source>Incoming transaction</source> <translation>流入交易</translation> </message> <message> <location filename="../paccoingui.cpp" line="631"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>日期: %1 金额: %2 类别: %3 地址: %4 </translation> </message> <message> <location filename="../paccoingui.cpp" line="751"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>钱包已被&lt;b&gt;加密&lt;/b&gt;,当前为&lt;b&gt;解锁&lt;/b&gt;状态</translation> </message> <message> <location filename="../paccoingui.cpp" line="759"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>钱包已被&lt;b&gt;加密&lt;/b&gt;,当前为&lt;b&gt;锁定&lt;/b&gt;状态</translation> </message> <message> <location filename="../paccoingui.cpp" line="782"/> <source>Backup Wallet</source> <translation>备份钱包</translation> </message> <message> <location filename="../paccoingui.cpp" line="782"/> <source>Wallet Data (*.dat)</source> <translation>钱包文件(*.dat)</translation> </message> <message> <location filename="../paccoingui.cpp" line="785"/> <source>Backup Failed</source> <translation>备份失败</translation> </message> <message> <location filename="../paccoingui.cpp" line="785"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>备份钱包到其它文件夹失败.</translation> </message> </context> <context> <name>DisplayOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="270"/> <source>&amp;Unit to show amounts in: </source> <translation>&amp;金额显示单位:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="274"/> <source>Choose the default subdivision unit to show in the interface, and when sending coins</source> <translation>选择显示及发送比特币时使用的最小单位</translation> </message> <message> <location filename="../optionsdialog.cpp" line="281"/> <source>Display addresses in transaction list</source> <translation>在交易列表中显示地址</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="14"/> <source>Edit Address</source> <translation>编辑地址</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="25"/> <source>&amp;Label</source> <translation>&amp;标签</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="35"/> <source>The label associated with this address book entry</source> <translation>与此地址条目关联的标签</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="42"/> <source>&amp;Address</source> <translation>&amp;地址</translation> </message> <message> <location filename="../forms/editaddressdialog.ui" line="52"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>该地址与地址簿中的条目已关联,无法作为发送地址编辑。</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="20"/> <source>New receiving address</source> <translation>新接收地址</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="24"/> <source>New sending address</source> <translation>新发送地址</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="27"/> <source>Edit receiving address</source> <translation>编辑接收地址</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="31"/> <source>Edit sending address</source> <translation>编辑发送地址</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="91"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>输入的地址 &quot;%1&quot; 已经存在于地址薄。</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="96"/> <source>The entered address &quot;%1&quot; is not a valid PACCoin address.</source> <translation>输入的地址 &quot;%1&quot; 并不是一个有效的比特币地址</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="101"/> <source>Could not unlock wallet.</source> <translation>无法解锁钱包</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="106"/> <source>New key generation failed.</source> <translation>密钥创建失败.</translation> </message> </context> <context> <name>MainOptionsPage</name> <message> <location filename="../optionsdialog.cpp" line="170"/> <source>&amp;Start PACCoin on window system startup</source> <translation>&amp;开机启动比特币</translation> </message> <message> <location filename="../optionsdialog.cpp" line="171"/> <source>Automatically start PACCoin after the computer is turned on</source> <translation>在计算机启动后自动运行比特币</translation> </message> <message> <location filename="../optionsdialog.cpp" line="175"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;最小化到托盘</translation> </message> <message> <location filename="../optionsdialog.cpp" line="176"/> <source>Show only a tray icon after minimizing the window</source> <translation>最小化窗口后只显示一个托盘标志</translation> </message> <message> <location filename="../optionsdialog.cpp" line="180"/> <source>Map port using &amp;UPnP</source> <translation>使用 &amp;UPnP 映射端口</translation> </message> <message> <location filename="../optionsdialog.cpp" line="181"/> <source>Automatically open the PACCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>自动在路由器中打开比特币端口。只有当您的路由器开启 UPnP 选项时此功能才有效。</translation> </message> <message> <location filename="../optionsdialog.cpp" line="185"/> <source>M&amp;inimize on close</source> <translation>关闭时最小化</translation> </message> <message> <location filename="../optionsdialog.cpp" line="186"/> <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>当窗口关闭时程序最小化而不是退出。当使用该选项时,程序只能通过在菜单中选择退出来关闭</translation> </message> <message> <location filename="../optionsdialog.cpp" line="190"/> <source>&amp;Connect through SOCKS4 proxy:</source> <translation>&amp;通过SOCKS4代理连接</translation> </message> <message> <location filename="../optionsdialog.cpp" line="191"/> <source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source> <translation>通过一个SOCKS4代理连接到比特币网络 (如使用Tor连接时)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="196"/> <source>Proxy &amp;IP: </source> <translation>代理 &amp;IP:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="202"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>代理服务器IP (如 127.0.0.1)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="205"/> <source>&amp;Port: </source> <translation>&amp;端口:</translation> </message> <message> <location filename="../optionsdialog.cpp" line="211"/> <source>Port of the proxy (e.g. 1234)</source> <translation>代理端口 (比如 1234)</translation> </message> <message> <location filename="../optionsdialog.cpp" line="217"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>建议支付交易费用,有助于您的交易得到尽快处理. 绝大多数交易的字节数为 1 kB. 建议支付0.01个比特币.</translation> </message> <message> <location filename="../optionsdialog.cpp" line="223"/> <source>Pay transaction &amp;fee</source> <translation>支付交易 &amp;费用</translation> </message> <message> <location filename="../optionsdialog.cpp" line="226"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>建议支付交易费用,有助于您的交易得到尽快处理. 绝大多数交易的字节数为 1 kB. 建议支付0.01个比特币.</translation> </message> </context> <context> <name>MessagePage</name> <message> <location filename="../forms/messagepage.ui" line="14"/> <source>Message</source> <translation>消息</translation> </message> <message> <location filename="../forms/messagepage.ui" line="20"/> <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>您可以用你的地址对消息进行签名,以证明您是该地址的所有人。注意不要对模棱两可的消息签名,以免遭受钓鱼式攻击。请确保消息真实明确的表达了您的意愿。</translation> </message> <message> <location filename="../forms/messagepage.ui" line="38"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>付款地址 (例如: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/messagepage.ui" line="48"/> <source>Choose adress from address book</source> <translation>从地址簿选择地址</translation> </message> <message> <location filename="../forms/messagepage.ui" line="58"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location filename="../forms/messagepage.ui" line="71"/> <source>Paste address from clipboard</source> <translation>从剪贴板粘贴地址</translation> </message> <message> <location filename="../forms/messagepage.ui" line="81"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/messagepage.ui" line="93"/> <source>Enter the message you want to sign here</source> <translation>请输入您要发送的签名消息</translation> </message> <message> <location filename="../forms/messagepage.ui" line="105"/> <source>Click &quot;Sign Message&quot; to get signature</source> <translation>单击“发送签名消息&quot;获取签名</translation> </message> <message> <location filename="../forms/messagepage.ui" line="117"/> <source>Sign a message to prove you own this address</source> <translation>发送签名消息以证明您是该比特币地址的拥有者</translation> </message> <message> <location filename="../forms/messagepage.ui" line="120"/> <source>&amp;Sign Message</source> <translation>&amp;发送签名消息</translation> </message> <message> <location filename="../forms/messagepage.ui" line="131"/> <source>Copy the currently selected address to the system clipboard</source> <translation>复制当前选中地址到系统剪贴板</translation> </message> <message> <location filename="../forms/messagepage.ui" line="134"/> <source>&amp;Copy to Clipboard</source> <translation>&amp;复制到剪贴板</translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <location filename="../messagepage.cpp" line="89"/> <location filename="../messagepage.cpp" line="101"/> <source>Error signing</source> <translation>签名错误</translation> </message> <message> <location filename="../messagepage.cpp" line="74"/> <source>%1 is not a valid address.</source> <translation>%1 不是合法的比特币地址。</translation> </message> <message> <location filename="../messagepage.cpp" line="89"/> <source>Private key for %1 is not available.</source> <translation>%1 的秘钥不可用。</translation> </message> <message> <location filename="../messagepage.cpp" line="101"/> <source>Sign failed</source> <translation>签名失败</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../optionsdialog.cpp" line="79"/> <source>Main</source> <translation>主要的</translation> </message> <message> <location filename="../optionsdialog.cpp" line="84"/> <source>Display</source> <translation>查看</translation> </message> <message> <location filename="../optionsdialog.cpp" line="104"/> <source>Options</source> <translation>选项</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="14"/> <source>Form</source> <translation>表单</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="40"/> <source>Balance:</source> <translation>余额</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="47"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="54"/> <source>Number of transactions:</source> <translation>交易笔数</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="61"/> <source>0</source> <translation>0</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="68"/> <source>Unconfirmed:</source> <translation>未确认:</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="75"/> <source>0 BTC</source> <translation>0 BTC</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="82"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Wallet&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Ubuntu&apos;; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;钱包&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../forms/overviewpage.ui" line="122"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;当前交易&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="103"/> <source>Your current balance</source> <translation>您的当前余额</translation> </message> <message> <location filename="../overviewpage.cpp" line="108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>尚未确认的交易总额, 未计入当前余额</translation> </message> <message> <location filename="../overviewpage.cpp" line="111"/> <source>Total number of transactions in wallet</source> <translation>钱包总交易数量</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="14"/> <source>Dialog</source> <translation>会话</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="32"/> <source>QR Code</source> <translation>二维码</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="52"/> <source>Request Payment</source> <translation>请求付款</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="67"/> <source>Amount:</source> <translation>金额:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="102"/> <source>BTC</source> <translation>BTC</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="118"/> <source>Label:</source> <translation>标签:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="141"/> <source>Message:</source> <translation>消息:</translation> </message> <message> <location filename="../forms/qrcodedialog.ui" line="183"/> <source>&amp;Save As...</source> <translation>&amp;另存为</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="101"/> <source>Save Image...</source> <translation>保存图像...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="101"/> <source>PNG Images (*.png)</source> <translation>PNG图像文件(*.png)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="14"/> <location filename="../sendcoinsdialog.cpp" line="122"/> <location filename="../sendcoinsdialog.cpp" line="127"/> <location filename="../sendcoinsdialog.cpp" line="132"/> <location filename="../sendcoinsdialog.cpp" line="137"/> <location filename="../sendcoinsdialog.cpp" line="143"/> <location filename="../sendcoinsdialog.cpp" line="148"/> <location filename="../sendcoinsdialog.cpp" line="153"/> <source>Send Coins</source> <translation>发送货币</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="64"/> <source>Send to multiple recipients at once</source> <translation>一次发送给多个接收者</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="67"/> <source>&amp;Add recipient...</source> <translation>&amp;添加接收者...</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="84"/> <source>Remove all transaction fields</source> <translation>移除所有交易项</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="87"/> <source>Clear all</source> <translation>清除全部</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="106"/> <source>Balance:</source> <translation>余额</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="113"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="144"/> <source>Confirm the send action</source> <translation>确认并发送货币</translation> </message> <message> <location filename="../forms/sendcoinsdialog.ui" line="147"/> <source>&amp;Send</source> <translation>&amp;发送</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="94"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; 到 %2 (%3)</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="99"/> <source>Confirm send coins</source> <translation>确认发送货币</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source>Are you sure you want to send %1?</source> <translation>确定您要发送 %1?</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="100"/> <source> and </source> <translation> 和 </translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="123"/> <source>The recepient address is not valid, please recheck.</source> <translation>接收者地址不合法,请检查。</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="128"/> <source>The amount to pay must be larger than 0.</source> <translation>支付金额必须大于0.</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="133"/> <source>Amount exceeds your balance</source> <translation>余额不足。</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="138"/> <source>Total exceeds your balance when the %1 transaction fee is included</source> <translation>计入 %1 的交易费后,您的余额不足以支付总价。</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="144"/> <source>Duplicate address found, can only send to each address once in one send operation</source> <translation>发现重复地址,一次操作中只可以给每个地址发送一次</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="149"/> <source>Error: Transaction creation failed </source> <translation>错误:交易创建失败。</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="154"/> <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>错误:交易被拒绝。这种情况通常发生在您钱包中的一些货币已经被消费之后,比如您使用了一个wallet.dat的副本,而货币在那个副本中已经被消费,但在当前钱包中未被标记为已消费。</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="14"/> <source>Form</source> <translation>表单</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="29"/> <source>A&amp;mount:</source> <translation>金额</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="42"/> <source>Pay &amp;To:</source> <translation>支付 &amp;到:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="66"/> <location filename="../sendcoinsentry.cpp" line="26"/> <source>Enter a label for this address to add it to your address book</source> <translation>为这个地址输入一个标签,以便将它添加到您的地址簿</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="75"/> <source>&amp;Label:</source> <translation>&amp;标签:</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="93"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>付款地址 (例如: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="103"/> <source>Choose address from address book</source> <translation>从地址薄选择地址</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="113"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message><|fim▁hole|> <translation>从剪贴板粘贴地址</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="130"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="137"/> <source>Remove this recipient</source> <translation>移除此接收者</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="25"/> <source>Enter a PACCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>请输入比特币地址 (例如: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="18"/> <source>Open for %1 blocks</source> <translation>开启 %1 个数据块</translation> </message> <message> <location filename="../transactiondesc.cpp" line="20"/> <source>Open until %1</source> <translation>至 %1 个数据块时开启</translation> </message> <message> <location filename="../transactiondesc.cpp" line="26"/> <source>%1/offline?</source> <translation>%1/离线?</translation> </message> <message> <location filename="../transactiondesc.cpp" line="28"/> <source>%1/unconfirmed</source> <translation>%1/未确认</translation> </message> <message> <location filename="../transactiondesc.cpp" line="30"/> <source>%1 confirmations</source> <translation>%1 确认项</translation> </message> <message> <location filename="../transactiondesc.cpp" line="47"/> <source>&lt;b&gt;Status:&lt;/b&gt; </source> <translation>&lt;b&gt;状态:&lt;/b&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="52"/> <source>, has not been successfully broadcast yet</source> <translation>, 未被成功广播</translation> </message> <message> <location filename="../transactiondesc.cpp" line="54"/> <source>, broadcast through %1 node</source> <translation>,同过 %1 节点广播</translation> </message> <message> <location filename="../transactiondesc.cpp" line="56"/> <source>, broadcast through %1 nodes</source> <translation>,同过 %1 节点组广播</translation> </message> <message> <location filename="../transactiondesc.cpp" line="60"/> <source>&lt;b&gt;Date:&lt;/b&gt; </source> <translation>&lt;b&gt;日期:&lt;/b&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="67"/> <source>&lt;b&gt;Source:&lt;/b&gt; Generated&lt;br&gt;</source> <translation>&lt;b&gt;来源:&lt;/b&gt; 生成&lt;br&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="73"/> <location filename="../transactiondesc.cpp" line="90"/> <source>&lt;b&gt;From:&lt;/b&gt; </source> <translation>&lt;b&gt;从:&lt;/b&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="90"/> <source>unknown</source> <translation>未知</translation> </message> <message> <location filename="../transactiondesc.cpp" line="91"/> <location filename="../transactiondesc.cpp" line="114"/> <location filename="../transactiondesc.cpp" line="173"/> <source>&lt;b&gt;To:&lt;/b&gt; </source> <translation>&lt;b&gt;到:&lt;/b&gt;</translation> </message> <message> <location filename="../transactiondesc.cpp" line="94"/> <source> (yours, label: </source> <translation>(您的, 标签:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="96"/> <source> (yours)</source> <translation>(您的)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="131"/> <location filename="../transactiondesc.cpp" line="145"/> <location filename="../transactiondesc.cpp" line="190"/> <location filename="../transactiondesc.cpp" line="207"/> <source>&lt;b&gt;Credit:&lt;/b&gt; </source> <translation>&lt;b&gt;到帐:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="133"/> <source>(%1 matures in %2 more blocks)</source> <translation>(%1 成熟于 %2 以上数据块)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="137"/> <source>(not accepted)</source> <translation>(未接受)</translation> </message> <message> <location filename="../transactiondesc.cpp" line="181"/> <location filename="../transactiondesc.cpp" line="189"/> <location filename="../transactiondesc.cpp" line="204"/> <source>&lt;b&gt;Debit:&lt;/b&gt; </source> <translation>支出</translation> </message> <message> <location filename="../transactiondesc.cpp" line="195"/> <source>&lt;b&gt;Transaction fee:&lt;/b&gt; </source> <translation>交易费</translation> </message> <message> <location filename="../transactiondesc.cpp" line="211"/> <source>&lt;b&gt;Net amount:&lt;/b&gt; </source> <translation>&lt;b&gt;网络金额:&lt;/b&gt; </translation> </message> <message> <location filename="../transactiondesc.cpp" line="217"/> <source>Message:</source> <translation>消息:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="219"/> <source>Comment:</source> <translation>备注</translation> </message> <message> <location filename="../transactiondesc.cpp" line="221"/> <source>Transaction ID:</source> <translation>交易ID:</translation> </message> <message> <location filename="../transactiondesc.cpp" line="224"/> <source>Generated coins must wait 120 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, it will change to &quot;not accepted&quot; and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>新生产的比特币必须等待120个数据块之后才能被使用. 当您生产出此数据块,它将被广播至比特币网络并添加至数据链. 如果添加到数据链失败, 它的状态将变成&quot;不被接受&quot;,生产的比特币将不能使用. 在您生产新数据块的几秒钟内, 如果其它节点也生产出同样的数据块,有可能会发生这种情况.</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="14"/> <source>Transaction details</source> <translation>交易细节</translation> </message> <message> <location filename="../forms/transactiondescdialog.ui" line="20"/> <source>This pane shows a detailed description of the transaction</source> <translation>当前面板显示了交易的详细描述</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Date</source> <translation>日期</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Type</source> <translation>类型</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Address</source> <translation>地址</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="213"/> <source>Amount</source> <translation>数量</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="274"/> <source>Open for %n block(s)</source> <translation><numerusform>开启 %n 个数据块</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="277"/> <source>Open until %1</source> <translation>至 %1 个数据块时开启</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="280"/> <source>Offline (%1 confirmations)</source> <translation>离线 (%1 个确认项)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="283"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>未确认 (%1 / %2 条确认信息)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="286"/> <source>Confirmed (%1 confirmations)</source> <translation>已确认 (%1 条确认信息)</translation> </message> <message numerus="yes"> <location filename="../transactiontablemodel.cpp" line="295"/> <source>Mined balance will be available in %n more blocks</source> <translation><numerusform>挖矿所得将在 %n 个数据块之后可用</numerusform></translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="301"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>此区块未被其他节点接收,并可能不被接受!</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="304"/> <source>Generated but not accepted</source> <translation>已生成但未被接受</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="347"/> <source>Received with</source> <translation>接收于</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="349"/> <source>Received from</source> <translation>收款来自</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="352"/> <source>Sent to</source> <translation>发送到</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="354"/> <source>Payment to yourself</source> <translation>付款给自己</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="356"/> <source>Mined</source> <translation>挖矿所得</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="394"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="593"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>交易状态。 鼠标移到此区域上可显示确认消息项的数目。</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="595"/> <source>Date and time that the transaction was received.</source> <translation>接收交易的时间</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="597"/> <source>Type of transaction.</source> <translation>交易类别。</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="599"/> <source>Destination address of transaction.</source> <translation>交易目的地址。</translation> </message> <message> <location filename="../transactiontablemodel.cpp" line="601"/> <source>Amount removed from or added to balance.</source> <translation>从余额添加或移除的金额</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="55"/> <location filename="../transactionview.cpp" line="71"/> <source>All</source> <translation>全部</translation> </message> <message> <location filename="../transactionview.cpp" line="56"/> <source>Today</source> <translation>今天</translation> </message> <message> <location filename="../transactionview.cpp" line="57"/> <source>This week</source> <translation>本周</translation> </message> <message> <location filename="../transactionview.cpp" line="58"/> <source>This month</source> <translation>本月</translation> </message> <message> <location filename="../transactionview.cpp" line="59"/> <source>Last month</source> <translation>上月</translation> </message> <message> <location filename="../transactionview.cpp" line="60"/> <source>This year</source> <translation>今年</translation> </message> <message> <location filename="../transactionview.cpp" line="61"/> <source>Range...</source> <translation>范围...</translation> </message> <message> <location filename="../transactionview.cpp" line="72"/> <source>Received with</source> <translation>接收于</translation> </message> <message> <location filename="../transactionview.cpp" line="74"/> <source>Sent to</source> <translation>发送到</translation> </message> <message> <location filename="../transactionview.cpp" line="76"/> <source>To yourself</source> <translation>到自己</translation> </message> <message> <location filename="../transactionview.cpp" line="77"/> <source>Mined</source> <translation>挖矿所得</translation> </message> <message> <location filename="../transactionview.cpp" line="78"/> <source>Other</source> <translation>其他</translation> </message> <message> <location filename="../transactionview.cpp" line="84"/> <source>Enter address or label to search</source> <translation>输入地址或标签进行搜索</translation> </message> <message> <location filename="../transactionview.cpp" line="90"/> <source>Min amount</source> <translation>最小金额</translation> </message> <message> <location filename="../transactionview.cpp" line="124"/> <source>Copy address</source> <translation>复制地址</translation> </message> <message> <location filename="../transactionview.cpp" line="125"/> <source>Copy label</source> <translation>复制标签</translation> </message> <message> <location filename="../transactionview.cpp" line="126"/> <source>Copy amount</source> <translation>复制金额</translation> </message> <message> <location filename="../transactionview.cpp" line="127"/> <source>Edit label</source> <translation>编辑标签</translation> </message> <message> <location filename="../transactionview.cpp" line="128"/> <source>Show details...</source> <translation>显示细节...</translation> </message> <message> <location filename="../transactionview.cpp" line="268"/> <source>Export Transaction Data</source> <translation>导出交易数据</translation> </message> <message> <location filename="../transactionview.cpp" line="269"/> <source>Comma separated file (*.csv)</source> <translation>逗号分隔文件(*.csv)</translation> </message> <message> <location filename="../transactionview.cpp" line="277"/> <source>Confirmed</source> <translation>已确认</translation> </message> <message> <location filename="../transactionview.cpp" line="278"/> <source>Date</source> <translation>日期</translation> </message> <message> <location filename="../transactionview.cpp" line="279"/> <source>Type</source> <translation>类别</translation> </message> <message> <location filename="../transactionview.cpp" line="280"/> <source>Label</source> <translation>标签</translation> </message> <message> <location filename="../transactionview.cpp" line="281"/> <source>Address</source> <translation>地址</translation> </message> <message> <location filename="../transactionview.cpp" line="282"/> <source>Amount</source> <translation>金额</translation> </message> <message> <location filename="../transactionview.cpp" line="283"/> <source>ID</source> <translation>ID</translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Error exporting</source> <translation>导出错误</translation> </message> <message> <location filename="../transactionview.cpp" line="287"/> <source>Could not write to file %1.</source> <translation>无法写入文件 %1。</translation> </message> <message> <location filename="../transactionview.cpp" line="382"/> <source>Range:</source> <translation>范围:</translation> </message> <message> <location filename="../transactionview.cpp" line="390"/> <source>to</source> <translation>到</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="145"/> <source>Sending...</source> <translation>发送中...</translation> </message> </context> <context> <name>PACCoin-core</name> <message> <location filename="../paccoinstrings.cpp" line="3"/> <source>PACCoin version</source> <translation>比特币版本</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="4"/> <source>Usage:</source> <translation>使用:</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="5"/> <source>Send command to -server or paccoind</source> <translation>发送命令到服务器或者 paccoind </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="6"/> <source>List commands</source> <translation>列出命令 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="7"/> <source>Get help for a command</source> <translation>获得某条命令的帮助 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="8"/> <source>Options:</source> <translation>选项: </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="9"/> <source>Specify configuration file (default: PACCoin.conf)</source> <translation>指定配置文件 (默认为 PACCoin.conf) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="10"/> <source>Specify pid file (default: paccoind.pid)</source> <translation>指定 pid 文件 (默认为 paccoind.pid) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="11"/> <source>Generate coins</source> <translation>生成货币 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="12"/> <source>Don&apos;t generate coins</source> <translation>不要生成货币 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="13"/> <source>Start minimized</source> <translation>启动时最小化 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="14"/> <source>Specify data directory</source> <translation>指定数据目录 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="15"/> <source>Specify connection timeout (in milliseconds)</source> <translation>指定连接超时时间 (微秒) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="16"/> <source>Connect through socks4 proxy</source> <translation>通过 socks4 代理连接 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="17"/> <source>Allow DNS lookups for addnode and connect</source> <translation>连接节点时允许DNS查找 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="18"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>监听端口连接 &lt;port&gt; (缺省: 8333 or testnet: 18333)</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="19"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>最大连接数 &lt;n&gt; (缺省: 125)</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="20"/> <source>Add a node to connect to</source> <translation>连接到指定节点</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="21"/> <source>Connect only to the specified node</source> <translation>只连接到指定节点 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="22"/> <source>Don&apos;t accept connections from outside</source> <translation>禁止接收外部连接 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="23"/> <source>Don&apos;t bootstrap list of peers using DNS</source> <translation>不要用DNS启动</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="24"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Threshold for disconnecting misbehaving peers (缺省: 100)</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="25"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Number of seconds to keep misbehaving peers from reconnecting (缺省: 86400)</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="28"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (缺省: 10000)</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="29"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 10000)</source> <translation>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (缺省: 10000)</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="30"/> <source>Don&apos;t attempt to use UPnP to map the listening port</source> <translation>禁止使用 UPnP 映射监听端口 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="31"/> <source>Attempt to use UPnP to map the listening port</source> <translation>尝试使用 UPnP 映射监听端口 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="32"/> <source>Fee per kB to add to transactions you send</source> <translation>为付款交易支付比特币(每kb)</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="33"/> <source>Accept command line and JSON-RPC commands</source> <translation>接受命令行和 JSON-RPC 命令 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="34"/> <source>Run in the background as a daemon and accept commands</source> <translation>在后台运行并接受命令 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="35"/> <source>Use the test network</source> <translation>使用测试网络 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="36"/> <source>Output extra debugging information</source> <translation>输出调试信息</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="37"/> <source>Prepend debug output with timestamp</source> <translation>为调试输出信息添加时间戳</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="38"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>跟踪/调试信息输出到控制台,不输出到debug.log文件</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="39"/> <source>Send trace/debug info to debugger</source> <translation>跟踪/调试信息输出到 调试器debugger</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="40"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC连接用户名 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="41"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC连接密码 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="42"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332)</source> <translation>JSON-RPC连接监听&lt;端口&gt; (默认为 8332) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="43"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>允许从指定IP接受到的JSON-RPC连接 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="44"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>向IP地址为 &lt;ip&gt; 的节点发送指令 (缺省: 127.0.0.1) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="45"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>设置密钥池大小为 &lt;n&gt; (缺省: 100) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="46"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>重新扫描数据链以查找遗漏的交易 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="47"/> <source> SSL options: (see the PACCoin Wiki for SSL setup instructions)</source> <translation> SSL 选项: (SSL 安装教程具体见比特币维基百科) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="50"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>为 JSON-RPC 连接使用 OpenSSL (https)连接</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="51"/> <source>Server certificate file (default: server.cert)</source> <translation>服务器证书 (默认为 server.cert) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="52"/> <source>Server private key (default: server.pem)</source> <translation>服务器私钥 (默认为 server.pem) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="53"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>可接受的加密器 (默认为 TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="56"/> <source>This help message</source> <translation>该帮助信息 </translation> </message> <message> <location filename="../paccoinstrings.cpp" line="57"/> <source>Cannot obtain a lock on data directory %s. PACCoin is probably already running.</source> <translation>无法给数据目录 %s 加锁。比特币进程可能已在运行。</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="60"/> <source>Loading addresses...</source> <translation>正在加载地址...</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="61"/> <source>Error loading addr.dat</source> <translation>addr.dat文件加载错误</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="63"/> <source>Error loading blkindex.dat</source> <translation>blkindex.dat文件加载错误</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="65"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>wallet.dat钱包文件加载错误:钱包损坏</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="66"/> <source>Error loading wallet.dat: Wallet requires newer version of PACCoin</source> <translation>wallet.dat钱包文件加载错误:请升级到最新PACCoin客户端</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="67"/> <source>Wallet needed to be rewritten: restart PACCoin to complete</source> <translation>钱包文件需要重写:请退出并重新启动PACCoin客户端</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="68"/> <source>Error loading wallet.dat</source> <translation>wallet.dat钱包文件加载错误</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="62"/> <source>Loading block index...</source> <translation>加载区块索引...</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="64"/> <source>Loading wallet...</source> <translation>正在加载钱包...</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="69"/> <source>Rescanning...</source> <translation>正在重新扫描...</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="70"/> <source>Done loading</source> <translation>加载完成</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="71"/> <source>Invalid -proxy address</source> <translation>代理地址不合法</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="72"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;</source> <translation>不合适的交易费 -paytxfee=&lt;amount&gt;</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="73"/> <source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source> <translation>警告: -paytxfee 交易费设置过高. 每进行一笔交易您都将支付该数量的交易费.</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="76"/> <source>Error: CreateThread(StartNode) failed</source> <translation>错误:线程创建(StartNode)失败</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="77"/> <source>Warning: Disk space is low </source> <translation>警告:磁盘空间不足</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="78"/> <source>Unable to bind to port %d on this computer. PACCoin is probably already running.</source> <translation>无法绑定端口 %d 到这台计算机。比特币进程可能已在运行。</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="81"/> <source>Warning: Please check that your computer&apos;s date and time are correct. If your clock is wrong PACCoin will not work properly.</source> <translation>警告:请确定您当前计算机的日期和时间是正确的。比特币将无法在错误的时间下正常工作。</translation> </message> <message> <location filename="../paccoinstrings.cpp" line="84"/> <source>beta</source> <translation>测试</translation> </message> </context> </TS><|fim▁end|>
<location filename="../forms/sendcoinsentry.ui" line="120"/> <source>Paste address from clipboard</source>
<|file_name|>dce.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2015, The Radare Project. All rights reserved. // See the COPYING file at the top-level directory of this distribution. // Licensed under the BSD 3-Clause License: // <http://opensource.org/licenses/BSD-3-Clause> // This file may not be copied, modified, or distributed // except according to those terms. //! Dead code elimination //! //! Removes SSA nodes that are not used by any other node. //! The algorithm will not consider whether the uses keeping a node alive //! are in code that is actually executed or not. For a better analysis //! look at `analysis::constant_propagation`. use crate::analysis::analyzer::{ Action, Analyzer, AnalyzerInfo, AnalyzerKind, AnalyzerResult, Change, FuncAnalyzer, RemoveValue, }; use crate::frontend::radeco_containers::RadecoFunction; use crate::middle::ssa::cfg_traits::{CFGMod, CFG}; use crate::middle::ssa::graph_traits::Graph; use crate::middle::ssa::ssa_traits::{NodeType, SSAExtra, SSAMod, SSA}; use crate::middle::ssa::ssastorage::SSAStorage; use std::any::Any; use std::collections::VecDeque; #[derive(Debug)] pub struct DCE {} const NAME: &str = "dce"; const REQUIRES: &[AnalyzerKind] = &[]; pub const INFO: AnalyzerInfo = AnalyzerInfo { name: NAME, kind: AnalyzerKind::DCE, requires: REQUIRES, uses_policy: true, }; impl DCE { pub fn new() -> Self { DCE {} } // Marks node for removal. This method does not remove nodes. fn mark(&self, ssa: &mut SSAStorage) { let nodes = ssa.values(); let roots = registers_in_err!(ssa, exit_node_err!(ssa), ssa.invalid_value().unwrap()); let mut queue = VecDeque::<<SSAStorage as SSA>::ValueRef>::new(); for node in &nodes { if let Ok(ref result) = ssa.node_data(*node) { if let NodeType::Op(ref op) = result.nt { if op.has_sideeffects() || ssa.is_selector(*node) { queue.push_back(*node); } } } else { ssa.mark(node); } } ssa.clear_mark(&roots); queue.extend(&[roots]); while let Some(ni) = queue.pop_front() { if ssa.is_marked(&ni) { continue; } ssa.mark(&ni); queue.extend(ssa.operands_of(ni)); } } // Sweeps away the un-marked nodes fn sweep<T: FnMut(Box<dyn Change>) -> Action>(&self, ssa: &mut SSAStorage, mut policy: T) { for node in &ssa.values() { if !ssa.is_marked(node) { match policy(Box::new(RemoveValue(*node))) { Action::Apply => { ssa.remove_value(*node); } Action::Skip => (), Action::Abort => { return; } }; } ssa.clear_mark(node); } // Remove empty blocks and redirect control flows. let blocks = ssa.blocks(); for block in &blocks { // Do not touch start or exit nodes if *block == entry_node_err!(ssa) || *block == exit_node_err!(ssa) { continue; } let remove_block = if ssa.exprs_in(*block).is_empty() && ssa.phis_in(*block).is_empty() { let incoming = ssa.incoming_edges(*block); let outgoing = ssa.outgoing_edges(*block); // Two cases. if outgoing.len() == 1 { let new_target = ssa .edge_info(outgoing[0].0) .expect("Less-endpoints edge") .target; for &(ie, ref i) in &incoming { let new_src = ssa.edge_info(ie).expect("Less-endpoints edge").source; ssa.remove_control_edge(ie); ssa.insert_control_edge(new_src, new_target, *i); } ssa.remove_control_edge(outgoing[0].0); true } else { // Incoming edge has to be an unconditional, // else we cannot re-route. // TODO: This is currently unimplemented! false } } else { false }; if remove_block { radeco_trace!("dce_rm_empty|{:?}", block);<|fim▁hole|> ssa.remove_block(*block); } } } } impl Analyzer for DCE { fn info(&self) -> &'static AnalyzerInfo { &INFO } fn as_any(&self) -> &dyn Any { self } } impl FuncAnalyzer for DCE { fn analyze<T: FnMut(Box<dyn Change>) -> Action>( &mut self, rfn: &mut RadecoFunction, policy: Option<T>, ) -> Option<Box<dyn AnalyzerResult>> { self.mark(rfn.ssa_mut()); self.sweep( rfn.ssa_mut(), policy.expect("A policy function must be provided"), ); None } }<|fim▁end|>
<|file_name|>error.ts<|end_file_name|><|fim▁begin|>import shortid from 'shortid'; import { ErrorLevel } from '~client/constants/error'; export const enum ActionTypeError { Opened = '@@error/OPENED', Closed = '@@error/CLOSED', Removed = '@@error/REMOVED', } type ActionErrorOpened = { type: ActionTypeError.Opened; message: { text: string; level: ErrorLevel; }; id: string; }; export const errorOpened = (<|fim▁hole|>): ActionErrorOpened => ({ type: ActionTypeError.Opened, message: { text, level }, id: shortid.generate(), }); type ActionErrorClosed = { type: ActionTypeError.Closed; id: string; }; export const errorClosed = (id: string): ActionErrorClosed => ({ type: ActionTypeError.Closed, id, }); type ActionErrorRemoved = { type: ActionTypeError.Removed; id: string; }; export const errorRemoved = (id: string): ActionErrorRemoved => ({ type: ActionTypeError.Removed, id, }); export type ActionError = ActionErrorOpened | ActionErrorClosed | ActionErrorRemoved;<|fim▁end|>
text: string, level: ErrorLevel = ErrorLevel.Err,
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>mod point; mod size; mod traits; #[macro_use] mod vector;<|fim▁hole|>pub use self::size::Size; pub use self::traits::{Advance, Collide, Position};<|fim▁end|>
pub use self::vector::Vector; pub use self::point::Point;
<|file_name|>u_str.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Unicode-intensive string manipulations. //! //! This module provides functionality to `str` that requires the Unicode methods provided by the //! unicode parts of the CharExt trait. use core::char; use core::iter::Filter; use core::slice; use core::str::Split; /// An iterator over the non-whitespace substrings of a string, /// separated by any amount of whitespace. #[stable(feature = "split_whitespace", since = "1.1.0")] pub struct SplitWhitespace<'a> { inner: Filter<Split<'a, fn(char) -> bool>, fn(&&str) -> bool>, } /// Methods for Unicode string slices #[allow(missing_docs)] // docs in libcollections pub trait UnicodeStr { fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>; fn is_whitespace(&self) -> bool; fn is_alphanumeric(&self) -> bool; fn trim<'a>(&'a self) -> &'a str; fn trim_left<'a>(&'a self) -> &'a str; fn trim_right<'a>(&'a self) -> &'a str; } impl UnicodeStr for str { #[inline] fn split_whitespace(&self) -> SplitWhitespace { fn is_not_empty(s: &&str) -> bool { !s.is_empty() } let is_not_empty: fn(&&str) -> bool = is_not_empty; // coerce to fn pointer fn is_whitespace(c: char) -> bool { c.is_whitespace() } let is_whitespace: fn(char) -> bool = is_whitespace; // coerce to fn pointer SplitWhitespace { inner: self.split(is_whitespace).filter(is_not_empty) } } #[inline] fn is_whitespace(&self) -> bool { self.chars().all(|c| c.is_whitespace()) } #[inline] fn is_alphanumeric(&self) -> bool { self.chars().all(|c| c.is_alphanumeric()) } #[inline] fn trim(&self) -> &str { self.trim_matches(|c: char| c.is_whitespace()) } #[inline] fn trim_left(&self) -> &str { self.trim_left_matches(|c: char| c.is_whitespace()) } #[inline] fn trim_right(&self) -> &str { self.trim_right_matches(|c: char| c.is_whitespace()) } } // https://tools.ietf.org/html/rfc3629 static UTF8_CHAR_WIDTH: [u8; 256] = [ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF ]; /// Given a first byte, determine how many bytes are in this UTF-8 character #[inline] pub fn utf8_char_width(b: u8) -> usize { return UTF8_CHAR_WIDTH[b as usize] as usize; } /// Determines if a vector of `u16` contains valid UTF-16 pub fn is_utf16(v: &[u16]) -> bool { let mut it = v.iter(); macro_rules! next { ($ret:expr) => { match it.next() { Some(u) => *u, None => return $ret } } } loop { let u = next!(true); match char::from_u32(u as u32) { Some(_) => {} None => { let u2 = next!(false); if u < 0xD7FF || u > 0xDBFF || u2 < 0xDC00 || u2 > 0xDFFF { return false; } } } } } /// An iterator that decodes UTF-16 encoded codepoints from a vector /// of `u16`s. #[derive(Clone)] pub struct Utf16Items<'a> { iter: slice::Iter<'a, u16> } /// The possibilities for values decoded from a `u16` stream. #[derive(Copy, PartialEq, Eq, Clone, Debug)] pub enum Utf16Item { /// A valid codepoint. ScalarValue(char), /// An invalid surrogate without its pair. LoneSurrogate(u16) } impl Utf16Item { /// Convert `self` to a `char`, taking `LoneSurrogate`s to the /// replacement character (U+FFFD). #[inline] pub fn to_char_lossy(&self) -> char { match *self { Utf16Item::ScalarValue(c) => c, Utf16Item::LoneSurrogate(_) => '\u{FFFD}' } } } impl<'a> Iterator for Utf16Items<'a> { type Item = Utf16Item; fn next(&mut self) -> Option<Utf16Item> { let u = match self.iter.next() { Some(u) => *u, None => return None }; if u < 0xD800 || 0xDFFF < u { // not a surrogate Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(u as u32) })) } else if u >= 0xDC00 { // a trailing surrogate Some(Utf16Item::LoneSurrogate(u)) } else { // preserve state for rewinding. let old = self.iter.clone(); let u2 = match self.iter.next() { Some(u2) => *u2, // eof None => return Some(Utf16Item::LoneSurrogate(u)) }; if u2 < 0xDC00 || u2 > 0xDFFF { // not a trailing surrogate so we're not a valid // surrogate pair, so rewind to redecode u2 next time. self.iter = old.clone(); return Some(Utf16Item::LoneSurrogate(u)) } // all ok, so lets decode it. let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000; Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(c) })) } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let (low, high) = self.iter.size_hint(); // we could be entirely valid surrogates (2 elements per // char), or entirely non-surrogates (1 element per char) (low / 2, high) } } /// Create an iterator over the UTF-16 encoded codepoints in `v`, /// returning invalid surrogates as `LoneSurrogate`s. /// /// # Examples /// /// ``` /// #![feature(unicode)] /// /// extern crate rustc_unicode; /// /// use rustc_unicode::str::Utf16Item::{ScalarValue, LoneSurrogate}; /// /// fn main() { /// // 𝄞mus<invalid>ic<invalid> /// let v = [0xD834, 0xDD1E, 0x006d, 0x0075, /// 0x0073, 0xDD1E, 0x0069, 0x0063, /// 0xD834]; /// /// assert_eq!(rustc_unicode::str::utf16_items(&v).collect::<Vec<_>>(), /// vec![ScalarValue('𝄞'), /// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'), /// LoneSurrogate(0xDD1E), /// ScalarValue('i'), ScalarValue('c'), /// LoneSurrogate(0xD834)]); /// } /// ``` pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> { Utf16Items { iter : v.iter() } } /// Iterator adaptor for encoding `char`s to UTF-16. #[derive(Clone)] pub struct Utf16Encoder<I> { chars: I, extra: u16 } impl<I> Utf16Encoder<I> { /// Create a UTF-16 encoder from any `char` iterator. pub fn new(chars: I) -> Utf16Encoder<I> where I: Iterator<Item=char> { Utf16Encoder { chars: chars, extra: 0 }<|fim▁hole|>} impl<I> Iterator for Utf16Encoder<I> where I: Iterator<Item=char> { type Item = u16; #[inline] fn next(&mut self) -> Option<u16> { if self.extra != 0 { let tmp = self.extra; self.extra = 0; return Some(tmp); } let mut buf = [0; 2]; self.chars.next().map(|ch| { let n = CharExt::encode_utf16(ch, &mut buf).unwrap_or(0); if n == 2 { self.extra = buf[1]; } buf[0] }) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let (low, high) = self.chars.size_hint(); // every char gets either one u16 or two u16, // so this iterator is between 1 or 2 times as // long as the underlying iterator. (low, high.and_then(|n| n.checked_mul(2))) } } impl<'a> Iterator for SplitWhitespace<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { self.inner.next() } } impl<'a> DoubleEndedIterator for SplitWhitespace<'a> { fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() } }<|fim▁end|>
}
<|file_name|>SearchParser.py<|end_file_name|><|fim▁begin|>__author__ = 'Liam' import types def flag(func): func.is_flag = True return func class BadSearchOp(Exception): def __init__(self, value = "bad search operation"): self.value = value def __str__(self): return "BadSearchOp: %s" % self.value class ImapSearchQueryParser(object): """ Receives a list of commands for the IMAP V4 search and returns a dictionary of the commands, that can be used in various mail API's including walla API for mail based on RFC3501: https://tools.ietf.org/html/rfc3501#section-6.4.4 example of commands: C: A282 SEARCH FLAGGED SINCE 1-Feb-1994 NOT FROM "Smith" S: * SEARCH 2 84 882 S: A282 OK SEARCH completed C: A283 SEARCH TEXT "string not in mailbox" S: * SEARCH S: A283 OK SEARCH completed C: A284 SEARCH CHARSET UTF-8 TEXT {6} C: XXXXXX S: * SEARCH 43 S: A284 OK SEARCH completed """ def __init__(self): """ :param query: :return: """ #self.log("{} constructor ".format(self.__class__.__name__)) self.opFunctionList = [x for x,y in self.__class__.__dict__.items() if type(y) == types.FunctionType] self.query = None self.commands = {} self.commands_list = [] #self.__validate() ######################################################################### # def __repr__(self): return self.__class__.__name__+", commands: %s" % self.commands def log(self,msg): print msg #self.logger.log(logging.DEBUG,msg) def __str__(self): return str(self.commands) def _update_command_list(self, command, idx1, idx2=None): """ Updates both the command list and commands as to prepare for OR parsing :param command: a single dictionary object with one key:value (command:argument) :param idx1: first index :param idx2: second index :return: """ command_wrapper = { 'data': command, 'pos': [idx1] } # update second position if idx2: command_wrapper['pos'].append(idx2) # adding to command list with positions of current command and argument self.commands_list.append(command_wrapper) # update the command self.commands.update(command) @flag def OP__ALL(self,currentIndex=None): self._update_command_list({'all': True}, currentIndex) @flag def OP__ANSWERED(self,currentIndex=None): self._update_command_list({'answered': True}, currentIndex) def OP__BCC(self,currentIndex=None): """ BCC <string> Messages that contain the specified string in the envelope structure's BCC field. :param currentIndex: :return: """ if currentIndex+1 < len(self.query): #todo check bcc validation self._update_command_list({'bcc': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "BCC" provided but with no argument in query list') def OP__BEFORE(self,currentIndex=None): argument = self._get_command_argument(currentIndex) if argument: self._update_command_list({'before': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "BEFORE" provided but with no argument in query list') def OP__BODY(self,currentIndex=None): argument = self._get_command_argument(currentIndex) if argument: self._update_command_list({'body': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "BODY" provided but with no argument in query list') def OP__CC(self,currentIndex=None): argument = self._get_command_argument(currentIndex) if argument: self._update_command_list({'cc': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "CC" provided but with no argument in query list') @flag def OP__DELETED(self,currentIndex=None): self._update_command_list({'deleted': True}, currentIndex) @flag def OP__DRAFT(self,currentIndex=None): self._update_command_list({'draft': True}, currentIndex) @flag def OP__FLAGGED(self,currentIndex=None): self._update_command_list({'flagged': True}, currentIndex) def OP__FROM(self,currentIndex=None): """ FROM <string> Messages that contain the specified string in the envelope structure's FROM field. :return: """ # assuming that next item is the value, such as: FROM '[email protected]' argument = self._get_command_argument(currentIndex) if argument: self._update_command_list({'from': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "FROM" provided but with no argument in query list') def OP__HEADER(self,currentIndex=None): # todo work on this one pass def OP__KEYWORD(self,currentIndex=None): argument = self._get_command_argument(currentIndex) if argument: self._update_command_list({'keyword': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "KEYWORD" provided but with no argument in query list') def OP__LARGER(self,currentIndex=None): argument = self._get_command_argument(currentIndex) if argument: self._update_command_list({'larger': argument}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "LARGER" provided but with no argument in query list') @flag def OP__NEW(self,currentIndex=None): self._update_command_list({'new': True}, currentIndex) @flag def OP__OLD(self,currentIndex=None): self._update_command_list({'old': True}, currentIndex) @flag def OP__RECENT(self,currentIndex=None): self._update_command_list({'recet': True}, currentIndex) @flag def OP__SEEN(self,currentIndex=None):<|fim▁hole|> self._update_command_list({'seen': True}, currentIndex) @flag def OP__UNANSWERED(self,currentIndex=None): self._update_command_list({'unanswered': True}, currentIndex) @flag def OP_UNDRAFT(self,currentIndex=None): self._update_command_list({'undraft': True}, currentIndex) @flag def OP__UNFLAGGED(self,currentIndex=None): self._update_command_list({'unflagged': True}, currentIndex) @flag def OP__UNKEYWORD(self,currentIndex=None): """ UNKEYWORD <flag> Messages that do not have the specified keyword flag set. """ # todo make it proper somehow #self.commands.update({'seen': True}) @flag def OP__UNSEEN(self,currentIndex=None): self._update_command_list({'unseen': True}, currentIndex) def OP__SENTBEFORE(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'sentbefore': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "SENTBEFORE" provided but with no argument in query list') def OP__SENTON(self, currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'senton': self.query[currentIndex+1]}, currentIndex) else: raise BadSearchOp('Operator "SENTON" provided but with no argument in query list') def OP__SENTSINCE(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'sentsince': self.query[currentIndex+1]},currentIndex) else: raise BadSearchOp('Operator "SENTSINCE" provided but with no argument in query list') def OP__SINCE(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'since': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "SINCE" provided but with no argument in query list') def OP__SMALLER(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'smaller': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "SMALLER" provided but with no argument in query list') def OP__SUBJECT(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'subject': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "SUBJECT" provided but with no argument in query list') def OP__TEXT(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'text': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "TEXT" provided but with no argument in query list') def OP__TO(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'to': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "TO" provided but with no argument in query list') def OP__UID(self,currentIndex=None): if currentIndex+1 < len(self.query): self._update_command_list({'uid': self.query[currentIndex+1]}, currentIndex, currentIndex+1) else: raise BadSearchOp('Operator "UID" provided but with no argument in query list') def _NOT_PARSER(self): #print "NOT PARSER---" for i in range(len(self.query)): operator = self.query[i] #print "operator:"+operator if (operator=="NOT"): #print "found NOT index:{}".format(i) # find what is next command if (i+1<len(self.query)): next_possible_command = self.query[i+1] #print "next_possible_command:{}".format(next_possible_command) # is possible command a valid operator function? possible_command_function = self.__get_op_function(next_possible_command) # indeed a function if (callable(possible_command_function)): is_flag = getattr(possible_command_function,'is_flag',False) if is_flag: command = {next_possible_command.lower(): False} self._update_command_list(command,i) else: old_operator_value = self.commands.get(next_possible_command.lower()) for command in self.commands_list: if command['data'].get(next_possible_command.lower(),None): del command['data'] command['data'] = { 'not-'+next_possible_command.lower():old_operator_value } # add the from position so it will be match when doing OR NOT command['pos'].append(i) self.commands['not-'+next_possible_command.lower()] = old_operator_value del self.commands[next_possible_command.lower()] def _OR_PARSER(self): """ we start parsing the OR command and dialectically correct / update the commands using the commands_list metadata :return: """ def _find_command_by_indexes(index1,index2): #for i in range(len(self.commands_list)): foundCommands = [] for command in self.commands_list: pos = command['pos'] #print "command:{}".format(command) if (index1 in pos): foundCommands.append(command['data']) if (index2 in pos): foundCommands.append(command['data']) #print "Found OR commands: {}".format(foundCommands) return foundCommands for i in range(len(self.query)): operator = self.query[i] rhs,lhs = None,None if operator== "OR": if (i+1<len(self.query)): rhs = i+1 if i-1 > -1: lhs = i-1 # only if both rhs and lhs exist can we go on if not rhs and not lhs: raise BadSearchOp('Operator "OR" provided but missing both left hand and right hand side params') or_commands = _find_command_by_indexes(lhs,rhs) if len(or_commands)==2: orDict = {} for command in or_commands: #orDict.update(command) # if command in commands for k,v in command.iteritems(): #print "K:{} v:{}".format(k,v) # key of command found if k in self.commands: orDict[k] = v del self.commands[k] #print "orDict:{}".format(orDict) self.commands['or'] = orDict #if command in self.commands #print "OR RHS:{} LHS:{}".format(rhs, lhs) def _get_command_argument(self,currentIndex): """ will treat the next command as argument to command in currentIndex. used for all commands that have parameters (arguments), such as: FROM <string> BEFORE <date> BODY <string> etc... :param currentIndex: :return: """ # assuming that next item is the value, such as: FROM '[email protected]' if currentIndex+1 < len(self.query): #todo check validation argument = self.query[currentIndex+1] return argument else: return None @property def opList(self): return self.opFunctionList def __get_op_function(self,operator): operatorFuncName = "OP__"+operator.upper() if operatorFuncName in self.opList: opFunction = getattr(self,operatorFuncName) return opFunction else: return None def __validate(self): """ tries to validate the command set :return: """ print "IMAP4 Search Query List:{}".format(self.query) if len(self.query) < 1: raise BadSearchOp("not enough items in list, has to be more then 1 (sequence set,search)") for i in range(len(self.query)): operator = self.query[i] opFunction = self.__get_op_function(operator) if (opFunction): #print "operator found:{}".format(operator) opFunction(i) else: pass #print "operator not found:{}".format(operator) self._NOT_PARSER() self._OR_PARSER() return self.commands def parse(self, query): self.query = query return self.__validate() if __name__ == "__main__": test_commands = [ ['NOT','FLAGGED','SINCE','1-Feb-1994','NOT','FROM','Smith','BCC', '[email protected]'], ['NOT','BEFORE','1-Feb-1994','NOT','FROM','Smith'], ['SEEN','BEFORE','1-Feb-1994','OR','NOT','FROM','Smith'], ['NOT','SENTBEFORE','1-Feb-1994','NOT','FROM','Smith'], ['SUBJECT','all about love','NOT','TO','[email protected]','SINCE','1-Feb-1994','NOT','FROM','Smith','UID','1:*','OR','NOT','TEXT','Go To Hello'], ['SEEN','BEFORE','1-Feb-1994','OR','NOT','FROM','Smith'] ] for command_set in test_commands: c = ImapSearchQueryParser() res = c.parse(command_set) print "Result:{}".format(res) #print "command_list:{}".format(c.commands_list)<|fim▁end|>
<|file_name|>Util.py<|end_file_name|><|fim▁begin|>#Boss Ogg - A Music Server #(c)2003 by Ted Kulp ([email protected]) #This project's homepage is: http://bossogg.wishy.org # #This program is free software; you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation; either version 2 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from boss3.util import Logger from boss3.util.Session import * import boss3.xmlrpc.bossxmlrpclib as xmlrpclib class Util: """ Util realm. This will contain basic functions that don't really fit anywhere else. They can generally have a very low security level. util("version"): Returns version information about the running server. Parameters: * None Returns: * Struct * version - string * name - string """ def handleRequest(self, cmd, argstuple): <|fim▁hole|> args.append(i) if (session.hasKey('cmdint')): cmdint = session['cmdint'] if cmd == "version": return cmdint.util.version() # vim:ts=8 sw=8 noet<|fim▁end|>
session = Session() args = [] for i in argstuple:
<|file_name|>cli.js<|end_file_name|><|fim▁begin|>#!/usr/bin/env node<|fim▁hole|><|fim▁end|>
require("./bin/npm-cli.js")
<|file_name|>word_index.rs<|end_file_name|><|fim▁begin|>#![stable] //! This module is used to index words and does the heavy lifting of our program. /// A counted word. /// /// This struct contains members for storing a word and the number of times it appeared. This /// struct is intended for use with [`add_word`](fn.add_word.html). /// /// # Examples /// /// ``` /// use lib_word_count::word_index; /// /// let indexed_word = word_index::IndexedWord{ /// word: "Text".to_string(), /// appeared: 12 /// }; /// /// assert_eq!(indexed_word.word, "Text".to_string()); /// assert_eq!(indexed_word.appeared, 12i64); /// ``` #[derive(Debug, PartialEq)] #[stable] pub struct IndexedWord { /// The word that's indexed. pub word: String, /// The amount of times this word appeared. pub appeared: i64 } /// Add a word to a given index. /// /// This function prevents duplicates and increments the count of the word appearances /// automatically. The vector will be modified accordingly. /// /// # Arguments /// /// * `word` A string containing the word to add. /// /// * `index` A reference to a vector containing all the indexed words. /// /// # Examples /// /// ``` /// use lib_word_count::word_index; /// /// let mut index = Vec::new(); /// /// word_index::add_word("Hello".to_string(), &mut index); /// word_index::add_word("hELLO".to_string(), &mut index); /// word_index::add_word("World".to_string(), &mut index); /// word_index::add_word("HELLO".to_string(), &mut index); /// word_index::add_word("PFUDOR".to_string(), &mut index);<|fim▁hole|>/// /// assert_eq!(index[0], word_index::IndexedWord{ /// word: "hello".to_string(), /// appeared: 3 /// }); /// assert_eq!(index[1], word_index::IndexedWord{ /// word: "world".to_string(), /// appeared: 1 /// }); /// assert_eq!(index[2], word_index::IndexedWord{ /// word: "pfudor".to_string(), /// appeared: 1 /// }); /// ``` #[stable] pub fn add_word(word: String, index: &mut Vec<IndexedWord>) { for indexed_word in index.iter_mut() { if word.to_lowercase() == indexed_word.word { indexed_word.appeared += 1; return; } } let new_word = IndexedWord{ word: word.to_lowercase(), appeared: 1 }; index.push(new_word); }<|fim▁end|>
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!env/bin/python from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db <|fim▁hole|> manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()<|fim▁end|>
migrate = Migrate(app, db)
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>fn is_prime(number: i32) -> bool { if number % 2 == 0 && number != 2 || number == 1 { return false; } let limit = (number as f32).sqrt() as i32 + 1; // We test if the number is divisible by any odd number up to the limit (3..limit).step_by(2).all(|x| number % x != 0)<|fim▁hole|> println!("{}", is_prime(15_485_863)); // The 1 000 000th prime. println!("{}", is_prime(62_773_913)); // The product of the 1000th and 1001st primes. } #[test] fn test_one() { // https://primes.utm.edu/notes/faq/one.html assert!(!is_prime(1)); } #[test] fn test_two() { assert!(is_prime(2)); } #[test] fn test_many() { let primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31]; assert!(primes.iter().all(|&x| is_prime(x))); }<|fim▁end|>
} fn main() {