code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
preprocess_fallback_config() global LIBIGRAPH_FALLBACK_LIBRARIES global LIBIGRAPH_FALLBACK_INCLUDE_DIRS global LIBIGRAPH_FALLBACK_LIBRARY_DIRS print("WARNING: we were not able to detect where igraph is installed on") print("your machine (if it is installed at ...
def use_educated_guess(self)
Tries to guess the proper library names, include and library paths if everything else failed.
3.718936
3.643941
1.020581
options, args, parser = parse_options(args) if options.regex and options.write_changes: print('ERROR: --write-changes cannot be used together with ' '--regex') parser.print_help() return 1 word_regex = options.regex or word_regex_def try: word_regex = ...
def main(*args)
Contains flow control
2.359972
2.348435
1.004912
start = time.time() if data_buffer is None: data_buffer = np.ndarray((Lepton.ROWS, Lepton.COLS, 1), dtype=np.uint16) elif data_buffer.ndim < 2 or data_buffer.shape[0] < Lepton.ROWS or data_buffer.shape[1] < Lepton.COLS or data_buffer.itemsize < 2: raise Exception("Provided input array not...
def capture(self, data_buffer = None, log_time = False, debug_print = False, retry_reset = True)
Capture a frame of data. Captures 80x60 uint16 array of non-normalized (raw 12-bit) data. Returns that frame and a frame_id (which is currently just the sum of all pixels). The Lepton will return multiple, identical frames at a rate of up to ~27 Hz, with unique frames at only ~9 Hz, so the frame_id can hel...
5.095973
4.851629
1.050363
matches = re.match(r'^per([bcdfghjklmnpqrstvwxyz])([a-z])er([aiueo])(.*)$', word) if matches: if matches.group(1) == 'r': return return matches.group(1) + matches.group(2) + 'er' + matches.group(3) + matches.group(4)
def disambiguate(self, word)
Disambiguate Prefix Rule 24 Rule 24 : perCAerV -> per-CAerV where C != 'r'
3.272203
2.348
1.393613
normalizedText = TextNormalizer.normalize_text(text) words = normalizedText.split(' ') stems = [] for word in words: stems.append(self.stem_word(word)) return ' '.join(stems)
def stem(self, text)
Stem a text string to its common stem form.
2.845206
2.909032
0.978059
if self.is_plural(word): return self.stem_plural_word(word) else: return self.stem_singular_word(word)
def stem_word(self, word)
Stem a word to its common stem form.
2.650779
2.61448
1.013884
matches = re.match(r'^(.*)-(.*)$', plural) #translated from PHP conditional check: #if (!isset($words[1]) || !isset($words[2])) if not matches: return plural words = [matches.group(1), matches.group(2)] #malaikat-malaikat-nya -> malaikat malaikat-nya...
def stem_plural_word(self, plural)
Stem a plural word to its common stem form. Asian J. (2007) "Effective Techniques for Indonesian Text Retrieval" page 76-77. @link http://researchbank.rmit.edu.au/eserv/rmit:6312/Asian.pdf
3.948844
3.957586
0.997791
context = Context(word, self.dictionary, self.visitor_provider) context.execute() return context.result
def stem_singular_word(self, word)
Stem a singular word to its common stem form.
12.731057
12.567162
1.013042
#step 1 - 5 self.start_stemming_process() #step 6 if self.dictionary.contains(self.current_word): self.result = self.current_word else: self.result = self.original_word
def execute(self)
Execute stemming process; the result can be retrieved with result
6.804576
5.651514
1.204027
self.restore_prefix() removals = self.removals reversed_removals = reversed(removals) current_word = self.current_word for removal in reversed_removals: if not self.is_suffix_removal(removal): continue if removal.get_removed_part...
def loop_pengembalian_akhiran(self)
ECS Loop Pengembalian Akhiran
4.174821
4.156407
1.00443
for removal in self.removals: #return the word before precoding (the subject of first prefix removal) self.current_word = removal.get_subject() break for removal in self.removals: if removal.get_affix_type() == 'DP': self.removals...
def restore_prefix(self)
Restore prefix to proceed with ECS loop pengembalian akhiran
10.143454
10.5531
0.961182
words = text.split(' ') stopped_words = [word for word in words if not self.dictionary.contains(word)] return ' '.join(stopped_words)
def remove(self, text)
Remove stop words.
4.220148
3.732316
1.130705
words = self.get_words(isDev) dictionary = ArrayDictionary(words) stemmer = Stemmer(dictionary) resultCache = ArrayCache() cachedStemmer = CachedStemmer(resultCache, stemmer) return cachedStemmer
def create_stemmer(self, isDev=False)
Returns Stemmer instance
5.416007
5.2123
1.039082
if not word or word.strip() == '': return self.words[word]=word
def add(self, word)
Add a word to the dictionary
7.758393
7.37507
1.051976
@wraps(f) def check(v): t = f(v) if not t: raise ValueError return v return check
def truth(f)
Convenience decorator to convert truth functions into validators. >>> @truth ... def isdir(v): ... return os.path.isdir(v) >>> validate = Schema(isdir) >>> validate('/') '/' >>> with raises(MultipleInvalid, 'not a valid value'): ... validate('/notaval...
4.816555
5.336923
0.902497
if isinstance(v, basestring): v = v.lower() if v in ('1', 'true', 'yes', 'on', 'enable'): return True if v in ('0', 'false', 'no', 'off', 'disable'): return False raise ValueError return bool(v)
def Boolean(v)
Convert human-readable boolean values to a bool. Accepted values are 1, true, yes, on, enable, and their negatives. Non-string values are cast to bool. >>> validate = Schema(Boolean()) >>> validate(True) True >>> validate("1") True >>> validate("0") False >>> with raises(Multip...
1.787644
1.997151
0.895097
try: if not v or "@" not in v: raise EmailInvalid("Invalid Email") user_part, domain_part = v.rsplit('@', 1) if not (USER_REGEX.match(user_part) and DOMAIN_REGEX.match(domain_part)): raise EmailInvalid("Invalid Email") return v except: raise ...
def Email(v)
Verify that the value is an Email or not. >>> s = Schema(Email()) >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a@.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a@.com") >>>...
2.913089
3.817719
0.763044
try: parsed_url = _url_validation(v) if "." not in parsed_url.netloc: raise UrlInvalid("must have a domain name in URL") return v except: raise ValueError
def FqdnUrl(v)
Verify that the value is a Fully qualified domain name URL. >>> s = Schema(FqdnUrl()) >>> with raises(MultipleInvalid, 'expected a Fully qualified domain name URL'): ... s("http://localhost/") >>> s('http://w3.org') 'http://w3.org'
6.956482
10.200995
0.681942
try: if v: v = str(v) return os.path.isfile(v) else: raise FileInvalid('Not a file') except TypeError: raise FileInvalid('Not a file')
def IsFile(v)
Verify the file exists. >>> os.path.basename(IsFile()(__file__)).startswith('validators.py') True >>> with raises(FileInvalid, 'not a file'): ... IsFile()("random_filename_goes_here.py") >>> with raises(FileInvalid, 'Not a file'): ... IsFile()(None)
3.450359
3.941011
0.875501
try: if v: v = str(v) return os.path.isdir(v) else: raise DirInvalid("Not a directory") except TypeError: raise DirInvalid("Not a directory")
def IsDir(v)
Verify the directory exists. >>> IsDir()('/') '/' >>> with raises(DirInvalid, 'Not a directory'): ... IsDir()(None)
3.413796
3.645874
0.936345
try: if v: v = str(v) return os.path.exists(v) else: raise PathInvalid("Not a Path") except TypeError: raise PathInvalid("Not a Path")
def PathExists(v)
Verify the path exists, regardless of its type. >>> os.path.basename(PathExists()(__file__)).startswith('validators.py') True >>> with raises(Invalid, 'path does not exist'): ... PathExists()("random_filename_goes_here.py") >>> with raises(PathInvalid, 'Not a Path'): ... PathExists()(None)
3.487366
4.074651
0.855869
try: decimal_num = Decimal(number) except InvalidOperation: raise Invalid(self.msg or 'Value must be a number enclosed with string') return (len(decimal_num.as_tuple().digits), -(decimal_num.as_tuple().exponent), decimal_num)
def _get_precision_scale(self, number)
:param number: :return: tuple(precision, scale, decimal_number)
6.816562
5.520791
1.234708
if isinstance(validation_error, MultipleInvalid): return '\n'.join(sorted( humanize_error(data, sub_error, max_sub_error_length) for sub_error in validation_error.errors )) else: offending_item_summary = repr(_nested_getitem(data, validation_error.path)) ...
def humanize_error(data, validation_error, max_sub_error_length=MAX_VALIDATION_ERROR_ITEM_LENGTH)
Provide a more helpful + complete validation error message than that provided automatically Invalid and MultipleInvalid do not include the offending value in error messages, and MultipleInvalid.__str__ only provides the first error.
2.455394
2.201335
1.115411
if inspect.isclass(schema): def validate_instance(path, data): if isinstance(data, schema): return data else: msg = 'expected %s' % schema.__name__ raise er.TypeInvalid(msg, path) return validate_instance if callable(...
def _compile_scalar(schema)
A scalar value. The schema can either be a value or a type. >>> _compile_scalar(int)([], 1) 1 >>> with raises(er.Invalid, 'expected float'): ... _compile_scalar(float)([], '1') Callables have >>> _compile_scalar(lambda v: float(v))([], '1') 1.0 As a convenience, ValueError's ar...
2.999756
2.940012
1.020321
'''return sort function of mappings''' def is_extra(key_): return key_ is Extra def is_remove(key_): return isinstance(key_, Remove) def is_marker(key_): return isinstance(key_, Marker) def is_type(key_): return inspect.isclass(key_) def is_callable(key_): ...
def _compile_itemsort()
return sort function of mappings
6.943422
6.640804
1.04557
d = {} try: d = vars(obj) except TypeError: # maybe we have named tuple here? if hasattr(obj, '_asdict'): d = obj._asdict() for item in iteritems(d): yield item try: slots = obj.__slots__ except AttributeError: pass else: ...
def _iterate_object(obj)
Return iterator over object attributes. Respect objects with defined __slots__.
3.282706
2.927063
1.121502
if cls and not issubclass(cls, er.Invalid): raise er.SchemaError("message can only use subclases of Invalid as custom class") def decorator(f): @wraps(f) def check(msg=None, clsoverride=None): @wraps(f) def wrapper(*args, **kwargs): try: ...
def message(default=None, cls=None)
Convenience decorator to allow functions to provide a message. Set a default message: >>> @message('not an integer') ... def isint(v): ... return int(v) >>> validate = Schema(isint()) >>> with raises(er.MultipleInvalid, 'not an integer'): ... validate('a') ...
4.99155
4.867865
1.025409
if sys.version_info >= (3, 0): arg_count = func.__code__.co_argcount arg_names = func.__code__.co_varnames[:arg_count] else: arg_count = func.func_code.co_argcount arg_names = func.func_code.co_varnames[:arg_count] arg_value_list = list(args) arguments = dict((arg_n...
def _args_to_dict(func, args)
Returns argument names as values as key-value pairs.
1.832911
1.734242
1.056894
ret = args_dict.copy() ret.update(kwargs_dict) return ret
def _merge_args_with_kwargs(args_dict, kwargs_dict)
Merge args with kwargs.
3.502342
3.121745
1.121918
RETURNS_KEY = '__return__' def validate_schema_decorator(func): returns_defined = False returns = None schema_args_dict = _args_to_dict(func, a) schema_arguments = _merge_args_with_kwargs(schema_args_dict, kw) if RETURNS_KEY in schema_arguments: retur...
def validate(*a, **kw)
Decorator for validating arguments of a function against a given schema. Set restrictions for arguments: >>> @validate(arg1=int, arg2=int) ... def foo(arg1, arg2): ... return arg1 * arg2 Set restriction for returned value: >>> @validate(arg=int, __return__=int) ... ...
2.739594
2.761383
0.992109
def value_to_schema_type(value): if isinstance(value, dict): if len(value) == 0: return dict return {k: value_to_schema_type(v) for k, v in iteritems(value)} if isinstance(value, list): i...
def infer(cls, data, **kwargs)
Create a Schema from concrete data (e.g. an API response). For example, this will take a dict like: { 'foo': 1, 'bar': { 'a': True, 'b': False }, 'baz': ['purple', 'monkey', 'dishwasher'] } And return a Sc...
2.147039
2.015513
1.065257
base_validate = self._compile_mapping( schema, invalid_msg='object value') def validate_object(path, data): if schema.cls is not UNDEFINED and not isinstance(data, schema.cls): raise er.ObjectInvalid('expected a {0!r}'.format(schema.cls), path) ...
def _compile_object(self, schema)
Validate an object. Has the same behavior as dictionary validator but work with object attributes. For example: >>> class Structure(object): ... def __init__(self, one=None, three=None): ... self.one = one ... self.three = th...
6.886664
6.855421
1.004557
_compiled = [self._compile(s) for s in schema] seq_type_name = seq_type.__name__ def validate_sequence(path, data): if not isinstance(data, seq_type): raise er.SequenceTypeInvalid('expected a %s' % seq_type_name, path) # Empty seq schema, allow ...
def _compile_sequence(self, schema, seq_type)
Validate a sequence type. This is a sequence of valid values or validators tried in order. >>> validator = Schema(['one', 'two', int]) >>> validator(['one']) ['one'] >>> with raises(er.MultipleInvalid, 'expected int @ data[0]'): ... validator([3.5]) >>> valida...
3.882854
3.782152
1.026625
type_ = type(schema) type_name = type_.__name__ def validate_set(path, data): if not isinstance(data, type_): raise er.Invalid('expected a %s' % type_name, path) _compiled = [self._compile(s) for s in schema] errors = [] ...
def _compile_set(self, schema)
Validate a set. A set is an unordered collection of unique elements. >>> validator = Schema({int}) >>> validator(set([42])) == set([42]) True >>> with raises(er.Invalid, 'expected a set'): ... validator(42) >>> with raises(er.MultipleInvalid, 'invalid value in...
3.017552
3.043763
0.991389
assert type(self.schema) == dict and type(schema) == dict, 'Both schemas must be dictionary-based' result = self.schema.copy() # returns the key that may have been passed as arugment to Marker constructor def key_literal(key): return (key.schema if isinstance(key,...
def extend(self, schema, required=None, extra=None)
Create a new `Schema` by merging this and the provided `schema`. Neither this `Schema` nor the provided `schema` are modified. The resulting `Schema` inherits the `required` and `extra` parameters of this, unless overridden. Both schemas must be dictionary-based. :param schema...
4.320275
4.20325
1.027842
if not instance.name: instance.name = filename # set original filename date = timezone.now().date() filename = '{name}.{ext}'.format(name=uuid4().hex, ext=filename.split('.')[-1]) return os.path.join('post_office_attachments', str(date.year), ...
def get_upload_path(instance, filename)
Overriding to store the original filename
3.586185
3.268932
1.097051
if isinstance(value, six.string_types): return value else: return ', '.join(map(lambda s: s.strip(), value))
def get_prep_value(self, value)
We need to accomodate queries where a single email, or list of email addresses is supplied as arguments. For example: - Email.objects.filter(to='mail@example.com') - Email.objects.filter(to=['one@example.com', 'two@example.com'])
3.710393
3.914216
0.947928
priority = parse_priority(priority) status = None if priority == PRIORITY.now else STATUS.queued if recipients is None: recipients = [] if cc is None: cc = [] if bcc is None: bcc = [] if context is None: context = '' # If email is to be rendered during ...
def create(sender, recipients=None, cc=None, bcc=None, subject='', message='', html_message='', context=None, scheduled_time=None, headers=None, template=None, priority=None, render_on_delivery=False, commit=True, backend='')
Creates an email from supplied keyword arguments. If template is specified, email subject and content will be rendered during delivery.
2.176484
2.143012
1.015619
emails = [] for kwargs in kwargs_list: emails.append(send(commit=False, **kwargs)) Email.objects.bulk_create(emails)
def send_many(kwargs_list)
Similar to mail.send(), but this function accepts a list of kwargs. Internally, it uses Django's bulk_create command for efficiency reasons. Currently send_many() can't be used to send emails with priority = 'now'.
3.954088
3.49403
1.13167
return Email.objects.filter(status=STATUS.queued) \ .select_related('template') \ .filter(Q(scheduled_time__lte=now()) | Q(scheduled_time=None)) \ .order_by(*get_sending_order()).prefetch_related('attachments')[:get_batch_size()]
def get_queued()
Returns a list of emails that should be sent: - Status is queued - Has scheduled_time lower than the current time or None
5.05855
4.250048
1.190234
queued_emails = get_queued() total_sent, total_failed = 0, 0 total_email = len(queued_emails) logger.info('Started sending %s emails with %s processes.' % (total_email, processes)) if log_level is None: log_level = get_log_level() if queued_emails: # Don'...
def send_queued(processes=1, log_level=None)
Sends out all queued mails that has scheduled_time less than now or None
2.494566
2.466054
1.011562
from .mail import create from .utils import create_attachments if not email_messages: return for email_message in email_messages: subject = email_message.subject from_email = email_message.from_email message = email_message.body ...
def send_messages(self, email_messages)
Queue one or more EmailMessage objects and returns the number of email messages sent.
2.477036
2.524985
0.98101
lock_pid = self.get_lock_pid() # If we're unable to get lock_pid if lock_pid is None: return False # this is our process if self._pid == lock_pid: return True # it is/was another process # see if it is running try: ...
def valid_lock(self)
See if the lock exists and is left over from an old process.
4.39631
3.937862
1.11642
pid_file = os.open(self.pid_filename, os.O_CREAT | os.O_EXCL | os.O_RDWR) os.write(pid_file, str(os.getpid()).encode('utf-8')) os.close(pid_file) if hasattr(os, 'symlink') and platform.system() != 'Windows': os.symlink(self.pid_filename, self.lock_filename) ...
def acquire(self)
Create a pid filename and create a symlink (the actual lock file) across platforms that points to it. Symlink is used because it's an atomic operation across platforms.
2.677228
2.254012
1.187761
if self.lock_filename != self.pid_filename: try: os.unlink(self.lock_filename) except OSError: pass try: os.remove(self.pid_filename) except OSError: pass
def release(self)
Try to delete the lock files. Doesn't matter if we fail
2.976149
2.414966
1.232377
value = force_text(value) recipient = value if '<' and '>' in value: start = value.find('<') + 1 end = value.find('>') if start < end: recipient = value[start:end] validate_email(recipient)
def validate_email_with_name(value)
Validate email address. Both "Recipient Name <email@example.com>" and "email@example.com" are valid.
3.423251
3.473785
0.985453
if not isinstance(value, (tuple, list)): raise ValidationError('Email list must be a list/tuple.') for email in value: try: validate_email_with_name(email) except ValidationError: raise ValidationError('Invalid email: %s' % email, code='invalid')
def validate_comma_separated_emails(value)
Validate every email address in a comma separated list of emails.
2.850492
2.760623
1.032554
try: Template(source) except (TemplateSyntaxError, TemplateDoesNotExist) as err: raise ValidationError(text_type(err))
def validate_template_syntax(source)
Basic Django Template syntax validation. This allows for robuster template authoring.
4.357803
4.249658
1.025448
backends = get_config().get('BACKENDS', {}) if backends: return backends # Try to get backend settings from old style # POST_OFFICE = { # 'EMAIL_BACKEND': 'mybackend' # } backend = get_config().get('EMAIL_BACKEND') if backend: warnings.warn('Please use the new ...
def get_available_backends()
Returns a dictionary of defined backend classes. For example: { 'default': 'django.core.mail.backends.smtp.EmailBackend', 'locmem': 'django.core.mail.backends.locmem.EmailBackend', }
3.819974
3.642339
1.048769
subject = force_text(subject) status = None if priority == PRIORITY.now else STATUS.queued emails = [] for address in recipient_list: emails.append( Email.objects.create( from_email=from_email, to=address, subject=subject, message=message, html_m...
def send_mail(subject, message, from_email, recipient_list, html_message='', scheduled_time=None, headers=None, priority=PRIORITY.medium)
Add a new message to the mail queue. This is a replacement for Django's ``send_mail`` core email method.
2.738866
2.836316
0.965642
use_cache = getattr(settings, 'POST_OFFICE_CACHE', True) if use_cache: use_cache = getattr(settings, 'POST_OFFICE_TEMPLATE_CACHE', True) if not use_cache: return EmailTemplate.objects.get(name=name, language=language) else: composite_name = '%s:%s' % (name, language) ...
def get_email_template(name, language='')
Function that returns an email template instance, from cache or DB.
2.127784
2.042571
1.041718
attachments = [] for filename, filedata in attachment_files.items(): if isinstance(filedata, dict): content = filedata.get('file', None) mimetype = filedata.get('mimetype', None) headers = filedata.get('headers', None) else: content = filedat...
def create_attachments(attachment_files)
Create Attachment instances from files attachment_files is a dict of: * Key - the filename to be used for the attachment. * Value - file-like object, or a filename to open OR a dict of {'file': file-like-object, 'mimetype': string} Returns a list of Attachment objects
2.268952
2.206722
1.028201
if isinstance(emails, string_types): emails = [emails] elif emails is None: emails = [] for email in emails: try: validate_email_with_name(email) except ValidationError: raise ValidationError('%s is not a valid email address' % email) retur...
def parse_emails(emails)
A function that returns a list of valid email addresses. This function will also convert a single email address into a list of email addresses. None value is also converted into an empty list.
2.570266
2.703204
0.950822
return int(re.match(r'^(\D+)(\d+)$', self.__class__.__name__).group(2))
def VERSION(self)
TAN mechanism version
6.190282
5.454175
1.134962
if isinstance(data, bytes): data = self.explode_segments(data) message = SegmentSequence() for segment in data: seg = self.parse_segment(segment) message.segments.append(seg) return message
def parse_message(self, data: bytes) -> SegmentSequence
Takes a FinTS 3.0 message as byte array, and returns a parsed segment sequence
3.457809
3.193034
1.082923
if isinstance(message, FinTS3Segment): message = SegmentSequence([message]) if isinstance(message, (list, tuple, Iterable)): message = SegmentSequence(list(message)) result = [] for segment in message.segments: result.append(self.serialize_s...
def serialize_message(self, message: SegmentSequence) -> bytes
Serialize a message (as SegmentSequence, list of FinTS3Segment, or FinTS3Segment) into a byte array
4.593494
2.790938
1.64586
# Inspired by Andreas Schiermeier # https://git.ccc-ffm.de/?p=smartkram.git;a=blob_plain;f=chiptan/flicker/flicker.sh;h # =7066293b4e790c2c4c1f6cbdab703ed9976ffe1f;hb=refs/heads/master code = parse(code).render() data = swap_bytes(code) high = '\033[48;05;15m' low = '\033[48;05;0m' ...
def terminal_flicker_unix(code, field_width=3, space_width=3, height=1, clear=False, wait=0.05)
Re-encodes a flicker code and prints it on a unix terminal. :param code: Challenge value :param field_width: Width of fields in characters (default: 3). :param space_width: Width of spaces in characters (default: 3). :param height: Height of fields in characters (default: 1). :param clear: Clear te...
3.786649
3.86853
0.978834
found_something = False if query is None: query = [] elif isinstance(query, str) or not isinstance(query, (list, tuple, Iterable)): query = [query] if version is None: version = [] elif not isinstance(version, (list, tuple, Iterable)...
def find_segments(self, query=None, version=None, callback=None, recurse=True, throw=False)
Yields an iterable of all matching segments. :param query: Either a str or class specifying a segment type (such as 'HNHBK', or :class:`~fints.segments.message.HNHBK3`), or a list or tuple of strings or classes. If a list/tuple is specified, segments returning any matching type will be ret...
3.010735
2.455861
1.225938
for m in self.find_segments(*args, **kwargs): return m return None
def find_segment_first(self, *args, **kwargs)
Finds the first matching segment. Same parameters as find_segments(), but only returns the first match, or None if no match is found.
6.024172
3.64086
1.654601
# FIXME Test retval = None for s in self.find_segments(query=query, version=version, callback=callback, recurse=recurse): if not retval or s.header.version > retval.header.version: retval = s if retval is None: return default r...
def find_segment_highest_version(self, query=None, version=None, callback=None, recurse=True, default=None)
Finds the highest matching segment. Same parameters as find_segments(), but returns the match with the highest version, or default if no match is found.
3.330172
3.13438
1.062466
import sys stream = stream or sys.stdout stream.write( ((prefix + level * indent) if first_level_indent else "") + "{}.{}(".format(self.__class__.__module__, self.__class__.__name__) + first_line_suffix + "\n" ) for name, ...
def print_nested(self, stream=None, level=0, indent=" ", prefix="", first_level_indent=True, trailer="", print_doc=True, first_line_suffix="")
Structured nested print of the object to the given stream. The print-out is eval()able to reconstruct the object.
2.550061
2.518393
1.012575
version, data = decompress_datablob(DATA_BLOB_MAGIC_RETRY, blob) if version == 1: for clazz in cls._all_subclasses(): if clazz.__name__ == data["_class_name"]: return clazz._from_data_v1(data) raise Exception("Invalid data blob data or v...
def from_data(cls, blob)
Restore an object instance from a compressed datablob. Returns an instance of a concrete subclass.
7.395569
7.064348
1.046886
data = self._deconstruct_v1(including_private=including_private) return compress_datablob(DATA_BLOB_MAGIC, 1, data)
def deconstruct(self, including_private: bool=False) -> bytes
Return state of this FinTSClient instance as an opaque datablob. You should not use this object after calling this method. Information about the connection is implicitly retrieved from the bank and cached in the FinTSClient. This includes: system identifier, bank parameter data, user pa...
10.357206
8.386257
1.235021
retval = { 'bank': {}, 'accounts': [], 'auth': {}, } if self.bpa: retval['bank']['name'] = self.bpa.bank_name if self.bpd.segments: retval['bank']['supported_operations'] = { op: any(self.bpd.find_segmen...
def get_information(self)
Return information about the connected bank. Note: Can only be filled after the first communication with the bank. If in doubt, use a construction like:: f = FinTS3Client(...) with f: info = f.get_information() Returns a nested dictionary:: ...
3.240331
2.477061
1.308135
with self._get_dialog() as dialog: response = dialog.send(HKSPA1()) self.accounts = [] for seg in response.find_segments(HISPA1, throw=True): self.accounts.extend(seg.accounts) return [a for a in [acc.as_sepa_account() for acc in self.accou...
def get_sepa_accounts(self)
Returns a list of SEPA accounts :return: List of SEPAAccount objects.
10.134074
9.99546
1.013868
responses = [] touchdown_counter = 1 touchdown = None while touchdown or touchdown_counter == 1: seg = segment_factory(touchdown) rm = dialog.send(seg) for resp in rm.response_segments(seg, *args, **kwargs): responses.append...
def _fetch_with_touchdowns(self, dialog, segment_factory, *args, **kwargs)
Execute a sequence of fetch commands on dialog. segment_factory must be a callable with one argument touchdown. Will be None for the first call and contains the institute's touchdown point on subsequent calls. segment_factory must return a command segment. Extra arguments will be passed ...
5.152574
4.474897
1.151439
return_parameter_segment = kwargs.get("return_parameter_segment", False) parameter_segment_name = "{}I{}S".format(segment_classes[0].TYPE[0], segment_classes[0].TYPE[2:]) version_map = dict((clazz.VERSION, clazz) for clazz in segment_classes) max_version = self.bpd.find_segment...
def _find_highest_supported_command(self, *segment_classes, **kwargs)
Search the BPD for the highest supported version of a segment.
4.177713
3.73782
1.117687
with self._get_dialog() as dialog: hkkaz = self._find_highest_supported_command(HKKAZ5, HKKAZ6, HKKAZ7) logger.info('Start fetching from {} to {}'.format(start_date, end_date)) responses = self._fetch_with_touchdowns( dialog, lambda ...
def get_transactions(self, account: SEPAAccount, start_date: datetime.date = None, end_date: datetime.date = None)
Fetches the list of transactions of a bank account in a certain timeframe. :param account: SEPA :param start_date: First day to fetch :param end_date: Last day to fetch :return: A list of mt940.models.Transaction objects
7.669596
7.532885
1.018149
with self._get_dialog() as dialog: hkcaz = self._find_highest_supported_command(HKCAZ1) logger.info('Start fetching from {} to {}'.format(start_date, end_date)) responses = self._fetch_with_touchdowns( dialog, lambda touchdown: hkcaz...
def get_transactions_xml(self, account: SEPAAccount, start_date: datetime.date = None, end_date: datetime.date = None) -> list
Fetches the list of transactions of a bank account in a certain timeframe as camt.052.001.02 XML files. :param account: SEPA :param start_date: First day to fetch :param end_date: Last day to fetch :return: A list of bytestrings containing XML documents
6.943066
6.612391
1.050008
with self._get_dialog() as dialog: hksal = self._find_highest_supported_command(HKSAL5, HKSAL6, HKSAL7) seg = hksal( account=hksal._fields['account'].type.from_sepa_account(account), all_accounts=False, ) response = dial...
def get_balance(self, account: SEPAAccount)
Fetches an accounts current balance. :param account: SEPA account to fetch the balance :return: A mt940.models.Balance object
14.718469
11.435843
1.287047
# init dialog with self._get_dialog() as dialog: hkwpd = self._find_highest_supported_command(HKWPD5, HKWPD6) responses = self._fetch_with_touchdowns( dialog, lambda touchdown: hkwpd( account=hkwpd._fields['account'].t...
def get_holdings(self, account: SEPAAccount)
Retrieve holdings of an account. :param account: SEPAAccount to retrieve holdings for. :return: List of Holding objects
7.741447
7.915691
0.977988
config = { "name": account_name, "IBAN": account.iban, "BIC": account.bic, "batch": False, "currency": "EUR", } sepa = SepaTransfer(config, 'pain.001.001.03') payment = { "name": recipient_name, ...
def simple_sepa_transfer(self, account: SEPAAccount, iban: str, bic: str, recipient_name: str, amount: Decimal, account_name: str, reason: str, endtoend_id='NOTPROVIDED')
Simple SEPA transfer. :param account: SEPAAccount to start the transfer from. :param iban: Recipient's IBAN :param bic: Recipient's BIC :param recipient_name: Recipient name :param amount: Amount as a ``Decimal`` :param account_name: Sender account name :param re...
2.72134
3.015016
0.902596
with self._get_dialog() as dialog: if multiple: command_class = HKCCM1 else: command_class = HKCCS1 hiccxs, hkccx = self._find_highest_supported_command( command_class, return_parameter_segment=True ...
def sepa_transfer(self, account: SEPAAccount, pain_message: str, multiple=False, control_sum=None, currency='EUR', book_as_single=False, pain_descriptor='urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')
Custom SEPA transfer. :param account: SEPAAccount to send the transfer from. :param pain_message: SEPA PAIN message containing the transfer details. :param multiple: Whether this message contains multiple transfers. :param control_sum: Sum of all transfers (required if there are multipl...
5.640389
5.638278
1.000375
with self._get_dialog() as dialog: if multiple: if cor1: command_candidates = (HKDMC1, ) else: command_candidates = (HKDME1, HKDME2) else: if cor1: command_candidates = (...
def sepa_debit(self, account: SEPAAccount, pain_message: str, multiple=False, cor1=False, control_sum=None, currency='EUR', book_as_single=False, pain_descriptor='urn:iso:std:iso:20022:tech:xsd:pain.008.003.01')
Custom SEPA debit. :param account: SEPAAccount to send the debit from. :param pain_message: SEPA PAIN message containing the debit details. :param multiple: Whether this message contains multiple debits. :param cor1: Whether to use COR1 debit (lead time reduced to 1 day) :param ...
5.038537
4.972063
1.013369
self.product_name = product_name self.product_version = product_version
def set_product(self, product_name, product_version)
Set the product name and version that is transmitted as part of our identification According to 'FinTS Financial Transaction Services, Schnittstellenspezifikation, Formals', version 3.0, section C.3.1.3, you should fill this with useful information about the end-user product, *NOT* the ...
2.824757
2.36498
1.194411
data = { "_class_name": self.__class__.__name__, "version": 1, "segments_bin": SegmentSequence([self.command_seg, self.tan_request]).render_bytes(), "resume_method": self.resume_method, "tan_request_structured": self.tan_request_structured, ...
def get_data(self) -> bytes
Return a compressed datablob representing this object. To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`.
12.992256
10.071066
1.290058
with self._get_dialog() as dialog: tan_seg = self._get_tan_segment(challenge.command_seg, '2', challenge.tan_request) self._pending_tan = tan response = dialog.send(tan_seg) resume_func = getattr(self, challenge.resume_method) return resume...
def send_tan(self, challenge: NeedTANResponse, tan: str)
Sends a TAN to confirm a pending operation. :param challenge: NeedTANResponse to respond to :param tan: TAN value :return: Currently no response
8.343554
7.585548
1.099928
retval = OrderedDict() for version in sorted(IMPLEMENTED_HKTAN_VERSIONS.keys()): for seg in self.bpd.find_segments('HITANS', version): for parameter in seg.parameter.twostep_parameters: if parameter.security_function in self.allowed_security_fun...
def get_tan_mechanisms(self)
Get the available TAN mechanisms. Note: Only checks for HITANS versions listed in IMPLEMENTED_HKTAN_VERSIONS. :return: Dictionary of security_function: TwoStepParameters objects.
14.124832
4.65875
3.031893
with self._get_dialog() as dialog: hktab = self._find_highest_supported_command(HKTAB4, HKTAB5) seg = hktab( tan_media_type = media_type, tan_media_class = str(media_class), ) response = dialog.send(seg) for...
def get_tan_media(self, media_type = TANMediaType2.ALL, media_class = TANMediaClass4.ALL)
Get information about TAN lists/generators. Returns tuple of fints.formals.TANUsageOption and a list of fints.formals.TANMedia4 or fints.formals.TANMedia5 objects.
11.07688
8.842294
1.252716
addr = [] for _ in range(segments): sub = ''.join(random.choice(charset) for _ in range(segment_length)) addr.append(sub) return delimiter.join(addr)
def _generate_MAC(segments=6, segment_length=2, delimiter=":", charset="0123456789abcdef")
generate a non-guaranteed-unique mac address
2.551446
2.292434
1.112986
if self.program: self.program.start() while self.keep_listening: for interface in self.interfaces: packet = interface.recv(self.mac_addr if not self.promiscuous else "00:00:00:00:00:00") if packet: self.recv(packet, int...
def run(self)
runloop that gets triggered by node.start() reads new packets off the link and feeds them to recv()
3.95715
3.403099
1.162808
# the packet is piped into the first filter, then the result of that into the second filter, etc. for f in self.filters: if not packet: break packet = f.tr(packet, interface) if packet: # if the packet wasn't dropped by a filter, log t...
def recv(self, packet, interface)
run incoming packet through the filters, then place it in its inq
7.928884
5.916868
1.340048
interfaces = interfaces or self.interfaces # default to all interfaces interfaces = interfaces if hasattr(interfaces, '__iter__') else [interfaces] for interface in interfaces: for f in self.filters: packet = f.tx(packet, interface) # run outgoing packet t...
def send(self, packet, interfaces=None)
write packet to given interfaces, default is broadcast to all interfaces
6.059552
6.131237
0.988308
items = [] for value in iterable: items.append(value) if len(items) == chunk_size: yield items items = [] if items: yield items
def chunk(iterable, chunk_size=20)
chunk an iterable [1,2,3,4,5,6,7,8] -> ([1,2,3], [4,5,6], [7,8])
2.07547
1.937797
1.071046
string_pattern = pattern invert_search = inverse class DefinedStringFilter(cls): pattern = string_pattern inverse = invert_search return DefinedStringFilter
def match(cls, pattern, inverse=False)
Factory method to create a StringFilter which filters with the given pattern.
8.202148
6.408288
1.279928
process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell) output = process.stdout.read().decode().strip().split('\n') if verbose: # return full output including empty lines return output return [line for line in output if line.strip()]
def run_cmd(command, verbose=True, shell='/bin/bash')
internal helper function to run shell commands and get output
3.204022
3.238118
0.98947
try: try: buffer = StringIO() sys.stdout = buffer exec(cmd) sys.stdout = sys.__stdout__ out = buffer.getvalue() except Exception as error: out = error out = str(out).strip() if len(out) < 1: tr...
def run_python(cmd, timeout=60)
interactively interpret recieved python code
3.31173
3.145039
1.053001
retcode = None try: p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, executable='/bin/bash') continue_running = True except Exception as e: yield("Failed: %s" % e) continue_running = False while continue_running: try: line = p.stdout.readli...
def run_shell(cmd, timeout=60, verbose=False)
run a shell command and return the output, verbose enables live command output via yield
4.227278
4.09566
1.032136
mac_version = str(platform.mac_ver()[0]).strip() # e.g. 10.11.2 if mac_version: return 'OS X %s' % mac_version return platform.platform().strip()
def get_platform()
get Mac OS X version or kernel version if mac version is not found
3.723196
3.270957
1.138259
while self.keep_listening: for interface in self.node.interfaces: try: self.recv(self.node.inq[interface].get(timeout=0), interface) except Empty: sleep(0.01)
def run(self)
runloop that reads packets off the node's incoming packet buffer (node.inq)
6.494596
4.483723
1.448483
for attachment in attachments or []: filename = attachment.strip() try: result = run_cmd('uuencode %s %s | mailx -s "%s" %s' % (filename, filename, subject, to))[0] return "Sending email From: %s; To: %s; Subject: %s; Attachment: %s (%s)" % (_from, to, subject, filename,...
def email(to='medusa@sweeting.me', _from=default_from, subject='BOT MSG', message="Info email", attachments=None)
function to send mail to a specified address with the given attachments
3.193149
3.205273
0.996218
print("%s %s" % (str(self).ljust(8), " ".join([str(x) for x in args])))
def log(self, *args)
stdout and stderr for the link
3.851903
4.155712
0.926894
self.keep_listening = False # if threaded, kill threads before going down if hasattr(self, 'join'): self.join() self.log("Went down.") return True
def stop(self)
all links also need stop() to stop their runloops
10.871142
9.704178
1.120254
# recv on the broadcast address "00:..:00" will give you all packets (for promiscuous mode) if self.keep_listening: try: return self.inq[str(mac_addr)].get(timeout=timeout) except Empty: return "" else: self.log("is dow...
def recv(self, mac_addr=broadcast_addr, timeout=0)
read packet off the recv queue for a given address, optional timeout to block and wait for packet
9.556841
8.92256
1.071087
if self.keep_listening: if mac_addr == self.broadcast_addr: for addr, recv_queue in self.inq.items(): recv_queue.put(packet) else: self.inq[mac_addr].put(packet) self.inq[self.broadcast_addr].put(packet) ...
def send(self, packet, mac_addr=broadcast_addr)
place sent packets directly into the reciever's queues (as if they are connected by wire)
3.414311
3.130025
1.090826
self.send_socket = socket(AF_INET, SOCK_DGRAM) self.send_socket.setblocking(0) self.send_socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) self.recv_socket = socket(AF_INET, SOCK_DGRAM) self.recv_socket.setblocking(0) if IS_BSD: self.recv_socket.setsock...
def _initsocket(self)
bind to the datagram socket (UDP), and enable BROADCAST mode
2.41008
2.356686
1.022657
# self.log("ready to receive.") # we use a runloop instead of synchronous recv so stopping the node mid-recv is possible read_ready = None while self.keep_listening: try: read_ready, w, x = select.select([self.recv_socket], [], [], 0.01) ...
def run(self)
runloop that reads incoming packets off the interface into the inq buffer
7.153922
6.068721
1.178819
addr = ('255.255.255.255', self.port) # 255. is the broadcast IP for UDP try: self.send_socket.sendto(packet, addr) except Exception as e: self.log("Link failed to send packet over socket %s" % e) sleep(0.2) if retry: self...
def send(self, packet, retry=True)
send a packet down the line to the inteface
3.997849
3.837463
1.041795
self.log("ready to receive.") # we use a runloop instead of synchronous recv so stopping the connection mid-recv is possible self.net_socket.settimeout(0.05) while self.keep_listening: try: packet = self.net_socket.recv(4096) except: ...
def run(self)
runloop that reads incoming packets off the interface into the inq buffer
6.148966
5.391556
1.140481
if not self.keep_listening: self.log('is down.') return try: # (because the IRC server sees this link as 1 connection no matter how many nodes use it, it wont send enough copies of the packet back) # for each node listening to this link object lo...
def send(self, packet, retry=True)
send a packet down the line to the inteface
8.741395
8.472001
1.031798