signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@task(name='<STR_LIT>')<EOL>def purge_old_event_logs(delete_before_days=<NUM_LIT:7>):
delete_before_date = timezone.now() - timedelta(days=delete_before_days)<EOL>logs_deleted = EventLog.objects.filter(<EOL>created_on__lte=delete_before_date).delete()<EOL>return logs_deleted<EOL>
Purges old event logs from the database table
f12291:m1
@task(name='<STR_LIT>')<EOL>def purge_old_request_logs(delete_before_days=<NUM_LIT:7>):
delete_before_date = timezone.now() - timedelta(days=delete_before_days)<EOL>logs_deleted = RequestLog.objects.filter(<EOL>created_on__lte=delete_before_date).delete()<EOL>return logs_deleted<EOL>
Purges old request logs from the database table
f12291:m2
def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None):
if logs:<EOL><INDENT>obj_logger = ObjectLogger()<EOL>if not isinstance(logs, list):<EOL><INDENT>logs = [logs, ]<EOL><DEDENT>for log in logs:<EOL><INDENT>log = obj_logger.log_response(<EOL>log,<EOL>context,<EOL>status=str(status),<EOL>headers='<STR_LIT>',<EOL>content_type=str(content_type))<EOL>log.save()<EOL><DEDENT><DEDENT>return django_render(<EOL>request,<EOL>template_name,<EOL>context=context,<EOL>content_type=content_type,<EOL>status=status,<EOL>using=using)<EOL>
Wrapper around Django render method. Can take one or a list of logs and logs the response. No overhead if no logs are passed.
f12294:m1
def cli():
parser = argparse.ArgumentParser(prog="<STR_LIT>",<EOL>formatter_class=argparse.ArgumentDefaultsHelpFormatter,<EOL>conflict_handler="<STR_LIT>",<EOL>description=__doc__<EOL>)<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:version>",<EOL>version="<STR_LIT>".format(__version__)<EOL>)<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>default="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>type=int, default=<NUM_LIT>,<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>default="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>return parser.parse_args()<EOL>
Parse options from the command line
f12307:m0
def find_build_dir(path, build="<STR_LIT>"):
path = os.path.abspath(os.path.expanduser(path))<EOL>contents = os.listdir(path)<EOL>filtered_contents = [directory for directory in contents<EOL>if os.path.isdir(os.path.join(path, directory))]<EOL>if build in filtered_contents:<EOL><INDENT>return os.path.join(path, build)<EOL><DEDENT>else:<EOL><INDENT>if path == os.path.realpath("<STR_LIT:/>"):<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return find_build_dir("<STR_LIT>".format(path), build)<EOL><DEDENT><DEDENT>
try to guess the build folder's location
f12307:m1
def stamp(iterable, key='<STR_LIT>'):
for item in iterable:<EOL><INDENT>item[key] = now()<EOL>yield item<EOL><DEDENT>
Compute an accurate timestamp for each dict or dict-like object in ``iterable``, adding an accurate timestamp to each one when received. The timestamp is a usecond-precision ISO8601 string. The timestamp is added to each dict with a key set by ``key``.
f12315:m1
def fields(iterable, fields=None):
if not fields:<EOL><INDENT>for item in iterable:<EOL><INDENT>yield item<EOL><DEDENT><DEDENT>prepared_fields = _prepare_fields(fields)<EOL>for item in iterable:<EOL><INDENT>yield _process_fields(item, prepared_fields)<EOL><DEDENT>
Add a set of fields to each item in ``iterable``. The set of fields have a key=value format. '@' are added to the front of each key.
f12315:m2
def tag(iterable, tags=None, key='<STR_LIT>'):
if not tags:<EOL><INDENT>for item in iterable:<EOL><INDENT>yield item<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for item in iterable:<EOL><INDENT>yield _tag(item, tags, key)<EOL><DEDENT><DEDENT>
Add tags to each dict or dict-like object in ``iterable``. Tags are added to each dict with a key set by ``key``. If a key already exists under the key given by ``key``, this function will attempt to ``.extend()``` it, but will fall back to replacing it in the event of error.
f12315:m5
def all_connections(self):
for i in _xrange(self.num_patterns):<EOL><INDENT>for c in self._available_connections[i]:<EOL><INDENT>yield c<EOL><DEDENT>for c in self._in_use_connections[i]:<EOL><INDENT>yield c<EOL><DEDENT><DEDENT>
Returns a generator over all current connection objects
f12316:c2:m5
def get_connection(self, command_name, *keys, **options):
self._checkpid()<EOL>try:<EOL><INDENT>connection = self._available_connections[self._pattern_idx].pop()<EOL><DEDENT>except IndexError:<EOL><INDENT>connection = self.make_connection()<EOL><DEDENT>self._in_use_connections[self._pattern_idx].add(connection)<EOL>self._next_pattern()<EOL>return connection<EOL>
Get a connection from the pool
f12316:c2:m6
def make_connection(self):
if self._created_connections[self._pattern_idx] >= self.max_connections_per_pattern:<EOL><INDENT>raise ConnectionError("<STR_LIT>")<EOL><DEDENT>self._created_connections[self._pattern_idx] += <NUM_LIT:1><EOL>conn = self.connection_class(**self.patterns[self._pattern_idx])<EOL>conn._pattern_idx = self._pattern_idx<EOL>return conn<EOL>
Create a new connection
f12316:c2:m7
def release(self, connection):
self._checkpid()<EOL>if connection.pid == self.pid:<EOL><INDENT>idx = connection._pattern_idx<EOL>self._in_use_connections[idx].remove(connection)<EOL>self._available_connections[idx].append(connection)<EOL><DEDENT>
Releases the connection back to the pool
f12316:c2:m8
def purge(self, connection):
self._checkpid()<EOL>if connection.pid == self.pid:<EOL><INDENT>idx = connection._pattern_idx<EOL>if connection in self._in_use_connections[idx]:<EOL><INDENT>self._in_use_connections[idx].remove(connection)<EOL><DEDENT>else:<EOL><INDENT>self._available_connections[idx].remove(connection)<EOL><DEDENT>connection.disconnect()<EOL><DEDENT>
Remove the connection from rotation
f12316:c2:m9
def disconnect(self):
for conn in self.all_connections():<EOL><INDENT>conn.disconnect()<EOL><DEDENT>
Disconnect all connections in the pool
f12316:c2:m10
def execute_command(self, *args, **options):
pool = self.connection_pool<EOL>command_name = args[<NUM_LIT:0>]<EOL>for i in _xrange(self.execution_attempts):<EOL><INDENT>connection = pool.get_connection(command_name, **options)<EOL>try:<EOL><INDENT>connection.send_command(*args)<EOL>res = self.parse_response(connection, command_name, **options)<EOL>pool.release(connection)<EOL>return res<EOL><DEDENT>except ConnectionError:<EOL><INDENT>pool.purge(connection)<EOL>if i >= self.execution_attempts - <NUM_LIT:1>:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>
Execute a command and return a parsed response
f12316:c3:m2
def messages(fp, key='<STR_LIT>'):
for line in lines(fp):<EOL><INDENT>txt = line.rstrip('<STR_LIT:\n>')<EOL>yield {key: txt}<EOL><DEDENT>
Read lines of UTF-8 from the file-like object given in ``fp``, with the same fault-tolerance as :function:`tagalog.io.lines`, but instead yield dicts with the line data stored in the key given by ``key`` (default: "@message").
f12317:m0
def lines(fp):
if fp.fileno() == sys.stdin.fileno():<EOL><INDENT>close = True<EOL>try: <EOL><INDENT>fp = open(fp.fileno(), mode='<STR_LIT:r>', buffering=BUF_LINEBUFFERED, errors='<STR_LIT:replace>')<EOL>decode = False<EOL><DEDENT>except TypeError:<EOL><INDENT>fp = os.fdopen(fp.fileno(), '<STR_LIT>', BUF_LINEBUFFERED)<EOL>decode = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>close = False<EOL>try:<EOL><INDENT>decode = (fp.encoding != UTF8)<EOL><DEDENT>except AttributeError:<EOL><INDENT>decode = True<EOL><DEDENT><DEDENT>try:<EOL><INDENT>while <NUM_LIT:1>:<EOL><INDENT>l = fp.readline()<EOL>if l:<EOL><INDENT>if decode:<EOL><INDENT>l = l.decode(UTF8, '<STR_LIT:replace>')<EOL><DEDENT>yield l<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>if close:<EOL><INDENT>fp.close()<EOL><DEDENT><DEDENT>
Read lines of UTF-8 from the file-like object given in ``fp``, making sure that when reading from STDIN, reads are at most line-buffered. UTF-8 decoding errors are handled silently. Invalid characters are replaced by U+FFFD REPLACEMENT CHARACTER. Line endings are normalised to newlines by Python's universal newlines feature. Returns an iterator yielding lines.
f12317:m1
@contextmanager<EOL><INDENT>def handle(self, logger, handler, level=logging.INFO):<DEDENT>
original_level = logger.level<EOL>logger.setLevel(level)<EOL>logger.addHandler(handler)<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>logger.setLevel(original_level)<EOL>logger.removeHandler(handler)<EOL><DEDENT>
Context manager that attach a handler to a logger.
f12339:c2:m0
@contextmanager<EOL><INDENT>def record(self, logger, level=logging.INFO):<DEDENT>
recorder = Recorder()<EOL>with self.handle(logger, recorder, level):<EOL><INDENT>yield recorder.emitted_records<EOL><DEDENT>
Context manager that capture the logger emitted records.
f12339:c2:m1
def mutable_model_prepared(signal, sender, definition, existing_model_class,<EOL>**kwargs):
referenced_models = set()<EOL>if existing_model_class:<EOL><INDENT>for field in existing_model_class._meta.local_fields:<EOL><INDENT>if isinstance(field, RelatedField):<EOL><INDENT>remote_field_model = get_remote_field_model(field)<EOL>if not isinstance(remote_field_model, string_types):<EOL><INDENT>referenced_models.add(remote_field_model)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for field in sender._meta.local_fields:<EOL><INDENT>if isinstance(field, RelatedField):<EOL><INDENT>remote_field_model = get_remote_field_model(field)<EOL>if not isinstance(remote_field_model, string_types):<EOL><INDENT>referenced_models.add(remote_field_model)<EOL>if (issubclass(remote_field_model, MutableModel) and<EOL>remote_field_model._definition != sender._definition):<EOL><INDENT>remote_field_model._dependencies.add(sender._definition)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>related_model_defs = ModelDefinition.objects.filter(<EOL>Q(fielddefinitions__foreignkeydefinition__to=definition) |<EOL>Q(fielddefinitions__manytomanyfielddefinition__to=definition)<EOL>).distinct()<EOL>for model_def in related_model_defs:<EOL><INDENT>if model_def != definition:<EOL><INDENT>sender._dependencies.add(model_def.model_class()._definition)<EOL><DEDENT><DEDENT>for model_class in referenced_models:<EOL><INDENT>clear_opts_related_cache(model_class)<EOL><DEDENT>
Make sure all related model class are created and marked as dependency when a mutable model class is prepared
f12367:m0
@property<EOL><INDENT>def is_recursive_relationship(self):<DEDENT>
return self.to_id == self.model_def_id<EOL>
Whether or not `to` points to this field's model definition
f12368:c0:m1
def CASCADE_MARK_ORIGIN(collector, field, sub_objs, using):
CASCADE(collector, field, sub_objs, using)<EOL>if sub_objs:<EOL><INDENT>for obj in sub_objs:<EOL><INDENT>obj._state._cascade_deletion_origin = field.name<EOL><DEDENT><DEDENT>
Custom on_delete handler which sets _cascade_deletion_origin on the _state of the all relating objects that will deleted. We use this handler on ModelDefinitionAttribute.model_def, so when we delete a ModelDefinition we can skip field_definition_post_delete and base_definition_post_delete and avoid an incremental columns deletion before the entire table is dropped.
f12392:m0
def _model_class_from_pk(definition_cls, definition_pk):
try:<EOL><INDENT>return definition_cls.objects.get(pk=definition_pk).model_class()<EOL><DEDENT>except definition_cls.DoesNotExist:<EOL><INDENT>pass<EOL><DEDENT>
Helper used to unpickle MutableModel model class from their definition pk.
f12399:m0
def get_model_bases(self):
bases = []<EOL>has_mutable_base = False<EOL>for base_def in self.basedefinitions.all():<EOL><INDENT>base = base_def.construct()<EOL>if issubclass(base, MutableModel):<EOL><INDENT>has_mutable_base = True<EOL>base._dependencies.add((self.__class__, self.pk))<EOL><DEDENT>bases.append(base)<EOL><DEDENT>if not has_mutable_base:<EOL><INDENT>bases.append(MutableModel)<EOL><DEDENT>return tuple(bases)<EOL>
Build a tuple of bases for the constructed definition
f12399:c1:m3
def clean(self):
if self.lookup == '<STR_LIT:?>': <EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>lookups = self.lookup.split(LOOKUP_SEP)<EOL>opts = self.model_def.model_class()._meta<EOL>valid = True<EOL>while len(lookups):<EOL><INDENT>lookup = lookups.pop(<NUM_LIT:0>)<EOL>try:<EOL><INDENT>field = opts.get_field(lookup)<EOL><DEDENT>except FieldDoesNotExist:<EOL><INDENT>valid = False<EOL><DEDENT>else:<EOL><INDENT>if isinstance(field, models.ForeignKey):<EOL><INDENT>opts = get_remote_field_model(field)._meta<EOL><DEDENT>elif len(lookups): <EOL><INDENT>valid = False<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if not valid:<EOL><INDENT>msg = _("<STR_LIT>")<EOL>raise ValidationError({'<STR_LIT>': [msg]})<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
Make sure the lookup makes sense
f12399:c5:m0
def construct_for_migrate(self):
return self.construct()<EOL>
Provide a suitable field to be used in migrations.
f12401:c1:m13
def connections_can_rollback_ddl():
return all(connection.features.can_rollback_ddl for connection in connections.all())<EOL>
Returns True if all implied connections have DDL transactions support.
f12403:m0
def nonraw_instance(receiver):
@wraps(receiver)<EOL>def wrapper(sender, instance, raw, using, **kwargs):<EOL><INDENT>if raw:<EOL><INDENT>instance = sender._default_manager.using(using).get(pk=instance.pk)<EOL><DEDENT>return receiver(sender=sender, raw=raw, instance=instance, using=using,<EOL>**kwargs)<EOL><DEDENT>return wrapper<EOL>
A signal receiver decorator that fetch the complete instance from db when it's passed as raw
f12410:m1
def base_definition_pre_delete(sender, instance, **kwargs):
<EOL>cascade_deletion_origin = popattr(<EOL>instance._state, '<STR_LIT>', None<EOL>)<EOL>if cascade_deletion_origin == '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>if (instance.base and issubclass(instance.base, models.Model) and<EOL>instance.base._meta.abstract):<EOL><INDENT>instance._state._deletion = instance.model_def.model_class().render_state()<EOL><DEDENT>
This is used to pass data required for deletion to the post_delete signal that is no more available thereafter.
f12410:m6
def base_definition_post_delete(sender, instance, **kwargs):
if hasattr(instance._state, '<STR_LIT>'):<EOL><INDENT>model = popattr(instance._state, '<STR_LIT>')<EOL>for field in instance.base._meta.fields:<EOL><INDENT>perform_ddl('<STR_LIT>', model, field)<EOL><DEDENT><DEDENT>
Make sure to delete fields inherited from an abstract model base.
f12410:m7
def raw_field_definition_proxy_post_save(sender, instance, raw, **kwargs):
if raw:<EOL><INDENT>model_class = instance.content_type.model_class()<EOL>opts = model_class._meta<EOL>if opts.proxy and opts.concrete_model is sender:<EOL><INDENT>field_definition_post_save(<EOL>sender=model_class, instance=instance.type_cast(), raw=raw,<EOL>**kwargs<EOL>)<EOL><DEDENT><DEDENT>
When proxy field definitions are loaded from a fixture they're not passing through the `field_definition_post_save` signal. Make sure they are.
f12410:m9
@nonraw_instance<EOL>def field_definition_post_save(sender, instance, created, raw, **kwargs):
model_class = instance.model_def.model_class().render_state()<EOL>field = instance.construct_for_migrate()<EOL>field.model = model_class<EOL>if created:<EOL><INDENT>if hasattr(instance._state, '<STR_LIT>'):<EOL><INDENT>field.default = instance._state._creation_default_value<EOL>delattr(instance._state, '<STR_LIT>')<EOL><DEDENT>add_column = popattr(instance._state, '<STR_LIT>', True)<EOL>if add_column:<EOL><INDENT>perform_ddl('<STR_LIT>', model_class, field)<EOL>if raw:<EOL><INDENT>instance.model_def.model_class().mark_as_obsolete()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>old_field = instance._state._pre_save_field<EOL>delattr(instance._state, '<STR_LIT>')<EOL>perform_ddl('<STR_LIT>', model_class, old_field, field, strict=True)<EOL><DEDENT>
This signal is connected by all FieldDefinition subclasses see comment in FieldDefinitionBase for more details
f12410:m10
def popattr(obj, attr, default=NOT_PROVIDED):
val = getattr(obj, attr, default)<EOL>try:<EOL><INDENT>delattr(obj, attr)<EOL><DEDENT>except AttributeError:<EOL><INDENT>if default is NOT_PROVIDED:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>return val<EOL>
Useful for retrieving an object attr and removing it if it's part of it's dict while allowing retrieving from subclass. i.e. class A: a = 'a' class B(A): b = 'b' >>> popattr(B, 'a', None) 'a' >>> A.a 'a'
f12411:m1
def _app_cache_deepcopy(obj):
if isinstance(obj, defaultdict):<EOL><INDENT>return deepcopy(obj)<EOL><DEDENT>elif isinstance(obj, dict):<EOL><INDENT>return type(obj)((_app_cache_deepcopy(key), _app_cache_deepcopy(val)) for key, val in obj.items())<EOL><DEDENT>elif isinstance(obj, list):<EOL><INDENT>return list(_app_cache_deepcopy(val) for val in obj)<EOL><DEDENT>elif isinstance(obj, AppConfig):<EOL><INDENT>app_conf = Empty()<EOL>app_conf.__class__ = AppConfig<EOL>app_conf.__dict__ = _app_cache_deepcopy(obj.__dict__)<EOL>return app_conf<EOL><DEDENT>return obj<EOL>
An helper that correctly deepcopy model cache state
f12411:m10
@contextmanager<EOL>def app_cache_restorer():
state = _app_cache_deepcopy(apps.__dict__)<EOL>try:<EOL><INDENT>yield state<EOL><DEDENT>finally:<EOL><INDENT>with apps_lock():<EOL><INDENT>apps.__dict__ = state<EOL>for app_conf in apps.get_app_configs():<EOL><INDENT>app_conf.models = apps.all_models[app_conf.label]<EOL><DEDENT>apps.clear_cache()<EOL><DEDENT><DEDENT>
A context manager that restore model cache state as it was before entering context.
f12411:m11
@staticmethod<EOL><INDENT>def str_to_bytes(s):<DEDENT>
return bytes.fromhex(s.replace("<STR_LIT>", "<STR_LIT>"))<EOL>
Convert 0xHexString to bytes :param s: 0x hexstring :return: byte sequence
f12416:c3:m0
@staticmethod<EOL><INDENT>def get_pseudo_abi_for_input(s, timeout=None, proxies=None):<DEDENT>
sighash = Utils.bytes_to_str(s[:<NUM_LIT:4>])<EOL>for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_sighash(sighash, timeout=timeout, proxies=proxies):<EOL><INDENT>types = [ti["<STR_LIT:type>"] for ti in pseudo_abi['<STR_LIT>']]<EOL>try:<EOL><INDENT>_ = decode_abi(types, s[<NUM_LIT:4>:])<EOL>yield pseudo_abi<EOL><DEDENT>except eth_abi.exceptions.DecodingError as e:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>
Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi. May return multiple results as sighashes may collide. :param s: bytes input :return: pseudo abi for method
f12416:c4:m3
def _prepare_abi(self, jsonabi):
self.signatures = {}<EOL>for element_description in jsonabi:<EOL><INDENT>abi_e = AbiMethod(element_description)<EOL>if abi_e["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>self.signatures[b"<STR_LIT>"] = abi_e<EOL><DEDENT>elif abi_e["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>abi_e.setdefault("<STR_LIT>", [])<EOL>self.signatures[b"<STR_LIT>"] = abi_e<EOL><DEDENT>elif abi_e["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>if abi_e.get("<STR_LIT>"):<EOL><INDENT>self.signatures[Utils.str_to_bytes(abi_e["<STR_LIT>"])] = abi_e<EOL><DEDENT><DEDENT>elif abi_e["<STR_LIT:type>"] == "<STR_LIT>":<EOL><INDENT>self.signatures[b"<STR_LIT>"] = abi_e<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % (abi_e.get("<STR_LIT:type>"),<EOL>element_description, abi_e))<EOL><DEDENT><DEDENT>
Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :return:
f12416:c5:m2
def describe_constructor(self, s):
method = self.signatures.get(b"<STR_LIT>")<EOL>if not method:<EOL><INDENT>m = AbiMethod({"<STR_LIT:type>": "<STR_LIT>", "<STR_LIT:name>": "<STR_LIT>", "<STR_LIT>": [], "<STR_LIT>": []})<EOL>return m<EOL><DEDENT>types_def = method["<STR_LIT>"]<EOL>types = [t["<STR_LIT:type>"] for t in types_def]<EOL>names = [t["<STR_LIT:name>"] for t in types_def]<EOL>if not len(s):<EOL><INDENT>values = len(types) * ["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>values = decode_abi(types, s)<EOL><DEDENT>method.inputs = [{"<STR_LIT:type>": t, "<STR_LIT:name>": n, "<STR_LIT:data>": v} for t, n, v in list(<EOL>zip(types, names, values))]<EOL>return method<EOL>
Describe the input bytesequence (constructor arguments) s based on the loaded contract abi definition :param s: bytes constructor arguments :return: AbiMethod instance
f12416:c5:m3
def describe_input(self, s):
signatures = self.signatures.items()<EOL>for sighash, method in signatures:<EOL><INDENT>if sighash is None or sighash.startswith(b"<STR_LIT>"):<EOL><INDENT>continue <EOL><DEDENT>if s.startswith(sighash):<EOL><INDENT>s = s[len(sighash):]<EOL>types_def = self.signatures.get(sighash)["<STR_LIT>"]<EOL>types = [t["<STR_LIT:type>"] for t in types_def]<EOL>names = [t["<STR_LIT:name>"] for t in types_def]<EOL>if not len(s):<EOL><INDENT>values = len(types) * ["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>values = decode_abi(types, s)<EOL><DEDENT>method.inputs = [{"<STR_LIT:type>": t, "<STR_LIT:name>": n, "<STR_LIT:data>": v} for t, n, v in list(<EOL>zip(types, names, values))]<EOL>return method<EOL><DEDENT><DEDENT>else:<EOL><INDENT>method = AbiMethod({"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT:name>": "<STR_LIT>",<EOL>"<STR_LIT>": [], "<STR_LIT>": []})<EOL>types_def = self.signatures.get(b"<STR_LIT>", {"<STR_LIT>": []})["<STR_LIT>"]<EOL>types = [t["<STR_LIT:type>"] for t in types_def]<EOL>names = [t["<STR_LIT:name>"] for t in types_def]<EOL>values = decode_abi(types, s)<EOL>method.inputs = [{"<STR_LIT:type>": t, "<STR_LIT:name>": n, "<STR_LIT:data>": v} for t, n, v in list(<EOL>zip(types, names, values))]<EOL>return method<EOL><DEDENT>
Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return: AbiMethod instance
f12416:c5:m4
@staticmethod<EOL><INDENT>def from_input_lookup(s):<DEDENT>
for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_input(s):<EOL><INDENT>method = AbiMethod(pseudo_abi)<EOL>types_def = pseudo_abi["<STR_LIT>"]<EOL>types = [t["<STR_LIT:type>"] for t in types_def]<EOL>names = [t["<STR_LIT:name>"] for t in types_def]<EOL>values = decode_abi(types, s[<NUM_LIT:4>:])<EOL>method.inputs = [{"<STR_LIT:type>": t, "<STR_LIT:name>": n, "<STR_LIT:data>": v} for t, n, v in list(<EOL>zip(types, names, values))]<EOL>return method<EOL><DEDENT>
Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod object matching the provided input stream
f12416:c6:m2
def describe(self):
outputs = "<STR_LIT:U+002CU+0020>".join(["<STR_LIT>" % (o["<STR_LIT:type>"], o["<STR_LIT:name>"]) for o in<EOL>self["<STR_LIT>"]]) if self.get("<STR_LIT>") else "<STR_LIT>"<EOL>inputs = "<STR_LIT:U+002CU+0020>".join(["<STR_LIT>" % (i["<STR_LIT:type>"], i["<STR_LIT:name>"], i["<STR_LIT:data>"]) for i in<EOL>self.inputs]) if self.inputs else "<STR_LIT>"<EOL>return "<STR_LIT>" % (self["<STR_LIT:type>"], self.get("<STR_LIT:name>"), "<STR_LIT>" % inputs<EOL>if inputs else "<STR_LIT>", "<STR_LIT>" % outputs if outputs else "<STR_LIT>")<EOL>
:return: string representation of the methods input decoded with the set abi
f12416:c6:m3
def qrplatba(pdf,<EOL>IBAN, castka=None, mena='<STR_LIT>', splatnost=None, msg=None, KS='<STR_LIT>', VS='<STR_LIT>', SS=None, IBAN2=None,<EOL>w=<NUM_LIT>, x=None, y=None, **payment_more):
if x is None:<EOL><INDENT>x = pdf.get_x()<EOL><DEDENT>if y is None:<EOL><INDENT>y = pdf.get_y()<EOL><DEDENT>qr = '<STR_LIT>' + IBAN<EOL>if IBAN2:<EOL><INDENT>qr += '<STR_LIT>' + IBAN2<EOL><DEDENT>if castka:<EOL><INDENT>qr += '<STR_LIT>'<EOL>try:<EOL><INDENT>qr += '<STR_LIT>' % castka<EOL><DEDENT>except TypeError:<EOL><INDENT>qr += castka<EOL><DEDENT><DEDENT>if mena:<EOL><INDENT>qr += '<STR_LIT>' + mena<EOL><DEDENT>if splatnost:<EOL><INDENT>qr += '<STR_LIT>'<EOL>try:<EOL><INDENT>qr += splatnost<EOL><DEDENT>except TypeError:<EOL><INDENT>qr += date.strftime(splatnost, '<STR_LIT>')<EOL><DEDENT><DEDENT>if msg:<EOL><INDENT>qr += '<STR_LIT>' + msg<EOL><DEDENT>if KS:<EOL><INDENT>qr += '<STR_LIT>' + KS<EOL><DEDENT>if VS:<EOL><INDENT>qr += '<STR_LIT>' + VS<EOL><DEDENT>if SS:<EOL><INDENT>qr += '<STR_LIT>' + SS<EOL><DEDENT>for key in payment_more:<EOL><INDENT>qr += '<STR_LIT>' % key.replace('<STR_LIT:_>', '<STR_LIT:->') + payment_more[key]<EOL><DEDENT>png, pixels = getQRCode(qr)<EOL>module_size = <NUM_LIT:1.0> * w / pixels<EOL>pdf.image(png, x=x + module_size, y=y + module_size, w=w, type='<STR_LIT>')<EOL>os.unlink(png)<EOL>pdf.set_font_size(<NUM_LIT:6>)<EOL>pllbl = '<STR_LIT>'<EOL>pllbl_w = pdf.get_string_width(pllbl)<EOL>pllbl_right = x + pllbl_w + <NUM_LIT:7> * module_size<EOL>square_size = w + <NUM_LIT:2> * module_size<EOL>pdf.line(x, y, x + square_size, y) <EOL>pdf.line(x, y, x, y + square_size) <EOL>pdf.line(x + square_size, y, x + square_size, y + square_size) <EOL>pdf.line(x, y + square_size, x + <NUM_LIT:2> * module_size, y + square_size) <EOL>pdf.line(pllbl_right, y + square_size, x + square_size, y + square_size) <EOL>pdf.set_xy(x + <NUM_LIT:3> * module_size, y + square_size)<EOL>pdf.cell(pllbl_w, h=<NUM_LIT:2>, txt=pllbl)<EOL>
This is the main method which generates the QR platba code. pdf - object from: with PDF(<outputfilename>) as pdf: (we use wfpdf (which is really minor wrapper), we haven't not tested the calling with fpdf directly, but maybe it is easy) IBAN..IBAN2 - ACC, AM, CC, DT, MSG, X-KS, X-VS, X-SS, ALT-ACC attributes of payment w - width [mm] of the generated image (real width is a little bigger thanks to lines and 'QR platba' label) code is printed at current position (if not defined using x,y) current position moves to the end of 'QR platba' label **payment_more - any other payment attributes (key=value will generate *key:value , '_' in key changes to '-')
f12418:m0
def _match(self, request, response):
is_html = '<STR_LIT>' in response.get('<STR_LIT:Content-Type>', '<STR_LIT>')<EOL>if is_html and hasattr(response, '<STR_LIT>'):<EOL><INDENT>correct_path = PATH_MATCHER.match(request.path) is not None<EOL>not_included = self.include_flag not in response.rendered_content<EOL>return correct_path and not_included<EOL><DEDENT>return False<EOL>
Match all requests/responses that satisfy the following conditions: * An Admin App; i.e. the path is something like /admin/some_app/ * The ``include_flag`` is not in the response's content
f12420:c0:m2
def _chosen_css(self):
css = render_to_string(self.css_template, {})<EOL>for sprite in self.chosen_sprites: <EOL><INDENT>css = css.replace(sprite, settings.STATIC_URL + "<STR_LIT>" + sprite)<EOL><DEDENT>return css<EOL>
Read the minified CSS file including STATIC_URL in the references to the sprite images.
f12420:c0:m3
def _chosen_js(self):
return render_to_string(self.js_template, {})<EOL>
Read the minified jquery plugin file.
f12420:c0:m4
def _embed(self, request, response):
if self._match(request, response):<EOL><INDENT>head = render_to_string(<EOL>"<STR_LIT>",<EOL>{"<STR_LIT>": self._chosen_css()}<EOL>)<EOL>body = render_to_string(<EOL>"<STR_LIT>",<EOL>{"<STR_LIT>": self._chosen_js()}<EOL>)<EOL>content = response.rendered_content<EOL>content = content.replace('<STR_LIT>', head)<EOL>content = content.replace('<STR_LIT>', body)<EOL>response.content = content<EOL><DEDENT>return response<EOL>
Embed Chosen.js directly in html of the response.
f12420:c0:m5
def __init__(self, queue_name, redis_connection):
self.redis = redis_connection<EOL>self.__raw_queue_name = queue_name<EOL>self.__should_run = True <EOL>self.log = logging.getLogger("<STR_LIT>" % (__name__, queue_name))<EOL>self.lua_next = self.redis.register_script(resource_string(__name__,<EOL>'<STR_LIT>'))<EOL>
Queues are responsible for both producing and consuming work You must pass in a connected Redis object as well as a string queue_name
f12426:c0:m0
def __len__(self):
return self.redis.llen(self.queue_name)<EOL>
Returns the number of jobs currently sitting in the queue
f12426:c0:m1
def enqueue(self, job):
if job.queue_name():<EOL><INDENT>raise EnqueueError("<STR_LIT>" % job.job_id)<EOL><DEDENT>new_len = self.redis.lpush(self.queue_name, job.serialize())<EOL>job.notify_queued(self)<EOL>return new_len<EOL>
Enqueue a job for later processing, returns the new length of the queue
f12426:c0:m3
def next_job(self, timeout_seconds=None):
if timeout_seconds is not None:<EOL><INDENT>timeout = timeout_seconds<EOL><DEDENT>else:<EOL><INDENT>timeout = BLOCK_SECONDS<EOL><DEDENT>response = self.lua_next(keys=[self.queue_name])<EOL>if not response:<EOL><INDENT>return<EOL><DEDENT>job = Job.from_serialized(response)<EOL>if not job:<EOL><INDENT>self.log.warn("<STR_LIT>", serialized_job)<EOL><DEDENT>return job<EOL>
Retuns the next job in the queue, or None if is nothing there
f12426:c0:m4
def finish(self, job_id):
pass<EOL>
Notify the queue that a worker has completed work on a job_id. This removes the record from the queue as well as the holding area
f12426:c0:m5
def __iter__(self):
while self.__should_run:<EOL><INDENT>job = self.next_job()<EOL>if job is not None:<EOL><INDENT>yield job<EOL><DEDENT><DEDENT>raise StopIteration<EOL>
Generator interface that will block on a queue and return items as they become available
f12426:c0:m6
def empty(self):
self.redis.delete(self.queue_name)<EOL>
Empties the queue, you rarely want this other than for testing
f12426:c0:m7
def notify_queued(self, queue):
self.__queue_name = queue.queue_name<EOL>
To be called by the queue itself when it inserts this job Do not call this yourself
f12427:c0:m4
def serialize(self):
return json.dumps(self.payload)<EOL>
Returns a suitable string representation of a job
f12427:c0:m5
def provider(func=None, *, singleton=False, injector=None):
def decorator(func):<EOL><INDENT>wrapped = _wrap_provider_func(func, {'<STR_LIT>': singleton})<EOL>if injector:<EOL><INDENT>injector.register_provider(wrapped)<EOL><DEDENT>return wrapped<EOL><DEDENT>if func:<EOL><INDENT>return decorator(func)<EOL><DEDENT>return decorator<EOL>
Decorator to mark a function as a provider. Args: singleton (bool): The returned value should be a singleton or shared instance. If False (the default) the provider function will be invoked again for every time it's needed for injection. injector (Injector): If provided, the function is immediately registered as a provider with the injector instance. Example: @diay.provider(singleton=True) def myfunc() -> MyClass: return MyClass(args)
f12439:m1
def inject(*args, **kwargs):
def wrapper(obj):<EOL><INDENT>if inspect.isclass(obj) or callable(obj):<EOL><INDENT>_inject_object(obj, *args, **kwargs)<EOL>return obj<EOL><DEDENT>raise DiayException("<STR_LIT>" % obj)<EOL><DEDENT>return wrapper<EOL>
Mark a class or function for injection, meaning that a DI container knows that it should inject dependencies into it. Normally you won't need this as the injector will inject the required arguments anyway, but it can be used to inject properties into a class without having to specify it in the constructor, or to inject arguments that aren't properly type hinted. Example: @diay.inject('foo', MyClass) class MyOtherClass: pass assert isinstance(injector.get(MyOtherClass).foo, MyClass)
f12439:m3
def register_plugin(self, plugin: Plugin):
if isinstance(plugin, Plugin):<EOL><INDENT>lazy = False<EOL><DEDENT>elif issubclass(plugin, Plugin):<EOL><INDENT>lazy = True<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>' % plugin<EOL>raise DiayException(msg)<EOL><DEDENT>predicate = inspect.isfunction if lazy else inspect.ismethod<EOL>methods = inspect.getmembers(plugin, predicate=predicate)<EOL>for _, method in methods:<EOL><INDENT>if getattr(method, '<STR_LIT>', {}).get('<STR_LIT>'):<EOL><INDENT>if lazy:<EOL><INDENT>self.register_lazy_provider_method(plugin, method)<EOL><DEDENT>else:<EOL><INDENT>self.register_provider(method)<EOL><DEDENT><DEDENT><DEDENT>
Register a plugin.
f12439:c2:m1
def register_provider(self, func):
if '<STR_LIT>' not in getattr(func, '<STR_LIT>', {}):<EOL><INDENT>raise DiayException('<STR_LIT>' % func)<EOL><DEDENT>self.factories[func.__di__['<STR_LIT>']] = func<EOL>
Register a provider function.
f12439:c2:m2
def register_lazy_provider_method(self, cls, method):
if '<STR_LIT>' not in getattr(method, '<STR_LIT>', {}):<EOL><INDENT>raise DiayException('<STR_LIT>' % method)<EOL><DEDENT>@functools.wraps(method)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>return getattr(self.get(cls), method.__name__)(*args, **kwargs)<EOL><DEDENT>self.factories[method.__di__['<STR_LIT>']] = wrapper<EOL>
Register a class method lazily as a provider.
f12439:c2:m3
def set_factory(self, thing: type, value, overwrite=False):
if thing in self.factories and not overwrite:<EOL><INDENT>raise DiayException('<STR_LIT>' % thing)<EOL><DEDENT>self.factories[thing] = value<EOL>
Set the factory for something.
f12439:c2:m4
def set_instance(self, thing: type, value, overwrite=False):
if thing in self.instances and not overwrite:<EOL><INDENT>raise DiayException('<STR_LIT>' % thing)<EOL><DEDENT>self.instances[thing] = value<EOL>
Set an instance of a thing.
f12439:c2:m5
def get(self, thing: type):
if thing in self.instances:<EOL><INDENT>return self.instances[thing]<EOL><DEDENT>if thing in self.factories:<EOL><INDENT>fact = self.factories[thing]<EOL>ret = self.get(fact)<EOL>if hasattr(fact, '<STR_LIT>') and fact.__di__['<STR_LIT>']:<EOL><INDENT>self.instances[thing] = ret<EOL><DEDENT>return ret<EOL><DEDENT>if inspect.isclass(thing):<EOL><INDENT>return self._call_class_init(thing)<EOL><DEDENT>elif callable(thing):<EOL><INDENT>return self.call(thing)<EOL><DEDENT>raise DiayException('<STR_LIT>' % thing)<EOL>
Get an instance of some type.
f12439:c2:m6
def call(self, func, *args, **kwargs):
guessed_kwargs = self._guess_kwargs(func)<EOL>for key, val in guessed_kwargs.items():<EOL><INDENT>kwargs.setdefault(key, val)<EOL><DEDENT>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>except TypeError as exc:<EOL><INDENT>msg = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>) % func<EOL>raise DiayException(msg) from exc<EOL><DEDENT>
Call a function, resolving any type-hinted arguments.
f12439:c2:m7
def provider(self, *args, **kwargs):
kwargs['<STR_LIT>'] = self<EOL>return provider(*args, **kwargs)<EOL>
Convenience decorator, shortcut for @diay.provider(injector=self)
f12439:c2:m10
def parse_config():
env = getenv('<STR_LIT>')<EOL>if env:<EOL><INDENT>logger.info('<STR_LIT>')<EOL>data = json.loads(env)<EOL><DEDENT>else:<EOL><INDENT>data = _parse_file()<EOL><DEDENT>data['<STR_LIT>'] = data.get('<STR_LIT>', '<STR_LIT>')<EOL>data['<STR_LIT>'] = define_services(data.get('<STR_LIT>', []))<EOL>data['<STR_LIT>'] = data.get('<STR_LIT>', '<STR_LIT:default>')<EOL>if data.get('<STR_LIT>'):<EOL><INDENT>data['<STR_LIT>'] = repr(data['<STR_LIT>'])<EOL><DEDENT>return data<EOL>
Parse the configuration and create required services. Note: Either takes the configuration from the environment (a variable named ``FLASH_CONFIG``) or a file at the module root (named ``config.json``). Either way, it will attempt to parse it as JSON, expecting the following format:: { "name": <Project Name>, "services": [ { "name": <Service Name>, <Service Settings> } ] }
f12450:m0
def _parse_file():
file_name = path.join(<EOL>path.abspath(path.dirname(path.dirname(__file__))), '<STR_LIT>'<EOL>)<EOL>logger.info('<STR_LIT>', file_name)<EOL>try:<EOL><INDENT>data = _read_file(file_name)<EOL><DEDENT>except FileNotFoundError:<EOL><INDENT>logger.error('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>exit()<EOL><DEDENT>for service in data.get('<STR_LIT>', []):<EOL><INDENT>for key, val in service.items():<EOL><INDENT>if isinstance(val, str) and re.match(r'<STR_LIT>', val):<EOL><INDENT>env_val = getenv(val[<NUM_LIT:1>:])<EOL>if env_val is None:<EOL><INDENT>logger.warning('<STR_LIT>', val[<NUM_LIT:1>:])<EOL><DEDENT>service[key] = env_val or val<EOL><DEDENT><DEDENT><DEDENT>return data<EOL>
Parse the config from a file. Note: Assumes any value that ``"$LOOKS_LIKE_THIS"`` in a service definition refers to an environment variable, and attempts to get it accordingly.
f12450:m1
def _read_file(file_name):
with open(file_name) as config_file:<EOL><INDENT>data = json.load(config_file)<EOL><DEDENT>return data<EOL>
Read the file content and load it as JSON. Arguments: file_name (:py:class:`str`): The filename. Returns: :py:class:`dict`: The loaded JSON data. Raises: :py:class:`FileNotFoundError`: If the file is not found.
f12450:m2
@app.route('<STR_LIT:/>')<EOL>def home():
return render_template(<EOL>'<STR_LIT>',<EOL>config=CONFIG,<EOL>data=_get_data(),<EOL>title='<STR_LIT>',<EOL>)<EOL>
Home page route.
f12451:m0
@app.route('<STR_LIT>')<EOL>def scratchpad():
return render_template(<EOL>'<STR_LIT>',<EOL>config=dict(<EOL>project_name='<STR_LIT>',<EOL>style=request.args.get('<STR_LIT>', '<STR_LIT:default>'),<EOL>),<EOL>title='<STR_LIT>',<EOL>)<EOL>
Dummy page for styling tests.
f12451:m1
@app.route('<STR_LIT>')<EOL>def services():
return jsonify(_get_data())<EOL>
AJAX route for accessing services.
f12451:m2
def update_service(name, service_map):
if name in service_map:<EOL><INDENT>service = service_map[name]<EOL>data = service.update()<EOL>if not data:<EOL><INDENT>logger.warning('<STR_LIT>', name)<EOL><DEDENT>else:<EOL><INDENT>data['<STR_LIT>'] = service.service_name<EOL>CACHE[name] = dict(data=data, updated=datetime.now())<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>', name)<EOL><DEDENT>if name in CACHE:<EOL><INDENT>return add_time(CACHE[name])<EOL><DEDENT>return {}<EOL>
Get an update from the specified service. Arguments: name (:py:class:`str`): The name of the service. service_map (:py:class:`dict`): A mapping of service names to :py:class:`flash.service.core.Service` instances. Returns: :py:class:`dict`: The updated data.
f12451:m4
def add_time(data):
payload = data['<STR_LIT:data>']<EOL>updated = data['<STR_LIT>'].date()<EOL>if updated == date.today():<EOL><INDENT>payload['<STR_LIT>'] = data['<STR_LIT>'].strftime('<STR_LIT>')<EOL><DEDENT>elif updated >= (date.today() - timedelta(days=<NUM_LIT:1>)):<EOL><INDENT>payload['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>elif updated >= (date.today() - timedelta(days=<NUM_LIT:7>)):<EOL><INDENT>payload['<STR_LIT>'] = updated.strftime('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>payload['<STR_LIT>'] = updated.strftime('<STR_LIT>')<EOL><DEDENT>return payload<EOL>
And a friendly update time to the supplied data. Arguments: data (:py:class:`dict`): The response data and its update time. Returns: :py:class:`dict`: The data with a friendly update time.
f12451:m5
def isvalue(self, sym, val):
tval = self.interp.symtable[sym]<EOL>if isinstance(val, np.ndarray):<EOL><INDENT>assert_allclose(tval, val, rtol=<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>assert(tval == val)<EOL><DEDENT>
assert that a symboltable symbol has a particular value
f12454:c0:m6
def istrue(self, expr):
val = self.interp(expr)<EOL>if isinstance(val, np.ndarray):<EOL><INDENT>val = np.all(val)<EOL><DEDENT>return self.assertTrue(val)<EOL>
assert that an expression evaluates to True
f12454:c0:m8
def isfalse(self, expr):
val = self.interp(expr)<EOL>if isinstance(val, np.ndarray):<EOL><INDENT>val = np.all(val)<EOL><DEDENT>return self.assertFalse(val)<EOL>
assert that an expression evaluates to False
f12454:c0:m9
def get_keywords():
<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>
Get the keywords needed to look up the version information.
f12455:m0
def get_config():
<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>
Create, populate and return the VersioneerConfig() object.
f12455:m1
def register_vcs_handler(vcs, method):
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
Decorator to mark a method as the handler for a particular VCS.
f12455:m2
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>
Call the given command(s).
f12455:m3
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root) <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
f12455:m4
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>
Extract version information from the given file.
f12455:m5
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>
Get version information from git keywords.
f12455:m6
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>] <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out) <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
f12455:m7
def plus_or_dot(pieces):
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
Return a + if we don't already have one, else return a .
f12455:m8
def render_pep440(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
f12455:m9
def render_pep440_pre(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
f12455:m10
def render_pep440_post(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
f12455:m11
def render_pep440_old(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
f12455:m12
def render_git_describe(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f12455:m13
def render_git_describe_long(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f12455:m14
def render(pieces, style):
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>
Render the given version pieces into the requested style.
f12455:m15
def get_versions():
<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>
Get version information or return default if unable to do so.
f12455:m16
def _open(filename, mode='<STR_LIT:r>', buffering=<NUM_LIT:0>):
if mode not in ('<STR_LIT:r>', '<STR_LIT:rb>', '<STR_LIT>'):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if buffering > MAX_OPEN_BUFFER:<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(MAX_OPEN_BUFFER))<EOL><DEDENT>return open(filename, mode, buffering)<EOL>
read only version of open()
f12457:m0
def _type(obj, *varargs, **varkws):
return type(obj).__name__<EOL>
type that prevents varargs and varkws
f12457:m1
def safe_pow(base, exp):
if exp > MAX_EXPONENT:<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(MAX_EXPONENT))<EOL><DEDENT>return base ** exp<EOL>
safe version of pow
f12457:m2
def safe_mult(a, b):
if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN:<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(MAX_STR_LEN))<EOL><DEDENT>return a * b<EOL>
safe version of multiply
f12457:m3
def safe_add(a, b):
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(MAX_STR_LEN))<EOL><DEDENT>return a + b<EOL>
safe version of add
f12457:m4
def safe_lshift(a, b):
if b > MAX_SHIFT:<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(MAX_SHIFT))<EOL><DEDENT>return a << b<EOL>
safe version of lshift
f12457:m5