code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
f.seek(0) # Check for BOMs if self.CHECK_BOM: encoding = self.has_bom(f) f.seek(0) else: util.warn_deprecated( "'CHECK_BOM' attribute is deprecated. " "Please override 'has_bom` function to control or avoid BOM...
def _analyze_file(self, f)
Analyze the file.
5.164325
4.995312
1.033834
encoding = self._guess(source_file) # If we didn't explicitly detect an encoding, assume default. if encoding is None: encoding = self.default_encoding return encoding
def _detect_encoding(self, source_file)
Detect encoding.
6.07585
5.255347
1.156127
self.reset() self.current_encoding = self.default_encoding encoding = None try: encoding = self._detect_encoding(source_file) content = self.filter(source_file, encoding) except UnicodeDecodeError: if not encoding or encoding != self....
def _run_first(self, source_file)
Run on as first in chain.
3.206778
3.103785
1.033183
encoding = None file_size = os.path.getsize(filename) # If the file is really big, lets just call it binary. # We don't have time to let Python chug through a massive file. if not self._is_very_large(file_size): with open(filename, "rb") as f: ...
def _guess(self, filename)
Guess the encoding and decode the content of the file.
4.887163
4.675526
1.045265
return [SourceText(source.text, source.context, source.encoding, 'text')]
def sfilter(self, source)
Execute filter.
25.051241
21.737949
1.15242
u default = default.lower() yes = [u'yes', u'ye', u'y'] no = [u'no', u'n'] if default in no: help_ = u'[N/y]?' default = False else: default = True help_ = u'[Y/n]?' while 1: display = question + '\n' + help_ if answer is None: log....
def ask_yes_no(question, default='no', answer=None)
u"""Will ask a question and keeps prompting until answered. Args: question (str): Question to ask end user default (str): Default answer if user just press enter at prompt answer (str): Used for testing Returns: (bool) Meaning: True - Answer is yes ...
2.906623
3.055542
0.951263
u while 1: if default is None: msg = u' - No Default Available' else: msg = (u'\n[DEFAULT] -> {}\nPress Enter To ' u'Use Default'.format(default)) prompt = question + msg + u'\n--> ' if answer is None: answer = six.moves.inpu...
def get_correct_answer(question, default=None, required=False, answer=None, is_answer_correct=None)
u"""Ask user a question and confirm answer Args: question (str): Question to ask user default (str): Default answer if no input from user required (str): Require user to input answer answer (str): Used for testing is_answer_correct (str): Used for testing
3.991746
4.048488
0.985985
parser = argparse.ArgumentParser(prog='spellcheck', description='Spell checking tool.') # Flag arguments parser.add_argument('--version', action='version', version=('%(prog)s ' + __version__)) parser.add_argument('--debug', action='store_true', default=False, help=argparse.SUPPRESS) parser.add...
def main()
Main.
2.786295
2.801035
0.994738
names = kwargs.get('names', []) groups = kwargs.get('groups', []) binary = kwargs.get('binary', '') spellchecker = kwargs.get('spellchecker', '') verbose = kwargs.get('verbose', 0) sources = kwargs.get('sources', []) debug = kwargs.get('debug', False) fail = False count = 0 ...
def run(config, **kwargs)
Run.
2.951914
2.92733
1.008398
@wraps(func) def deprecated_func(*args, **kwargs): warnings.warn( "'{}' is deprecated. {}".format(func.__name__, message), category=DeprecationWarning, stacklevel=2 ) return func(*args, **kwargs) ...
def deprecated(message): # pragma: no cover def deprecated_decorator(func)
Raise a `DeprecationWarning` when wrapped function/method is called. Borrowed from https://stackoverflow.com/a/48632082/866026
1.858268
2.097722
0.885851
if sys.platform.startswith('win'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen( cmd, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ...
def get_process(cmd)
Get a command process.
1.557367
1.529833
1.017998
output = process.communicate() returncode = process.returncode if not encoding: try: encoding = sys.stdout.encoding except Exception: encoding = locale.getpreferredencoding() if returncode != 0: raise RuntimeError("Runtime Error: %s" % (output[0].r...
def get_process_output(process, encoding=None)
Get the output from the process.
2.760593
2.623619
1.052208
process = get_process(cmd) if input_file is not None: with open(input_file, 'rb') as f: process.stdin.write(f.read()) if input_text is not None: process.stdin.write(input_text) return get_process_output(process, encoding)
def call(cmd, input_file=None, input_text=None, encoding=None)
Call with arguments.
2.081723
2.117393
0.983154
process = get_process(cmd) # A buffer has been provided if input_text is not None: for line in input_text.splitlines(): # Hunspell truncates lines at `0x1fff` (at least on Windows this has been observed) # Avoid truncation by chunking the line on white space and insert...
def call_spellchecker(cmd, input_text=None, encoding=None)
Call spell checker with arguments.
4.468021
4.415374
1.011924
return ''.join( [random.choice(string.ascii_uppercase)] + [random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)] ) if size > 0 else ''
def random_name_gen(size=6)
Generate a random python attribute name.
3.199751
2.806136
1.14027
def construct_yaml_str(self, node): return self.construct_scalar(node) class Loader(loader): # Attach our Unicode constructor to our custom loader ensuring all strings # will be Unicode on translation. Loader.add_constructor('tag:yaml.org,2002:str', construct_yaml_s...
def yaml_load(source, loader=yaml.Loader)
Wrap PyYaml's loader so we can extend it to suit our needs. Load all strings as Unicode: http://stackoverflow.com/a/2967461/3609487.
6.684039
4.975671
1.343344
config = {} for name in (['.pyspelling.yml', '.spelling.yml'] if not file_name else [file_name]): if os.path.exists(name): if not file_name and name == '.spelling.yml': warn_deprecated( "Using '.spelling.yml' as the default is deprecated. Default con...
def read_config(file_name)
Read configuration.
3.999852
3.976975
1.005752
# We don't need to do anything if we're not on 3.7 or above if version < (3, 7): return func def fix_timedelta(match): values = match.group(1).split(", ") param_repr = ", ".join( "{}={}".format(param, value) for param, value in zip(("days", "seconds", "m...
def fix_timedelta_repr(func)
Account repr change for timedelta in Python 3.7 and above in docstrings. This is needed to make some doctests pass on Python 3.7 and above. This change was introduced by `bpo-30302 <https://bugs.python.org/issue30302>`_
3.217519
3.132644
1.027094
# construct complete url complete_url = urljoin(self.base_url, url) # check if exists if requests.get('http:' + complete_url).ok: # construct tag if tag == 'script': return '<script src="{0}"></script>'.format(complete_url) eli...
def _get_tag(self, url, tag, print_warn=True)
Check if url is available and returns given tag type :param url: url to content relative to base url :param anchor: anchor type to return :param print_warn: if True print warn when url is unavailable
3.011671
2.914402
1.033375
contents = [] # base js = self._get_tag('codemirror.js', 'script') css = self._get_tag('codemirror.css', 'stylesheet') if js and css: contents.append(js) contents.append(css) # languages for language in self.languages: ...
def include_codemirror(self)
Include resources in pages
2.202811
2.224895
0.990074
if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['codemirror'] = CodeMirrorHeaders(app.config) app.context_processor(self.context_processor)
def init_app(self, app)
Register CodeMirror as a Flask extension :param app: Flask instance
4.150339
3.746547
1.107777
self._netrc.hosts = dedictify_machines(self.machines) rep = "" for host in self._netrc.hosts.keys(): attrs = self._netrc.hosts[host] rep += "machine {host}\n\tlogin {attrs[0]}\n".format(host=host, a...
def format(self)
Dump the class data in the format of a .netrc file.
2.83279
2.510441
1.128403
hash_bytes = binascii.hexlify(base58.b58decode_check(address)) return reverse_hex(hash_bytes[2:].decode('utf-8'))
def neo_get_scripthash_from_address(address)
Convert a Public Address String to a ScriptHash (Address) String. :param address: The Public address to convert. :type address: str :return: String containing the converted ScriptHash.
3.52531
4.154097
0.848635
with open(file) as fp: return re.sub( "^\.\.\s+include:: (.*?)$", lambda x: (rst_preprocess(x.group(1)) or "").rstrip(), fp.read(), flags=re.MULTILINE)
def rst_preprocess(file)
Preprocess reST file to support Sphinx like include directive. Includes are relative to the current working directory.
4.341286
3.8425
1.129808
# if (type(number) != = 'number') throw new Error('num must be numeric') # if (num < 0) throw new RangeError('num is unsigned (>= 0)') # if (size % 1 !== 0) throw new Error('size must be a whole integer') # if (!Number.isSafeInteger(num)) throw new RangeError(`num (${num}) must be a safe integer`) ...
def num2hexstring(number, size=1, little_endian=False)
Converts a number to a big endian hexstring of a suitable size, optionally little endian :param {number} number :param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2. :param {boolean} little_endian - Encode the hex in little endian form :return {string}
3.244695
3.498229
0.927525
# if (typeof num !== 'number') throw new Error('VarInt must be numeric') # if (num < 0) throw new RangeError('VarInts are unsigned (> 0)') # if (!Number.isSafeInteger(num)) throw new RangeError('VarInt must be a safe integer') if num < 0xfd: return num2hexstring(num) elif num <= 0xffff:...
def num2varint(num)
Converts a number to a variable length Int. Used for array length header :param: {number} num - The number :return: {string} hexstring of the variable Int.
2.211394
2.28413
0.968156
r = requests.get(url=self.url + path, params=params, timeout=self.timeout) r.raise_for_status() return r.json()
def get(self, path, params=None)
Perform GET request
2.293125
2.522839
0.908946
r = requests.post(url=self.url + path, data=data, json=json_data, params=params, timeout=self.timeout) try: r.raise_for_status() except requests.exceptions.HTTPError: raise SwitcheoApiException(r.json()['error_code'], r.json()['error_message'], r.json()['error'])...
def post(self, path, data=None, json_data=None, params=None)
Perform POST request
2.313558
2.381674
0.9714
super().validate_options(k, v) if k == 'mode' and v not in MODE: raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
def validate_options(self, k, v)
Validate options.
3.660811
3.529875
1.037094
self.user_break_tags = set(self.config['break_tags']) self.comments = self.config.get('comments', True) is True self.attributes = set(self.config['attributes']) self.type = self.config['mode'] if self.type not in MODE: self.type = 'html' self.parser ...
def setup(self)
Setup.
3.771306
3.642285
1.035423
encode = None # Look for meta charset m = RE_HTML_ENCODE.search(content) if m: enc = m.group(1).decode('ascii') try: codecs.getencoder(enc) encode = enc except LookupError: pass else: ...
def header_check(self, content)
Special HTML encoding check.
5.984289
5.350644
1.118424
name = sv.util.lower(el.name) if self.type != 'xhtml' else el.name return name in self.break_tags or name in self.user_break_tags
def is_break_tag(self, el)
Check if tag is an element we should break on.
9.10785
7.54201
1.207616
if self.type != 'xhtml': return el.attrs.get('class', []) else: return [c for c in el.attrs.get('class', '').strip().split(' ') if c]
def get_classes(self, el)
Get classes.
3.761577
3.55378
1.058472
selector = deque() ancestor = el while ancestor and ancestor.parent: if ancestor is not el: selector.appendleft(ancestor.name) else: tag = ancestor.name prefix = ancestor.prefix classes = self.get_c...
def construct_selector(self, el, attr='')
Construct an selector for context.
2.641801
2.542106
1.039218
self.additional_context = '' self.comments = False self.attributes = [] self.parser = 'xml' self.type = None self.filepattern = '' self.ignores = None self.captures = None
def setup(self)
Setup.
10.174479
9.412868
1.080912
content = filestream.read(4) if content == b'PK\x03\x04': # Zip file found. # Return `BINARY_ENCODE` as content is binary type, # but don't return None which means we don't know what we have. return filters.BINARY_ENCODE # We only handle ...
def has_bom(self, filestream)
Check if has BOM.
11.2769
10.606898
1.063167
content = z.read('[Content_Types].xml') with io.BytesIO(content) as b: encoding = self._analyze_file(b) if encoding is None: encoding = 'utf-8' b.seek(0) text = b.read().decode(encoding) soup = bs4.BeautifulSoup(text, ...
def determine_file_type(self, z)
Determine file type.
3.681336
3.673861
1.002035
# Break word documents by paragraphs. if self.type == 'docx' and el.namespace == self.namespaces['w'] and el.name == 'p': text.append('\n') # Break slides by paragraphs. if self.type == 'pptx' and el.namespace == self.namespaces['a'] and el.name == 'p': ...
def soft_break(self, el, text)
Apply soft break.
3.662184
3.503416
1.045318
if self.type == 'pptx': context = '{}: '.format(RE_SLIDE.search(filename).group(1)) elif self.type == 'docx': context = '{}: '.format(RE_DOCS.match(filename).group(1)) else: context = '' return context
def get_context(self, filename)
Get context.
4.206321
3.981014
1.056595
self.additional_context = self.get_context(filename) sources.extend(self._filter(content, source_file, enc)) return sources
def filter(self, source_file, encoding): # noqa A001 sources = [] for content, filename, enc in self.get_content(source_file)
Parse XML file.
6.114416
5.495748
1.112572
sources = [] for content, filename, enc in self.get_content(io.BytesIO(source.text.encode(source.encoding))): self.additional_context = self.get_context(filename) sources.extend(self._filter(content, source.context, enc)) return sources
def sfilter(self, source)
Filter.
7.367933
7.108576
1.036485
other = ProtoFeed() for key in cs.PROTOFEED_ATTRS: value = getattr(self, key) if isinstance(value, pd.DataFrame): # Pandas copy DataFrame value = value.copy() setattr(other, key, value) return other
def copy(self)
Return a copy of this ProtoFeed, that is, a feed with all the same attributes.
7.36045
5.251547
1.401577
mapper = mapping if not callable(mapping): if not isinstance(mapping, collections.Mapping): raise TypeError("Argument mapping is not collable or an instance " "of collections.Mapping") mapper = lambda name: mapping.get(name, name) class mapped_j...
def mapped_jsontree_class(mapping)
Return a class which is a jsontree, but with a supplied attribute name mapping. The mapping argument can be a mapping object (dict, jsontree, etc.) or it can be a callable which takes a single argument (the attribute name), and returns a new name. This is useful in situations where you have a jsont...
2.399065
2.326124
1.031357
return json.loads(json.dumps(root, cls=JSONTreeEncoder, datetimeencoder=datetimeencoder), cls=JSONTreeDecoder, jsontreecls=jsontreecls, datetimedecoder=datetimedecoder)
def clone(root, jsontreecls=jsontree, datetimeencoder=_datetimeencoder, datetimedecoder=_datetimedecoder)
Clone an object by first searializing out and then loading it back in.
2.757236
3.146308
0.87634
return json.load(fp, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kargs)
def load(fp, encoding=None, cls=JSONTreeDecoder, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kargs)
JSON load from file function that defaults the loading class to be JSONTreeDecoder
1.917345
1.997942
0.95966
return json.loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kargs)
def loads(s, encoding=None, cls=JSONTreeDecoder, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kargs)
JSON load from string function that defaults the loading class to be JSONTreeDecoder
1.787141
1.937818
0.922244
self.comments = self.config['comments'] self.docstrings = self.config['docstrings'] self.strings = self.config['strings'] self.group_comments = self.config['group_comments'] self.string_types, self.wild_string_types = self.eval_string_type(self.config['string_types']) ...
def setup(self)
Setup.
3.780931
3.6376
1.039403
super().validate_options(k, v) if k == 'string_types': if RE_VALID_STRING_TYPES.match(v) is None: raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v))
def validate_options(self, k, v)
Validate options.
4.434944
4.281384
1.035867
encode = None m = RE_PY_ENCODE.match(content) if m: if m.group(1): encode = m.group(1).decode('ascii') elif m.group(2): encode = m.group(2).decode('ascii') if encode is None: encode = 'utf-8' return en...
def header_check(self, content)
Special Python encoding check.
3.246453
2.800441
1.159265
stype = set() wstype = set() for m in RE_ITER_STRING_TYPES.finditer(text): value = m.group(0) if value == '*': wstype.add('u') wstype.add('f') wstype.add('r') wstype.add('b') elif value...
def eval_string_type(self, text, is_string=False)
Evaluate string type.
3.030784
2.966489
1.021674
groups = m.groupdict() esc = m.group(0) if groups.get('fesc'): value = m.group(0) elif groups.get('format'): value = ' ' elif groups.get('special'): value = BACK_SLASH_TRANSLATION[esc] elif groups.get('char'): try:...
def replace_unicode(self, m)
Replace escapes.
3.354457
3.194655
1.050022
esc = m.group(0) value = esc if m.group('special'): value = BACK_SLASH_TRANSLATION[esc] elif m.group('char'): try: value = chr(int(esc[2:], 16)) except Exception: value = esc elif m.group('oct'): ...
def replace_bytes(self, m)
Replace escapes.
3.475436
3.293541
1.055228
m = RE_STRING_TYPE.match(string) stype = self.get_string_type(m.group(1) if m.group(1) else '') if not self.match_string(stype) and not docstrings: return '', False is_bytes = 'b' in stype is_raw = 'r' in stype is_format = 'f' in stype conten...
def process_strings(self, string, docstrings=False)
Process escapes.
3.219236
3.148558
1.022448
slots = set() for c in cls.__mro__: cslots = getattr(c, "__slots__", tuple()) if not cslots: continue elif isinstance(cslots, (bstr, ustr)): cslots = (cslots,) slots.update(cslots) return slots
def find_slots(cls)
Return a set of all slots for a given class and its parents
3.790611
3.188659
1.188779
if accept_none and obj is None: return True return isinstance(obj, date) and not isinstance(obj, datetime)
def _is_valid_date(obj, accept_none=True)
Check if an object is an instance of, or a subclass deriving from, a ``date``. However, it does not consider ``datetime`` or subclasses thereof as valid dates. :param obj: Object to test as date. :param accept_none: If True None is considered as a valid date object.
3.361017
3.320017
1.012349
self = cls.__new__(cls) self._range = _empty_internal_range return self
def empty(cls)
Returns an empty set. An empty set is unbounded and only contain the empty set. >>> intrange.empty() in intrange.empty() True It is unbounded but the boundaries are not infinite. Its boundaries are returned as ``None``. Every set contains the empty set.
14.452301
13.595302
1.063036
replacements = { "lower" : self.lower, "upper" : self.upper, "lower_inc" : self.lower_inc, "upper_inc" : self.upper_inc } replacements.update( dict(zip(("lower", "upper", "lower_inc", "upper_inc"), args))) replacements...
def replace(self, *args, **kwargs)
replace(lower=None, upper=None, lower_inc=None, upper_inc=None) Returns a new instance of self with the given arguments replaced. It takes the exact same arguments as the constructor. >>> intrange(1, 5).replace(upper=10) intrange([1,10)) >>> intrange(1, 10).replace(...
2.576195
2.158893
1.193294
if self.is_valid_range(other): if not self: return not other elif not other or other.startsafter(self) and other.endsbefore(self): return True else: return False elif self.is_valid_scalar(other): # ...
def contains(self, other)
Return True if this contains other. Other may be either range of same type or scalar of same type as the boundaries. >>> intrange(1, 10).contains(intrange(1, 5)) True >>> intrange(1, 10).contains(intrange(5, 10)) True >>> intrange(1, 10).contains(intr...
3.10813
2.949477
1.05379
if not self.is_valid_range(other): raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other)) return other.contains(self)
def within(self, other)
Tests if this range is within `other`. >>> a = intrange(1, 10) >>> b = intrange(3, 8) >>> a.contains(b) True >>> b.within(a) True This is the same as the ``self <@ other`` in PostgreSQL. One difference however is that unlike Postg...
7.264282
6.59277
1.101856
# Special case for empty ranges if not self or not other: return False if self < other: a, b = self, other else: a, b = other, self # We need to explicitly handle unbounded ranges since a.upper and b.lower # make the interva...
def overlap(self, other)
Returns True if both ranges share any points. >>> intrange(1, 10).overlap(intrange(5, 15)) True >>> intrange(1, 5).overlap(intrange(5, 10)) False This is the same as the ``&&`` operator for two ranges in PostgreSQL. :param other: Range to test against. ...
5.027517
5.029433
0.999619
if not self.is_valid_range(other): raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other)) # Must return False if either is an empty set elif not self or not other: return False ...
def adjacent(self, other)
Returns True if ranges are directly next to each other but does not overlap. >>> intrange(1, 5).adjacent(intrange(5, 10)) True >>> intrange(1, 5).adjacent(intrange(10, 15)) False The empty set is not adjacent to any set. This is the same as the ...
4.347334
4.002875
1.086053
if not self.is_valid_range(other): msg = "Unsupported type to test for union '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Optimize empty ranges if not self: return other elif not other: return self # Ord...
def union(self, other)
Merges this range with a given range. >>> intrange(1, 5).union(intrange(5, 10)) intrange([1,10)) >>> intrange(1, 10).union(intrange(5, 15)) intrange([1,15)) Two ranges can not be merged if the resulting range would be split in two. This happens when the ...
3.21135
2.927747
1.096867
if not self.is_valid_range(other): msg = "Unsupported type to test for difference '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Consider empty ranges or no overlap if not self or not other or not self.overlap(other): return self ...
def difference(self, other)
Compute the difference between this and a given range. >>> intrange(1, 10).difference(intrange(10, 15)) intrange([1,10)) >>> intrange(1, 10).difference(intrange(5, 10)) intrange([1,5)) >>> intrange(1, 5).difference(intrange(5, 10)) intrange([1,5))...
4.080678
3.454396
1.1813
if not self.is_valid_range(other): msg = "Unsupported type to test for intersection '{.__class__.__name__}'" raise TypeError(msg.format(other)) # Handle ranges not intersecting if not self or not other or not self.overlap(other): return self.empty()...
def intersection(self, other)
Returns a new range containing all points shared by both ranges. If no points are shared an empty range is returned. >>> intrange(1, 5).intersection(intrange(1, 10)) intrange([1,5)) >>> intrange(1, 5).intersection(intrange(5, 10)) intrange(empty) >>> ...
4.639168
4.363366
1.063209
if self.is_valid_range(other): if self.lower_inc == other.lower_inc: return self.lower == other.lower else: return False elif self.is_valid_scalar(other): if self.lower_inc: return self.lower == other ...
def startswith(self, other)
Test if this range starts with `other`. `other` may be either range or scalar. >>> intrange(1, 5).startswith(1) True >>> intrange(1, 5).startswith(intrange(1, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range starts...
3.328662
2.875984
1.1574
if self.is_valid_range(other): if self.upper_inc == other.upper_inc: return self.upper == other.upper else: return False elif self.is_valid_scalar(other): if self.upper_inc: return self.upper == other ...
def endswith(self, other)
Test if this range ends with `other`. `other` may be either range or scalar. >>> intrange(1, 5).endswith(4) True >>> intrange(1, 10).endswith(intrange(5, 10)) True :param other: Range or scalar to test. :return: ``True`` if this range ends with `...
3.354311
2.926831
1.146056
if self.is_valid_range(other): if self.lower == other.lower: return other.lower_inc or not self.lower_inc elif self.lower_inf: return False elif other.lower_inf: return True else: return sel...
def startsafter(self, other)
Test if this range starts after `other`. `other` may be either range or scalar. This only takes the lower end of the ranges into consideration. If the scalar or the lower end of the given range is greater than or equal to this range's lower end, ``True`` is returned. >>> intrange(1,...
3.442537
2.978775
1.155689
if self.is_valid_range(other): if self.upper == other.upper: return not self.upper_inc or other.upper_inc elif self.upper_inf: return False elif other.upper_inf: return True else: return sel...
def endsbefore(self, other)
Test if this range ends before `other`. `other` may be either range or scalar. This only takes the upper end of the ranges into consideration. If the scalar or the upper end of the given range is less than or equal to this range's upper end, ``True`` is returned. >>> intrange(1, 5)....
3.471322
2.919137
1.18916
if not self.is_valid_range(other): msg = ( "Left of is not supported for '{}', provide a proper range " "class").format(other.__class__.__name__) raise TypeError(msg) return self < other and not self.overlap(other)
def left_of(self, other)
Test if this range `other` is strictly left of `other`. >>> intrange(1, 5).left_of(intrange(5, 10)) True >>> intrange(1, 10).left_of(intrange(5, 10)) False The bitwise right shift operator ``<<`` is overloaded for this operation too. >>> int...
6.320064
5.970551
1.05854
# If range is empty it can't be offset if not self: return self offset_type = self.type if self.offset_type is None else self.offset_type if offset is not None and not isinstance(offset, offset_type): raise TypeError(( "Invalid type for...
def offset(self, offset)
Shift the range to the left or right with the given offset >>> intrange(0, 5).offset(5) intrange([5,10)) >>> intrange(5, 10).offset(-5) intrange([0,5)) >>> intrange.empty().offset(5) intrange(empty) Note that range objects are immutable a...
2.907004
2.83058
1.026999
if period is None or period == "day": return cls(date, date, upper_inc=True) elif period == "week": start = date - timedelta(date.weekday()) return cls(start, start + timedelta(7)) elif period == "american_week": start = date - timedelta(...
def from_date(cls, date, period=None)
Create a day long daterange from for the given date. >>> daterange.from_date(date(2000, 1, 1)) daterange([datetime.date(2000, 1, 1),datetime.date(2000, 1, 2))) :param date: A date to convert. :param period: The period to normalize date to. A period may be one of: ...
1.896871
1.716361
1.10517
first_day = date_from_iso_week(year, iso_week) return cls.from_date(first_day, period="week")
def from_week(cls, year, iso_week)
Create ``daterange`` based on a year and an ISO week :param year: Year as an integer :param iso_week: ISO week number :return: A new ``daterange`` for the given week .. versionadded:: 0.4.0
4.77212
5.096211
0.936405
first_day = date(year, month, 1) return cls.from_date(first_day, period="month")
def from_month(cls, year, month)
Create ``daterange`` based on a year and amonth :param year: Year as an integer :param iso_week: Month as an integer between 1 and 12 :return: A new ``daterange`` for the given month .. versionadded:: 0.4.0
5.15524
5.630447
0.9156
quarter_months = { 1: 1, 2: 4, 3: 7, 4: 10, } if quarter not in quarter_months: error_msg = ( "quarter is not a valid quarter. Expected a value between 1 " "and 4 got {!r}") raise V...
def from_quarter(cls, year, quarter)
Create ``daterange`` based on a year and quarter. A quarter is considered to be: - January through March (Q1), - April through June (Q2), - July through September (Q3) or, - October through December (Q4) :param year: Year as an integer :param quarter: Quarter a...
2.91915
3.109349
0.93883
first_day = date(year, 1, 1) return cls.from_date(first_day, period="year")
def from_year(cls, year)
Create ``daterange`` based on a year :param year: Year as an integer :return: A new ``daterange`` for the given year .. versionadded:: 0.4.0
5.492813
5.755548
0.954351
return daterange( lower=self.lower, upper=self.upper, lower_inc=self.lower_inc, upper_inc=self.upper_inc)
def daterange(self)
This ``PeriodRange`` represented as a naive :class:`~spans.types.daterange`.
3.372527
2.826931
1.192999
span = self if offset > 0: for i in iter_range(offset): span = span.next_period() elif offset < 0: for i in iter_range(-offset): span = span.prev_period() return span
def offset(self, offset)
Offset the date range by the given amount of periods. This differs from :meth:`~spans.types.OffsetableRangeMixin.offset` on :class:`spans.types.daterange` by not accepting a ``timedelta`` object. Instead it expects an integer to adjust the typed date range by. The given value may be neg...
3.504369
3.351648
1.045566
return self.from_date(self.prev(self.lower), period=self.period)
def prev_period(self)
The period before this range. >>> span = PeriodRange.from_date(date(2000, 1, 1), period="month") >>> span.prev_period() PeriodRange([datetime.date(1999, 12, 1),datetime.date(2000, 1, 1))) :return: A new :class:`~spans.types.PeriodRange` for the period befor...
24.939482
12.736362
1.958132
log.debug('Getting package hashes') filename = os.path.abspath(filename) with open(filename, 'rb') as f: data = f.read() _hash = hashlib.sha256(data).hexdigest() log.debug('Hash for file %s: %s', filename, _hash) return _hash
def get_package_hashes(filename)
Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash
2.515208
2.557699
0.983387
self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] # If the style isn't found, just go with CSS, then use the appropriate prefix. self.stylesheets = STYLESHEET_TYPE.get(self.config['s...
def setup(self)
Setup.
6.165905
5.979544
1.031166
g = m.groupdict() if g["strings"]: self.line_num += g['strings'].count('\n') elif g["code"]: self.line_num += g["code"].count('\n') else: if g['block']: self.evaluate_block(g) elif self.stylesheets != CSS: ...
def evaluate(self, m)
Search for comments.
4.606119
4.401644
1.046454
self.extend_src_text(content, context, self.block_comments, 'block-comment') self.extend_src_text(content, context, self.line_comments, 'line-comment')
def extend_src(self, content, context)
Extend source list.
3.644013
3.35452
1.086299
for m in self.pattern.finditer(self.norm_nl(text)): self.evaluate(m)
def find_content(self, text)
Find content.
11.426899
10.88203
1.05007
content = [] self.current_encoding = encoding self.line_num = 1 self.prev_line = -1 self.leading = '' self.block_comments = [] self.line_comments = [] self.find_content(text) self.extend_src(content, context) return content
def _filter(self, text, context, encoding)
Filter JavaScript comments.
5.968655
5.264421
1.133772
### pick up kwargs dropdeg = kwargs.pop('dropdeg', False) ndim = len(cube.dims) ### load yaml FITSINFO = get_data('decode', 'data/fitsinfo.yaml') hdrdata = yaml.load(FITSINFO, dc.utils.OrderedLoader) ### default header if ndim == 2: header = fits.Header(hdrdata['dcube_2...
def savefits(cube, fitsname, **kwargs)
Save a cube to a 3D-cube FITS file. Args: cube (xarray.DataArray): Cube to be saved. fitsname (str): Name of output FITS file. kwargs (optional): Other arguments common with astropy.io.fits.writeto().
3.262137
3.250396
1.003612
filename = str(Path(filename).expanduser()) if copy: dataarray = xr.open_dataarray(filename).copy() else: dataarray = xr.open_dataarray(filename, chunks={}) if dataarray.name is None: dataarray.name = filename.rstrip('.nc') for key, val in dataarray.coords.items(): ...
def loadnetcdf(filename, copy=True)
Load a dataarray from a NetCDF file. Args: filename (str): Filename (*.nc). copy (bool): If True, dataarray is copied in memory. Default is True. Returns: dataarray (xarray.DataArray): Loaded dataarray.
2.493151
2.800437
0.890272
if filename is None: if dataarray.name is not None: filename = dataarray.name else: filename = uuid4().hex[:8] else: filename = str(Path(filename).expanduser()) if not filename.endswith('.nc'): filename += '.nc' dataarray.to_netcdf(filename)...
def savenetcdf(dataarray, filename=None)
Save a dataarray to a NetCDF file. Args: dataarray (xarray.DataArray): Dataarray to be saved. filename (str): Filename (used as <filename>.nc). If not spacified, random 8-character name will be used.
2.621505
2.589418
1.012391
super().validate_options(k, v) if k == 'errors' and v.lower() not in ('strict', 'replace', 'ignore', 'backslashreplace'): raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k)) if k == 'normalize' and v.upper() not in ('NFC', 'NFKC', ...
def validate_options(self, k, v)
Validate options.
2.581638
2.520076
1.024429
self.normalize = self.config['normalize'].upper() self.convert_encoding = self.config['convert_encoding'].lower() self.errors = self.config['errors'].lower() if self.convert_encoding: self.convert_encoding = codecs.lookup( filters.PYTHON_ENCODING_NA...
def setup(self)
Setup.
3.753628
3.65748
1.026288
if self.normalize in ('NFC', 'NFKC', 'NFD', 'NFKD'): text = unicodedata.normalize(self.normalize, text) if self.convert_encoding: text = text.encode(self.convert_encoding, self.errors).decode(self.convert_encoding) encoding = self.convert_encoding re...
def convert(self, text, encoding)
Convert the text.
2.495979
2.36755
1.054245
text, encoding = self.convert(source.text, source.encoding) return [filters.SourceText(text, source.context, encoding, 'text')]
def sfilter(self, source)
Execute filter.
13.383329
11.829406
1.131361
hash_message = defunct_hash_message(text=stringify_message(cancellation_params)) hex_message = binascii.hexlify(hash_message).decode() signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode() create_params = cancellation_params.copy() creat...
def sign_create_cancellation(cancellation_params, private_key)
Function to sign the parameters required to create a cancellation request from the Switcheo Exchange. Execution of this function is as follows:: sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: ...
2.976239
3.0364
0.980187
cancellation_sha256 = cancellation_params['transaction']['sha256'] signed_sha256 = binascii.hexlify( Account.signHash(cancellation_sha256, private_key=private_key)['signature']).decode() return {'signature': '0x' + signed_sha256}
def sign_execute_cancellation(cancellation_params, private_key)
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange. Execution of this function is as follows:: sign_execute_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: ...
3.882045
3.843295
1.010082
create_deposit_upper = deposit_params.copy() create_deposit_upper['transaction']['from'] = to_checksum_address(create_deposit_upper['transaction']['from']) create_deposit_upper['transaction']['to'] = to_checksum_address(create_deposit_upper['transaction']['to']) create_deposit_upper['transaction']....
def sign_execute_deposit(deposit_params, private_key, infura_url)
Function to execute the deposit request by signing the transaction generated from the create deposit function. Execution of this function is as follows:: sign_execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: ...
2.838112
2.639483
1.075253
execute_params = { 'signatures': { 'fill_groups': sign_txn_array(messages=order_params['fill_groups'], private_key=private_key), 'fills': {}, 'makes': sign_txn_array(messages=order_params['makes'], private_key=private_key), } } return execute_params
def sign_execute_order(order_params, private_key)
Function to execute the order request by signing the transaction generated from the create order function. Execution of this function is as follows:: sign_execute_order(order_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { ...
4.007823
2.994801
1.33826
withdrawal_sha256 = withdrawal_params['transaction']['sha256'] signed_sha256 = binascii.hexlify(Account.signHash(withdrawal_sha256, private_key=private_key)['signature']).decode() return {'signature': '0x' + signed_sha256}
def sign_execute_withdrawal(withdrawal_params, private_key)
Function to execute the withdrawal request by signing the transaction generated from the create withdrawal function. Execution of this function is as follows:: sign_execute_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expected return result for this function is as fol...
3.535
3.606617
0.980143
self.additional_context = '' self.comments = False self.attributes = [] self.parser = 'xml' self.type = None self.filepattern = 'content.xml' self.namespaces = { 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'draw': 'u...
def setup(self)
Setup.
5.113347
4.96575
1.029723
mimetype = z.read('mimetype').decode('utf-8').strip() self.type = MIMEMAP[mimetype]
def determine_file_type(self, z)
Determine file type.
8.711179
7.310047
1.191672
with zipfile.ZipFile(filename, 'r') as z: self.determine_file_type(z) for item in z.infolist(): if glob.globmatch(item.filename, self.filepattern, flags=self.FLAGS): yield z.read(item.filename), item.filename
def get_zip_content(self, filename)
Get zip content.
4.280706
4.327765
0.989126
for content, filename in self.get_zip_content(zipbundle): with io.BytesIO(content) as b: encoding = self._analyze_file(b) if encoding is None: encoding = self.default_encoding b.seek(0) text = b.read().deco...
def get_content(self, zipbundle)
Get content.
3.850131
3.70309
1.039708