repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
facelessuser/pyspelling
pyspelling/util/__init__.py
read_config
def read_config(file_name): """Read configuration.""" 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 config is now '.pyspelling.yml'" ) with codecs.open(name, 'r', encoding='utf-8') as f: config = yaml_load(f.read()) break return config
python
def read_config(file_name): """Read configuration.""" 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 config is now '.pyspelling.yml'" ) with codecs.open(name, 'r', encoding='utf-8') as f: config = yaml_load(f.read()) break return config
[ "def", "read_config", "(", "file_name", ")", ":", "config", "=", "{", "}", "for", "name", "in", "(", "[", "'.pyspelling.yml'", ",", "'.spelling.yml'", "]", "if", "not", "file_name", "else", "[", "file_name", "]", ")", ":", "if", "os", ".", "path", ".",...
Read configuration.
[ "Read", "configuration", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L170-L183
train
49,600
runfalk/spans
spans/_compat.py
fix_timedelta_repr
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>`_ """ # 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", "microseconds"), values) if value != "0" ) # If we have a zero length timedelta it should be represented as # timedelta(0), i.e. without named parameters if not param_repr: param_repr = "0" return "timedelta({})".format(param_repr) func.__doc__ = re.sub(r"timedelta\(([^)]+)\)", fix_timedelta, func.__doc__) return func
python
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>`_ """ # 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", "microseconds"), values) if value != "0" ) # If we have a zero length timedelta it should be represented as # timedelta(0), i.e. without named parameters if not param_repr: param_repr = "0" return "timedelta({})".format(param_repr) func.__doc__ = re.sub(r"timedelta\(([^)]+)\)", fix_timedelta, func.__doc__) return func
[ "def", "fix_timedelta_repr", "(", "func", ")", ":", "# 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", ".", ...
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>`_
[ "Account", "repr", "change", "for", "timedelta", "in", "Python", "3", ".", "7", "and", "above", "in", "docstrings", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/_compat.py#L69-L96
train
49,601
j0ack/flask-codemirror
flask_codemirror/__init__.py
CodeMirrorHeaders.include_codemirror
def include_codemirror(self): """Include resources in pages""" 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: url = self.__class__.LANGUAGE_REL_URL.format(language) js = self._get_tag(url, 'script') if js: contents.append(js) # theme if self.theme: url = self.__class__.THEME_REL_URL.format(self.theme) css = self._get_tag(url, 'stylesheet') if css: contents.append(css) # addons if self.addons: # add to list for addon_type, name in self.addons: url = self.__class__.ADDON_REL_URL.format(addon_type, name) js = self._get_tag(url, 'script') if js: contents.append(js) # if there is a css file relative to this addon url = self.__class__.ADDON_CSS_REL_URL.format(addon_type, name) css = self._get_tag(url, 'stylesheet', False) if css: contents.append(css) # return html return Markup('\n'.join(contents))
python
def include_codemirror(self): """Include resources in pages""" 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: url = self.__class__.LANGUAGE_REL_URL.format(language) js = self._get_tag(url, 'script') if js: contents.append(js) # theme if self.theme: url = self.__class__.THEME_REL_URL.format(self.theme) css = self._get_tag(url, 'stylesheet') if css: contents.append(css) # addons if self.addons: # add to list for addon_type, name in self.addons: url = self.__class__.ADDON_REL_URL.format(addon_type, name) js = self._get_tag(url, 'script') if js: contents.append(js) # if there is a css file relative to this addon url = self.__class__.ADDON_CSS_REL_URL.format(addon_type, name) css = self._get_tag(url, 'stylesheet', False) if css: contents.append(css) # return html return Markup('\n'.join(contents))
[ "def", "include_codemirror", "(", "self", ")", ":", "contents", "=", "[", "]", "# base", "js", "=", "self", ".", "_get_tag", "(", "'codemirror.js'", ",", "'script'", ")", "css", "=", "self", ".", "_get_tag", "(", "'codemirror.css'", ",", "'stylesheet'", ")...
Include resources in pages
[ "Include", "resources", "in", "pages" ]
81ad831ff849b60bb34de5db727ad626ff3c9bdc
https://github.com/j0ack/flask-codemirror/blob/81ad831ff849b60bb34de5db727ad626ff3c9bdc/flask_codemirror/__init__.py#L92-L127
train
49,602
runfalk/spans
setup.py
rst_preprocess
def rst_preprocess(file): """ Preprocess reST file to support Sphinx like include directive. Includes are relative to the current working directory. """ with open(file) as fp: return re.sub( "^\.\.\s+include:: (.*?)$", lambda x: (rst_preprocess(x.group(1)) or "").rstrip(), fp.read(), flags=re.MULTILINE)
python
def rst_preprocess(file): """ Preprocess reST file to support Sphinx like include directive. Includes are relative to the current working directory. """ 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", ")", ":", "with", "open", "(", "file", ")", "as", "fp", ":", "return", "re", ".", "sub", "(", "\"^\\.\\.\\s+include:: (.*?)$\"", ",", "lambda", "x", ":", "(", "rst_preprocess", "(", "x", ".", "group", "(", "1", ")"...
Preprocess reST file to support Sphinx like include directive. Includes are relative to the current working directory.
[ "Preprocess", "reST", "file", "to", "support", "Sphinx", "like", "include", "directive", ".", "Includes", "are", "relative", "to", "the", "current", "working", "directory", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/setup.py#L113-L124
train
49,603
KeithSSmith/switcheo-python
switcheo/utils.py
num2varint
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. """ # 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: # uint16 return 'fd' + num2hexstring(number=num, size=2, little_endian=True) elif num <= 0xffffffff: # uint32 return 'fe' + num2hexstring(number=num, size=4, little_endian=True) else: # uint64 return 'ff' + num2hexstring(number=num, size=8, little_endian=True)
python
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. """ # 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: # uint16 return 'fd' + num2hexstring(number=num, size=2, little_endian=True) elif num <= 0xffffffff: # uint32 return 'fe' + num2hexstring(number=num, size=4, little_endian=True) else: # uint64 return 'ff' + num2hexstring(number=num, size=8, little_endian=True)
[ "def", "num2varint", "(", "num", ")", ":", "# 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", "<...
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.
[ "Converts", "a", "number", "to", "a", "variable", "length", "Int", ".", "Used", "for", "array", "length", "header" ]
22f943dea1ad7d692b2bfcd9f0822ec80f4641a6
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L50-L70
train
49,604
KeithSSmith/switcheo-python
switcheo/utils.py
Request.get
def get(self, path, params=None): """Perform GET request""" r = requests.get(url=self.url + path, params=params, timeout=self.timeout) r.raise_for_status() return r.json()
python
def get(self, path, params=None): """Perform GET request""" 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", ")", ":", "r", "=", "requests", ".", "get", "(", "url", "=", "self", ".", "url", "+", "path", ",", "params", "=", "params", ",", "timeout", "=", "self", ".", "timeout", ")", "r...
Perform GET request
[ "Perform", "GET", "request" ]
22f943dea1ad7d692b2bfcd9f0822ec80f4641a6
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L101-L105
train
49,605
KeithSSmith/switcheo-python
switcheo/utils.py
Request.post
def post(self, path, data=None, json_data=None, params=None): """Perform POST request""" 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']) return r.json()
python
def post(self, path, data=None, json_data=None, params=None): """Perform POST request""" 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']) return r.json()
[ "def", "post", "(", "self", ",", "path", ",", "data", "=", "None", ",", "json_data", "=", "None", ",", "params", "=", "None", ")", ":", "r", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "url", "+", "path", ",", "data", "=", "data...
Perform POST request
[ "Perform", "POST", "request" ]
22f943dea1ad7d692b2bfcd9f0822ec80f4641a6
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L107-L114
train
49,606
facelessuser/pyspelling
pyspelling/filters/html.py
HtmlFilter.header_check
def header_check(self, content): """Special HTML encoding check.""" 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: encode = self._has_xml_encode(content) return encode
python
def header_check(self, content): """Special HTML encoding check.""" 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: encode = self._has_xml_encode(content) return encode
[ "def", "header_check", "(", "self", ",", "content", ")", ":", "encode", "=", "None", "# Look for meta charset", "m", "=", "RE_HTML_ENCODE", ".", "search", "(", "content", ")", "if", "m", ":", "enc", "=", "m", ".", "group", "(", "1", ")", ".", "decode",...
Special HTML encoding check.
[ "Special", "HTML", "encoding", "check", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/html.py#L79-L96
train
49,607
facelessuser/pyspelling
pyspelling/filters/ooxml.py
OoxmlFilter.has_bom
def has_bom(self, filestream): """Check if has BOM.""" 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 zip files, so if we are checking this, we've already failed. return None
python
def has_bom(self, filestream): """Check if has BOM.""" 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 zip files, so if we are checking this, we've already failed. return None
[ "def", "has_bom", "(", "self", ",", "filestream", ")", ":", "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 whic...
Check if has BOM.
[ "Check", "if", "has", "BOM", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L69-L79
train
49,608
facelessuser/pyspelling
pyspelling/filters/ooxml.py
OoxmlFilter.soft_break
def soft_break(self, el, text): """Apply soft break.""" # 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': text.append('\n')
python
def soft_break(self, el, text): """Apply soft break.""" # 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': text.append('\n')
[ "def", "soft_break", "(", "self", ",", "el", ",", "text", ")", ":", "# Break word documents by paragraphs.", "if", "self", ".", "type", "==", "'docx'", "and", "el", ".", "namespace", "==", "self", ".", "namespaces", "[", "'w'", "]", "and", "el", ".", "na...
Apply soft break.
[ "Apply", "soft", "break", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L116-L124
train
49,609
mrcagney/make_gtfs
make_gtfs/protofeed.py
ProtoFeed.copy
def copy(self): """ Return a copy of this ProtoFeed, that is, a feed with all the same attributes. """ 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
python
def copy(self): """ Return a copy of this ProtoFeed, that is, a feed with all the same attributes. """ 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", ")", ":", "other", "=", "ProtoFeed", "(", ")", "for", "key", "in", "cs", ".", "PROTOFEED_ATTRS", ":", "value", "=", "getattr", "(", "self", ",", "key", ")", "if", "isinstance", "(", "value", ",", "pd", ".", "DataFrame", ...
Return a copy of this ProtoFeed, that is, a feed with all the same attributes.
[ "Return", "a", "copy", "of", "this", "ProtoFeed", "that", "is", "a", "feed", "with", "all", "the", "same", "attributes", "." ]
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/protofeed.py#L73-L86
train
49,610
dougn/jsontree
jsontree.py
clone
def clone(root, jsontreecls=jsontree, datetimeencoder=_datetimeencoder, datetimedecoder=_datetimedecoder): """Clone an object by first searializing out and then loading it back in. """ return json.loads(json.dumps(root, cls=JSONTreeEncoder, datetimeencoder=datetimeencoder), cls=JSONTreeDecoder, jsontreecls=jsontreecls, datetimedecoder=datetimedecoder)
python
def clone(root, jsontreecls=jsontree, datetimeencoder=_datetimeencoder, datetimedecoder=_datetimedecoder): """Clone an object by first searializing out and then loading it back in. """ 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", ")", ":", "return", "json", ".", "loads", "(", "json", ".", "dumps", "(", "root", ",", "cls", ...
Clone an object by first searializing out and then loading it back in.
[ "Clone", "an", "object", "by", "first", "searializing", "out", "and", "then", "loading", "it", "back", "in", "." ]
e65ebc220528dfc15acb3813ab77c936c1ffc623
https://github.com/dougn/jsontree/blob/e65ebc220528dfc15acb3813ab77c936c1ffc623/jsontree.py#L233-L240
train
49,611
dougn/jsontree
jsontree.py
load
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 """ return json.load(fp, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kargs)
python
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 """ 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", "=", ...
JSON load from file function that defaults the loading class to be JSONTreeDecoder
[ "JSON", "load", "from", "file", "function", "that", "defaults", "the", "loading", "class", "to", "be", "JSONTreeDecoder" ]
e65ebc220528dfc15acb3813ab77c936c1ffc623
https://github.com/dougn/jsontree/blob/e65ebc220528dfc15acb3813ab77c936c1ffc623/jsontree.py#L261-L269
train
49,612
dougn/jsontree
jsontree.py
loads
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 """ return json.loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kargs)
python
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 """ 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", "=", ...
JSON load from string function that defaults the loading class to be JSONTreeDecoder
[ "JSON", "load", "from", "string", "function", "that", "defaults", "the", "loading", "class", "to", "be", "JSONTreeDecoder" ]
e65ebc220528dfc15acb3813ab77c936c1ffc623
https://github.com/dougn/jsontree/blob/e65ebc220528dfc15acb3813ab77c936c1ffc623/jsontree.py#L271-L279
train
49,613
facelessuser/pyspelling
pyspelling/filters/python.py
PythonFilter.header_check
def header_check(self, content): """Special Python encoding check.""" 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 encode
python
def header_check(self, content): """Special Python encoding check.""" 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 encode
[ "def", "header_check", "(", "self", ",", "content", ")", ":", "encode", "=", "None", "m", "=", "RE_PY_ENCODE", ".", "match", "(", "content", ")", "if", "m", ":", "if", "m", ".", "group", "(", "1", ")", ":", "encode", "=", "m", ".", "group", "(", ...
Special Python encoding check.
[ "Special", "Python", "encoding", "check", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L133-L146
train
49,614
facelessuser/pyspelling
pyspelling/filters/python.py
PythonFilter.eval_string_type
def eval_string_type(self, text, is_string=False): """Evaluate string type.""" 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.endswith('*'): wstype.add(value[0].lower()) else: stype.add(value.lower()) if is_string and 'b' not in stype and 'f' not in stype: stype.add('u') return stype, wstype
python
def eval_string_type(self, text, is_string=False): """Evaluate string type.""" 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.endswith('*'): wstype.add(value[0].lower()) else: stype.add(value.lower()) if is_string and 'b' not in stype and 'f' not in stype: stype.add('u') return stype, wstype
[ "def", "eval_string_type", "(", "self", ",", "text", ",", "is_string", "=", "False", ")", ":", "stype", "=", "set", "(", ")", "wstype", "=", "set", "(", ")", "for", "m", "in", "RE_ITER_STRING_TYPES", ".", "finditer", "(", "text", ")", ":", "value", "...
Evaluate string type.
[ "Evaluate", "string", "type", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L148-L169
train
49,615
facelessuser/pyspelling
pyspelling/filters/python.py
PythonFilter.process_strings
def process_strings(self, string, docstrings=False): """Process escapes.""" 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 content = m.group(3) if is_raw and (not is_format or not self.decode_escapes): string = self.norm_nl(content) elif is_raw and is_format: string = self.norm_nl(FE_RFESC.sub(self.replace_unicode, content)) elif is_bytes: string = self.norm_nl(RE_BESC.sub(self.replace_bytes, content)) elif is_format: string = self.norm_nl(RE_FESC.sub(self.replace_unicode, content)) else: string = self.norm_nl(RE_ESC.sub(self.replace_unicode, content)) return textwrap.dedent(RE_NON_PRINTABLE.sub('\n', string) if is_bytes else string), is_bytes
python
def process_strings(self, string, docstrings=False): """Process escapes.""" 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 content = m.group(3) if is_raw and (not is_format or not self.decode_escapes): string = self.norm_nl(content) elif is_raw and is_format: string = self.norm_nl(FE_RFESC.sub(self.replace_unicode, content)) elif is_bytes: string = self.norm_nl(RE_BESC.sub(self.replace_bytes, content)) elif is_format: string = self.norm_nl(RE_FESC.sub(self.replace_unicode, content)) else: string = self.norm_nl(RE_ESC.sub(self.replace_unicode, content)) return textwrap.dedent(RE_NON_PRINTABLE.sub('\n', string) if is_bytes else string), is_bytes
[ "def", "process_strings", "(", "self", ",", "string", ",", "docstrings", "=", "False", ")", ":", "m", "=", "RE_STRING_TYPE", ".", "match", "(", "string", ")", "stype", "=", "self", ".", "get_string_type", "(", "m", ".", "group", "(", "1", ")", "if", ...
Process escapes.
[ "Process", "escapes", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L225-L247
train
49,616
runfalk/spans
spans/_utils.py
find_slots
def find_slots(cls): """Return a set of all slots for a given class and its parents""" 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
python
def find_slots(cls): """Return a set of all slots for a given class and its parents""" 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", ")", ":", "slots", "=", "set", "(", ")", "for", "c", "in", "cls", ".", "__mro__", ":", "cslots", "=", "getattr", "(", "c", ",", "\"__slots__\"", ",", "tuple", "(", ")", ")", "if", "not", "cslots", ":", "continue", ...
Return a set of all slots for a given class and its parents
[ "Return", "a", "set", "of", "all", "slots", "for", "a", "given", "class", "and", "its", "parents" ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/_utils.py#L33-L47
train
49,617
runfalk/spans
spans/types.py
_is_valid_date
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. """ if accept_none and obj is None: return True return isinstance(obj, date) and not isinstance(obj, datetime)
python
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. """ 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", ")", ":", "if", "accept_none", "and", "obj", "is", "None", ":", "return", "True", "return", "isinstance", "(", "obj", ",", "date", ")", "and", "not", "isinstance", "(", "obj", ",", "...
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.
[ "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", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1100-L1112
train
49,618
runfalk/spans
spans/types.py
Range.empty
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. """ self = cls.__new__(cls) self._range = _empty_internal_range return self
python
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. """ self = cls.__new__(cls) self._range = _empty_internal_range return self
[ "def", "empty", "(", "cls", ")", ":", "self", "=", "cls", ".", "__new__", "(", "cls", ")", "self", ".", "_range", "=", "_empty_internal_range", "return", "self" ]
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.
[ "Returns", "an", "empty", "set", ".", "An", "empty", "set", "is", "unbounded", "and", "only", "contain", "the", "empty", "set", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L92-L106
train
49,619
runfalk/spans
spans/types.py
Range.contains
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(intrange(5, 10, upper_inc=True)) False >>> intrange(1, 10).contains(1) True >>> intrange(1, 10).contains(10) False Contains can also be called using the ``in`` operator. >>> 1 in intrange(1, 10) True This is the same as the ``self @> other`` in PostgreSQL. :param other: Object to be checked whether it exists within this range or not. :return: ``True`` if `other` is completely within this range, otherwise ``False``. :raises TypeError: If `other` is not of the correct type. """ 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): # If the lower bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_lower = True if not self.lower_inf: lower_cmp = operator.le if self.lower_inc else operator.lt is_within_lower = lower_cmp(self.lower, other) # If the upper bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_upper = True if not self.upper_inf: upper_cmp = operator.ge if self.upper_inc else operator.gt is_within_upper = upper_cmp(self.upper, other) return is_within_lower and is_within_upper else: raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other))
python
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(intrange(5, 10, upper_inc=True)) False >>> intrange(1, 10).contains(1) True >>> intrange(1, 10).contains(10) False Contains can also be called using the ``in`` operator. >>> 1 in intrange(1, 10) True This is the same as the ``self @> other`` in PostgreSQL. :param other: Object to be checked whether it exists within this range or not. :return: ``True`` if `other` is completely within this range, otherwise ``False``. :raises TypeError: If `other` is not of the correct type. """ 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): # If the lower bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_lower = True if not self.lower_inf: lower_cmp = operator.le if self.lower_inc else operator.lt is_within_lower = lower_cmp(self.lower, other) # If the upper bounary is not unbound we can safely perform the # comparison. Otherwise we'll try to compare a scalar to None, which # is bad is_within_upper = True if not self.upper_inf: upper_cmp = operator.ge if self.upper_inc else operator.gt is_within_upper = upper_cmp(self.upper, other) return is_within_lower and is_within_upper else: raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other))
[ "def", "contains", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "not", "self", ":", "return", "not", "other", "elif", "not", "other", "or", "other", ".", "startsafter", "(", "self", ")", "and...
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(intrange(5, 10, upper_inc=True)) False >>> intrange(1, 10).contains(1) True >>> intrange(1, 10).contains(10) False Contains can also be called using the ``in`` operator. >>> 1 in intrange(1, 10) True This is the same as the ``self @> other`` in PostgreSQL. :param other: Object to be checked whether it exists within this range or not. :return: ``True`` if `other` is completely within this range, otherwise ``False``. :raises TypeError: If `other` is not of the correct type.
[ "Return", "True", "if", "this", "contains", "other", ".", "Other", "may", "be", "either", "range", "of", "same", "type", "or", "scalar", "of", "same", "type", "as", "the", "boundaries", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L289-L347
train
49,620
runfalk/spans
spans/types.py
Range.within
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 PostgreSQL ``self`` in this can't be a scalar value. :param other: Range to test against. :return: ``True`` if this range is completely within the given range, otherwise ``False``. :raises TypeError: If given range is of the wrong type. .. seealso:: This method is the inverse of :meth:`~spans.types.Range.contains` """ if not self.is_valid_range(other): raise TypeError( "Unsupported type to test for inclusion '{0.__class__.__name__}'".format( other)) return other.contains(self)
python
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 PostgreSQL ``self`` in this can't be a scalar value. :param other: Range to test against. :return: ``True`` if this range is completely within the given range, otherwise ``False``. :raises TypeError: If given range is of the wrong type. .. seealso:: This method is the inverse of :meth:`~spans.types.Range.contains` """ 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", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "raise", "TypeError", "(", "\"Unsupported type to test for inclusion '{0.__class__.__name__}'\"", ".", "format", "(", "other", ")", ")", "re...
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 PostgreSQL ``self`` in this can't be a scalar value. :param other: Range to test against. :return: ``True`` if this range is completely within the given range, otherwise ``False``. :raises TypeError: If given range is of the wrong type. .. seealso:: This method is the inverse of :meth:`~spans.types.Range.contains`
[ "Tests", "if", "this", "range", "is", "within", "other", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L349-L377
train
49,621
runfalk/spans
spans/types.py
Range.overlap
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. :return: ``True`` if ranges overlap, otherwise ``False``. :raises TypeError: If `other` is of another type than this range. .. seealso:: If you need to know which part that overlapped, consider using :meth:`~spans.types.Range.intersection`. """ # 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 intervals seem adjacent even though they are not if a.upper_inf or b.lower_inf: return True return a.upper > b.lower or a.upper == b.lower and a.upper_inc and b.lower_inc
python
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. :return: ``True`` if ranges overlap, otherwise ``False``. :raises TypeError: If `other` is of another type than this range. .. seealso:: If you need to know which part that overlapped, consider using :meth:`~spans.types.Range.intersection`. """ # 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 intervals seem adjacent even though they are not if a.upper_inf or b.lower_inf: return True return a.upper > b.lower or a.upper == b.lower and a.upper_inc and b.lower_inc
[ "def", "overlap", "(", "self", ",", "other", ")", ":", "# Special case for empty ranges", "if", "not", "self", "or", "not", "other", ":", "return", "False", "if", "self", "<", "other", ":", "a", ",", "b", "=", "self", ",", "other", "else", ":", "a", ...
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. :return: ``True`` if ranges overlap, otherwise ``False``. :raises TypeError: If `other` is of another type than this range. .. seealso:: If you need to know which part that overlapped, consider using :meth:`~spans.types.Range.intersection`.
[ "Returns", "True", "if", "both", "ranges", "share", "any", "points", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L379-L412
train
49,622
runfalk/spans
spans/types.py
Range.adjacent
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 ``-|-`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if this range is adjacent with `other`, otherwise ``False``. :raises TypeError: If given argument is of invalid type """ 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 return ( (self.lower == other.upper and self.lower_inc != other.upper_inc) or (self.upper == other.lower and self.upper_inc != other.lower_inc))
python
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 ``-|-`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if this range is adjacent with `other`, otherwise ``False``. :raises TypeError: If given argument is of invalid type """ 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 return ( (self.lower == other.upper and self.lower_inc != other.upper_inc) or (self.upper == other.lower and self.upper_inc != other.lower_inc))
[ "def", "adjacent", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "raise", "TypeError", "(", "\"Unsupported type to test for inclusion '{0.__class__.__name__}'\"", ".", "format", "(", "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 ``-|-`` operator for two ranges in PostgreSQL. :param other: Range to test against. :return: ``True`` if this range is adjacent with `other`, otherwise ``False``. :raises TypeError: If given argument is of invalid type
[ "Returns", "True", "if", "ranges", "are", "directly", "next", "to", "each", "other", "but", "does", "not", "overlap", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L414-L443
train
49,623
runfalk/spans
spans/types.py
Range.union
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 two sets are neither adjacent nor overlaps. >>> intrange(1, 5).union(intrange(10, 15)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Ranges must be either adjacent or overlapping This does not modify the range in place. This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to merge with. :return: A new range that is the union of this and `other`. :raises ValueError: If `other` can not be merged with this range. """ 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 # Order ranges to simplify checks if self < other: a, b = self, other else: a, b = other, self if (a.upper < b.lower or a.upper == b.lower and not a.upper_inc and not b.lower_inc) and not a.adjacent(b): raise ValueError("Ranges must be either adjacent or overlapping") # a.lower is guaranteed to be the lower bound, but either a.upper or # b.upper can be the upper bound if a.upper == b.upper: upper = a.upper upper_inc = a.upper_inc or b.upper_inc elif a.upper < b.upper: upper = b.upper upper_inc = b.upper_inc else: upper = a.upper upper_inc = a.upper_inc return self.__class__(a.lower, upper, a.lower_inc, upper_inc)
python
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 two sets are neither adjacent nor overlaps. >>> intrange(1, 5).union(intrange(10, 15)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Ranges must be either adjacent or overlapping This does not modify the range in place. This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to merge with. :return: A new range that is the union of this and `other`. :raises ValueError: If `other` can not be merged with this range. """ 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 # Order ranges to simplify checks if self < other: a, b = self, other else: a, b = other, self if (a.upper < b.lower or a.upper == b.lower and not a.upper_inc and not b.lower_inc) and not a.adjacent(b): raise ValueError("Ranges must be either adjacent or overlapping") # a.lower is guaranteed to be the lower bound, but either a.upper or # b.upper can be the upper bound if a.upper == b.upper: upper = a.upper upper_inc = a.upper_inc or b.upper_inc elif a.upper < b.upper: upper = b.upper upper_inc = b.upper_inc else: upper = a.upper upper_inc = a.upper_inc return self.__class__(a.lower, upper, a.lower_inc, upper_inc)
[ "def", "union", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "\"Unsupported type to test for union '{.__class__.__name__}'\"", "raise", "TypeError", "(", "msg", ".", "format", "(", "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 two sets are neither adjacent nor overlaps. >>> intrange(1, 5).union(intrange(10, 15)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Ranges must be either adjacent or overlapping This does not modify the range in place. This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to merge with. :return: A new range that is the union of this and `other`. :raises ValueError: If `other` can not be merged with this range.
[ "Merges", "this", "range", "with", "a", "given", "range", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L445-L503
train
49,624
runfalk/spans
spans/types.py
Range.difference
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)) >>> intrange(1, 5).difference(intrange(1, 10)) intrange(empty) The difference can not be computed if the resulting range would be split in two separate ranges. This happens when the given range is completely within this range and does not start or end at the same value. >>> intrange(1, 15).difference(intrange(5, 10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Other range must not be within this range This does not modify the range in place. This is the same as the ``-`` operator for two ranges in PostgreSQL. :param other: Range to difference against. :return: A new range that is the difference between this and `other`. :raises ValueError: If difference bethween this and `other` can not be computed. """ 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 # If self is contained within other, the result is empty elif self in other: return self.empty() elif other in self and not (self.startswith(other) or self.endswith(other)): raise ValueError("Other range must not be within this range") elif self.endsbefore(other): return self.replace(upper=other.lower, upper_inc=not other.lower_inc) elif self.startsafter(other): return self.replace(lower=other.upper, lower_inc=not other.upper_inc) else: return self.empty()
python
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)) >>> intrange(1, 5).difference(intrange(1, 10)) intrange(empty) The difference can not be computed if the resulting range would be split in two separate ranges. This happens when the given range is completely within this range and does not start or end at the same value. >>> intrange(1, 15).difference(intrange(5, 10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Other range must not be within this range This does not modify the range in place. This is the same as the ``-`` operator for two ranges in PostgreSQL. :param other: Range to difference against. :return: A new range that is the difference between this and `other`. :raises ValueError: If difference bethween this and `other` can not be computed. """ 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 # If self is contained within other, the result is empty elif self in other: return self.empty() elif other in self and not (self.startswith(other) or self.endswith(other)): raise ValueError("Other range must not be within this range") elif self.endsbefore(other): return self.replace(upper=other.lower, upper_inc=not other.lower_inc) elif self.startsafter(other): return self.replace(lower=other.upper, lower_inc=not other.upper_inc) else: return self.empty()
[ "def", "difference", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "\"Unsupported type to test for difference '{.__class__.__name__}'\"", "raise", "TypeError", "(", "msg", ".", "format", "(", ...
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)) >>> intrange(1, 5).difference(intrange(1, 10)) intrange(empty) The difference can not be computed if the resulting range would be split in two separate ranges. This happens when the given range is completely within this range and does not start or end at the same value. >>> intrange(1, 15).difference(intrange(5, 10)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Other range must not be within this range This does not modify the range in place. This is the same as the ``-`` operator for two ranges in PostgreSQL. :param other: Range to difference against. :return: A new range that is the difference between this and `other`. :raises ValueError: If difference bethween this and `other` can not be computed.
[ "Compute", "the", "difference", "between", "this", "and", "a", "given", "range", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L505-L554
train
49,625
runfalk/spans
spans/types.py
Range.intersection
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) >>> intrange(1, 10).intersection(intrange(5, 10)) intrange([5,10)) This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to interect with. :return: A new range that is the intersection between this and `other`. """ 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() lower_end_span = self if self.startsafter(other) else other upper_end_span = self if self.endsbefore(other) else other return lower_end_span.replace( upper=upper_end_span.upper, upper_inc=upper_end_span.upper_inc)
python
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) >>> intrange(1, 10).intersection(intrange(5, 10)) intrange([5,10)) This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to interect with. :return: A new range that is the intersection between this and `other`. """ 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() lower_end_span = self if self.startsafter(other) else other upper_end_span = self if self.endsbefore(other) else other return lower_end_span.replace( upper=upper_end_span.upper, upper_inc=upper_end_span.upper_inc)
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "\"Unsupported type to test for intersection '{.__class__.__name__}'\"", "raise", "TypeError", "(", "msg", ".", "format", "(...
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) >>> intrange(1, 10).intersection(intrange(5, 10)) intrange([5,10)) This is the same as the ``+`` operator for two ranges in PostgreSQL. :param other: Range to interect with. :return: A new range that is the intersection between this and `other`.
[ "Returns", "a", "new", "range", "containing", "all", "points", "shared", "by", "both", "ranges", ".", "If", "no", "points", "are", "shared", "an", "empty", "range", "is", "returned", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L556-L587
train
49,626
runfalk/spans
spans/types.py
Range.startswith
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 with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 else: return False else: raise TypeError( "Unsupported type to test for starts with '{}'".format( other.__class__.__name__))
python
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 with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 else: return False else: raise TypeError( "Unsupported type to test for starts with '{}'".format( other.__class__.__name__))
[ "def", "startswith", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "lower_inc", "==", "other", ".", "lower_inc", ":", "return", "self", ".", "lower", "==", "other", ".", "lower", ...
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 with `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "Test", "if", "this", "range", "starts", "with", "other", ".", "other", "may", "be", "either", "range", "or", "scalar", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L589-L617
train
49,627
runfalk/spans
spans/types.py
Range.endswith
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 `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 else: return False else: raise TypeError( "Unsupported type to test for ends with '{}'".format( other.__class__.__name__))
python
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 `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 else: return False else: raise TypeError( "Unsupported type to test for ends with '{}'".format( other.__class__.__name__))
[ "def", "endswith", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "upper_inc", "==", "other", ".", "upper_inc", ":", "return", "self", ".", "upper", "==", "other", ".", "upper", "e...
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 `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "Test", "if", "this", "range", "ends", "with", "other", ".", "other", "may", "be", "either", "range", "or", "scalar", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L619-L647
train
49,628
runfalk/spans
spans/types.py
Range.startsafter
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, 5).startsafter(0) True >>> intrange(1, 5).startsafter(intrange(0, 5)) True If ``other`` has the same start as the given :param other: Range or scalar to test. :return: ``True`` if this range starts after `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 self.lower > other.lower elif self.is_valid_scalar(other): return self.lower >= other else: raise TypeError( "Unsupported type to test for starts after '{}'".format( other.__class__.__name__))
python
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, 5).startsafter(0) True >>> intrange(1, 5).startsafter(intrange(0, 5)) True If ``other`` has the same start as the given :param other: Range or scalar to test. :return: ``True`` if this range starts after `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 self.lower > other.lower elif self.is_valid_scalar(other): return self.lower >= other else: raise TypeError( "Unsupported type to test for starts after '{}'".format( other.__class__.__name__))
[ "def", "startsafter", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "lower", "==", "other", ".", "lower", ":", "return", "other", ".", "lower_inc", "or", "not", "self", ".", "lowe...
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, 5).startsafter(0) True >>> intrange(1, 5).startsafter(intrange(0, 5)) True If ``other`` has the same start as the given :param other: Range or scalar to test. :return: ``True`` if this range starts after `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "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"...
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L649-L682
train
49,629
runfalk/spans
spans/types.py
Range.endsbefore
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).endsbefore(5) True >>> intrange(1, 5).endsbefore(intrange(1, 5)) True :param other: Range or scalar to test. :return: ``True`` if this range ends before `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 self.upper <= other.upper elif self.is_valid_scalar(other): return self.upper <= other else: raise TypeError( "Unsupported type to test for ends before '{}'".format( other.__class__.__name__))
python
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).endsbefore(5) True >>> intrange(1, 5).endsbefore(intrange(1, 5)) True :param other: Range or scalar to test. :return: ``True`` if this range ends before `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type. """ 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 self.upper <= other.upper elif self.is_valid_scalar(other): return self.upper <= other else: raise TypeError( "Unsupported type to test for ends before '{}'".format( other.__class__.__name__))
[ "def", "endsbefore", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_valid_range", "(", "other", ")", ":", "if", "self", ".", "upper", "==", "other", ".", "upper", ":", "return", "not", "self", ".", "upper_inc", "or", "other", ".", "upper...
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).endsbefore(5) True >>> intrange(1, 5).endsbefore(intrange(1, 5)) True :param other: Range or scalar to test. :return: ``True`` if this range ends before `other`, otherwise ``False`` :raises TypeError: If `other` is of the wrong type.
[ "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",...
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L684-L715
train
49,630
runfalk/spans
spans/types.py
Range.left_of
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. >>> intrange(1, 5) << intrange(5, 10) True The choice of overloading ``<<`` might seem strange, but it is to mimick PostgreSQL's operators for ranges. As this is not obvious the use of ``<<`` is discouraged. :param other: Range to test against. :return: ``True`` if this range is completely to the left of ``other``. """ 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)
python
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. >>> intrange(1, 5) << intrange(5, 10) True The choice of overloading ``<<`` might seem strange, but it is to mimick PostgreSQL's operators for ranges. As this is not obvious the use of ``<<`` is discouraged. :param other: Range to test against. :return: ``True`` if this range is completely to the left of ``other``. """ 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", ")", ":", "if", "not", "self", ".", "is_valid_range", "(", "other", ")", ":", "msg", "=", "(", "\"Left of is not supported for '{}', provide a proper range \"", "\"class\"", ")", ".", "format", "(", "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. >>> intrange(1, 5) << intrange(5, 10) True The choice of overloading ``<<`` might seem strange, but it is to mimick PostgreSQL's operators for ranges. As this is not obvious the use of ``<<`` is discouraged. :param other: Range to test against. :return: ``True`` if this range is completely to the left of ``other``.
[ "Test", "if", "this", "range", "other", "is", "strictly", "left", "of", "other", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L717-L746
train
49,631
runfalk/spans
spans/types.py
OffsetableRangeMixin.offset
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 and are never modified in place. :param offset: Scalar to offset by. .. versionadded:: 0.1.3 """ # 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 offset '{offset_type.__name__}'" " expected '{expected_type.__name__}'").format( expected_type=offset_type, offset_type=offset.__class__)) lower = None if self.lower is None else self.lower + offset upper = None if self.upper is None else self.upper + offset return self.replace(lower=lower, upper=upper)
python
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 and are never modified in place. :param offset: Scalar to offset by. .. versionadded:: 0.1.3 """ # 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 offset '{offset_type.__name__}'" " expected '{expected_type.__name__}'").format( expected_type=offset_type, offset_type=offset.__class__)) lower = None if self.lower is None else self.lower + offset upper = None if self.upper is None else self.upper + offset return self.replace(lower=lower, upper=upper)
[ "def", "offset", "(", "self", ",", "offset", ")", ":", "# 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...
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 and are never modified in place. :param offset: Scalar to offset by. .. versionadded:: 0.1.3
[ "Shift", "the", "range", "to", "the", "left", "or", "right", "with", "the", "given", "offset" ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L972-L1006
train
49,632
runfalk/spans
spans/types.py
daterange.from_date
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: ``day`` (default), ``week``, ``american_week``, ``month``, ``quarter`` or ``year``. :return: A new range that contains the given date. .. seealso:: There are convenience methods for most period types: :meth:`~spans.types.daterange.from_week`, :meth:`~spans.types.daterange.from_month`, :meth:`~spans.types.daterange.from_quarter` and :meth:`~spans.types.daterange.from_year`. :class:`~spans.types.PeriodRange` has the same interface but is period aware. This means it is possible to get things like next week or month. .. versionchanged:: 0.4.0 Added the period parameter. """ 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((date.weekday() + 1) % 7) return cls(start, start + timedelta(7)) elif period == "month": start = date.replace(day=1) return cls(start, (start + timedelta(31)).replace(day=1)) elif period == "quarter": start = date.replace(month=(date.month - 1) // 3 * 3 + 1, day=1) return cls(start, (start + timedelta(93)).replace(day=1)) elif period == "year": start = date.replace(month=1, day=1) return cls(start, (start + timedelta(366)).replace(day=1)) else: raise ValueError("Unexpected period, got {!r}".format(period))
python
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: ``day`` (default), ``week``, ``american_week``, ``month``, ``quarter`` or ``year``. :return: A new range that contains the given date. .. seealso:: There are convenience methods for most period types: :meth:`~spans.types.daterange.from_week`, :meth:`~spans.types.daterange.from_month`, :meth:`~spans.types.daterange.from_quarter` and :meth:`~spans.types.daterange.from_year`. :class:`~spans.types.PeriodRange` has the same interface but is period aware. This means it is possible to get things like next week or month. .. versionchanged:: 0.4.0 Added the period parameter. """ 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((date.weekday() + 1) % 7) return cls(start, start + timedelta(7)) elif period == "month": start = date.replace(day=1) return cls(start, (start + timedelta(31)).replace(day=1)) elif period == "quarter": start = date.replace(month=(date.month - 1) // 3 * 3 + 1, day=1) return cls(start, (start + timedelta(93)).replace(day=1)) elif period == "year": start = date.replace(month=1, day=1) return cls(start, (start + timedelta(366)).replace(day=1)) else: raise ValueError("Unexpected period, got {!r}".format(period))
[ "def", "from_date", "(", "cls", ",", "date", ",", "period", "=", "None", ")", ":", "if", "period", "is", "None", "or", "period", "==", "\"day\"", ":", "return", "cls", "(", "date", ",", "date", ",", "upper_inc", "=", "True", ")", "elif", "period", ...
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: ``day`` (default), ``week``, ``american_week``, ``month``, ``quarter`` or ``year``. :return: A new range that contains the given date. .. seealso:: There are convenience methods for most period types: :meth:`~spans.types.daterange.from_week`, :meth:`~spans.types.daterange.from_month`, :meth:`~spans.types.daterange.from_quarter` and :meth:`~spans.types.daterange.from_year`. :class:`~spans.types.PeriodRange` has the same interface but is period aware. This means it is possible to get things like next week or month. .. versionchanged:: 0.4.0 Added the period parameter.
[ "Create", "a", "day", "long", "daterange", "from", "for", "the", "given", "date", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1155-L1203
train
49,633
runfalk/spans
spans/types.py
daterange.from_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 """ first_day = date_from_iso_week(year, iso_week) return cls.from_date(first_day, period="week")
python
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 """ first_day = date_from_iso_week(year, iso_week) return cls.from_date(first_day, period="week")
[ "def", "from_week", "(", "cls", ",", "year", ",", "iso_week", ")", ":", "first_day", "=", "date_from_iso_week", "(", "year", ",", "iso_week", ")", "return", "cls", ".", "from_date", "(", "first_day", ",", "period", "=", "\"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
[ "Create", "daterange", "based", "on", "a", "year", "and", "an", "ISO", "week" ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1206-L1218
train
49,634
runfalk/spans
spans/types.py
daterange.from_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 """ first_day = date(year, month, 1) return cls.from_date(first_day, period="month")
python
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 """ first_day = date(year, month, 1) return cls.from_date(first_day, period="month")
[ "def", "from_month", "(", "cls", ",", "year", ",", "month", ")", ":", "first_day", "=", "date", "(", "year", ",", "month", ",", "1", ")", "return", "cls", ".", "from_date", "(", "first_day", ",", "period", "=", "\"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
[ "Create", "daterange", "based", "on", "a", "year", "and", "amonth" ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1224-L1236
train
49,635
runfalk/spans
spans/types.py
daterange.from_quarter
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 as an integer between 1 and 4 :return: A new ``daterange`` for the given quarter .. versionadded:: 0.4.0 """ 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 ValueError(error_msg.format(quarter)) first_day = date(year, quarter_months[quarter], 1) return cls.from_date(first_day, period="quarter")
python
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 as an integer between 1 and 4 :return: A new ``daterange`` for the given quarter .. versionadded:: 0.4.0 """ 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 ValueError(error_msg.format(quarter)) first_day = date(year, quarter_months[quarter], 1) return cls.from_date(first_day, period="quarter")
[ "def", "from_quarter", "(", "cls", ",", "year", ",", "quarter", ")", ":", "quarter_months", "=", "{", "1", ":", "1", ",", "2", ":", "4", ",", "3", ":", "7", ",", "4", ":", "10", ",", "}", "if", "quarter", "not", "in", "quarter_months", ":", "er...
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 as an integer between 1 and 4 :return: A new ``daterange`` for the given quarter .. versionadded:: 0.4.0
[ "Create", "daterange", "based", "on", "a", "year", "and", "quarter", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1239-L1271
train
49,636
runfalk/spans
spans/types.py
daterange.from_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 """ first_day = date(year, 1, 1) return cls.from_date(first_day, period="year")
python
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 """ first_day = date(year, 1, 1) return cls.from_date(first_day, period="year")
[ "def", "from_year", "(", "cls", ",", "year", ")", ":", "first_day", "=", "date", "(", "year", ",", "1", ",", "1", ")", "return", "cls", ".", "from_date", "(", "first_day", ",", "period", "=", "\"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
[ "Create", "daterange", "based", "on", "a", "year" ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1274-L1285
train
49,637
runfalk/spans
spans/types.py
PeriodRange.offset
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 negative as well. :param offset: Number of periods to offset this range by. A period is either a day, week, american week, month, quarter or year, depending on this range's period type. :return: New offset :class:`~spans.types.PeriodRange` """ 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
python
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 negative as well. :param offset: Number of periods to offset this range by. A period is either a day, week, american week, month, quarter or year, depending on this range's period type. :return: New offset :class:`~spans.types.PeriodRange` """ 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", ")", ":", "span", "=", "self", "if", "offset", ">", "0", ":", "for", "i", "in", "iter_range", "(", "offset", ")", ":", "span", "=", "span", ".", "next_period", "(", ")", "elif", "offset", "<", "0", ":"...
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 negative as well. :param offset: Number of periods to offset this range by. A period is either a day, week, american week, month, quarter or year, depending on this range's period type. :return: New offset :class:`~spans.types.PeriodRange`
[ "Offset", "the", "date", "range", "by", "the", "given", "amount", "of", "periods", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1406-L1428
train
49,638
runfalk/spans
spans/types.py
PeriodRange.prev_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 before this period """ return self.from_date(self.prev(self.lower), period=self.period)
python
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 before this period """ return self.from_date(self.prev(self.lower), period=self.period)
[ "def", "prev_period", "(", "self", ")", ":", "return", "self", ".", "from_date", "(", "self", ".", "prev", "(", "self", ".", "lower", ")", ",", "period", "=", "self", ".", "period", ")" ]
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 before this period
[ "The", "period", "before", "this", "range", "." ]
59ed73407a569c3be86cfdb4b8f438cb8c794540
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L1430-L1442
train
49,639
JMSwag/dsdev-utils
dsdev_utils/crypto.py
get_package_hashes
def get_package_hashes(filename): """Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash """ 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
python
def get_package_hashes(filename): """Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash """ 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", ")", ":", "log", ".", "debug", "(", "'Getting package hashes'", ")", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":"...
Provides hash of given filename. Args: filename (str): Name of file to hash Returns: (str): sha256 hash
[ "Provides", "hash", "of", "given", "filename", "." ]
5adbf9b3fd9fff92d1dd714423b08e26a5038e14
https://github.com/JMSwag/dsdev-utils/blob/5adbf9b3fd9fff92d1dd714423b08e26a5038e14/dsdev_utils/crypto.py#L31-L49
train
49,640
facelessuser/pyspelling
pyspelling/filters/stylesheets.py
StylesheetsFilter.extend_src
def extend_src(self, content, context): """Extend source list.""" self.extend_src_text(content, context, self.block_comments, 'block-comment') self.extend_src_text(content, context, self.line_comments, 'line-comment')
python
def extend_src(self, content, context): """Extend source list.""" 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", ")", ":", "self", ".", "extend_src_text", "(", "content", ",", "context", ",", "self", ".", "block_comments", ",", "'block-comment'", ")", "self", ".", "extend_src_text", "(", "content", ",", ...
Extend source list.
[ "Extend", "source", "list", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L137-L141
train
49,641
facelessuser/pyspelling
pyspelling/filters/stylesheets.py
StylesheetsFilter._filter
def _filter(self, text, context, encoding): """Filter JavaScript comments.""" 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
python
def _filter(self, text, context, encoding): """Filter JavaScript comments.""" 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", ")", ":", "content", "=", "[", "]", "self", ".", "current_encoding", "=", "encoding", "self", ".", "line_num", "=", "1", "self", ".", "prev_line", "=", "-", "1", "self", "."...
Filter JavaScript comments.
[ "Filter", "JavaScript", "comments", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/stylesheets.py#L149-L163
train
49,642
deshima-dev/decode
decode/io/functions.py
savefits
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(). """ ### 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_2d']) data = cube.values.T elif ndim == 3: if dropdeg: header = fits.Header(hdrdata['dcube_2d']) data = cube.values[:, :, 0].T else: header = fits.Header(hdrdata['dcube_3d']) kidfq = cube.kidfq.values freqrange = ~np.isnan(kidfq) orderedfq = np.argsort(kidfq[freqrange]) newcube = cube[:, :, orderedfq] data = newcube.values.T else: raise TypeError(ndim) ### update Header if cube.coordsys == 'AZEL': header.update({'CTYPE1': 'dAZ', 'CTYPE2': 'dEL'}) elif cube.coordsys == 'RADEC': header.update({'OBSRA': float(cube.xref), 'OBSDEC': float(cube.yref)}) else: pass header.update({'CRVAL1': float(cube.x[0]), 'CDELT1': float(cube.x[1] - cube.x[0]), 'CRVAL2': float(cube.y[0]), 'CDELT2': float(cube.y[1] - cube.y[0]), 'DATE': datetime.now(timezone('UTC')).isoformat()}) if (ndim == 3) and (not dropdeg): header.update({'CRVAL3': float(newcube.kidfq[0]), 'CDELT3': float(newcube.kidfq[1] - newcube.kidfq[0])}) fitsname = str(Path(fitsname).expanduser()) fits.writeto(fitsname, data, header, **kwargs) logger.info('{} has been created.'.format(fitsname))
python
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(). """ ### 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_2d']) data = cube.values.T elif ndim == 3: if dropdeg: header = fits.Header(hdrdata['dcube_2d']) data = cube.values[:, :, 0].T else: header = fits.Header(hdrdata['dcube_3d']) kidfq = cube.kidfq.values freqrange = ~np.isnan(kidfq) orderedfq = np.argsort(kidfq[freqrange]) newcube = cube[:, :, orderedfq] data = newcube.values.T else: raise TypeError(ndim) ### update Header if cube.coordsys == 'AZEL': header.update({'CTYPE1': 'dAZ', 'CTYPE2': 'dEL'}) elif cube.coordsys == 'RADEC': header.update({'OBSRA': float(cube.xref), 'OBSDEC': float(cube.yref)}) else: pass header.update({'CRVAL1': float(cube.x[0]), 'CDELT1': float(cube.x[1] - cube.x[0]), 'CRVAL2': float(cube.y[0]), 'CDELT2': float(cube.y[1] - cube.y[0]), 'DATE': datetime.now(timezone('UTC')).isoformat()}) if (ndim == 3) and (not dropdeg): header.update({'CRVAL3': float(newcube.kidfq[0]), 'CDELT3': float(newcube.kidfq[1] - newcube.kidfq[0])}) fitsname = str(Path(fitsname).expanduser()) fits.writeto(fitsname, data, header, **kwargs) logger.info('{} has been created.'.format(fitsname))
[ "def", "savefits", "(", "cube", ",", "fitsname", ",", "*", "*", "kwargs", ")", ":", "### pick up kwargs", "dropdeg", "=", "kwargs", ".", "pop", "(", "'dropdeg'", ",", "False", ")", "ndim", "=", "len", "(", "cube", ".", "dims", ")", "### load yaml", "FI...
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().
[ "Save", "a", "cube", "to", "a", "3D", "-", "cube", "FITS", "file", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/io/functions.py#L268-L321
train
49,643
deshima-dev/decode
decode/io/functions.py
loadnetcdf
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. """ 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(): if val.dtype.kind == 'S': dataarray[key] = val.astype('U') elif val.dtype == np.int32: dataarray[key] = val.astype('i8') return dataarray
python
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. """ 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(): if val.dtype.kind == 'S': dataarray[key] = val.astype('U') elif val.dtype == np.int32: dataarray[key] = val.astype('i8') return dataarray
[ "def", "loadnetcdf", "(", "filename", ",", "copy", "=", "True", ")", ":", "filename", "=", "str", "(", "Path", "(", "filename", ")", ".", "expanduser", "(", ")", ")", "if", "copy", ":", "dataarray", "=", "xr", ".", "open_dataarray", "(", "filename", ...
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.
[ "Load", "a", "dataarray", "from", "a", "NetCDF", "file", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/io/functions.py#L324-L350
train
49,644
deshima-dev/decode
decode/io/functions.py
savenetcdf
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. """ 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) logger.info('{} has been created.'.format(filename))
python
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. """ 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) logger.info('{} has been created.'.format(filename))
[ "def", "savenetcdf", "(", "dataarray", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "if", "dataarray", ".", "name", "is", "not", "None", ":", "filename", "=", "dataarray", ".", "name", "else", ":", "filename", "=", "uuid...
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.
[ "Save", "a", "dataarray", "to", "a", "NetCDF", "file", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/io/functions.py#L353-L373
train
49,645
facelessuser/pyspelling
pyspelling/filters/text.py
TextFilter.convert
def convert(self, text, encoding): """Convert the text.""" 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 return text, encoding
python
def convert(self, text, encoding): """Convert the text.""" 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 return text, encoding
[ "def", "convert", "(", "self", ",", "text", ",", "encoding", ")", ":", "if", "self", ".", "normalize", "in", "(", "'NFC'", ",", "'NFKC'", ",", "'NFD'", ",", "'NFKD'", ")", ":", "text", "=", "unicodedata", ".", "normalize", "(", "self", ".", "normaliz...
Convert the text.
[ "Convert", "the", "text", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/text.py#L56-L64
train
49,646
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.get_zip_content
def get_zip_content(self, filename): """Get zip content.""" 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
python
def get_zip_content(self, filename): """Get zip content.""" 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", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "filename", ",", "'r'", ")", "as", "z", ":", "self", ".", "determine_file_type", "(", "z", ")", "for", "item", "in", "z", ".", "infolist", "(", ...
Get zip content.
[ "Get", "zip", "content", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L75-L82
train
49,647
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.get_content
def get_content(self, zipbundle): """Get content.""" 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().decode(encoding) yield text, filename, encoding
python
def get_content(self, zipbundle): """Get content.""" 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().decode(encoding) yield text, filename, encoding
[ "def", "get_content", "(", "self", ",", "zipbundle", ")", ":", "for", "content", ",", "filename", "in", "self", ".", "get_zip_content", "(", "zipbundle", ")", ":", "with", "io", ".", "BytesIO", "(", "content", ")", "as", "b", ":", "encoding", "=", "sel...
Get content.
[ "Get", "content", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L84-L94
train
49,648
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.content_break
def content_break(self, el): """Break on specified boundaries.""" should_break = False if self.type == 'odp': if el.name == 'page' and el.namespace and el.namespace == self.namespaces['draw']: should_break = True return should_break
python
def content_break(self, el): """Break on specified boundaries.""" should_break = False if self.type == 'odp': if el.name == 'page' and el.namespace and el.namespace == self.namespaces['draw']: should_break = True return should_break
[ "def", "content_break", "(", "self", ",", "el", ")", ":", "should_break", "=", "False", "if", "self", ".", "type", "==", "'odp'", ":", "if", "el", ".", "name", "==", "'page'", "and", "el", ".", "namespace", "and", "el", ".", "namespace", "==", "self"...
Break on specified boundaries.
[ "Break", "on", "specified", "boundaries", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L96-L103
train
49,649
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.soft_break
def soft_break(self, el, text): """Apply soft break if needed.""" if el.name == 'p' and el.namespace and el.namespace == self.namespaces["text"]: text.append('\n')
python
def soft_break(self, el, text): """Apply soft break if needed.""" if el.name == 'p' and el.namespace and el.namespace == self.namespaces["text"]: text.append('\n')
[ "def", "soft_break", "(", "self", ",", "el", ",", "text", ")", ":", "if", "el", ".", "name", "==", "'p'", "and", "el", ".", "namespace", "and", "el", ".", "namespace", "==", "self", ".", "namespaces", "[", "\"text\"", "]", ":", "text", ".", "append...
Apply soft break if needed.
[ "Apply", "soft", "break", "if", "needed", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L105-L109
train
49,650
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.extract_tag_metadata
def extract_tag_metadata(self, el): """Extract meta data.""" if self.type == 'odp': if el.namespace and el.namespace == self.namespaces['draw'] and el.name == 'page-thumbnail': name = el.attrs.get('draw:page-number', '') self.additional_context = 'slide{}:'.format(name) super().extract_tag_metadata(el)
python
def extract_tag_metadata(self, el): """Extract meta data.""" if self.type == 'odp': if el.namespace and el.namespace == self.namespaces['draw'] and el.name == 'page-thumbnail': name = el.attrs.get('draw:page-number', '') self.additional_context = 'slide{}:'.format(name) super().extract_tag_metadata(el)
[ "def", "extract_tag_metadata", "(", "self", ",", "el", ")", ":", "if", "self", ".", "type", "==", "'odp'", ":", "if", "el", ".", "namespace", "and", "el", ".", "namespace", "==", "self", ".", "namespaces", "[", "'draw'", "]", "and", "el", ".", "name"...
Extract meta data.
[ "Extract", "meta", "data", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L123-L130
train
49,651
facelessuser/pyspelling
pyspelling/filters/odf.py
OdfFilter.get_sub_node
def get_sub_node(self, node): """Extract node from document if desired.""" subnode = node.find('office:document') if subnode: mimetype = subnode.attrs['office:mimetype'] self.type = MIMEMAP[mimetype] node = node.find('office:body') return node
python
def get_sub_node(self, node): """Extract node from document if desired.""" subnode = node.find('office:document') if subnode: mimetype = subnode.attrs['office:mimetype'] self.type = MIMEMAP[mimetype] node = node.find('office:body') return node
[ "def", "get_sub_node", "(", "self", ",", "node", ")", ":", "subnode", "=", "node", ".", "find", "(", "'office:document'", ")", "if", "subnode", ":", "mimetype", "=", "subnode", ".", "attrs", "[", "'office:mimetype'", "]", "self", ".", "type", "=", "MIMEM...
Extract node from document if desired.
[ "Extract", "node", "from", "document", "if", "desired", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/odf.py#L139-L147
train
49,652
deshima-dev/decode
decode/core/array/functions.py
array
def array(data, tcoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None): """Create an array as an instance of xarray.DataArray with Decode accessor. Args: data (numpy.ndarray): 2D (time x channel) array. tcoords (dict, optional): Dictionary of arrays that label time axis. chcoords (dict, optional): Dictionary of arrays that label channel axis. scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like). datacoords (dict, optional): Dictionary of arrays that label time and channel axes. attrs (dict, optional): Dictionary of attributes to add to the instance. name (str, optional): String that names the instance. Returns: array (decode.array): Deode array. """ # initialize coords with default values array = xr.DataArray(data, dims=('t', 'ch'), attrs=attrs, name=name) array.dca._initcoords() # update coords with input values (if any) if tcoords is not None: array.coords.update({key: ('t', tcoords[key]) for key in tcoords}) if chcoords is not None: array.coords.update({key: ('ch', chcoords[key]) for key in chcoords}) if scalarcoords is not None: array.coords.update(scalarcoords) if datacoords is not None: array.coords.update({key: (('t', 'ch'), datacoords[key]) for key in datacoords}) return array
python
def array(data, tcoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None): """Create an array as an instance of xarray.DataArray with Decode accessor. Args: data (numpy.ndarray): 2D (time x channel) array. tcoords (dict, optional): Dictionary of arrays that label time axis. chcoords (dict, optional): Dictionary of arrays that label channel axis. scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like). datacoords (dict, optional): Dictionary of arrays that label time and channel axes. attrs (dict, optional): Dictionary of attributes to add to the instance. name (str, optional): String that names the instance. Returns: array (decode.array): Deode array. """ # initialize coords with default values array = xr.DataArray(data, dims=('t', 'ch'), attrs=attrs, name=name) array.dca._initcoords() # update coords with input values (if any) if tcoords is not None: array.coords.update({key: ('t', tcoords[key]) for key in tcoords}) if chcoords is not None: array.coords.update({key: ('ch', chcoords[key]) for key in chcoords}) if scalarcoords is not None: array.coords.update(scalarcoords) if datacoords is not None: array.coords.update({key: (('t', 'ch'), datacoords[key]) for key in datacoords}) return array
[ "def", "array", "(", "data", ",", "tcoords", "=", "None", ",", "chcoords", "=", "None", ",", "scalarcoords", "=", "None", ",", "datacoords", "=", "None", ",", "attrs", "=", "None", ",", "name", "=", "None", ")", ":", "# initialize coords with default value...
Create an array as an instance of xarray.DataArray with Decode accessor. Args: data (numpy.ndarray): 2D (time x channel) array. tcoords (dict, optional): Dictionary of arrays that label time axis. chcoords (dict, optional): Dictionary of arrays that label channel axis. scalarcoords (dict, optional): Dictionary of values that don't label any axes (point-like). datacoords (dict, optional): Dictionary of arrays that label time and channel axes. attrs (dict, optional): Dictionary of attributes to add to the instance. name (str, optional): String that names the instance. Returns: array (decode.array): Deode array.
[ "Create", "an", "array", "as", "an", "instance", "of", "xarray", ".", "DataArray", "with", "Decode", "accessor", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L29-L61
train
49,653
deshima-dev/decode
decode/core/array/functions.py
zeros
def zeros(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with zeros. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with zeros. """ data = np.zeros(shape, dtype) return dc.array(data, **kwargs)
python
def zeros(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with zeros. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with zeros. """ data = np.zeros(shape, dtype) return dc.array(data, **kwargs)
[ "def", "zeros", "(", "shape", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "np", ".", "zeros", "(", "shape", ",", "dtype", ")", "return", "dc", ".", "array", "(", "data", ",", "*", "*", "kwargs", ")" ]
Create an array of given shape and type, filled with zeros. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with zeros.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "filled", "with", "zeros", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L64-L76
train
49,654
deshima-dev/decode
decode/core/array/functions.py
ones
def ones(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with ones. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with ones. """ data = np.ones(shape, dtype) return dc.array(data, **kwargs)
python
def ones(shape, dtype=None, **kwargs): """Create an array of given shape and type, filled with ones. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with ones. """ data = np.ones(shape, dtype) return dc.array(data, **kwargs)
[ "def", "ones", "(", "shape", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "np", ".", "ones", "(", "shape", ",", "dtype", ")", "return", "dc", ".", "array", "(", "data", ",", "*", "*", "kwargs", ")" ]
Create an array of given shape and type, filled with ones. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with ones.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "filled", "with", "ones", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L79-L91
train
49,655
deshima-dev/decode
decode/core/array/functions.py
full
def full(shape, fill_value, dtype=None, **kwargs): """Create an array of given shape and type, filled with `fill_value`. Args: shape (sequence of ints): 2D shape of the array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with `fill_value`. """ return (dc.zeros(shape, **kwargs) + fill_value).astype(dtype)
python
def full(shape, fill_value, dtype=None, **kwargs): """Create an array of given shape and type, filled with `fill_value`. Args: shape (sequence of ints): 2D shape of the array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with `fill_value`. """ return (dc.zeros(shape, **kwargs) + fill_value).astype(dtype)
[ "def", "full", "(", "shape", ",", "fill_value", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "(", "dc", ".", "zeros", "(", "shape", ",", "*", "*", "kwargs", ")", "+", "fill_value", ")", ".", "astype", "(", "dtype", ")" ...
Create an array of given shape and type, filled with `fill_value`. Args: shape (sequence of ints): 2D shape of the array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array filled with `fill_value`.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "filled", "with", "fill_value", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L94-L106
train
49,656
deshima-dev/decode
decode/core/array/functions.py
empty
def empty(shape, dtype=None, **kwargs): """Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries. """ data = np.empty(shape, dtype) return dc.array(data, **kwargs)
python
def empty(shape, dtype=None, **kwargs): """Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries. """ data = np.empty(shape, dtype) return dc.array(data, **kwargs)
[ "def", "empty", "(", "shape", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "data", "=", "np", ".", "empty", "(", "shape", ",", "dtype", ")", "return", "dc", ".", "array", "(", "data", ",", "*", "*", "kwargs", ")" ]
Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries.
[ "Create", "an", "array", "of", "given", "shape", "and", "type", "without", "initializing", "entries", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L109-L121
train
49,657
deshima-dev/decode
decode/core/array/functions.py
zeros_like
def zeros_like(array, dtype=None, keepmeta=True): """Create an array of zeros with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If specified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with zeros. """ if keepmeta: return xr.zeros_like(array, dtype) else: return dc.zeros(array.shape, dtype)
python
def zeros_like(array, dtype=None, keepmeta=True): """Create an array of zeros with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If specified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with zeros. """ if keepmeta: return xr.zeros_like(array, dtype) else: return dc.zeros(array.shape, dtype)
[ "def", "zeros_like", "(", "array", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "xr", ".", "zeros_like", "(", "array", ",", "dtype", ")", "else", ":", "return", "dc", ".", "zeros", "(", "array", ...
Create an array of zeros with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If specified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with zeros.
[ "Create", "an", "array", "of", "zeros", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L124-L141
train
49,658
deshima-dev/decode
decode/core/array/functions.py
ones_like
def ones_like(array, dtype=None, keepmeta=True): """Create an array of ones with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with ones. """ if keepmeta: return xr.ones_like(array, dtype) else: return dc.ones(array.shape, dtype)
python
def ones_like(array, dtype=None, keepmeta=True): """Create an array of ones with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with ones. """ if keepmeta: return xr.ones_like(array, dtype) else: return dc.ones(array.shape, dtype)
[ "def", "ones_like", "(", "array", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "xr", ".", "ones_like", "(", "array", ",", "dtype", ")", "else", ":", "return", "dc", ".", "ones", "(", "array", "...
Create an array of ones with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with ones.
[ "Create", "an", "array", "of", "ones", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L144-L161
train
49,659
deshima-dev/decode
decode/core/array/functions.py
full_like
def full_like(array, fill_value, reverse=False, dtype=None, keepmeta=True): """Create an array of `fill_value` with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with `fill_value`. """ if keepmeta: return (dc.zeros_like(array) + fill_value).astype(dtype) else: return dc.full(array.shape, fill_value, dtype)
python
def full_like(array, fill_value, reverse=False, dtype=None, keepmeta=True): """Create an array of `fill_value` with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with `fill_value`. """ if keepmeta: return (dc.zeros_like(array) + fill_value).astype(dtype) else: return dc.full(array.shape, fill_value, dtype)
[ "def", "full_like", "(", "array", ",", "fill_value", ",", "reverse", "=", "False", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "(", "dc", ".", "zeros_like", "(", "array", ")", "+", "fill_value", ...
Create an array of `fill_value` with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. fill_value (scalar or numpy.ndarray): Fill value or array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array filled with `fill_value`.
[ "Create", "an", "array", "of", "fill_value", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L164-L182
train
49,660
deshima-dev/decode
decode/core/array/functions.py
empty_like
def empty_like(array, dtype=None, keepmeta=True): """Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array without initializing entries. """ if keepmeta: return dc.empty(array.shape, dtype, tcoords=array.dca.tcoords, chcoords=array.dca.chcoords, scalarcoords=array.dca.scalarcoords, attrs=array.attrs, name=array.name ) else: return dc.empty(array.shape, dtype)
python
def empty_like(array, dtype=None, keepmeta=True): """Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array without initializing entries. """ if keepmeta: return dc.empty(array.shape, dtype, tcoords=array.dca.tcoords, chcoords=array.dca.chcoords, scalarcoords=array.dca.scalarcoords, attrs=array.attrs, name=array.name ) else: return dc.empty(array.shape, dtype)
[ "def", "empty_like", "(", "array", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "dc", ".", "empty", "(", "array", ".", "shape", ",", "dtype", ",", "tcoords", "=", "array", ".", "dca", ".", "tco...
Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array without initializing entries.
[ "Create", "an", "array", "of", "empty", "with", "the", "same", "shape", "and", "type", "as", "the", "input", "array", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L185-L205
train
49,661
facelessuser/pyspelling
pyspelling/__init__.py
iter_tasks
def iter_tasks(matrix, names, groups): """Iterate tasks.""" # Build name index name_index = dict([(task.get('name', ''), index) for index, task in enumerate(matrix)]) for index, task in enumerate(matrix): name = task.get('name', '') group = task.get('group', '') hidden = task.get('hidden', False) if names and name in names and index == name_index[name]: yield task elif groups and group in groups and not hidden: yield task elif not names and not groups and not hidden: yield task
python
def iter_tasks(matrix, names, groups): """Iterate tasks.""" # Build name index name_index = dict([(task.get('name', ''), index) for index, task in enumerate(matrix)]) for index, task in enumerate(matrix): name = task.get('name', '') group = task.get('group', '') hidden = task.get('hidden', False) if names and name in names and index == name_index[name]: yield task elif groups and group in groups and not hidden: yield task elif not names and not groups and not hidden: yield task
[ "def", "iter_tasks", "(", "matrix", ",", "names", ",", "groups", ")", ":", "# Build name index", "name_index", "=", "dict", "(", "[", "(", "task", ".", "get", "(", "'name'", ",", "''", ")", ",", "index", ")", "for", "index", ",", "task", "in", "enume...
Iterate tasks.
[ "Iterate", "tasks", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L570-L585
train
49,662
facelessuser/pyspelling
pyspelling/__init__.py
spellcheck
def spellcheck(config_file, names=None, groups=None, binary='', checker='', sources=None, verbose=0, debug=False): """Spell check.""" hunspell = None aspell = None spellchecker = None config = util.read_config(config_file) if sources is None: sources = [] matrix = config.get('matrix', []) preferred_checker = config.get('spellchecker', 'aspell') if not matrix: matrix = config.get('documents', []) if matrix: util.warn_deprecated("'documents' key in config is deprecated. 'matrix' should be used going forward.") groups = set() if groups is None else set(groups) names = set() if names is None else set(names) # Sources are only recognized when requesting a single name. if (len(names) != 1 and len(sources)): sources = [] for task in iter_tasks(matrix, names, groups): if not checker: checker = preferred_checker if checker == "hunspell": # pragma: no cover if hunspell is None: hunspell = Hunspell(config, binary, verbose, debug) spellchecker = hunspell elif checker == "aspell": if aspell is None: aspell = Aspell(config, binary, verbose, debug) spellchecker = aspell else: raise ValueError('%s is not a valid spellchecker!' % checker) spellchecker.log('Using %s to spellcheck %s' % (checker, task.get('name', '')), 1) for result in spellchecker.run_task(task, source_patterns=sources): spellchecker.log('Context: %s' % result.context, 2) yield result spellchecker.log("", 1)
python
def spellcheck(config_file, names=None, groups=None, binary='', checker='', sources=None, verbose=0, debug=False): """Spell check.""" hunspell = None aspell = None spellchecker = None config = util.read_config(config_file) if sources is None: sources = [] matrix = config.get('matrix', []) preferred_checker = config.get('spellchecker', 'aspell') if not matrix: matrix = config.get('documents', []) if matrix: util.warn_deprecated("'documents' key in config is deprecated. 'matrix' should be used going forward.") groups = set() if groups is None else set(groups) names = set() if names is None else set(names) # Sources are only recognized when requesting a single name. if (len(names) != 1 and len(sources)): sources = [] for task in iter_tasks(matrix, names, groups): if not checker: checker = preferred_checker if checker == "hunspell": # pragma: no cover if hunspell is None: hunspell = Hunspell(config, binary, verbose, debug) spellchecker = hunspell elif checker == "aspell": if aspell is None: aspell = Aspell(config, binary, verbose, debug) spellchecker = aspell else: raise ValueError('%s is not a valid spellchecker!' % checker) spellchecker.log('Using %s to spellcheck %s' % (checker, task.get('name', '')), 1) for result in spellchecker.run_task(task, source_patterns=sources): spellchecker.log('Context: %s' % result.context, 2) yield result spellchecker.log("", 1)
[ "def", "spellcheck", "(", "config_file", ",", "names", "=", "None", ",", "groups", "=", "None", ",", "binary", "=", "''", ",", "checker", "=", "''", ",", "sources", "=", "None", ",", "verbose", "=", "0", ",", "debug", "=", "False", ")", ":", "hunsp...
Spell check.
[ "Spell", "check", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L588-L633
train
49,663
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker.get_error
def get_error(self, e): """Get the error.""" import traceback return traceback.format_exc() if self.debug else str(e)
python
def get_error(self, e): """Get the error.""" import traceback return traceback.format_exc() if self.debug else str(e)
[ "def", "get_error", "(", "self", ",", "e", ")", ":", "import", "traceback", "return", "traceback", ".", "format_exc", "(", ")", "if", "self", ".", "debug", "else", "str", "(", "e", ")" ]
Get the error.
[ "Get", "the", "error", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L68-L73
train
49,664
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._pipeline_step
def _pipeline_step(self, sources, options, personal_dict, filter_index=1, flow_status=flow_control.ALLOW): """Recursively run text objects through the pipeline steps.""" for source in sources: if source._has_error(): yield source elif not source._is_bytes() and filter_index < len(self.pipeline_steps): f = self.pipeline_steps[filter_index] if isinstance(f, flow_control.FlowControl): err = '' try: status = f._run(source.category) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: if filter_index < len(self.pipeline_steps): yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1, status ) else: if flow_status == flow_control.ALLOW: err = '' try: srcs = f._run(source) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: yield from self._pipeline_step( srcs, options, personal_dict, filter_index + 1 ) elif flow_status == flow_control.SKIP: yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1 ) else: # Halted tasks yield source else: # Binary content yield source
python
def _pipeline_step(self, sources, options, personal_dict, filter_index=1, flow_status=flow_control.ALLOW): """Recursively run text objects through the pipeline steps.""" for source in sources: if source._has_error(): yield source elif not source._is_bytes() and filter_index < len(self.pipeline_steps): f = self.pipeline_steps[filter_index] if isinstance(f, flow_control.FlowControl): err = '' try: status = f._run(source.category) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: if filter_index < len(self.pipeline_steps): yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1, status ) else: if flow_status == flow_control.ALLOW: err = '' try: srcs = f._run(source) except Exception as e: err = self.get_error(e) yield filters.SourceText('', source.context, '', '', err) if not err: yield from self._pipeline_step( srcs, options, personal_dict, filter_index + 1 ) elif flow_status == flow_control.SKIP: yield from self._pipeline_step( [source], options, personal_dict, filter_index + 1 ) else: # Halted tasks yield source else: # Binary content yield source
[ "def", "_pipeline_step", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ",", "filter_index", "=", "1", ",", "flow_status", "=", "flow_control", ".", "ALLOW", ")", ":", "for", "source", "in", "sources", ":", "if", "source", ".", "_has_er...
Recursively run text objects through the pipeline steps.
[ "Recursively", "run", "text", "objects", "through", "the", "pipeline", "steps", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L80-L121
train
49,665
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._spelling_pipeline
def _spelling_pipeline(self, sources, options, personal_dict): """Check spelling pipeline.""" for source in self._pipeline_step(sources, options, personal_dict): # Don't waste time on empty strings if source._has_error(): yield Results([], source.context, source.category, source.error) elif not source.text or source.text.isspace(): continue else: encoding = source.encoding if source._is_bytes(): text = source.text else: # UTF-16 and UTF-32 don't work well with Aspell and Hunspell, # so encode with the compatible UTF-8 instead. if encoding.startswith(('utf-16', 'utf-32')): encoding = 'utf-8' text = source.text.encode(encoding) self.log('', 3) self.log(text, 3) cmd = self.setup_command(encoding, options, personal_dict) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=text, encoding=encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
python
def _spelling_pipeline(self, sources, options, personal_dict): """Check spelling pipeline.""" for source in self._pipeline_step(sources, options, personal_dict): # Don't waste time on empty strings if source._has_error(): yield Results([], source.context, source.category, source.error) elif not source.text or source.text.isspace(): continue else: encoding = source.encoding if source._is_bytes(): text = source.text else: # UTF-16 and UTF-32 don't work well with Aspell and Hunspell, # so encode with the compatible UTF-8 instead. if encoding.startswith(('utf-16', 'utf-32')): encoding = 'utf-8' text = source.text.encode(encoding) self.log('', 3) self.log(text, 3) cmd = self.setup_command(encoding, options, personal_dict) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=text, encoding=encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
[ "def", "_spelling_pipeline", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ")", ":", "for", "source", "in", "self", ".", "_pipeline_step", "(", "sources", ",", "options", ",", "personal_dict", ")", ":", "# Don't waste time on empty strings", ...
Check spelling pipeline.
[ "Check", "spelling", "pipeline", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L123-L156
train
49,666
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._walk_src
def _walk_src(self, targets, flags, pipeline): """Walk source and parse files.""" for target in targets: for f in glob.iglob(target, flags=flags | glob.S): if not os.path.isdir(f): self.log('', 2) self.log('> Processing: %s' % f, 1) if pipeline: try: yield pipeline[0]._run_first(f) except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)] else: try: if self.default_encoding: encoding = filters.PYTHON_ENCODING_NAMES.get( self.default_encoding, self.default_encoding ).lower() encoding = codecs.lookup(encoding).name else: encoding = self.default_encoding yield [filters.SourceText('', f, encoding, 'file')] except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)]
python
def _walk_src(self, targets, flags, pipeline): """Walk source and parse files.""" for target in targets: for f in glob.iglob(target, flags=flags | glob.S): if not os.path.isdir(f): self.log('', 2) self.log('> Processing: %s' % f, 1) if pipeline: try: yield pipeline[0]._run_first(f) except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)] else: try: if self.default_encoding: encoding = filters.PYTHON_ENCODING_NAMES.get( self.default_encoding, self.default_encoding ).lower() encoding = codecs.lookup(encoding).name else: encoding = self.default_encoding yield [filters.SourceText('', f, encoding, 'file')] except Exception as e: err = self.get_error(e) yield [filters.SourceText('', f, '', '', err)]
[ "def", "_walk_src", "(", "self", ",", "targets", ",", "flags", ",", "pipeline", ")", ":", "for", "target", "in", "targets", ":", "for", "f", "in", "glob", ".", "iglob", "(", "target", ",", "flags", "=", "flags", "|", "glob", ".", "S", ")", ":", "...
Walk source and parse files.
[ "Walk", "source", "and", "parse", "files", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L164-L190
train
49,667
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._build_pipeline
def _build_pipeline(self, task): """Build up the pipeline.""" self.pipeline_steps = [] kwargs = {} if self.default_encoding: kwargs["default_encoding"] = self.default_encoding steps = task.get('pipeline', []) if steps is None: self.pipeline_steps = None else: if not steps: steps = task.get('filters', []) if steps: util.warn_deprecated( "'filters' key in config is deprecated. 'pipeline' should be used going forward." ) if not steps: steps.append('pyspelling.filters.text') for step in steps: # Retrieve module and module options if isinstance(step, dict): name, options = list(step.items())[0] else: name = step options = {} if options is None: options = {} module = self._get_module(name) if issubclass(module, filters.Filter): self.pipeline_steps.append(module(options, **kwargs)) elif issubclass(module, flow_control.FlowControl): if self.pipeline_steps: self.pipeline_steps.append(module(options)) else: raise ValueError("Pipeline cannot start with a 'Flow Control' plugin!") else: raise ValueError("'%s' is not a valid plugin!" % name)
python
def _build_pipeline(self, task): """Build up the pipeline.""" self.pipeline_steps = [] kwargs = {} if self.default_encoding: kwargs["default_encoding"] = self.default_encoding steps = task.get('pipeline', []) if steps is None: self.pipeline_steps = None else: if not steps: steps = task.get('filters', []) if steps: util.warn_deprecated( "'filters' key in config is deprecated. 'pipeline' should be used going forward." ) if not steps: steps.append('pyspelling.filters.text') for step in steps: # Retrieve module and module options if isinstance(step, dict): name, options = list(step.items())[0] else: name = step options = {} if options is None: options = {} module = self._get_module(name) if issubclass(module, filters.Filter): self.pipeline_steps.append(module(options, **kwargs)) elif issubclass(module, flow_control.FlowControl): if self.pipeline_steps: self.pipeline_steps.append(module(options)) else: raise ValueError("Pipeline cannot start with a 'Flow Control' plugin!") else: raise ValueError("'%s' is not a valid plugin!" % name)
[ "def", "_build_pipeline", "(", "self", ",", "task", ")", ":", "self", ".", "pipeline_steps", "=", "[", "]", "kwargs", "=", "{", "}", "if", "self", ".", "default_encoding", ":", "kwargs", "[", "\"default_encoding\"", "]", "=", "self", ".", "default_encoding...
Build up the pipeline.
[ "Build", "up", "the", "pipeline", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L202-L243
train
49,668
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._get_module
def _get_module(self, module): """Get module.""" if isinstance(module, str): mod = importlib.import_module(module) for name in ('get_plugin', 'get_filter'): attr = getattr(mod, name, None) if attr is not None: break if name == 'get_filter': util.warn_deprecated("'get_filter' is deprecated. Plugins should use 'get_plugin'.") if not attr: raise ValueError("Could not find the 'get_plugin' function in module '%s'!" % module) return attr()
python
def _get_module(self, module): """Get module.""" if isinstance(module, str): mod = importlib.import_module(module) for name in ('get_plugin', 'get_filter'): attr = getattr(mod, name, None) if attr is not None: break if name == 'get_filter': util.warn_deprecated("'get_filter' is deprecated. Plugins should use 'get_plugin'.") if not attr: raise ValueError("Could not find the 'get_plugin' function in module '%s'!" % module) return attr()
[ "def", "_get_module", "(", "self", ",", "module", ")", ":", "if", "isinstance", "(", "module", ",", "str", ")", ":", "mod", "=", "importlib", ".", "import_module", "(", "module", ")", "for", "name", "in", "(", "'get_plugin'", ",", "'get_filter'", ")", ...
Get module.
[ "Get", "module", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L245-L258
train
49,669
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker._to_flags
def _to_flags(self, text): """Convert text representation of flags to actual flags.""" flags = 0 for x in text.split('|'): value = x.strip().upper() if value: flags |= self.GLOB_FLAG_MAP.get(value, 0) return flags
python
def _to_flags(self, text): """Convert text representation of flags to actual flags.""" flags = 0 for x in text.split('|'): value = x.strip().upper() if value: flags |= self.GLOB_FLAG_MAP.get(value, 0) return flags
[ "def", "_to_flags", "(", "self", ",", "text", ")", ":", "flags", "=", "0", "for", "x", "in", "text", ".", "split", "(", "'|'", ")", ":", "value", "=", "x", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "value", ":", "flags", "|=", "se...
Convert text representation of flags to actual flags.
[ "Convert", "text", "representation", "of", "flags", "to", "actual", "flags", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L260-L268
train
49,670
facelessuser/pyspelling
pyspelling/__init__.py
SpellChecker.run_task
def run_task(self, task, source_patterns=None): """Walk source and initiate spell check.""" # Perform spell check self.log('Running Task: %s...' % task.get('name', ''), 1) # Setup filters and variables for the spell check self.default_encoding = task.get('default_encoding', '') options = self.setup_spellchecker(task) personal_dict = self.setup_dictionary(task) glob_flags = self._to_flags(task.get('glob_flags', "N|B|G")) self._build_pipeline(task) if not source_patterns: source_patterns = task.get('sources', []) for sources in self._walk_src(source_patterns, glob_flags, self.pipeline_steps): if self.pipeline_steps is not None: yield from self._spelling_pipeline(sources, options, personal_dict) else: yield from self.spell_check_no_pipeline(sources, options, personal_dict)
python
def run_task(self, task, source_patterns=None): """Walk source and initiate spell check.""" # Perform spell check self.log('Running Task: %s...' % task.get('name', ''), 1) # Setup filters and variables for the spell check self.default_encoding = task.get('default_encoding', '') options = self.setup_spellchecker(task) personal_dict = self.setup_dictionary(task) glob_flags = self._to_flags(task.get('glob_flags', "N|B|G")) self._build_pipeline(task) if not source_patterns: source_patterns = task.get('sources', []) for sources in self._walk_src(source_patterns, glob_flags, self.pipeline_steps): if self.pipeline_steps is not None: yield from self._spelling_pipeline(sources, options, personal_dict) else: yield from self.spell_check_no_pipeline(sources, options, personal_dict)
[ "def", "run_task", "(", "self", ",", "task", ",", "source_patterns", "=", "None", ")", ":", "# Perform spell check", "self", ".", "log", "(", "'Running Task: %s...'", "%", "task", ".", "get", "(", "'name'", ",", "''", ")", ",", "1", ")", "# Setup filters a...
Walk source and initiate spell check.
[ "Walk", "source", "and", "initiate", "spell", "check", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L270-L291
train
49,671
facelessuser/pyspelling
pyspelling/__init__.py
Hunspell.setup_dictionary
def setup_dictionary(self, task): """Setup dictionary.""" dictionary_options = task.get('dictionary', {}) output = os.path.abspath(dictionary_options.get('output', self.dict_bin)) lang = dictionary_options.get('lang', 'en_US') wordlists = dictionary_options.get('wordlists', []) if lang and wordlists: self.compile_dictionary(lang, dictionary_options.get('wordlists', []), None, output) else: output = None return output
python
def setup_dictionary(self, task): """Setup dictionary.""" dictionary_options = task.get('dictionary', {}) output = os.path.abspath(dictionary_options.get('output', self.dict_bin)) lang = dictionary_options.get('lang', 'en_US') wordlists = dictionary_options.get('wordlists', []) if lang and wordlists: self.compile_dictionary(lang, dictionary_options.get('wordlists', []), None, output) else: output = None return output
[ "def", "setup_dictionary", "(", "self", ",", "task", ")", ":", "dictionary_options", "=", "task", ".", "get", "(", "'dictionary'", ",", "{", "}", ")", "output", "=", "os", ".", "path", ".", "abspath", "(", "dictionary_options", ".", "get", "(", "'output'...
Setup dictionary.
[ "Setup", "dictionary", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L471-L482
train
49,672
facelessuser/pyspelling
pyspelling/__init__.py
Hunspell.spell_check_no_pipeline
def spell_check_no_pipeline(self, sources, options, personal_dict): """Spell check without the pipeline.""" for source in sources: if source._has_error(): # pragma: no cover yield Results([], source.context, source.category, source.error) cmd = self.setup_command(source.encoding, options, personal_dict, source.context) self.log('', 3) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=None, encoding=source.encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
python
def spell_check_no_pipeline(self, sources, options, personal_dict): """Spell check without the pipeline.""" for source in sources: if source._has_error(): # pragma: no cover yield Results([], source.context, source.category, source.error) cmd = self.setup_command(source.encoding, options, personal_dict, source.context) self.log('', 3) self.log("Command: " + str(cmd), 4) try: wordlist = util.call_spellchecker(cmd, input_text=None, encoding=source.encoding) yield Results( [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w], source.context, source.category ) except Exception as e: # pragma: no cover err = self.get_error(e) yield Results([], source.context, source.category, err)
[ "def", "spell_check_no_pipeline", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ")", ":", "for", "source", "in", "sources", ":", "if", "source", ".", "_has_error", "(", ")", ":", "# pragma: no cover", "yield", "Results", "(", "[", "]", ...
Spell check without the pipeline.
[ "Spell", "check", "without", "the", "pipeline", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L511-L530
train
49,673
facelessuser/pyspelling
pyspelling/__init__.py
Hunspell.setup_command
def setup_command(self, encoding, options, personal_dict, file_name=None): """Setup command.""" cmd = [ self.binary, '-l' ] if encoding: cmd.extend(['-i', encoding]) if personal_dict: cmd.extend(['-p', personal_dict]) allowed = { 'check-apostrophe', 'check-url', 'd', 'H', 'i', 'n', 'O', 'r', 't', 'X' } for k, v in options.items(): if k in allowed: key = ('-%s' if len(k) == 1 else '--%s') % k if isinstance(v, bool) and v is True: cmd.append(key) elif isinstance(v, str): cmd.extend([key, v]) elif isinstance(v, int): cmd.extend([key, str(v)]) elif isinstance(v, list): for value in v: cmd.extend([key, str(value)]) if file_name is not None: cmd.append(file_name) return cmd
python
def setup_command(self, encoding, options, personal_dict, file_name=None): """Setup command.""" cmd = [ self.binary, '-l' ] if encoding: cmd.extend(['-i', encoding]) if personal_dict: cmd.extend(['-p', personal_dict]) allowed = { 'check-apostrophe', 'check-url', 'd', 'H', 'i', 'n', 'O', 'r', 't', 'X' } for k, v in options.items(): if k in allowed: key = ('-%s' if len(k) == 1 else '--%s') % k if isinstance(v, bool) and v is True: cmd.append(key) elif isinstance(v, str): cmd.extend([key, v]) elif isinstance(v, int): cmd.extend([key, str(v)]) elif isinstance(v, list): for value in v: cmd.extend([key, str(value)]) if file_name is not None: cmd.append(file_name) return cmd
[ "def", "setup_command", "(", "self", ",", "encoding", ",", "options", ",", "personal_dict", ",", "file_name", "=", "None", ")", ":", "cmd", "=", "[", "self", ".", "binary", ",", "'-l'", "]", "if", "encoding", ":", "cmd", ".", "extend", "(", "[", "'-i...
Setup command.
[ "Setup", "command", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L532-L567
train
49,674
facelessuser/pyspelling
pyspelling/flow_control/wildcard.py
WildcardFlowControl.setup
def setup(self): """Get default configuration.""" self.allow = self.config['allow'] self.halt = self.config['halt'] self.skip = self.config['skip']
python
def setup(self): """Get default configuration.""" self.allow = self.config['allow'] self.halt = self.config['halt'] self.skip = self.config['skip']
[ "def", "setup", "(", "self", ")", ":", "self", ".", "allow", "=", "self", ".", "config", "[", "'allow'", "]", "self", ".", "halt", "=", "self", ".", "config", "[", "'halt'", "]", "self", ".", "skip", "=", "self", ".", "config", "[", "'skip'", "]"...
Get default configuration.
[ "Get", "default", "configuration", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/flow_control/wildcard.py#L26-L31
train
49,675
facelessuser/pyspelling
pyspelling/flow_control/wildcard.py
WildcardFlowControl.match
def match(self, category, pattern): """Match the category.""" return fnmatch.fnmatch(category, pattern, flags=self.FNMATCH_FLAGS)
python
def match(self, category, pattern): """Match the category.""" return fnmatch.fnmatch(category, pattern, flags=self.FNMATCH_FLAGS)
[ "def", "match", "(", "self", ",", "category", ",", "pattern", ")", ":", "return", "fnmatch", ".", "fnmatch", "(", "category", ",", "pattern", ",", "flags", "=", "self", ".", "FNMATCH_FLAGS", ")" ]
Match the category.
[ "Match", "the", "category", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/flow_control/wildcard.py#L33-L36
train
49,676
facelessuser/pyspelling
pyspelling/flow_control/wildcard.py
WildcardFlowControl.adjust_flow
def adjust_flow(self, category): """Adjust the flow of source control objects.""" status = flow_control.SKIP for allow in self.allow: if self.match(category, allow): status = flow_control.ALLOW for skip in self.skip: if self.match(category, skip): status = flow_control.SKIP for halt in self.halt: if self.match(category, halt): status = flow_control.HALT if status != flow_control.ALLOW: break return status
python
def adjust_flow(self, category): """Adjust the flow of source control objects.""" status = flow_control.SKIP for allow in self.allow: if self.match(category, allow): status = flow_control.ALLOW for skip in self.skip: if self.match(category, skip): status = flow_control.SKIP for halt in self.halt: if self.match(category, halt): status = flow_control.HALT if status != flow_control.ALLOW: break return status
[ "def", "adjust_flow", "(", "self", ",", "category", ")", ":", "status", "=", "flow_control", ".", "SKIP", "for", "allow", "in", "self", ".", "allow", ":", "if", "self", ".", "match", "(", "category", ",", "allow", ")", ":", "status", "=", "flow_control...
Adjust the flow of source control objects.
[ "Adjust", "the", "flow", "of", "source", "control", "objects", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/flow_control/wildcard.py#L38-L53
train
49,677
deshima-dev/decode
decode/plot/functions.py
plot_tcoords
def plot_tcoords(array, coords, scantypes=None, ax=None, **kwargs): """Plot coordinates related to the time axis. Args: array (xarray.DataArray): Array which the coodinate information is included. coords (list): Name of x axis and y axis. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() if scantypes is None: ax.plot(array[coords[0]], array[coords[1]], label='ALL', **kwargs) else: for scantype in scantypes: ax.plot(array[coords[0]][array.scantype == scantype], array[coords[1]][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel(coords[0]) ax.set_ylabel(coords[1]) ax.set_title('{} vs {}'.format(coords[1], coords[0])) ax.legend() logger.info('{} vs {} has been plotted.'.format(coords[1], coords[0]))
python
def plot_tcoords(array, coords, scantypes=None, ax=None, **kwargs): """Plot coordinates related to the time axis. Args: array (xarray.DataArray): Array which the coodinate information is included. coords (list): Name of x axis and y axis. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() if scantypes is None: ax.plot(array[coords[0]], array[coords[1]], label='ALL', **kwargs) else: for scantype in scantypes: ax.plot(array[coords[0]][array.scantype == scantype], array[coords[1]][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel(coords[0]) ax.set_ylabel(coords[1]) ax.set_title('{} vs {}'.format(coords[1], coords[0])) ax.legend() logger.info('{} vs {} has been plotted.'.format(coords[1], coords[0]))
[ "def", "plot_tcoords", "(", "array", ",", "coords", ",", "scantypes", "=", "None", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "if", "scantypes", "is", "None", ...
Plot coordinates related to the time axis. Args: array (xarray.DataArray): Array which the coodinate information is included. coords (list): Name of x axis and y axis. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot().
[ "Plot", "coordinates", "related", "to", "the", "time", "axis", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L29-L53
train
49,678
deshima-dev/decode
decode/plot/functions.py
plot_timestream
def plot_timestream(array, kidid, xtick='time', scantypes=None, ax=None, **kwargs): """Plot timestream data. Args: array (xarray.DataArray): Array which the timestream data are included. kidid (int): Kidid. xtick (str): Type of x axis. 'time': Time. 'index': Time index. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() index = np.where(array.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) if scantypes is None: if xtick == 'time': ax.plot(array.time, array[:, index], label='ALL', **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time)], array[:, index], label='ALL', **kwargs) else: for scantype in scantypes: if xtick == 'time': ax.plot(array.time[array.scantype == scantype], array[:, index][array.scantype == scantype], label=scantype, **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time[array.scantype == scantype])], array[:, index][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel('{}'.format(xtick)) ax.set_ylabel(str(array.datatype.values)) ax.legend() kidtpdict = {0: 'wideband', 1: 'filter', 2: 'blind'} try: kidtp = kidtpdict[int(array.kidtp[index])] except KeyError: kidtp = 'filter' ax.set_title('ch #{} ({})'.format(kidid, kidtp)) logger.info('timestream data (ch={}) has been plotted.'.format(kidid))
python
def plot_timestream(array, kidid, xtick='time', scantypes=None, ax=None, **kwargs): """Plot timestream data. Args: array (xarray.DataArray): Array which the timestream data are included. kidid (int): Kidid. xtick (str): Type of x axis. 'time': Time. 'index': Time index. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() index = np.where(array.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) if scantypes is None: if xtick == 'time': ax.plot(array.time, array[:, index], label='ALL', **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time)], array[:, index], label='ALL', **kwargs) else: for scantype in scantypes: if xtick == 'time': ax.plot(array.time[array.scantype == scantype], array[:, index][array.scantype == scantype], label=scantype, **kwargs) elif xtick == 'index': ax.plot(np.ogrid[:len(array.time[array.scantype == scantype])], array[:, index][array.scantype == scantype], label=scantype, **kwargs) ax.set_xlabel('{}'.format(xtick)) ax.set_ylabel(str(array.datatype.values)) ax.legend() kidtpdict = {0: 'wideband', 1: 'filter', 2: 'blind'} try: kidtp = kidtpdict[int(array.kidtp[index])] except KeyError: kidtp = 'filter' ax.set_title('ch #{} ({})'.format(kidid, kidtp)) logger.info('timestream data (ch={}) has been plotted.'.format(kidid))
[ "def", "plot_timestream", "(", "array", ",", "kidid", ",", "xtick", "=", "'time'", ",", "scantypes", "=", "None", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", ...
Plot timestream data. Args: array (xarray.DataArray): Array which the timestream data are included. kidid (int): Kidid. xtick (str): Type of x axis. 'time': Time. 'index': Time index. scantypes (list): Scantypes. If None, all scantypes are used. ax (matplotlib.axes): Axis you want to plot on. kwargs (optional): Plot options passed to ax.plot().
[ "Plot", "timestream", "data", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L56-L101
train
49,679
deshima-dev/decode
decode/plot/functions.py
plot_chmap
def plot_chmap(cube, kidid, ax=None, **kwargs): """Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow(). """ if ax is None: ax = plt.gca() index = np.where(cube.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('intensity map ch #{}'.format(kidid)) return im
python
def plot_chmap(cube, kidid, ax=None, **kwargs): """Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow(). """ if ax is None: ax = plt.gca() index = np.where(cube.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('intensity map ch #{}'.format(kidid)) return im
[ "def", "plot_chmap", "(", "cube", ",", "kidid", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "index", "=", "np", ".", "where", "(", "cube", ".", "kidid", "==...
Plot an intensity map. Args: cube (xarray.DataArray): Cube which the spectrum information is included. kidid (int): Kidid. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.imshow().
[ "Plot", "an", "intensity", "map", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L198-L219
train
49,680
deshima-dev/decode
decode/plot/functions.py
plotallanvar
def plotallanvar(data, dt, tmax=10, ax=None, **kwargs): """Plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() tk, allanvar = allan_variance(data, dt, tmax) ax.loglog(tk, allanvar, **kwargs) ax.set_xlabel('Time [s]') ax.set_ylabel('Allan Variance') ax.legend()
python
def plotallanvar(data, dt, tmax=10, ax=None, **kwargs): """Plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot(). """ if ax is None: ax = plt.gca() tk, allanvar = allan_variance(data, dt, tmax) ax.loglog(tk, allanvar, **kwargs) ax.set_xlabel('Time [s]') ax.set_ylabel('Allan Variance') ax.legend()
[ "def", "plotallanvar", "(", "data", ",", "dt", ",", "tmax", "=", "10", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "tk", ",", "allanvar", "=", "allan_variance...
Plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot().
[ "Plot", "Allan", "variance", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/plot/functions.py#L242-L258
train
49,681
facelessuser/pyspelling
pyspelling/filters/url.py
URLFilter._filter
def _filter(self, text): """Filter out the URL and email addresses.""" if self.urls: text = RE_LINK.sub('', text) if self.emails: text = RE_MAIL.sub('', text) return text
python
def _filter(self, text): """Filter out the URL and email addresses.""" if self.urls: text = RE_LINK.sub('', text) if self.emails: text = RE_MAIL.sub('', text) return text
[ "def", "_filter", "(", "self", ",", "text", ")", ":", "if", "self", ".", "urls", ":", "text", "=", "RE_LINK", ".", "sub", "(", "''", ",", "text", ")", "if", "self", ".", "emails", ":", "text", "=", "RE_MAIL", ".", "sub", "(", "''", ",", "text",...
Filter out the URL and email addresses.
[ "Filter", "out", "the", "URL", "and", "email", "addresses", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/url.py#L55-L62
train
49,682
JMSwag/dsdev-utils
dsdev_utils/paths.py
get_mac_dot_app_dir
def get_mac_dot_app_dir(directory): """Returns parent directory of mac .app Args: directory (str): Current directory Returns: (str): Parent directory of mac .app """ return os.path.dirname(os.path.dirname(os.path.dirname(directory)))
python
def get_mac_dot_app_dir(directory): """Returns parent directory of mac .app Args: directory (str): Current directory Returns: (str): Parent directory of mac .app """ return os.path.dirname(os.path.dirname(os.path.dirname(directory)))
[ "def", "get_mac_dot_app_dir", "(", "directory", ")", ":", "return", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "directory", ")", ")", ")" ]
Returns parent directory of mac .app Args: directory (str): Current directory Returns: (str): Parent directory of mac .app
[ "Returns", "parent", "directory", "of", "mac", ".", "app" ]
5adbf9b3fd9fff92d1dd714423b08e26a5038e14
https://github.com/JMSwag/dsdev-utils/blob/5adbf9b3fd9fff92d1dd714423b08e26a5038e14/dsdev_utils/paths.py#L36-L47
train
49,683
deshima-dev/decode
decode/utils/misc/functions.py
copy_function
def copy_function(func, name=None): """Copy a function object with different name. Args: func (function): Function to be copied. name (string, optional): Name of the new function. If not spacified, the same name of `func` will be used. Returns: newfunc (function): New function with different name. """ code = func.__code__ newname = name or func.__name__ newcode = CodeType( code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co_names, code.co_varnames, code.co_filename, newname, code.co_firstlineno, code.co_lnotab, code.co_freevars, code.co_cellvars, ) newfunc = FunctionType( newcode, func.__globals__, newname, func.__defaults__, func.__closure__, ) newfunc.__dict__.update(func.__dict__) return newfunc
python
def copy_function(func, name=None): """Copy a function object with different name. Args: func (function): Function to be copied. name (string, optional): Name of the new function. If not spacified, the same name of `func` will be used. Returns: newfunc (function): New function with different name. """ code = func.__code__ newname = name or func.__name__ newcode = CodeType( code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co_names, code.co_varnames, code.co_filename, newname, code.co_firstlineno, code.co_lnotab, code.co_freevars, code.co_cellvars, ) newfunc = FunctionType( newcode, func.__globals__, newname, func.__defaults__, func.__closure__, ) newfunc.__dict__.update(func.__dict__) return newfunc
[ "def", "copy_function", "(", "func", ",", "name", "=", "None", ")", ":", "code", "=", "func", ".", "__code__", "newname", "=", "name", "or", "func", ".", "__name__", "newcode", "=", "CodeType", "(", "code", ".", "co_argcount", ",", "code", ".", "co_kwo...
Copy a function object with different name. Args: func (function): Function to be copied. name (string, optional): Name of the new function. If not spacified, the same name of `func` will be used. Returns: newfunc (function): New function with different name.
[ "Copy", "a", "function", "object", "with", "different", "name", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/utils/misc/functions.py#L61-L100
train
49,684
deshima-dev/decode
decode/utils/misc/functions.py
one_thread_per_process
def one_thread_per_process(): """Return a context manager where only one thread is allocated to a process. This function is intended to be used as a with statement like:: >>> with process_per_thread(): ... do_something() # one thread per process Notes: This function only works when MKL (Intel Math Kernel Library) is installed and used in, for example, NumPy and SciPy. Otherwise this function does nothing. """ try: import mkl is_mkl = True except ImportError: is_mkl = False if is_mkl: n_threads = mkl.get_max_threads() mkl.set_num_threads(1) try: # block nested in the with statement yield finally: # revert to the original value mkl.set_num_threads(n_threads) else: yield
python
def one_thread_per_process(): """Return a context manager where only one thread is allocated to a process. This function is intended to be used as a with statement like:: >>> with process_per_thread(): ... do_something() # one thread per process Notes: This function only works when MKL (Intel Math Kernel Library) is installed and used in, for example, NumPy and SciPy. Otherwise this function does nothing. """ try: import mkl is_mkl = True except ImportError: is_mkl = False if is_mkl: n_threads = mkl.get_max_threads() mkl.set_num_threads(1) try: # block nested in the with statement yield finally: # revert to the original value mkl.set_num_threads(n_threads) else: yield
[ "def", "one_thread_per_process", "(", ")", ":", "try", ":", "import", "mkl", "is_mkl", "=", "True", "except", "ImportError", ":", "is_mkl", "=", "False", "if", "is_mkl", ":", "n_threads", "=", "mkl", ".", "get_max_threads", "(", ")", "mkl", ".", "set_num_t...
Return a context manager where only one thread is allocated to a process. This function is intended to be used as a with statement like:: >>> with process_per_thread(): ... do_something() # one thread per process Notes: This function only works when MKL (Intel Math Kernel Library) is installed and used in, for example, NumPy and SciPy. Otherwise this function does nothing.
[ "Return", "a", "context", "manager", "where", "only", "one", "thread", "is", "allocated", "to", "a", "process", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/utils/misc/functions.py#L104-L134
train
49,685
MFreidank/ARSpy
arspy/hull.py
sample_upper_hull
def sample_upper_hull(upper_hull, random_stream): """ Return a single value randomly sampled from the given `upper_hull`. Parameters ---------- upper_hull : List[pyars.hull.HullNode] Upper hull to evaluate. random_stream : numpy.random.RandomState (Seeded) stream of random values to use during sampling. Returns ---------- sample : float Single value randomly sampled from `upper_hull`. """ cdf = cumsum([node.pr for node in upper_hull]) # randomly choose a line segment U = random_stream.rand() node = next( (node for node, cdf_value in zip(upper_hull, cdf) if U < cdf_value), upper_hull[-1] # default is last line segment ) # sample along that line segment U = random_stream.rand() m, left, right = node.m, node.left, node.right M = max(m * right, m * left) x = (log(U * (exp(m * right - M) - exp(m * left - M)) + exp(m * left - M)) + M) / m assert(x >= left and x <= right) if isinf(x) or isnan(x): raise ValueError("sampled an infinite or 'nan' x") return x
python
def sample_upper_hull(upper_hull, random_stream): """ Return a single value randomly sampled from the given `upper_hull`. Parameters ---------- upper_hull : List[pyars.hull.HullNode] Upper hull to evaluate. random_stream : numpy.random.RandomState (Seeded) stream of random values to use during sampling. Returns ---------- sample : float Single value randomly sampled from `upper_hull`. """ cdf = cumsum([node.pr for node in upper_hull]) # randomly choose a line segment U = random_stream.rand() node = next( (node for node, cdf_value in zip(upper_hull, cdf) if U < cdf_value), upper_hull[-1] # default is last line segment ) # sample along that line segment U = random_stream.rand() m, left, right = node.m, node.left, node.right M = max(m * right, m * left) x = (log(U * (exp(m * right - M) - exp(m * left - M)) + exp(m * left - M)) + M) / m assert(x >= left and x <= right) if isinf(x) or isnan(x): raise ValueError("sampled an infinite or 'nan' x") return x
[ "def", "sample_upper_hull", "(", "upper_hull", ",", "random_stream", ")", ":", "cdf", "=", "cumsum", "(", "[", "node", ".", "pr", "for", "node", "in", "upper_hull", "]", ")", "# randomly choose a line segment", "U", "=", "random_stream", ".", "rand", "(", ")...
Return a single value randomly sampled from the given `upper_hull`. Parameters ---------- upper_hull : List[pyars.hull.HullNode] Upper hull to evaluate. random_stream : numpy.random.RandomState (Seeded) stream of random values to use during sampling. Returns ---------- sample : float Single value randomly sampled from `upper_hull`.
[ "Return", "a", "single", "value", "randomly", "sampled", "from", "the", "given", "upper_hull", "." ]
866885071b43e36a529f2fecf584ceef5248d800
https://github.com/MFreidank/ARSpy/blob/866885071b43e36a529f2fecf584ceef5248d800/arspy/hull.py#L207-L249
train
49,686
mrcagney/make_gtfs
make_gtfs/validators.py
check_for_required_columns
def check_for_required_columns(problems, table, df): """ Check that the given ProtoFeed table has the required columns. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the ProtoFeed is violated; ``'warning'`` means there is a problem but it is not a ProtoFeed violation 2. A message (string) that describes the problem 3. A ProtoFeed table name, e.g. ``'meta'``, in which the problem occurs 4. A list of rows (integers) of the table's DataFrame where the problem occurs table : string Name of a ProtoFeed table df : DataFrame The ProtoFeed table corresponding to ``table`` Returns ------- list The ``problems`` list extended as follows. Check that the DataFrame contains the colums required by the ProtoFeed spec and append to the problems list one error for each column missing. """ r = cs.PROTOFEED_REF req_columns = r.loc[(r['table'] == table) & r['column_required'], 'column'].values for col in req_columns: if col not in df.columns: problems.append(['error', 'Missing column {!s}'.format(col), table, []]) return problems
python
def check_for_required_columns(problems, table, df): """ Check that the given ProtoFeed table has the required columns. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the ProtoFeed is violated; ``'warning'`` means there is a problem but it is not a ProtoFeed violation 2. A message (string) that describes the problem 3. A ProtoFeed table name, e.g. ``'meta'``, in which the problem occurs 4. A list of rows (integers) of the table's DataFrame where the problem occurs table : string Name of a ProtoFeed table df : DataFrame The ProtoFeed table corresponding to ``table`` Returns ------- list The ``problems`` list extended as follows. Check that the DataFrame contains the colums required by the ProtoFeed spec and append to the problems list one error for each column missing. """ r = cs.PROTOFEED_REF req_columns = r.loc[(r['table'] == table) & r['column_required'], 'column'].values for col in req_columns: if col not in df.columns: problems.append(['error', 'Missing column {!s}'.format(col), table, []]) return problems
[ "def", "check_for_required_columns", "(", "problems", ",", "table", ",", "df", ")", ":", "r", "=", "cs", ".", "PROTOFEED_REF", "req_columns", "=", "r", ".", "loc", "[", "(", "r", "[", "'table'", "]", "==", "table", ")", "&", "r", "[", "'column_required...
Check that the given ProtoFeed table has the required columns. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the ProtoFeed is violated; ``'warning'`` means there is a problem but it is not a ProtoFeed violation 2. A message (string) that describes the problem 3. A ProtoFeed table name, e.g. ``'meta'``, in which the problem occurs 4. A list of rows (integers) of the table's DataFrame where the problem occurs table : string Name of a ProtoFeed table df : DataFrame The ProtoFeed table corresponding to ``table`` Returns ------- list The ``problems`` list extended as follows. Check that the DataFrame contains the colums required by the ProtoFeed spec and append to the problems list one error for each column missing.
[ "Check", "that", "the", "given", "ProtoFeed", "table", "has", "the", "required", "columns", "." ]
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/validators.py#L24-L66
train
49,687
mrcagney/make_gtfs
make_gtfs/validators.py
check_for_invalid_columns
def check_for_invalid_columns(problems, table, df): """ Check for invalid columns in the given ProtoFeed DataFrame. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the ProtoFeed is violated; ``'warning'`` means there is a problem but it is not a ProtoFeed violation 2. A message (string) that describes the problem 3. A ProtoFeed table name, e.g. ``'meta'``, in which the problem occurs 4. A list of rows (integers) of the table's DataFrame where the problem occurs table : string Name of a ProtoFeed table df : DataFrame The ProtoFeed table corresponding to ``table`` Returns ------- list The ``problems`` list extended as follows. Check whether the DataFrame contains extra columns not in the ProtoFeed and append to the problems list one warning for each extra column. """ r = cs.PROTOFEED_REF valid_columns = r.loc[r['table'] == table, 'column'].values for col in df.columns: if col not in valid_columns: problems.append(['warning', 'Unrecognized column {!s}'.format(col), table, []]) return problems
python
def check_for_invalid_columns(problems, table, df): """ Check for invalid columns in the given ProtoFeed DataFrame. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the ProtoFeed is violated; ``'warning'`` means there is a problem but it is not a ProtoFeed violation 2. A message (string) that describes the problem 3. A ProtoFeed table name, e.g. ``'meta'``, in which the problem occurs 4. A list of rows (integers) of the table's DataFrame where the problem occurs table : string Name of a ProtoFeed table df : DataFrame The ProtoFeed table corresponding to ``table`` Returns ------- list The ``problems`` list extended as follows. Check whether the DataFrame contains extra columns not in the ProtoFeed and append to the problems list one warning for each extra column. """ r = cs.PROTOFEED_REF valid_columns = r.loc[r['table'] == table, 'column'].values for col in df.columns: if col not in valid_columns: problems.append(['warning', 'Unrecognized column {!s}'.format(col), table, []]) return problems
[ "def", "check_for_invalid_columns", "(", "problems", ",", "table", ",", "df", ")", ":", "r", "=", "cs", ".", "PROTOFEED_REF", "valid_columns", "=", "r", ".", "loc", "[", "r", "[", "'table'", "]", "==", "table", ",", "'column'", "]", ".", "values", "for...
Check for invalid columns in the given ProtoFeed DataFrame. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the ProtoFeed is violated; ``'warning'`` means there is a problem but it is not a ProtoFeed violation 2. A message (string) that describes the problem 3. A ProtoFeed table name, e.g. ``'meta'``, in which the problem occurs 4. A list of rows (integers) of the table's DataFrame where the problem occurs table : string Name of a ProtoFeed table df : DataFrame The ProtoFeed table corresponding to ``table`` Returns ------- list The ``problems`` list extended as follows. Check whether the DataFrame contains extra columns not in the ProtoFeed and append to the problems list one warning for each extra column.
[ "Check", "for", "invalid", "columns", "in", "the", "given", "ProtoFeed", "DataFrame", "." ]
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/validators.py#L68-L110
train
49,688
mrcagney/make_gtfs
make_gtfs/validators.py
validate
def validate(pfeed, *, as_df=True, include_warnings=True): """ Check whether the given pfeed satisfies the ProtoFeed spec. Parameters ---------- pfeed : ProtoFeed as_df : boolean If ``True``, then return the resulting report as a DataFrame; otherwise return the result as a list include_warnings : boolean If ``True``, then include problems of types ``'error'`` and ``'warning'``; otherwise, only return problems of type ``'error'`` Returns ------- list or DataFrame Run all the table-checking functions: :func:`check_agency`, :func:`check_calendar`, etc. This yields a possibly empty list of items [problem type, message, table, rows]. If ``as_df``, then format the error list as a DataFrame with the columns - ``'type'``: 'error' or 'warning'; 'error' means the ProtoFeed spec is violated; 'warning' means there is a problem but it's not a ProtoFeed spec violation - ``'message'``: description of the problem - ``'table'``: table in which problem occurs, e.g. 'routes' - ``'rows'``: rows of the table's DataFrame where problem occurs Return early if the pfeed is missing required tables or required columns. """ problems = [] # Check for invalid columns and check the required tables checkers = [ 'check_frequencies', 'check_meta', 'check_service_windows', 'check_shapes', 'check_stops', ] for checker in checkers: problems.extend(globals()[checker](pfeed, include_warnings=include_warnings)) return gt.format_problems(problems, as_df=as_df)
python
def validate(pfeed, *, as_df=True, include_warnings=True): """ Check whether the given pfeed satisfies the ProtoFeed spec. Parameters ---------- pfeed : ProtoFeed as_df : boolean If ``True``, then return the resulting report as a DataFrame; otherwise return the result as a list include_warnings : boolean If ``True``, then include problems of types ``'error'`` and ``'warning'``; otherwise, only return problems of type ``'error'`` Returns ------- list or DataFrame Run all the table-checking functions: :func:`check_agency`, :func:`check_calendar`, etc. This yields a possibly empty list of items [problem type, message, table, rows]. If ``as_df``, then format the error list as a DataFrame with the columns - ``'type'``: 'error' or 'warning'; 'error' means the ProtoFeed spec is violated; 'warning' means there is a problem but it's not a ProtoFeed spec violation - ``'message'``: description of the problem - ``'table'``: table in which problem occurs, e.g. 'routes' - ``'rows'``: rows of the table's DataFrame where problem occurs Return early if the pfeed is missing required tables or required columns. """ problems = [] # Check for invalid columns and check the required tables checkers = [ 'check_frequencies', 'check_meta', 'check_service_windows', 'check_shapes', 'check_stops', ] for checker in checkers: problems.extend(globals()[checker](pfeed, include_warnings=include_warnings)) return gt.format_problems(problems, as_df=as_df)
[ "def", "validate", "(", "pfeed", ",", "*", ",", "as_df", "=", "True", ",", "include_warnings", "=", "True", ")", ":", "problems", "=", "[", "]", "# Check for invalid columns and check the required tables", "checkers", "=", "[", "'check_frequencies'", ",", "'check_...
Check whether the given pfeed satisfies the ProtoFeed spec. Parameters ---------- pfeed : ProtoFeed as_df : boolean If ``True``, then return the resulting report as a DataFrame; otherwise return the result as a list include_warnings : boolean If ``True``, then include problems of types ``'error'`` and ``'warning'``; otherwise, only return problems of type ``'error'`` Returns ------- list or DataFrame Run all the table-checking functions: :func:`check_agency`, :func:`check_calendar`, etc. This yields a possibly empty list of items [problem type, message, table, rows]. If ``as_df``, then format the error list as a DataFrame with the columns - ``'type'``: 'error' or 'warning'; 'error' means the ProtoFeed spec is violated; 'warning' means there is a problem but it's not a ProtoFeed spec violation - ``'message'``: description of the problem - ``'table'``: table in which problem occurs, e.g. 'routes' - ``'rows'``: rows of the table's DataFrame where problem occurs Return early if the pfeed is missing required tables or required columns.
[ "Check", "whether", "the", "given", "pfeed", "satisfies", "the", "ProtoFeed", "spec", "." ]
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/validators.py#L286-L336
train
49,689
deshima-dev/decode
decode/joke/functions.py
youtube
def youtube(keyword=None): """Open youtube. Args: keyword (optional): Search word. """ if keyword is None: web.open('https://www.youtube.com/watch?v=L_mBVT2jBFw') else: web.open(quote('https://www.youtube.com/results?search_query={}'.format(keyword), RESERVED))
python
def youtube(keyword=None): """Open youtube. Args: keyword (optional): Search word. """ if keyword is None: web.open('https://www.youtube.com/watch?v=L_mBVT2jBFw') else: web.open(quote('https://www.youtube.com/results?search_query={}'.format(keyword), RESERVED))
[ "def", "youtube", "(", "keyword", "=", "None", ")", ":", "if", "keyword", "is", "None", ":", "web", ".", "open", "(", "'https://www.youtube.com/watch?v=L_mBVT2jBFw'", ")", "else", ":", "web", ".", "open", "(", "quote", "(", "'https://www.youtube.com/results?sear...
Open youtube. Args: keyword (optional): Search word.
[ "Open", "youtube", "." ]
e789e174cd316e7ec8bc55be7009ad35baced3c0
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/joke/functions.py#L21-L30
train
49,690
facelessuser/pyspelling
pyspelling/filters/javascript.py
JavaScriptFilter.replace_surrogates
def replace_surrogates(self, m): """Replace surrogates.""" high, low = ord(m.group(1)), ord(m.group(2)) return chr((high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000)
python
def replace_surrogates(self, m): """Replace surrogates.""" high, low = ord(m.group(1)), ord(m.group(2)) return chr((high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000)
[ "def", "replace_surrogates", "(", "self", ",", "m", ")", ":", "high", ",", "low", "=", "ord", "(", "m", ".", "group", "(", "1", ")", ")", ",", "ord", "(", "m", ".", "group", "(", "2", ")", ")", "return", "chr", "(", "(", "high", "-", "0xD800"...
Replace surrogates.
[ "Replace", "surrogates", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/javascript.py#L110-L114
train
49,691
facelessuser/pyspelling
pyspelling/plugin.py
Plugin.override_config
def override_config(self, options): """Override the default configuration.""" for k, v in options.items(): # Reject names not in the default configuration if k not in self.config: raise KeyError("'{}' is not a valid option for '{}'".format(k, self.__class__.__name__)) self.validate_options(k, v) self.config[k] = v
python
def override_config(self, options): """Override the default configuration.""" for k, v in options.items(): # Reject names not in the default configuration if k not in self.config: raise KeyError("'{}' is not a valid option for '{}'".format(k, self.__class__.__name__)) self.validate_options(k, v) self.config[k] = v
[ "def", "override_config", "(", "self", ",", "options", ")", ":", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", ":", "# Reject names not in the default configuration", "if", "k", "not", "in", "self", ".", "config", ":", "raise", "KeyError", ...
Override the default configuration.
[ "Override", "the", "default", "configuration", "." ]
c25d5292cc2687ad65891a12ead43f7182ca8bb3
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/plugin.py#L33-L41
train
49,692
mrcagney/make_gtfs
make_gtfs/main.py
build_stop_ids
def build_stop_ids(shape_id): """ Create a pair of stop IDs based on the given shape ID. """ return [cs.SEP.join(['stp', shape_id, str(i)]) for i in range(2)]
python
def build_stop_ids(shape_id): """ Create a pair of stop IDs based on the given shape ID. """ return [cs.SEP.join(['stp', shape_id, str(i)]) for i in range(2)]
[ "def", "build_stop_ids", "(", "shape_id", ")", ":", "return", "[", "cs", ".", "SEP", ".", "join", "(", "[", "'stp'", ",", "shape_id", ",", "str", "(", "i", ")", "]", ")", "for", "i", "in", "range", "(", "2", ")", "]" ]
Create a pair of stop IDs based on the given shape ID.
[ "Create", "a", "pair", "of", "stop", "IDs", "based", "on", "the", "given", "shape", "ID", "." ]
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/main.py#L32-L36
train
49,693
mrcagney/make_gtfs
make_gtfs/main.py
build_agency
def build_agency(pfeed): """ Given a ProtoFeed, return a DataFrame representing ``agency.txt`` """ return pd.DataFrame({ 'agency_name': pfeed.meta['agency_name'].iat[0], 'agency_url': pfeed.meta['agency_url'].iat[0], 'agency_timezone': pfeed.meta['agency_timezone'].iat[0], }, index=[0])
python
def build_agency(pfeed): """ Given a ProtoFeed, return a DataFrame representing ``agency.txt`` """ return pd.DataFrame({ 'agency_name': pfeed.meta['agency_name'].iat[0], 'agency_url': pfeed.meta['agency_url'].iat[0], 'agency_timezone': pfeed.meta['agency_timezone'].iat[0], }, index=[0])
[ "def", "build_agency", "(", "pfeed", ")", ":", "return", "pd", ".", "DataFrame", "(", "{", "'agency_name'", ":", "pfeed", ".", "meta", "[", "'agency_name'", "]", ".", "iat", "[", "0", "]", ",", "'agency_url'", ":", "pfeed", ".", "meta", "[", "'agency_u...
Given a ProtoFeed, return a DataFrame representing ``agency.txt``
[ "Given", "a", "ProtoFeed", "return", "a", "DataFrame", "representing", "agency", ".", "txt" ]
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/main.py#L45-L53
train
49,694
mrcagney/make_gtfs
make_gtfs/main.py
build_routes
def build_routes(pfeed): """ Given a ProtoFeed, return a DataFrame representing ``routes.txt``. """ f = pfeed.frequencies[['route_short_name', 'route_long_name', 'route_type', 'shape_id']].drop_duplicates().copy() # Create route IDs f['route_id'] = 'r' + f['route_short_name'].map(str) del f['shape_id'] return f
python
def build_routes(pfeed): """ Given a ProtoFeed, return a DataFrame representing ``routes.txt``. """ f = pfeed.frequencies[['route_short_name', 'route_long_name', 'route_type', 'shape_id']].drop_duplicates().copy() # Create route IDs f['route_id'] = 'r' + f['route_short_name'].map(str) del f['shape_id'] return f
[ "def", "build_routes", "(", "pfeed", ")", ":", "f", "=", "pfeed", ".", "frequencies", "[", "[", "'route_short_name'", ",", "'route_long_name'", ",", "'route_type'", ",", "'shape_id'", "]", "]", ".", "drop_duplicates", "(", ")", ".", "copy", "(", ")", "# Cr...
Given a ProtoFeed, return a DataFrame representing ``routes.txt``.
[ "Given", "a", "ProtoFeed", "return", "a", "DataFrame", "representing", "routes", ".", "txt", "." ]
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/main.py#L92-L104
train
49,695
mrcagney/make_gtfs
make_gtfs/main.py
build_shapes
def build_shapes(pfeed): """ Given a ProtoFeed, return DataFrame representing ``shapes.txt``. Only use shape IDs that occur in both ``pfeed.shapes`` and ``pfeed.frequencies``. Create reversed shapes where routes traverse shapes in both directions. """ rows = [] for shape, geom in pfeed.shapes[['shape_id', 'geometry']].itertuples(index=False): if shape not in pfeed.shapes_extra: continue if pfeed.shapes_extra[shape] == 2: # Add shape and its reverse shid = shape + '-1' new_rows = [[shid, i, lon, lat] for i, (lon, lat) in enumerate(geom.coords)] rows.extend(new_rows) shid = shape + '-0' new_rows = [[shid, i, lon, lat] for i, (lon, lat) in enumerate(reversed(geom.coords))] rows.extend(new_rows) else: # Add shape shid = '{}{}{}'.format(shape, cs.SEP, pfeed.shapes_extra[shape]) new_rows = [[shid, i, lon, lat] for i, (lon, lat) in enumerate(geom.coords)] rows.extend(new_rows) return pd.DataFrame(rows, columns=['shape_id', 'shape_pt_sequence', 'shape_pt_lon', 'shape_pt_lat'])
python
def build_shapes(pfeed): """ Given a ProtoFeed, return DataFrame representing ``shapes.txt``. Only use shape IDs that occur in both ``pfeed.shapes`` and ``pfeed.frequencies``. Create reversed shapes where routes traverse shapes in both directions. """ rows = [] for shape, geom in pfeed.shapes[['shape_id', 'geometry']].itertuples(index=False): if shape not in pfeed.shapes_extra: continue if pfeed.shapes_extra[shape] == 2: # Add shape and its reverse shid = shape + '-1' new_rows = [[shid, i, lon, lat] for i, (lon, lat) in enumerate(geom.coords)] rows.extend(new_rows) shid = shape + '-0' new_rows = [[shid, i, lon, lat] for i, (lon, lat) in enumerate(reversed(geom.coords))] rows.extend(new_rows) else: # Add shape shid = '{}{}{}'.format(shape, cs.SEP, pfeed.shapes_extra[shape]) new_rows = [[shid, i, lon, lat] for i, (lon, lat) in enumerate(geom.coords)] rows.extend(new_rows) return pd.DataFrame(rows, columns=['shape_id', 'shape_pt_sequence', 'shape_pt_lon', 'shape_pt_lat'])
[ "def", "build_shapes", "(", "pfeed", ")", ":", "rows", "=", "[", "]", "for", "shape", ",", "geom", "in", "pfeed", ".", "shapes", "[", "[", "'shape_id'", ",", "'geometry'", "]", "]", ".", "itertuples", "(", "index", "=", "False", ")", ":", "if", "sh...
Given a ProtoFeed, return DataFrame representing ``shapes.txt``. Only use shape IDs that occur in both ``pfeed.shapes`` and ``pfeed.frequencies``. Create reversed shapes where routes traverse shapes in both directions.
[ "Given", "a", "ProtoFeed", "return", "DataFrame", "representing", "shapes", ".", "txt", ".", "Only", "use", "shape", "IDs", "that", "occur", "in", "both", "pfeed", ".", "shapes", "and", "pfeed", ".", "frequencies", ".", "Create", "reversed", "shapes", "where...
37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/main.py#L106-L137
train
49,696
j0ack/flask-codemirror
flask_codemirror/widgets.py
CodeMirrorWidget._generate_content
def _generate_content(self): """Dumps content using JSON to send to CodeMirror""" # concat into a dict dic = self.config dic['mode'] = self.language if self.theme: dic['theme'] = self.theme # dumps with json return json.dumps(dic, indent=8, separators=(',', ': '))
python
def _generate_content(self): """Dumps content using JSON to send to CodeMirror""" # concat into a dict dic = self.config dic['mode'] = self.language if self.theme: dic['theme'] = self.theme # dumps with json return json.dumps(dic, indent=8, separators=(',', ': '))
[ "def", "_generate_content", "(", "self", ")", ":", "# concat into a dict", "dic", "=", "self", ".", "config", "dic", "[", "'mode'", "]", "=", "self", ".", "language", "if", "self", ".", "theme", ":", "dic", "[", "'theme'", "]", "=", "self", ".", "theme...
Dumps content using JSON to send to CodeMirror
[ "Dumps", "content", "using", "JSON", "to", "send", "to", "CodeMirror" ]
81ad831ff849b60bb34de5db727ad626ff3c9bdc
https://github.com/j0ack/flask-codemirror/blob/81ad831ff849b60bb34de5db727ad626ff3c9bdc/flask_codemirror/widgets.py#L70-L78
train
49,697
tjwalch/django-livereload-server
livereload/server.py
Server.ignore_file_extension
def ignore_file_extension(self, extension): """ Configure a file extension to be ignored. :param extension: file extension to be ignored (ex. .less, .scss, etc) """ logger.info('Ignoring file extension: {}'.format(extension)) self.watcher.ignore_file_extension(extension)
python
def ignore_file_extension(self, extension): """ Configure a file extension to be ignored. :param extension: file extension to be ignored (ex. .less, .scss, etc) """ logger.info('Ignoring file extension: {}'.format(extension)) self.watcher.ignore_file_extension(extension)
[ "def", "ignore_file_extension", "(", "self", ",", "extension", ")", ":", "logger", ".", "info", "(", "'Ignoring file extension: {}'", ".", "format", "(", "extension", ")", ")", "self", ".", "watcher", ".", "ignore_file_extension", "(", "extension", ")" ]
Configure a file extension to be ignored. :param extension: file extension to be ignored (ex. .less, .scss, etc)
[ "Configure", "a", "file", "extension", "to", "be", "ignored", "." ]
ea3edaa1a5b2f8cb49761dd32f2fcc4554c4aa0c
https://github.com/tjwalch/django-livereload-server/blob/ea3edaa1a5b2f8cb49761dd32f2fcc4554c4aa0c/livereload/server.py#L97-L105
train
49,698
tjwalch/django-livereload-server
livereload/watcher.py
Watcher.should_ignore
def should_ignore(self, filename): """Should ignore a given filename?""" _, ext = os.path.splitext(filename) return ext in self.ignored_file_extensions
python
def should_ignore(self, filename): """Should ignore a given filename?""" _, ext = os.path.splitext(filename) return ext in self.ignored_file_extensions
[ "def", "should_ignore", "(", "self", ",", "filename", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "return", "ext", "in", "self", ".", "ignored_file_extensions" ]
Should ignore a given filename?
[ "Should", "ignore", "a", "given", "filename?" ]
ea3edaa1a5b2f8cb49761dd32f2fcc4554c4aa0c
https://github.com/tjwalch/django-livereload-server/blob/ea3edaa1a5b2f8cb49761dd32f2fcc4554c4aa0c/livereload/watcher.py#L37-L40
train
49,699