repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
BBVA/data-refinery | datarefinery/tuple/Formats.py | csv_to_map | def csv_to_map(fields, delimiter=','):
"""
Convert csv to dict
:param delimiter:
:param fields:
:return:
"""
def _csv_to_list(csv_input):
"""
Util function to overcome the use of files by in-memory io buffer
:param csv_input:
:return:
"""
io... | python | def csv_to_map(fields, delimiter=','):
"""
Convert csv to dict
:param delimiter:
:param fields:
:return:
"""
def _csv_to_list(csv_input):
"""
Util function to overcome the use of files by in-memory io buffer
:param csv_input:
:return:
"""
io... | [
"def",
"csv_to_map",
"(",
"fields",
",",
"delimiter",
"=",
"','",
")",
":",
"def",
"_csv_to_list",
"(",
"csv_input",
")",
":",
"\"\"\"\n Util function to overcome the use of files by in-memory io buffer\n\n :param csv_input:\n :return:\n \"\"\"",
"io_fil... | Convert csv to dict
:param delimiter:
:param fields:
:return: | [
"Convert",
"csv",
"to",
"dict"
] | train | https://github.com/BBVA/data-refinery/blob/4ff19186ac570269f64a245ad6297cf882c70aa4/datarefinery/tuple/Formats.py#L34-L63 |
BBVA/data-refinery | datarefinery/tuple/Formats.py | map_to_csv | def map_to_csv(fields, delimiter=","):
"""
Convert dict to csv
:param fields:
:return:
"""
def _list_to_csv(l):
"""
Util function to overcome the use of files by in-memory io buffer
:param l:
:return:
"""
io_file = io.StringIO()
writer =... | python | def map_to_csv(fields, delimiter=","):
"""
Convert dict to csv
:param fields:
:return:
"""
def _list_to_csv(l):
"""
Util function to overcome the use of files by in-memory io buffer
:param l:
:return:
"""
io_file = io.StringIO()
writer =... | [
"def",
"map_to_csv",
"(",
"fields",
",",
"delimiter",
"=",
"\",\"",
")",
":",
"def",
"_list_to_csv",
"(",
"l",
")",
":",
"\"\"\"\n Util function to overcome the use of files by in-memory io buffer\n\n :param l:\n :return:\n \"\"\"",
"io_file",
"=",
"... | Convert dict to csv
:param fields:
:return: | [
"Convert",
"dict",
"to",
"csv"
] | train | https://github.com/BBVA/data-refinery/blob/4ff19186ac570269f64a245ad6297cf882c70aa4/datarefinery/tuple/Formats.py#L66-L99 |
deshima-dev/decode | decode/core/array/decorators.py | xarrayfunc | def xarrayfunc(func):
"""Make a function compatible with xarray.DataArray.
This function is intended to be used as a decorator like::
>>> @dc.xarrayfunc
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array)
Args:
... | python | def xarrayfunc(func):
"""Make a function compatible with xarray.DataArray.
This function is intended to be used as a decorator like::
>>> @dc.xarrayfunc
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array)
Args:
... | [
"def",
"xarrayfunc",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"arg",
",",
"xr",
".",
"DataArray",
")",
"for",
"arg",
"in",
... | Make a function compatible with xarray.DataArray.
This function is intended to be used as a decorator like::
>>> @dc.xarrayfunc
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array)
Args:
func (function): Funct... | [
"Make",
"a",
"function",
"compatible",
"with",
"xarray",
".",
"DataArray",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/decorators.py#L30-L63 |
deshima-dev/decode | decode/core/array/decorators.py | chunk | def chunk(*argnames, concatfunc=None):
"""Make a function compatible with multicore chunk processing.
This function is intended to be used as a decorator like::
>>> @dc.chunk('array')
>>> def func(array):
... # do something
... return newarray
>>>
>>> re... | python | def chunk(*argnames, concatfunc=None):
"""Make a function compatible with multicore chunk processing.
This function is intended to be used as a decorator like::
>>> @dc.chunk('array')
>>> def func(array):
... # do something
... return newarray
>>>
>>> re... | [
"def",
"chunk",
"(",
"*",
"argnames",
",",
"concatfunc",
"=",
"None",
")",
":",
"def",
"_chunk",
"(",
"func",
")",
":",
"depth",
"=",
"[",
"s",
".",
"function",
"for",
"s",
"in",
"stack",
"(",
")",
"]",
".",
"index",
"(",
"'<module>'",
")",
"f_gl... | Make a function compatible with multicore chunk processing.
This function is intended to be used as a decorator like::
>>> @dc.chunk('array')
>>> def func(array):
... # do something
... return newarray
>>>
>>> result = func(array, timechunk=10)
or you c... | [
"Make",
"a",
"function",
"compatible",
"with",
"multicore",
"chunk",
"processing",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/decorators.py#L66-L160 |
deshima-dev/decode | decode/core/__init__.py | BaseAccessor.scalarcoords | def scalarcoords(self):
"""A dictionary of values that don't label any axes (point-like)."""
return {k: v.values for k, v in self.coords.items() if v.dims==()} | python | def scalarcoords(self):
"""A dictionary of values that don't label any axes (point-like)."""
return {k: v.values for k, v in self.coords.items() if v.dims==()} | [
"def",
"scalarcoords",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
".",
"values",
"for",
"k",
",",
"v",
"in",
"self",
".",
"coords",
".",
"items",
"(",
")",
"if",
"v",
".",
"dims",
"==",
"(",
")",
"}"
] | A dictionary of values that don't label any axes (point-like). | [
"A",
"dictionary",
"of",
"values",
"that",
"don",
"t",
"label",
"any",
"axes",
"(",
"point",
"-",
"like",
")",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/__init__.py#L22-L24 |
facelessuser/pyspelling | pyspelling/filters/markdown.py | MarkdownFilter.setup | def setup(self):
"""Setup."""
extensions = []
extension_configs = {}
for item in self.config['markdown_extensions']:
if isinstance(item, str):
extensions.append(item)
else:
k, v = list(item.items())[0]
extensions.ap... | python | def setup(self):
"""Setup."""
extensions = []
extension_configs = {}
for item in self.config['markdown_extensions']:
if isinstance(item, str):
extensions.append(item)
else:
k, v = list(item.items())[0]
extensions.ap... | [
"def",
"setup",
"(",
"self",
")",
":",
"extensions",
"=",
"[",
"]",
"extension_configs",
"=",
"{",
"}",
"for",
"item",
"in",
"self",
".",
"config",
"[",
"'markdown_extensions'",
"]",
":",
"if",
"isinstance",
"(",
"item",
",",
"str",
")",
":",
"extensio... | Setup. | [
"Setup",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/markdown.py#L23-L36 |
facelessuser/pyspelling | pyspelling/filters/markdown.py | MarkdownFilter._filter | def _filter(self, text):
"""Filter markdown."""
self.markdown.reset()
return self.markdown.convert(text) | python | def _filter(self, text):
"""Filter markdown."""
self.markdown.reset()
return self.markdown.convert(text) | [
"def",
"_filter",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"markdown",
".",
"reset",
"(",
")",
"return",
"self",
".",
"markdown",
".",
"convert",
"(",
"text",
")"
] | Filter markdown. | [
"Filter",
"markdown",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/markdown.py#L45-L49 |
runfalk/spans | benchmark.py | format_sec | def format_sec(s):
"""
Format seconds in a more human readable way. It supports units down to
nanoseconds.
:param s: Float of seconds to format
:return: String second representation, like 12.4 us
"""
prefixes = ["", "m", "u", "n"]
unit = 0
while s < 1 and unit + 1 < len(prefixes):... | python | def format_sec(s):
"""
Format seconds in a more human readable way. It supports units down to
nanoseconds.
:param s: Float of seconds to format
:return: String second representation, like 12.4 us
"""
prefixes = ["", "m", "u", "n"]
unit = 0
while s < 1 and unit + 1 < len(prefixes):... | [
"def",
"format_sec",
"(",
"s",
")",
":",
"prefixes",
"=",
"[",
"\"\"",
",",
"\"m\"",
",",
"\"u\"",
",",
"\"n\"",
"]",
"unit",
"=",
"0",
"while",
"s",
"<",
"1",
"and",
"unit",
"+",
"1",
"<",
"len",
"(",
"prefixes",
")",
":",
"s",
"*=",
"1000",
... | Format seconds in a more human readable way. It supports units down to
nanoseconds.
:param s: Float of seconds to format
:return: String second representation, like 12.4 us | [
"Format",
"seconds",
"in",
"a",
"more",
"human",
"readable",
"way",
".",
"It",
"supports",
"units",
"down",
"to",
"nanoseconds",
"."
] | train | https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/benchmark.py#L6-L22 |
racker/rackspace-monitoring | rackspace_monitoring/drivers/rackspace.py | RackspaceMonitoringDriver.create_entity | def create_entity(self, **kwargs):
"""
kwargs expected:
'who': kwargs.get('who')
'why': kwargs.get('why')
'uri': kwargs.get('uri')
'ip_addresses': kwargs.get('ip_addresses', {})
'label': kwargs.get('label')
'agent_id': kwargs.get('a... | python | def create_entity(self, **kwargs):
"""
kwargs expected:
'who': kwargs.get('who')
'why': kwargs.get('why')
'uri': kwargs.get('uri')
'ip_addresses': kwargs.get('ip_addresses', {})
'label': kwargs.get('label')
'agent_id': kwargs.get('a... | [
"def",
"create_entity",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
"headers",
"=",
"kwargs",
".",
"get",
"(",
"'headers'",
",",
"{",
"}",
")",
"if",
"'headers'",
"in",
"data",
":",
"del",
"data",
"[",
"'headers'",
"]",
"... | kwargs expected:
'who': kwargs.get('who')
'why': kwargs.get('why')
'uri': kwargs.get('uri')
'ip_addresses': kwargs.get('ip_addresses', {})
'label': kwargs.get('label')
'agent_id': kwargs.get('agent_id')
'metadata': kwargs.get('extra', {... | [
"kwargs",
"expected",
":",
"who",
":",
"kwargs",
".",
"get",
"(",
"who",
")",
"why",
":",
"kwargs",
".",
"get",
"(",
"why",
")",
"uri",
":",
"kwargs",
".",
"get",
"(",
"uri",
")",
"ip_addresses",
":",
"kwargs",
".",
"get",
"(",
"ip_addresses",
"{}"... | train | https://github.com/racker/rackspace-monitoring/blob/8a9929e5fd51826c0a392e21bc55acb2aefe54f7/rackspace_monitoring/drivers/rackspace.py#L846-L861 |
mrcagney/make_gtfs | make_gtfs/cli.py | make_gtfs | def make_gtfs(source_path, target_path, buffer, ndigits):
"""
Create a GTFS feed from the files in the directory SOURCE_PATH.
See the project README for a description of the required source
files.
Save the feed to the file or directory TARGET_PATH.
If the target path ends in '.zip', then write t... | python | def make_gtfs(source_path, target_path, buffer, ndigits):
"""
Create a GTFS feed from the files in the directory SOURCE_PATH.
See the project README for a description of the required source
files.
Save the feed to the file or directory TARGET_PATH.
If the target path ends in '.zip', then write t... | [
"def",
"make_gtfs",
"(",
"source_path",
",",
"target_path",
",",
"buffer",
",",
"ndigits",
")",
":",
"pfeed",
"=",
"pf",
".",
"read_protofeed",
"(",
"source_path",
")",
"feed",
"=",
"m",
".",
"build_feed",
"(",
"pfeed",
",",
"buffer",
"=",
"buffer",
")",... | Create a GTFS feed from the files in the directory SOURCE_PATH.
See the project README for a description of the required source
files.
Save the feed to the file or directory TARGET_PATH.
If the target path ends in '.zip', then write the feed as a zip
archive.
Otherwise assume the path is a direc... | [
"Create",
"a",
"GTFS",
"feed",
"from",
"the",
"files",
"in",
"the",
"directory",
"SOURCE_PATH",
".",
"See",
"the",
"project",
"README",
"for",
"a",
"description",
"of",
"the",
"required",
"source",
"files",
".",
"Save",
"the",
"feed",
"to",
"the",
"file",
... | train | https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/cli.py#L18-L37 |
deshima-dev/decode | decode/utils/ndarray/functions.py | psd | def psd(data, dt, ndivide=1, window=hanning, overlap_half=False):
"""Calculate power spectrum density of data.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
ax (m... | python | def psd(data, dt, ndivide=1, window=hanning, overlap_half=False):
"""Calculate power spectrum density of data.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
ax (m... | [
"def",
"psd",
"(",
"data",
",",
"dt",
",",
"ndivide",
"=",
"1",
",",
"window",
"=",
"hanning",
",",
"overlap_half",
"=",
"False",
")",
":",
"logger",
"=",
"getLogger",
"(",
"'decode.utils.ndarray.psd'",
")",
"if",
"overlap_half",
":",
"step",
"=",
"int",... | Calculate power spectrum density of data.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them).
ax (matplotlib.axes): Axis you want to plot on.
doplot (bool): Plot ho... | [
"Calculate",
"power",
"spectrum",
"density",
"of",
"data",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/utils/ndarray/functions.py#L20-L68 |
deshima-dev/decode | decode/utils/ndarray/functions.py | allan_variance | def allan_variance(data, dt, tmax=10):
"""Calculate Allan variance.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
tmax (float): Maximum time.
Returns:
vk (np.ndarray): Frequency.
allanvar (np.ndarray): Allan variance.
"""
allanvar ... | python | def allan_variance(data, dt, tmax=10):
"""Calculate Allan variance.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
tmax (float): Maximum time.
Returns:
vk (np.ndarray): Frequency.
allanvar (np.ndarray): Allan variance.
"""
allanvar ... | [
"def",
"allan_variance",
"(",
"data",
",",
"dt",
",",
"tmax",
"=",
"10",
")",
":",
"allanvar",
"=",
"[",
"]",
"nmax",
"=",
"len",
"(",
"data",
")",
"if",
"len",
"(",
"data",
")",
"<",
"tmax",
"/",
"dt",
"else",
"int",
"(",
"tmax",
"/",
"dt",
... | Calculate Allan variance.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
tmax (float): Maximum time.
Returns:
vk (np.ndarray): Frequency.
allanvar (np.ndarray): Allan variance. | [
"Calculate",
"Allan",
"variance",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/utils/ndarray/functions.py#L71-L89 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.discover | def discover(cls, path, depth="0"):
"""Discover a list of collections under the given ``path``.
If ``depth`` is "0", only the actual object under ``path`` is
returned.
If ``depth`` is anything but "0", it is considered as "1" and direct
children are included in the result.
... | python | def discover(cls, path, depth="0"):
"""Discover a list of collections under the given ``path``.
If ``depth`` is "0", only the actual object under ``path`` is
returned.
If ``depth`` is anything but "0", it is considered as "1" and direct
children are included in the result.
... | [
"def",
"discover",
"(",
"cls",
",",
"path",
",",
"depth",
"=",
"\"0\"",
")",
":",
"# Path should already be sanitized",
"attributes",
"=",
"_get_attributes_from_path",
"(",
"path",
")",
"try",
":",
"if",
"len",
"(",
"attributes",
")",
"==",
"3",
":",
"# If a... | Discover a list of collections under the given ``path``.
If ``depth`` is "0", only the actual object under ``path`` is
returned.
If ``depth`` is anything but "0", it is considered as "1" and direct
children are included in the result.
The ``path`` is relative.
The roo... | [
"Discover",
"a",
"list",
"of",
"collections",
"under",
"the",
"given",
"path",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L185-L232 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.etag | def etag(self):
"""Encoded as quoted-string (see RFC 2616)."""
if self.is_fake:
return
entry = None
for entry in self.journal.list():
pass
return entry.uid if entry is not None else hashlib.sha256(b"").hexdigest() | python | def etag(self):
"""Encoded as quoted-string (see RFC 2616)."""
if self.is_fake:
return
entry = None
for entry in self.journal.list():
pass
return entry.uid if entry is not None else hashlib.sha256(b"").hexdigest() | [
"def",
"etag",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"entry",
"=",
"None",
"for",
"entry",
"in",
"self",
".",
"journal",
".",
"list",
"(",
")",
":",
"pass",
"return",
"entry",
".",
"uid",
"if",
"entry",
"is",
"not",
... | Encoded as quoted-string (see RFC 2616). | [
"Encoded",
"as",
"quoted",
"-",
"string",
"(",
"see",
"RFC",
"2616",
")",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L235-L244 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.create_collection | def create_collection(cls, href, collection=None, props=None):
"""Create a collection.
If the collection already exists and neither ``collection`` nor
``props`` are set, this method shouldn't do anything. Otherwise the
existing collection must be replaced.
``collection`` is a l... | python | def create_collection(cls, href, collection=None, props=None):
"""Create a collection.
If the collection already exists and neither ``collection`` nor
``props`` are set, this method shouldn't do anything. Otherwise the
existing collection must be replaced.
``collection`` is a l... | [
"def",
"create_collection",
"(",
"cls",
",",
"href",
",",
"collection",
"=",
"None",
",",
"props",
"=",
"None",
")",
":",
"# Path should already be sanitized",
"attributes",
"=",
"_get_attributes_from_path",
"(",
"href",
")",
"if",
"len",
"(",
"attributes",
")",... | Create a collection.
If the collection already exists and neither ``collection`` nor
``props`` are set, this method shouldn't do anything. Otherwise the
existing collection must be replaced.
``collection`` is a list of vobject components.
``props`` are metadata values for the ... | [
"Create",
"a",
"collection",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L247-L319 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.sync | def sync(self, old_token=None):
"""Get the current sync token and changed items for synchronization.
``old_token`` an old sync token which is used as the base of the
delta update. If sync token is missing, all items are returned.
ValueError is raised for invalid or old tokens.
"... | python | def sync(self, old_token=None):
"""Get the current sync token and changed items for synchronization.
``old_token`` an old sync token which is used as the base of the
delta update. If sync token is missing, all items are returned.
ValueError is raised for invalid or old tokens.
"... | [
"def",
"sync",
"(",
"self",
",",
"old_token",
"=",
"None",
")",
":",
"# FIXME: Actually implement",
"token",
"=",
"\"http://radicale.org/ns/sync/%s\"",
"%",
"self",
".",
"etag",
".",
"strip",
"(",
"\"\\\"\"",
")",
"if",
"old_token",
":",
"raise",
"ValueError",
... | Get the current sync token and changed items for synchronization.
``old_token`` an old sync token which is used as the base of the
delta update. If sync token is missing, all items are returned.
ValueError is raised for invalid or old tokens. | [
"Get",
"the",
"current",
"sync",
"token",
"and",
"changed",
"items",
"for",
"synchronization",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L321-L332 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.list | def list(self):
"""List collection items."""
if self.is_fake:
return
for item in self.collection.list():
yield item.uid + self.content_suffix | python | def list(self):
"""List collection items."""
if self.is_fake:
return
for item in self.collection.list():
yield item.uid + self.content_suffix | [
"def",
"list",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"for",
"item",
"in",
"self",
".",
"collection",
".",
"list",
"(",
")",
":",
"yield",
"item",
".",
"uid",
"+",
"self",
".",
"content_suffix"
] | List collection items. | [
"List",
"collection",
"items",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L334-L340 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.get | def get(self, href):
"""Fetch a single item."""
if self.is_fake:
return
uid = _trim_suffix(href, ('.ics', '.ical', '.vcf'))
etesync_item = self.collection.get(uid)
if etesync_item is None:
return None
try:
item = vobject.readOne(etesy... | python | def get(self, href):
"""Fetch a single item."""
if self.is_fake:
return
uid = _trim_suffix(href, ('.ics', '.ical', '.vcf'))
etesync_item = self.collection.get(uid)
if etesync_item is None:
return None
try:
item = vobject.readOne(etesy... | [
"def",
"get",
"(",
"self",
",",
"href",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"uid",
"=",
"_trim_suffix",
"(",
"href",
",",
"(",
"'.ics'",
",",
"'.ical'",
",",
"'.vcf'",
")",
")",
"etesync_item",
"=",
"self",
".",
"collection",
".",
... | Fetch a single item. | [
"Fetch",
"a",
"single",
"item",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L342-L361 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.upload | def upload(self, href, vobject_item):
"""Upload a new or replace an existing item."""
if self.is_fake:
return
content = vobject_item.serialize()
try:
item = self.get(href)
etesync_item = item.etesync_item
etesync_item.content = content
... | python | def upload(self, href, vobject_item):
"""Upload a new or replace an existing item."""
if self.is_fake:
return
content = vobject_item.serialize()
try:
item = self.get(href)
etesync_item = item.etesync_item
etesync_item.content = content
... | [
"def",
"upload",
"(",
"self",
",",
"href",
",",
"vobject_item",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"content",
"=",
"vobject_item",
".",
"serialize",
"(",
")",
"try",
":",
"item",
"=",
"self",
".",
"get",
"(",
"href",
")",
"etesync... | Upload a new or replace an existing item. | [
"Upload",
"a",
"new",
"or",
"replace",
"an",
"existing",
"item",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L363-L378 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.delete | def delete(self, href=None):
"""Delete an item.
When ``href`` is ``None``, delete the collection.
"""
if self.is_fake:
return
if href is None:
self.collection.delete()
return
item = self.get(href)
if item is None:
... | python | def delete(self, href=None):
"""Delete an item.
When ``href`` is ``None``, delete the collection.
"""
if self.is_fake:
return
if href is None:
self.collection.delete()
return
item = self.get(href)
if item is None:
... | [
"def",
"delete",
"(",
"self",
",",
"href",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"if",
"href",
"is",
"None",
":",
"self",
".",
"collection",
".",
"delete",
"(",
")",
"return",
"item",
"=",
"self",
".",
"get",
"(",
"h... | Delete an item.
When ``href`` is ``None``, delete the collection. | [
"Delete",
"an",
"item",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L380-L397 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.get_meta | def get_meta(self, key=None):
"""Get metadata value for collection."""
if self.is_fake:
return {}
if key == "tag":
return self.tag
elif key is None:
ret = {}
for key in self.journal.info.keys():
ret[key] = self.meta_mapping... | python | def get_meta(self, key=None):
"""Get metadata value for collection."""
if self.is_fake:
return {}
if key == "tag":
return self.tag
elif key is None:
ret = {}
for key in self.journal.info.keys():
ret[key] = self.meta_mapping... | [
"def",
"get_meta",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"{",
"}",
"if",
"key",
"==",
"\"tag\"",
":",
"return",
"self",
".",
"tag",
"elif",
"key",
"is",
"None",
":",
"ret",
"=",
"{",
"}",
"... | Get metadata value for collection. | [
"Get",
"metadata",
"value",
"for",
"collection",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L399-L413 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.set_meta | def set_meta(self, _props):
"""Set metadata values for collection."""
if self.is_fake:
return
props = {}
for key, value in _props.items():
key, value = self.meta_mappings.map_set(key, value)
props[key] = value
# Pop out tag which we don't wan... | python | def set_meta(self, _props):
"""Set metadata values for collection."""
if self.is_fake:
return
props = {}
for key, value in _props.items():
key, value = self.meta_mappings.map_set(key, value)
props[key] = value
# Pop out tag which we don't wan... | [
"def",
"set_meta",
"(",
"self",
",",
"_props",
")",
":",
"if",
"self",
".",
"is_fake",
":",
"return",
"props",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"_props",
".",
"items",
"(",
")",
":",
"key",
",",
"value",
"=",
"self",
".",
"meta_ma... | Set metadata values for collection. | [
"Set",
"metadata",
"values",
"for",
"collection",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L415-L430 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.set_meta_all | def set_meta_all(self, props):
"""Set metadata values for collection.
``props`` a dict with values for properties.
"""
delta_props = self.get_meta()
for key in delta_props.keys():
if key not in props:
delta_props[key] = None
delta_props.updat... | python | def set_meta_all(self, props):
"""Set metadata values for collection.
``props`` a dict with values for properties.
"""
delta_props = self.get_meta()
for key in delta_props.keys():
if key not in props:
delta_props[key] = None
delta_props.updat... | [
"def",
"set_meta_all",
"(",
"self",
",",
"props",
")",
":",
"delta_props",
"=",
"self",
".",
"get_meta",
"(",
")",
"for",
"key",
"in",
"delta_props",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"props",
":",
"delta_props",
"[",
"key",
"]",
... | Set metadata values for collection.
``props`` a dict with values for properties. | [
"Set",
"metadata",
"values",
"for",
"collection",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L433-L444 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.last_modified | def last_modified(self):
"""Get the HTTP-datetime of when the collection was modified."""
# FIXME: Make this sensible
last_modified = time.strftime(
"%a, %d %b %Y %H:%M:%S GMT",
time.gmtime(time.time()))
return last_modified | python | def last_modified(self):
"""Get the HTTP-datetime of when the collection was modified."""
# FIXME: Make this sensible
last_modified = time.strftime(
"%a, %d %b %Y %H:%M:%S GMT",
time.gmtime(time.time()))
return last_modified | [
"def",
"last_modified",
"(",
"self",
")",
":",
"# FIXME: Make this sensible",
"last_modified",
"=",
"time",
".",
"strftime",
"(",
"\"%a, %d %b %Y %H:%M:%S GMT\"",
",",
"time",
".",
"gmtime",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"return",
"last_modified"... | Get the HTTP-datetime of when the collection was modified. | [
"Get",
"the",
"HTTP",
"-",
"datetime",
"of",
"when",
"the",
"collection",
"was",
"modified",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L447-L453 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.serialize | def serialize(self):
"""Get the unicode string representing the whole collection."""
import datetime
items = []
time_begin = datetime.datetime.now()
for href in self.list():
items.append(self.get(href).item)
time_end = datetime.datetime.now()
self.logg... | python | def serialize(self):
"""Get the unicode string representing the whole collection."""
import datetime
items = []
time_begin = datetime.datetime.now()
for href in self.list():
items.append(self.get(href).item)
time_end = datetime.datetime.now()
self.logg... | [
"def",
"serialize",
"(",
"self",
")",
":",
"import",
"datetime",
"items",
"=",
"[",
"]",
"time_begin",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"for",
"href",
"in",
"self",
".",
"list",
"(",
")",
":",
"items",
".",
"append",
"(",
"se... | Get the unicode string representing the whole collection. | [
"Get",
"the",
"unicode",
"string",
"representing",
"the",
"whole",
"collection",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L455-L477 |
etesync/radicale_storage_etesync | radicale_storage_etesync/__init__.py | Collection.acquire_lock | def acquire_lock(cls, mode, user=None):
"""Set a context manager to lock the whole storage.
``mode`` must either be "r" for shared access or "w" for exclusive
access.
``user`` is the name of the logged in user or empty.
"""
if not user:
return
with... | python | def acquire_lock(cls, mode, user=None):
"""Set a context manager to lock the whole storage.
``mode`` must either be "r" for shared access or "w" for exclusive
access.
``user`` is the name of the logged in user or empty.
"""
if not user:
return
with... | [
"def",
"acquire_lock",
"(",
"cls",
",",
"mode",
",",
"user",
"=",
"None",
")",
":",
"if",
"not",
"user",
":",
"return",
"with",
"EteSyncCache",
".",
"lock",
":",
"cls",
".",
"user",
"=",
"user",
"cls",
".",
"etesync",
"=",
"cls",
".",
"_get_etesync_f... | Set a context manager to lock the whole storage.
``mode`` must either be "r" for shared access or "w" for exclusive
access.
``user`` is the name of the logged in user or empty. | [
"Set",
"a",
"context",
"manager",
"to",
"lock",
"the",
"whole",
"storage",
"."
] | train | https://github.com/etesync/radicale_storage_etesync/blob/73d549bad7a37f060ece65c653c18a859a9962f2/radicale_storage_etesync/__init__.py#L505-L536 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.validate_options | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'charset_size':
if v not in (1, 2, 4):
raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v))
elif k == 'wide_charset_size... | python | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'charset_size':
if v not in (1, 2, 4):
raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v))
elif k == 'wide_charset_size... | [
"def",
"validate_options",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"super",
"(",
")",
".",
"validate_options",
"(",
"k",
",",
"v",
")",
"if",
"k",
"==",
"'charset_size'",
":",
"if",
"v",
"not",
"in",
"(",
"1",
",",
"2",
",",
"4",
")",
":",
... | Validate options. | [
"Validate",
"options",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L130-L145 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.match_string | def match_string(self, stype):
"""Match string type."""
return not (stype - self.string_types) or bool(stype & self.wild_string_types) | python | def match_string(self, stype):
"""Match string type."""
return not (stype - self.string_types) or bool(stype & self.wild_string_types) | [
"def",
"match_string",
"(",
"self",
",",
"stype",
")",
":",
"return",
"not",
"(",
"stype",
"-",
"self",
".",
"string_types",
")",
"or",
"bool",
"(",
"stype",
"&",
"self",
".",
"wild_string_types",
")"
] | Match string type. | [
"Match",
"string",
"type",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L169-L172 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.get_encoding_name | def get_encoding_name(self, name):
"""Get encoding name."""
name = codecs.lookup(
filters.PYTHON_ENCODING_NAMES.get(name, name).lower()
).name
if name.startswith(('utf-32', 'utf-16')):
name = name[:6]
if CURRENT_ENDIAN == BIG_ENDIAN:
... | python | def get_encoding_name(self, name):
"""Get encoding name."""
name = codecs.lookup(
filters.PYTHON_ENCODING_NAMES.get(name, name).lower()
).name
if name.startswith(('utf-32', 'utf-16')):
name = name[:6]
if CURRENT_ENDIAN == BIG_ENDIAN:
... | [
"def",
"get_encoding_name",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"codecs",
".",
"lookup",
"(",
"filters",
".",
"PYTHON_ENCODING_NAMES",
".",
"get",
"(",
"name",
",",
"name",
")",
".",
"lower",
"(",
")",
")",
".",
"name",
"if",
"name",
"."... | Get encoding name. | [
"Get",
"encoding",
"name",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L179-L195 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.setup | def setup(self):
"""Setup."""
self.blocks = self.config['block_comments']
self.lines = self.config['line_comments']
self.group_comments = self.config['group_comments']
self.prefix = self.config['prefix']
self.generic_mode = self.config['generic_mode']
self.string... | python | def setup(self):
"""Setup."""
self.blocks = self.config['block_comments']
self.lines = self.config['line_comments']
self.group_comments = self.config['group_comments']
self.prefix = self.config['prefix']
self.generic_mode = self.config['generic_mode']
self.string... | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"blocks",
"=",
"self",
".",
"config",
"[",
"'block_comments'",
"]",
"self",
".",
"lines",
"=",
"self",
".",
"config",
"[",
"'line_comments'",
"]",
"self",
".",
"group_comments",
"=",
"self",
".",
"con... | Setup. | [
"Setup",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L197-L214 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.evaluate_block | def evaluate_block(self, groups):
"""Evaluate block comments."""
if self.blocks:
self.block_comments.append([groups['block'][2:-2], self.line_num, self.current_encoding]) | python | def evaluate_block(self, groups):
"""Evaluate block comments."""
if self.blocks:
self.block_comments.append([groups['block'][2:-2], self.line_num, self.current_encoding]) | [
"def",
"evaluate_block",
"(",
"self",
",",
"groups",
")",
":",
"if",
"self",
".",
"blocks",
":",
"self",
".",
"block_comments",
".",
"append",
"(",
"[",
"groups",
"[",
"'block'",
"]",
"[",
"2",
":",
"-",
"2",
"]",
",",
"self",
".",
"line_num",
",",... | Evaluate block comments. | [
"Evaluate",
"block",
"comments",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L216-L220 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.evaluate_inline_tail | def evaluate_inline_tail(self, groups):
"""Evaluate inline comments at the tail of source code."""
if self.lines:
self.line_comments.append([groups['line'][2:].replace('\\\n', ''), self.line_num, self.current_encoding]) | python | def evaluate_inline_tail(self, groups):
"""Evaluate inline comments at the tail of source code."""
if self.lines:
self.line_comments.append([groups['line'][2:].replace('\\\n', ''), self.line_num, self.current_encoding]) | [
"def",
"evaluate_inline_tail",
"(",
"self",
",",
"groups",
")",
":",
"if",
"self",
".",
"lines",
":",
"self",
".",
"line_comments",
".",
"append",
"(",
"[",
"groups",
"[",
"'line'",
"]",
"[",
"2",
":",
"]",
".",
"replace",
"(",
"'\\\\\\n'",
",",
"''"... | Evaluate inline comments at the tail of source code. | [
"Evaluate",
"inline",
"comments",
"at",
"the",
"tail",
"of",
"source",
"code",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L222-L226 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.evaluate_inline | def evaluate_inline(self, groups):
"""Evaluate inline comments on their own lines."""
# Consecutive lines with only comments with same leading whitespace
# will be captured as a single block.
if self.lines:
if (
self.group_comments and
self.li... | python | def evaluate_inline(self, groups):
"""Evaluate inline comments on their own lines."""
# Consecutive lines with only comments with same leading whitespace
# will be captured as a single block.
if self.lines:
if (
self.group_comments and
self.li... | [
"def",
"evaluate_inline",
"(",
"self",
",",
"groups",
")",
":",
"# Consecutive lines with only comments with same leading whitespace",
"# will be captured as a single block.",
"if",
"self",
".",
"lines",
":",
"if",
"(",
"self",
".",
"group_comments",
"and",
"self",
".",
... | Evaluate inline comments on their own lines. | [
"Evaluate",
"inline",
"comments",
"on",
"their",
"own",
"lines",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L228-L245 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.evaluate_unicode | def evaluate_unicode(self, value):
"""Evaluate Unicode."""
if value.startswith('u8'):
length = 1
value = value[3:-1]
encoding = 'utf-8'
elif value.startswith('u'):
length = 2
value = value[2:-1]
encoding = 'utf-16'
... | python | def evaluate_unicode(self, value):
"""Evaluate Unicode."""
if value.startswith('u8'):
length = 1
value = value[3:-1]
encoding = 'utf-8'
elif value.startswith('u'):
length = 2
value = value[2:-1]
encoding = 'utf-16'
... | [
"def",
"evaluate_unicode",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
".",
"startswith",
"(",
"'u8'",
")",
":",
"length",
"=",
"1",
"value",
"=",
"value",
"[",
"3",
":",
"-",
"1",
"]",
"encoding",
"=",
"'utf-8'",
"elif",
"value",
".",
"sta... | Evaluate Unicode. | [
"Evaluate",
"Unicode",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L247-L286 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.evaluate_normal | def evaluate_normal(self, value):
"""Evaluate normal string."""
if value.startswith('L'):
size = self.wide_charset_size
encoding = self.wide_exec_charset
value = value[2:-1]
pack = BYTE_STORE[size | CURRENT_ENDIAN]
else:
size = self.ch... | python | def evaluate_normal(self, value):
"""Evaluate normal string."""
if value.startswith('L'):
size = self.wide_charset_size
encoding = self.wide_exec_charset
value = value[2:-1]
pack = BYTE_STORE[size | CURRENT_ENDIAN]
else:
size = self.ch... | [
"def",
"evaluate_normal",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
".",
"startswith",
"(",
"'L'",
")",
":",
"size",
"=",
"self",
".",
"wide_charset_size",
"encoding",
"=",
"self",
".",
"wide_exec_charset",
"value",
"=",
"value",
"[",
"2",
":",... | Evaluate normal string. | [
"Evaluate",
"normal",
"string",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L288-L336 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.evaluate_strings | def evaluate_strings(self, groups):
"""Evaluate strings."""
if self.strings:
encoding = self.current_encoding
if self.generic_mode:
# Generic assumes no escapes rules.
self.quoted_strings.append([groups['strings'][1:-1], self.line_num, encoding])
... | python | def evaluate_strings(self, groups):
"""Evaluate strings."""
if self.strings:
encoding = self.current_encoding
if self.generic_mode:
# Generic assumes no escapes rules.
self.quoted_strings.append([groups['strings'][1:-1], self.line_num, encoding])
... | [
"def",
"evaluate_strings",
"(",
"self",
",",
"groups",
")",
":",
"if",
"self",
".",
"strings",
":",
"encoding",
"=",
"self",
".",
"current_encoding",
"if",
"self",
".",
"generic_mode",
":",
"# Generic assumes no escapes rules.",
"self",
".",
"quoted_strings",
".... | Evaluate strings. | [
"Evaluate",
"strings",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L338-L372 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.evaluate | def evaluate(self, m):
"""Search for comments."""
g = m.groupdict()
if g["strings"]:
self.evaluate_strings(g)
self.line_num += g['strings'].count('\n')
elif g["code"]:
self.line_num += g["code"].count('\n')
else:
if g['block']:
... | python | def evaluate(self, m):
"""Search for comments."""
g = m.groupdict()
if g["strings"]:
self.evaluate_strings(g)
self.line_num += g['strings'].count('\n')
elif g["code"]:
self.line_num += g["code"].count('\n')
else:
if g['block']:
... | [
"def",
"evaluate",
"(",
"self",
",",
"m",
")",
":",
"g",
"=",
"m",
".",
"groupdict",
"(",
")",
"if",
"g",
"[",
"\"strings\"",
"]",
":",
"self",
".",
"evaluate_strings",
"(",
"g",
")",
"self",
".",
"line_num",
"+=",
"g",
"[",
"'strings'",
"]",
"."... | Search for comments. | [
"Search",
"for",
"comments",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L374-L390 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.extend_src_text | def extend_src_text(self, content, context, text_list, category):
"""Extend the source text list with the gathered text data."""
prefix = self.prefix + '-' if self.prefix else ''
for comment, line, encoding in text_list:
content.append(
filters.SourceText(
... | python | def extend_src_text(self, content, context, text_list, category):
"""Extend the source text list with the gathered text data."""
prefix = self.prefix + '-' if self.prefix else ''
for comment, line, encoding in text_list:
content.append(
filters.SourceText(
... | [
"def",
"extend_src_text",
"(",
"self",
",",
"content",
",",
"context",
",",
"text_list",
",",
"category",
")",
":",
"prefix",
"=",
"self",
".",
"prefix",
"+",
"'-'",
"if",
"self",
".",
"prefix",
"else",
"''",
"for",
"comment",
",",
"line",
",",
"encodi... | Extend the source text list with the gathered text data. | [
"Extend",
"the",
"source",
"text",
"list",
"with",
"the",
"gathered",
"text",
"data",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L392-L405 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | CppFilter.find_content | def find_content(self, text):
"""Find content."""
if self.trigraphs:
text = RE_TRIGRAPHS.sub(self.process_trigraphs, text)
for m in self.pattern.finditer(self.norm_nl(text)):
self.evaluate(m) | python | def find_content(self, text):
"""Find content."""
if self.trigraphs:
text = RE_TRIGRAPHS.sub(self.process_trigraphs, text)
for m in self.pattern.finditer(self.norm_nl(text)):
self.evaluate(m) | [
"def",
"find_content",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"trigraphs",
":",
"text",
"=",
"RE_TRIGRAPHS",
".",
"sub",
"(",
"self",
".",
"process_trigraphs",
",",
"text",
")",
"for",
"m",
"in",
"self",
".",
"pattern",
".",
"finditer",... | Find content. | [
"Find",
"content",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L419-L426 |
deshima-dev/decode | decode/core/cube/functions.py | cube | def cube(data, xcoords=None, ycoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None):
"""Create a cube as an instance of xarray.DataArray with Decode accessor.
Args:
data (numpy.ndarray): 3D (x x y x channel) array.
xcoords (dict, optional): Dictionary of arrays ... | python | def cube(data, xcoords=None, ycoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None):
"""Create a cube as an instance of xarray.DataArray with Decode accessor.
Args:
data (numpy.ndarray): 3D (x x y x channel) array.
xcoords (dict, optional): Dictionary of arrays ... | [
"def",
"cube",
"(",
"data",
",",
"xcoords",
"=",
"None",
",",
"ycoords",
"=",
"None",
",",
"chcoords",
"=",
"None",
",",
"scalarcoords",
"=",
"None",
",",
"datacoords",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# ... | Create a cube as an instance of xarray.DataArray with Decode accessor.
Args:
data (numpy.ndarray): 3D (x x y x channel) array.
xcoords (dict, optional): Dictionary of arrays that label x axis.
ycoords (dict, optional): Dictionary of arrays that label y axis.
chcoords (dict, optional... | [
"Create",
"a",
"cube",
"as",
"an",
"instance",
"of",
"xarray",
".",
"DataArray",
"with",
"Decode",
"accessor",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/cube/functions.py#L25-L61 |
deshima-dev/decode | decode/core/cube/functions.py | fromcube | def fromcube(cube, template):
"""Covert a decode cube to a decode array.
Args:
cube (decode.cube): Decode cube to be cast.
template (decode.array): Decode array whose shape the cube is cast on.
Returns:
decode array (decode.array): Decode array.
Notes:
This functions i... | python | def fromcube(cube, template):
"""Covert a decode cube to a decode array.
Args:
cube (decode.cube): Decode cube to be cast.
template (decode.array): Decode array whose shape the cube is cast on.
Returns:
decode array (decode.array): Decode array.
Notes:
This functions i... | [
"def",
"fromcube",
"(",
"cube",
",",
"template",
")",
":",
"array",
"=",
"dc",
".",
"zeros_like",
"(",
"template",
")",
"y",
",",
"x",
"=",
"array",
".",
"y",
".",
"values",
",",
"array",
".",
"x",
".",
"values",
"gy",
",",
"gx",
"=",
"cube",
"... | Covert a decode cube to a decode array.
Args:
cube (decode.cube): Decode cube to be cast.
template (decode.array): Decode array whose shape the cube is cast on.
Returns:
decode array (decode.array): Decode array.
Notes:
This functions is under development. | [
"Covert",
"a",
"decode",
"cube",
"to",
"a",
"decode",
"array",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/cube/functions.py#L64-L87 |
deshima-dev/decode | decode/core/cube/functions.py | tocube | def tocube(array, **kwargs):
"""Convert a decode array to decode cube.
Args:
array (decode.array): Decode array which will be converted.
kwargs (optional): Other arguments.
xarr (list or numpy.ndarray): Grid array of x direction.
yarr (list or numpy.ndarray): Grid array ... | python | def tocube(array, **kwargs):
"""Convert a decode array to decode cube.
Args:
array (decode.array): Decode array which will be converted.
kwargs (optional): Other arguments.
xarr (list or numpy.ndarray): Grid array of x direction.
yarr (list or numpy.ndarray): Grid array ... | [
"def",
"tocube",
"(",
"array",
",",
"*",
"*",
"kwargs",
")",
":",
"# pick up kwargs",
"unit",
"=",
"kwargs",
".",
"pop",
"(",
"'unit'",
",",
"'deg'",
")",
"unit2deg",
"=",
"getattr",
"(",
"u",
",",
"unit",
")",
".",
"to",
"(",
"'deg'",
")",
"xc",
... | Convert a decode array to decode cube.
Args:
array (decode.array): Decode array which will be converted.
kwargs (optional): Other arguments.
xarr (list or numpy.ndarray): Grid array of x direction.
yarr (list or numpy.ndarray): Grid array of y direction.
gx (floa... | [
"Convert",
"a",
"decode",
"array",
"to",
"decode",
"cube",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/cube/functions.py#L90-L231 |
deshima-dev/decode | decode/core/cube/functions.py | makecontinuum | def makecontinuum(cube, **kwargs):
"""Make a continuum array.
Args:
cube (decode.cube): Decode cube which will be averaged over channels.
kwargs (optional): Other arguments.
inchs (list): Included channel kidids.
exchs (list): Excluded channel kidids.
Returns:
... | python | def makecontinuum(cube, **kwargs):
"""Make a continuum array.
Args:
cube (decode.cube): Decode cube which will be averaged over channels.
kwargs (optional): Other arguments.
inchs (list): Included channel kidids.
exchs (list): Excluded channel kidids.
Returns:
... | [
"def",
"makecontinuum",
"(",
"cube",
",",
"*",
"*",
"kwargs",
")",
":",
"### pick up kwargs",
"inchs",
"=",
"kwargs",
".",
"pop",
"(",
"'inchs'",
",",
"None",
")",
"exchs",
"=",
"kwargs",
".",
"pop",
"(",
"'exchs'",
",",
"None",
")",
"if",
"(",
"inch... | Make a continuum array.
Args:
cube (decode.cube): Decode cube which will be averaged over channels.
kwargs (optional): Other arguments.
inchs (list): Included channel kidids.
exchs (list): Excluded channel kidids.
Returns:
decode cube (decode.cube): Decode cube ... | [
"Make",
"a",
"continuum",
"array",
"."
] | train | https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/cube/functions.py#L234-L283 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter._verify_encoding | def _verify_encoding(self, enc):
"""Verify encoding is okay."""
enc = PYTHON_ENCODING_NAMES.get(enc, enc)
try:
codecs.getencoder(enc)
encoding = enc
except LookupError:
encoding = None
return encoding | python | def _verify_encoding(self, enc):
"""Verify encoding is okay."""
enc = PYTHON_ENCODING_NAMES.get(enc, enc)
try:
codecs.getencoder(enc)
encoding = enc
except LookupError:
encoding = None
return encoding | [
"def",
"_verify_encoding",
"(",
"self",
",",
"enc",
")",
":",
"enc",
"=",
"PYTHON_ENCODING_NAMES",
".",
"get",
"(",
"enc",
",",
"enc",
")",
"try",
":",
"codecs",
".",
"getencoder",
"(",
"enc",
")",
"encoding",
"=",
"enc",
"except",
"LookupError",
":",
... | Verify encoding is okay. | [
"Verify",
"encoding",
"is",
"okay",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L95-L104 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter.has_bom | def has_bom(self, f):
"""Check for UTF8, UTF16, and UTF32 BOMs."""
content = f.read(4)
encoding = None
m = RE_UTF_BOM.match(content)
if m is not None:
if m.group(1):
encoding = 'utf-8-sig'
elif m.group(2):
encoding = 'utf-3... | python | def has_bom(self, f):
"""Check for UTF8, UTF16, and UTF32 BOMs."""
content = f.read(4)
encoding = None
m = RE_UTF_BOM.match(content)
if m is not None:
if m.group(1):
encoding = 'utf-8-sig'
elif m.group(2):
encoding = 'utf-3... | [
"def",
"has_bom",
"(",
"self",
",",
"f",
")",
":",
"content",
"=",
"f",
".",
"read",
"(",
"4",
")",
"encoding",
"=",
"None",
"m",
"=",
"RE_UTF_BOM",
".",
"match",
"(",
"content",
")",
"if",
"m",
"is",
"not",
"None",
":",
"if",
"m",
".",
"group"... | Check for UTF8, UTF16, and UTF32 BOMs. | [
"Check",
"for",
"UTF8",
"UTF16",
"and",
"UTF32",
"BOMs",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L106-L123 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter._utf_strip_bom | def _utf_strip_bom(self, encoding):
"""Return an encoding that will ignore the BOM."""
if encoding is None:
pass
elif encoding.lower() == 'utf-8':
encoding = 'utf-8-sig'
elif encoding.lower().startswith('utf-16'):
encoding = 'utf-16'
elif enco... | python | def _utf_strip_bom(self, encoding):
"""Return an encoding that will ignore the BOM."""
if encoding is None:
pass
elif encoding.lower() == 'utf-8':
encoding = 'utf-8-sig'
elif encoding.lower().startswith('utf-16'):
encoding = 'utf-16'
elif enco... | [
"def",
"_utf_strip_bom",
"(",
"self",
",",
"encoding",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"pass",
"elif",
"encoding",
".",
"lower",
"(",
")",
"==",
"'utf-8'",
":",
"encoding",
"=",
"'utf-8-sig'",
"elif",
"encoding",
".",
"lower",
"(",
")",
... | Return an encoding that will ignore the BOM. | [
"Return",
"an",
"encoding",
"that",
"will",
"ignore",
"the",
"BOM",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L125-L136 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter._detect_buffer_encoding | def _detect_buffer_encoding(self, f):
"""Guess by checking BOM, and checking `_special_encode_check`, and using memory map."""
encoding = None
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
encoding = self._analyze_file(m)
return encoding | python | def _detect_buffer_encoding(self, f):
"""Guess by checking BOM, and checking `_special_encode_check`, and using memory map."""
encoding = None
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
encoding = self._analyze_file(m)
return encoding | [
"def",
"_detect_buffer_encoding",
"(",
"self",
",",
"f",
")",
":",
"encoding",
"=",
"None",
"with",
"contextlib",
".",
"closing",
"(",
"mmap",
".",
"mmap",
"(",
"f",
".",
"fileno",
"(",
")",
",",
"0",
",",
"access",
"=",
"mmap",
".",
"ACCESS_READ",
"... | Guess by checking BOM, and checking `_special_encode_check`, and using memory map. | [
"Guess",
"by",
"checking",
"BOM",
"and",
"checking",
"_special_encode_check",
"and",
"using",
"memory",
"map",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L138-L144 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter._analyze_file | def _analyze_file(self, f):
"""Analyze the file."""
f.seek(0)
# Check for BOMs
if self.CHECK_BOM:
encoding = self.has_bom(f)
f.seek(0)
else:
util.warn_deprecated(
"'CHECK_BOM' attribute is deprecated. "
"Please ... | python | def _analyze_file(self, f):
"""Analyze the file."""
f.seek(0)
# Check for BOMs
if self.CHECK_BOM:
encoding = self.has_bom(f)
f.seek(0)
else:
util.warn_deprecated(
"'CHECK_BOM' attribute is deprecated. "
"Please ... | [
"def",
"_analyze_file",
"(",
"self",
",",
"f",
")",
":",
"f",
".",
"seek",
"(",
"0",
")",
"# Check for BOMs",
"if",
"self",
".",
"CHECK_BOM",
":",
"encoding",
"=",
"self",
".",
"has_bom",
"(",
"f",
")",
"f",
".",
"seek",
"(",
"0",
")",
"else",
":... | Analyze the file. | [
"Analyze",
"the",
"file",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L146-L167 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter._detect_encoding | def _detect_encoding(self, source_file):
"""Detect encoding."""
encoding = self._guess(source_file)
# If we didn't explicitly detect an encoding, assume default.
if encoding is None:
encoding = self.default_encoding
return encoding | python | def _detect_encoding(self, source_file):
"""Detect encoding."""
encoding = self._guess(source_file)
# If we didn't explicitly detect an encoding, assume default.
if encoding is None:
encoding = self.default_encoding
return encoding | [
"def",
"_detect_encoding",
"(",
"self",
",",
"source_file",
")",
":",
"encoding",
"=",
"self",
".",
"_guess",
"(",
"source_file",
")",
"# If we didn't explicitly detect an encoding, assume default.",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"self",
".",... | Detect encoding. | [
"Detect",
"encoding",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L169-L177 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter._run_first | def _run_first(self, source_file):
"""Run on as first in chain."""
self.reset()
self.current_encoding = self.default_encoding
encoding = None
try:
encoding = self._detect_encoding(source_file)
content = self.filter(source_file, encoding)
except Un... | python | def _run_first(self, source_file):
"""Run on as first in chain."""
self.reset()
self.current_encoding = self.default_encoding
encoding = None
try:
encoding = self._detect_encoding(source_file)
content = self.filter(source_file, encoding)
except Un... | [
"def",
"_run_first",
"(",
"self",
",",
"source_file",
")",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"current_encoding",
"=",
"self",
".",
"default_encoding",
"encoding",
"=",
"None",
"try",
":",
"encoding",
"=",
"self",
".",
"_detect_encoding",
"(... | Run on as first in chain. | [
"Run",
"on",
"as",
"first",
"in",
"chain",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L179-L193 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter._guess | def _guess(self, filename):
"""Guess the encoding and decode the content of the file."""
encoding = None
file_size = os.path.getsize(filename)
# If the file is really big, lets just call it binary.
# We don't have time to let Python chug through a massive file.
if not s... | python | def _guess(self, filename):
"""Guess the encoding and decode the content of the file."""
encoding = None
file_size = os.path.getsize(filename)
# If the file is really big, lets just call it binary.
# We don't have time to let Python chug through a massive file.
if not s... | [
"def",
"_guess",
"(",
"self",
",",
"filename",
")",
":",
"encoding",
"=",
"None",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
"# If the file is really big, lets just call it binary.",
"# We don't have time to let Python chug through a massiv... | Guess the encoding and decode the content of the file. | [
"Guess",
"the",
"encoding",
"and",
"decode",
"the",
"content",
"of",
"the",
"file",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L201-L222 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | Filter.sfilter | def sfilter(self, source):
"""Execute filter."""
return [SourceText(source.text, source.context, source.encoding, 'text')] | python | def sfilter(self, source):
"""Execute filter."""
return [SourceText(source.text, source.context, source.encoding, 'text')] | [
"def",
"sfilter",
"(",
"self",
",",
"source",
")",
":",
"return",
"[",
"SourceText",
"(",
"source",
".",
"text",
",",
"source",
".",
"context",
",",
"source",
".",
"encoding",
",",
"'text'",
")",
"]"
] | Execute filter. | [
"Execute",
"filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L246-L249 |
JMSwag/dsdev-utils | dsdev_utils/terminal.py | ask_yes_no | def ask_yes_no(question, default='no', answer=None):
u"""Will ask a question and keeps prompting until
answered.
Args:
question (str): Question to ask end user
default (str): Default answer if user just press enter at prompt
answer (str): Used for testing
Returns:
(... | python | def ask_yes_no(question, default='no', answer=None):
u"""Will ask a question and keeps prompting until
answered.
Args:
question (str): Question to ask end user
default (str): Default answer if user just press enter at prompt
answer (str): Used for testing
Returns:
(... | [
"def",
"ask_yes_no",
"(",
"question",
",",
"default",
"=",
"'no'",
",",
"answer",
"=",
"None",
")",
":",
"default",
"=",
"default",
".",
"lower",
"(",
")",
"yes",
"=",
"[",
"u'yes'",
",",
"u'ye'",
",",
"u'y'",
"]",
"no",
"=",
"[",
"u'no'",
",",
"... | u"""Will ask a question and keeps prompting until
answered.
Args:
question (str): Question to ask end user
default (str): Default answer if user just press enter at prompt
answer (str): Used for testing
Returns:
(bool) Meaning:
True - Answer is yes
... | [
"u",
"Will",
"ask",
"a",
"question",
"and",
"keeps",
"prompting",
"until",
"answered",
"."
] | train | https://github.com/JMSwag/dsdev-utils/blob/5adbf9b3fd9fff92d1dd714423b08e26a5038e14/dsdev_utils/terminal.py#L192-L242 |
JMSwag/dsdev-utils | dsdev_utils/terminal.py | get_correct_answer | def get_correct_answer(question, default=None, required=False,
answer=None, is_answer_correct=None):
u"""Ask user a question and confirm answer
Args:
question (str): Question to ask user
default (str): Default answer if no input from user
required (str): Requir... | python | def get_correct_answer(question, default=None, required=False,
answer=None, is_answer_correct=None):
u"""Ask user a question and confirm answer
Args:
question (str): Question to ask user
default (str): Default answer if no input from user
required (str): Requir... | [
"def",
"get_correct_answer",
"(",
"question",
",",
"default",
"=",
"None",
",",
"required",
"=",
"False",
",",
"answer",
"=",
"None",
",",
"is_answer_correct",
"=",
"None",
")",
":",
"while",
"1",
":",
"if",
"default",
"is",
"None",
":",
"msg",
"=",
"u... | u"""Ask user a question and confirm answer
Args:
question (str): Question to ask user
default (str): Default answer if no input from user
required (str): Require user to input answer
answer (str): Used for testing
is_answer_correct (str): Used for testing | [
"u",
"Ask",
"user",
"a",
"question",
"and",
"confirm",
"answer"
] | train | https://github.com/JMSwag/dsdev-utils/blob/5adbf9b3fd9fff92d1dd714423b08e26a5038e14/dsdev_utils/terminal.py#L245-L284 |
facelessuser/pyspelling | pyspelling/__main__.py | main | def main():
"""Main."""
parser = argparse.ArgumentParser(prog='spellcheck', description='Spell checking tool.')
# Flag arguments
parser.add_argument('--version', action='version', version=('%(prog)s ' + __version__))
parser.add_argument('--debug', action='store_true', default=False, help=argparse.S... | python | def main():
"""Main."""
parser = argparse.ArgumentParser(prog='spellcheck', description='Spell checking tool.')
# Flag arguments
parser.add_argument('--version', action='version', version=('%(prog)s ' + __version__))
parser.add_argument('--debug', action='store_true', default=False, help=argparse.S... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'spellcheck'",
",",
"description",
"=",
"'Spell checking tool.'",
")",
"# Flag arguments",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
... | Main. | [
"Main",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__main__.py#L8-L36 |
facelessuser/pyspelling | pyspelling/__main__.py | run | def run(config, **kwargs):
"""Run."""
names = kwargs.get('names', [])
groups = kwargs.get('groups', [])
binary = kwargs.get('binary', '')
spellchecker = kwargs.get('spellchecker', '')
verbose = kwargs.get('verbose', 0)
sources = kwargs.get('sources', [])
debug = kwargs.get('debug', Fals... | python | def run(config, **kwargs):
"""Run."""
names = kwargs.get('names', [])
groups = kwargs.get('groups', [])
binary = kwargs.get('binary', '')
spellchecker = kwargs.get('spellchecker', '')
verbose = kwargs.get('verbose', 0)
sources = kwargs.get('sources', [])
debug = kwargs.get('debug', Fals... | [
"def",
"run",
"(",
"config",
",",
"*",
"*",
"kwargs",
")",
":",
"names",
"=",
"kwargs",
".",
"get",
"(",
"'names'",
",",
"[",
"]",
")",
"groups",
"=",
"kwargs",
".",
"get",
"(",
"'groups'",
",",
"[",
"]",
")",
"binary",
"=",
"kwargs",
".",
"get... | Run. | [
"Run",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__main__.py#L39-L80 |
facelessuser/pyspelling | pyspelling/util/__init__.py | deprecated | def deprecated(message): # pragma: no cover
"""
Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026
"""
def deprecated_decorator(func):
"""Deprecation decorator."""
@wraps(func)
def deprecated_func... | python | def deprecated(message): # pragma: no cover
"""
Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026
"""
def deprecated_decorator(func):
"""Deprecation decorator."""
@wraps(func)
def deprecated_func... | [
"def",
"deprecated",
"(",
"message",
")",
":",
"# pragma: no cover",
"def",
"deprecated_decorator",
"(",
"func",
")",
":",
"\"\"\"Deprecation decorator.\"\"\"",
"@",
"wraps",
"(",
"func",
")",
"def",
"deprecated_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | Raise a `DeprecationWarning` when wrapped function/method is called.
Borrowed from https://stackoverflow.com/a/48632082/866026 | [
"Raise",
"a",
"DeprecationWarning",
"when",
"wrapped",
"function",
"/",
"method",
"is",
"called",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L18-L39 |
facelessuser/pyspelling | pyspelling/util/__init__.py | get_process | def get_process(cmd):
"""Get a command process."""
if sys.platform.startswith('win'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(
cmd,
startupinfo=startupinfo,
stdout=subpro... | python | def get_process(cmd):
"""Get a command process."""
if sys.platform.startswith('win'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(
cmd,
startupinfo=startupinfo,
stdout=subpro... | [
"def",
"get_process",
"(",
"cmd",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"startupinfo",
"=",
"subprocess",
".",
"STARTUPINFO",
"(",
")",
"startupinfo",
".",
"dwFlags",
"|=",
"subprocess",
".",
"STARTF_USESHOWWINDOW... | Get a command process. | [
"Get",
"a",
"command",
"process",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L52-L74 |
facelessuser/pyspelling | pyspelling/util/__init__.py | get_process_output | def get_process_output(process, encoding=None):
"""Get the output from the process."""
output = process.communicate()
returncode = process.returncode
if not encoding:
try:
encoding = sys.stdout.encoding
except Exception:
encoding = locale.getpreferredencoding()
... | python | def get_process_output(process, encoding=None):
"""Get the output from the process."""
output = process.communicate()
returncode = process.returncode
if not encoding:
try:
encoding = sys.stdout.encoding
except Exception:
encoding = locale.getpreferredencoding()
... | [
"def",
"get_process_output",
"(",
"process",
",",
"encoding",
"=",
"None",
")",
":",
"output",
"=",
"process",
".",
"communicate",
"(",
")",
"returncode",
"=",
"process",
".",
"returncode",
"if",
"not",
"encoding",
":",
"try",
":",
"encoding",
"=",
"sys",
... | Get the output from the process. | [
"Get",
"the",
"output",
"from",
"the",
"process",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L77-L92 |
facelessuser/pyspelling | pyspelling/util/__init__.py | call | def call(cmd, input_file=None, input_text=None, encoding=None):
"""Call with arguments."""
process = get_process(cmd)
if input_file is not None:
with open(input_file, 'rb') as f:
process.stdin.write(f.read())
if input_text is not None:
process.stdin.write(input_text)
r... | python | def call(cmd, input_file=None, input_text=None, encoding=None):
"""Call with arguments."""
process = get_process(cmd)
if input_file is not None:
with open(input_file, 'rb') as f:
process.stdin.write(f.read())
if input_text is not None:
process.stdin.write(input_text)
r... | [
"def",
"call",
"(",
"cmd",
",",
"input_file",
"=",
"None",
",",
"input_text",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"process",
"=",
"get_process",
"(",
"cmd",
")",
"if",
"input_file",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"inp... | Call with arguments. | [
"Call",
"with",
"arguments",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L95-L106 |
facelessuser/pyspelling | pyspelling/util/__init__.py | call_spellchecker | def call_spellchecker(cmd, input_text=None, encoding=None):
"""Call spell checker with arguments."""
process = get_process(cmd)
# A buffer has been provided
if input_text is not None:
for line in input_text.splitlines():
# Hunspell truncates lines at `0x1fff` (at least on Windows t... | python | def call_spellchecker(cmd, input_text=None, encoding=None):
"""Call spell checker with arguments."""
process = get_process(cmd)
# A buffer has been provided
if input_text is not None:
for line in input_text.splitlines():
# Hunspell truncates lines at `0x1fff` (at least on Windows t... | [
"def",
"call_spellchecker",
"(",
"cmd",
",",
"input_text",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"process",
"=",
"get_process",
"(",
"cmd",
")",
"# A buffer has been provided",
"if",
"input_text",
"is",
"not",
"None",
":",
"for",
"line",
"in",... | Call spell checker with arguments. | [
"Call",
"spell",
"checker",
"with",
"arguments",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L109-L137 |
facelessuser/pyspelling | pyspelling/util/__init__.py | random_name_gen | def random_name_gen(size=6):
"""Generate a random python attribute name."""
return ''.join(
[random.choice(string.ascii_uppercase)] +
[random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)]
) if size > 0 else '' | python | def random_name_gen(size=6):
"""Generate a random python attribute name."""
return ''.join(
[random.choice(string.ascii_uppercase)] +
[random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)]
) if size > 0 else '' | [
"def",
"random_name_gen",
"(",
"size",
"=",
"6",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_uppercase",
")",
"]",
"+",
"[",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_uppercase",
"+",
... | Generate a random python attribute name. | [
"Generate",
"a",
"random",
"python",
"attribute",
"name",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L140-L146 |
facelessuser/pyspelling | pyspelling/util/__init__.py | yaml_load | def yaml_load(source, loader=yaml.Loader):
"""
Wrap PyYaml's loader so we can extend it to suit our needs.
Load all strings as Unicode: http://stackoverflow.com/a/2967461/3609487.
"""
def construct_yaml_str(self, node):
"""Override the default string handling function to always return Unic... | python | def yaml_load(source, loader=yaml.Loader):
"""
Wrap PyYaml's loader so we can extend it to suit our needs.
Load all strings as Unicode: http://stackoverflow.com/a/2967461/3609487.
"""
def construct_yaml_str(self, node):
"""Override the default string handling function to always return Unic... | [
"def",
"yaml_load",
"(",
"source",
",",
"loader",
"=",
"yaml",
".",
"Loader",
")",
":",
"def",
"construct_yaml_str",
"(",
"self",
",",
"node",
")",
":",
"\"\"\"Override the default string handling function to always return Unicode objects.\"\"\"",
"return",
"self",
".",... | Wrap PyYaml's loader so we can extend it to suit our needs.
Load all strings as Unicode: http://stackoverflow.com/a/2967461/3609487. | [
"Wrap",
"PyYaml",
"s",
"loader",
"so",
"we",
"can",
"extend",
"it",
"to",
"suit",
"our",
"needs",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L149-L167 |
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 '.sp... | 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 '.sp... | [
"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",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/util/__init__.py#L170-L183 |
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'... | 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'... | [
"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",
"."
] | train | https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/_compat.py#L69-L96 |
j0ack/flask-codemirror | flask_codemirror/__init__.py | CodeMirrorHeaders._get_tag | def _get_tag(self, url, tag, print_warn=True):
"""Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable
"""
# construct comple... | python | def _get_tag(self, url, tag, print_warn=True):
"""Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable
"""
# construct comple... | [
"def",
"_get_tag",
"(",
"self",
",",
"url",
",",
"tag",
",",
"print_warn",
"=",
"True",
")",
":",
"# construct complete url",
"complete_url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"url",
")",
"# check if exists",
"if",
"requests",
".",
"get",
... | Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable | [
"Check",
"if",
"url",
"is",
"available",
"and",
"returns",
"given",
"tag",
"type",
":",
"param",
"url",
":",
"url",
"to",
"content",
"relative",
"to",
"base",
"url",
":",
"param",
"anchor",
":",
"anchor",
"type",
"to",
"return",
":",
"param",
"print_warn... | train | https://github.com/j0ack/flask-codemirror/blob/81ad831ff849b60bb34de5db727ad626ff3c9bdc/flask_codemirror/__init__.py#L71-L90 |
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)
# ... | 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)
# ... | [
"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"
] | train | https://github.com/j0ack/flask-codemirror/blob/81ad831ff849b60bb34de5db727ad626ff3c9bdc/flask_codemirror/__init__.py#L92-L127 |
j0ack/flask-codemirror | flask_codemirror/__init__.py | CodeMirror.init_app | def init_app(self, app):
"""Register CodeMirror as a Flask extension
:param app: Flask instance
"""
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['codemirror'] = CodeMirrorHeaders(app.config)
app.context_processor(self.context_processor... | python | def init_app(self, app):
"""Register CodeMirror as a Flask extension
:param app: Flask instance
"""
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['codemirror'] = CodeMirrorHeaders(app.config)
app.context_processor(self.context_processor... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"app",
".",
"extensions",
"[",
"'codemirror'",
"]",
"=",
"CodeMirrorHeaders",
"(",
"app",
... | Register CodeMirror as a Flask extension
:param app: Flask instance | [
"Register",
"CodeMirror",
"as",
"a",
"Flask",
"extension",
":",
"param",
"app",
":",
"Flask",
"instance"
] | train | https://github.com/j0ack/flask-codemirror/blob/81ad831ff849b60bb34de5db727ad626ff3c9bdc/flask_codemirror/__init__.py#L138-L145 |
sloria/tinynetrc | tinynetrc.py | Netrc.format | def format(self):
"""Dump the class data in the format of a .netrc file."""
self._netrc.hosts = dedictify_machines(self.machines)
rep = ""
for host in self._netrc.hosts.keys():
attrs = self._netrc.hosts[host]
rep += "machine {host}\n\tlogin {attrs[0]}\n".format(ho... | python | def format(self):
"""Dump the class data in the format of a .netrc file."""
self._netrc.hosts = dedictify_machines(self.machines)
rep = ""
for host in self._netrc.hosts.keys():
attrs = self._netrc.hosts[host]
rep += "machine {host}\n\tlogin {attrs[0]}\n".format(ho... | [
"def",
"format",
"(",
"self",
")",
":",
"self",
".",
"_netrc",
".",
"hosts",
"=",
"dedictify_machines",
"(",
"self",
".",
"machines",
")",
"rep",
"=",
"\"\"",
"for",
"host",
"in",
"self",
".",
"_netrc",
".",
"hosts",
".",
"keys",
"(",
")",
":",
"at... | Dump the class data in the format of a .netrc file. | [
"Dump",
"the",
"class",
"data",
"in",
"the",
"format",
"of",
"a",
".",
"netrc",
"file",
"."
] | train | https://github.com/sloria/tinynetrc/blob/1d65069e520dce969b6740fa49bf87a04a1d7b59/tinynetrc.py#L84-L100 |
KeithSSmith/switcheo-python | switcheo/neo/utils.py | neo_get_scripthash_from_address | def neo_get_scripthash_from_address(address):
"""
Convert a Public Address String to a ScriptHash (Address) String.
:param address: The Public address to convert.
:type address: str
:return: String containing the converted ScriptHash.
"""
hash_bytes = binascii.hexlify(base58.b58decode_check... | python | def neo_get_scripthash_from_address(address):
"""
Convert a Public Address String to a ScriptHash (Address) String.
:param address: The Public address to convert.
:type address: str
:return: String containing the converted ScriptHash.
"""
hash_bytes = binascii.hexlify(base58.b58decode_check... | [
"def",
"neo_get_scripthash_from_address",
"(",
"address",
")",
":",
"hash_bytes",
"=",
"binascii",
".",
"hexlify",
"(",
"base58",
".",
"b58decode_check",
"(",
"address",
")",
")",
"return",
"reverse_hex",
"(",
"hash_bytes",
"[",
"2",
":",
"]",
".",
"decode",
... | Convert a Public Address String to a ScriptHash (Address) String.
:param address: The Public address to convert.
:type address: str
:return: String containing the converted ScriptHash. | [
"Convert",
"a",
"Public",
"Address",
"String",
"to",
"a",
"ScriptHash",
"(",
"Address",
")",
"String",
"."
] | train | https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/neo/utils.py#L51-L60 |
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 "").rst... | 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 "").rst... | [
"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",
"."
] | train | https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/setup.py#L113-L124 |
KeithSSmith/switcheo-python | switcheo/utils.py | num2hexstring | def num2hexstring(number, size=1, little_endian=False):
"""
Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endi... | python | def num2hexstring(number, size=1, little_endian=False):
"""
Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endi... | [
"def",
"num2hexstring",
"(",
"number",
",",
"size",
"=",
"1",
",",
"little_endian",
"=",
"False",
")",
":",
"# if (type(number) != = 'number') throw new Error('num must be numeric')",
"# if (num < 0) throw new RangeError('num is unsigned (>= 0)')",
"# if (size % 1 !== 0) throw new Er... | Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endian - Encode the hex in little endian form
:return {string} | [
"Converts",
"a",
"number",
"to",
"a",
"big",
"endian",
"hexstring",
"of",
"a",
"suitable",
"size",
"optionally",
"little",
"endian",
":",
"param",
"{",
"number",
"}",
"number",
":",
"param",
"{",
"number",
"}",
"size",
"-",
"The",
"required",
"size",
"in... | train | https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L29-L47 |
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 RangeErr... | 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 RangeErr... | [
"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"
] | train | https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L50-L70 |
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"
] | train | https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L101-L105 |
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 Sw... | 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 Sw... | [
"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"
] | train | https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L107-L114 |
facelessuser/pyspelling | pyspelling/filters/html.py | HtmlFilter.validate_options | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'mode' and v not in MODE:
raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k)) | python | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'mode' and v not in MODE:
raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k)) | [
"def",
"validate_options",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"super",
"(",
")",
".",
"validate_options",
"(",
"k",
",",
"v",
")",
"if",
"k",
"==",
"'mode'",
"and",
"v",
"not",
"in",
"MODE",
":",
"raise",
"ValueError",
"(",
"\"{}: '{}' is not... | Validate options. | [
"Validate",
"options",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/html.py#L57-L62 |
facelessuser/pyspelling | pyspelling/filters/html.py | HtmlFilter.setup | def setup(self):
"""Setup."""
self.user_break_tags = set(self.config['break_tags'])
self.comments = self.config.get('comments', True) is True
self.attributes = set(self.config['attributes'])
self.type = self.config['mode']
if self.type not in MODE:
self.type ... | python | def setup(self):
"""Setup."""
self.user_break_tags = set(self.config['break_tags'])
self.comments = self.config.get('comments', True) is True
self.attributes = set(self.config['attributes'])
self.type = self.config['mode']
if self.type not in MODE:
self.type ... | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"user_break_tags",
"=",
"set",
"(",
"self",
".",
"config",
"[",
"'break_tags'",
"]",
")",
"self",
".",
"comments",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'comments'",
",",
"True",
")",
"is",
... | Setup. | [
"Setup",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/html.py#L64-L77 |
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
... | 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
... | [
"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",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/html.py#L79-L96 |
facelessuser/pyspelling | pyspelling/filters/html.py | HtmlFilter.is_break_tag | def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = sv.util.lower(el.name) if self.type != 'xhtml' else el.name
return name in self.break_tags or name in self.user_break_tags | python | def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = sv.util.lower(el.name) if self.type != 'xhtml' else el.name
return name in self.break_tags or name in self.user_break_tags | [
"def",
"is_break_tag",
"(",
"self",
",",
"el",
")",
":",
"name",
"=",
"sv",
".",
"util",
".",
"lower",
"(",
"el",
".",
"name",
")",
"if",
"self",
".",
"type",
"!=",
"'xhtml'",
"else",
"el",
".",
"name",
"return",
"name",
"in",
"self",
".",
"break... | Check if tag is an element we should break on. | [
"Check",
"if",
"tag",
"is",
"an",
"element",
"we",
"should",
"break",
"on",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/html.py#L98-L102 |
facelessuser/pyspelling | pyspelling/filters/html.py | HtmlFilter.get_classes | def get_classes(self, el):
"""Get classes."""
if self.type != 'xhtml':
return el.attrs.get('class', [])
else:
return [c for c in el.attrs.get('class', '').strip().split(' ') if c] | python | def get_classes(self, el):
"""Get classes."""
if self.type != 'xhtml':
return el.attrs.get('class', [])
else:
return [c for c in el.attrs.get('class', '').strip().split(' ') if c] | [
"def",
"get_classes",
"(",
"self",
",",
"el",
")",
":",
"if",
"self",
".",
"type",
"!=",
"'xhtml'",
":",
"return",
"el",
".",
"attrs",
".",
"get",
"(",
"'class'",
",",
"[",
"]",
")",
"else",
":",
"return",
"[",
"c",
"for",
"c",
"in",
"el",
".",... | Get classes. | [
"Get",
"classes",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/html.py#L104-L110 |
facelessuser/pyspelling | pyspelling/filters/html.py | HtmlFilter.construct_selector | def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancestor... | python | def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancestor... | [
"def",
"construct_selector",
"(",
"self",
",",
"el",
",",
"attr",
"=",
"''",
")",
":",
"selector",
"=",
"deque",
"(",
")",
"ancestor",
"=",
"el",
"while",
"ancestor",
"and",
"ancestor",
".",
"parent",
":",
"if",
"ancestor",
"is",
"not",
"el",
":",
"s... | Construct an selector for context. | [
"Construct",
"an",
"selector",
"for",
"context",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/html.py#L122-L147 |
facelessuser/pyspelling | pyspelling/filters/ooxml.py | OoxmlFilter.setup | def setup(self):
"""Setup."""
self.additional_context = ''
self.comments = False
self.attributes = []
self.parser = 'xml'
self.type = None
self.filepattern = ''
self.ignores = None
self.captures = None | python | def setup(self):
"""Setup."""
self.additional_context = ''
self.comments = False
self.attributes = []
self.parser = 'xml'
self.type = None
self.filepattern = ''
self.ignores = None
self.captures = None | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"additional_context",
"=",
"''",
"self",
".",
"comments",
"=",
"False",
"self",
".",
"attributes",
"=",
"[",
"]",
"self",
".",
"parser",
"=",
"'xml'",
"self",
".",
"type",
"=",
"None",
"self",
".",
... | Setup. | [
"Setup",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L57-L67 |
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.
... | 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.
... | [
"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",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L69-L79 |
facelessuser/pyspelling | pyspelling/filters/ooxml.py | OoxmlFilter.determine_file_type | def determine_file_type(self, z):
"""Determine file type."""
content = z.read('[Content_Types].xml')
with io.BytesIO(content) as b:
encoding = self._analyze_file(b)
if encoding is None:
encoding = 'utf-8'
b.seek(0)
text = b.read().... | python | def determine_file_type(self, z):
"""Determine file type."""
content = z.read('[Content_Types].xml')
with io.BytesIO(content) as b:
encoding = self._analyze_file(b)
if encoding is None:
encoding = 'utf-8'
b.seek(0)
text = b.read().... | [
"def",
"determine_file_type",
"(",
"self",
",",
"z",
")",
":",
"content",
"=",
"z",
".",
"read",
"(",
"'[Content_Types].xml'",
")",
"with",
"io",
".",
"BytesIO",
"(",
"content",
")",
"as",
"b",
":",
"encoding",
"=",
"self",
".",
"_analyze_file",
"(",
"... | Determine file type. | [
"Determine",
"file",
"type",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L93-L114 |
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 =... | 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 =... | [
"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",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L116-L124 |
facelessuser/pyspelling | pyspelling/filters/ooxml.py | OoxmlFilter.get_context | def get_context(self, filename):
"""Get context."""
if self.type == 'pptx':
context = '{}: '.format(RE_SLIDE.search(filename).group(1))
elif self.type == 'docx':
context = '{}: '.format(RE_DOCS.match(filename).group(1))
else:
context = ''
retu... | python | def get_context(self, filename):
"""Get context."""
if self.type == 'pptx':
context = '{}: '.format(RE_SLIDE.search(filename).group(1))
elif self.type == 'docx':
context = '{}: '.format(RE_DOCS.match(filename).group(1))
else:
context = ''
retu... | [
"def",
"get_context",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"type",
"==",
"'pptx'",
":",
"context",
"=",
"'{}: '",
".",
"format",
"(",
"RE_SLIDE",
".",
"search",
"(",
"filename",
")",
".",
"group",
"(",
"1",
")",
")",
"elif",
"... | Get context. | [
"Get",
"context",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L132-L141 |
facelessuser/pyspelling | pyspelling/filters/ooxml.py | OoxmlFilter.filter | def filter(self, source_file, encoding): # noqa A001
"""Parse XML file."""
sources = []
for content, filename, enc in self.get_content(source_file):
self.additional_context = self.get_context(filename)
sources.extend(self._filter(content, source_file, enc))
retu... | python | def filter(self, source_file, encoding): # noqa A001
"""Parse XML file."""
sources = []
for content, filename, enc in self.get_content(source_file):
self.additional_context = self.get_context(filename)
sources.extend(self._filter(content, source_file, enc))
retu... | [
"def",
"filter",
"(",
"self",
",",
"source_file",
",",
"encoding",
")",
":",
"# noqa A001",
"sources",
"=",
"[",
"]",
"for",
"content",
",",
"filename",
",",
"enc",
"in",
"self",
".",
"get_content",
"(",
"source_file",
")",
":",
"self",
".",
"additional_... | Parse XML file. | [
"Parse",
"XML",
"file",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L148-L155 |
facelessuser/pyspelling | pyspelling/filters/ooxml.py | OoxmlFilter.sfilter | def sfilter(self, source):
"""Filter."""
sources = []
for content, filename, enc in self.get_content(io.BytesIO(source.text.encode(source.encoding))):
self.additional_context = self.get_context(filename)
sources.extend(self._filter(content, source.context, enc))
... | python | def sfilter(self, source):
"""Filter."""
sources = []
for content, filename, enc in self.get_content(io.BytesIO(source.text.encode(source.encoding))):
self.additional_context = self.get_context(filename)
sources.extend(self._filter(content, source.context, enc))
... | [
"def",
"sfilter",
"(",
"self",
",",
"source",
")",
":",
"sources",
"=",
"[",
"]",
"for",
"content",
",",
"filename",
",",
"enc",
"in",
"self",
".",
"get_content",
"(",
"io",
".",
"BytesIO",
"(",
"source",
".",
"text",
".",
"encode",
"(",
"source",
... | Filter. | [
"Filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/ooxml.py#L157-L164 |
mrcagney/make_gtfs | make_gtfs/protofeed.py | read_protofeed | def read_protofeed(path):
"""
Read the data files at the given directory path
(string or Path object) and build a ProtoFeed from them.
Validate the resulting ProtoFeed.
If invalid, raise a ``ValueError`` specifying the errors.
Otherwise, return the resulting ProtoFeed.
The data files needed... | python | def read_protofeed(path):
"""
Read the data files at the given directory path
(string or Path object) and build a ProtoFeed from them.
Validate the resulting ProtoFeed.
If invalid, raise a ``ValueError`` specifying the errors.
Otherwise, return the resulting ProtoFeed.
The data files needed... | [
"def",
"read_protofeed",
"(",
"path",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"service_windows",
"=",
"pd",
".",
"read_csv",
"(",
"path",
"/",
"'service_windows.csv'",
")",
"meta",
"=",
"pd",
".",
"read_csv",
"(",
"path",
"/",
"'meta.csv'",
",",... | Read the data files at the given directory path
(string or Path object) and build a ProtoFeed from them.
Validate the resulting ProtoFeed.
If invalid, raise a ``ValueError`` specifying the errors.
Otherwise, return the resulting ProtoFeed.
The data files needed to build a ProtoFeed are
- ``fre... | [
"Read",
"the",
"data",
"files",
"at",
"the",
"given",
"directory",
"path",
"(",
"string",
"or",
"Path",
"object",
")",
"and",
"build",
"a",
"ProtoFeed",
"from",
"them",
".",
"Validate",
"the",
"resulting",
"ProtoFeed",
".",
"If",
"invalid",
"raise",
"a",
... | train | https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/protofeed.py#L88-L213 |
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 D... | 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 D... | [
"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",
"."
] | train | https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/protofeed.py#L73-L86 |
dougn/jsontree | jsontree.py | mapped_jsontree_class | def mapped_jsontree_class(mapping):
"""Return a class which is a jsontree, but with a supplied attribute name
mapping. The mapping argument can be a mapping object
(dict, jsontree, etc.) or it can be a callable which takes a single
argument (the attribute name), and returns a new name.
This is ... | python | def mapped_jsontree_class(mapping):
"""Return a class which is a jsontree, but with a supplied attribute name
mapping. The mapping argument can be a mapping object
(dict, jsontree, etc.) or it can be a callable which takes a single
argument (the attribute name), and returns a new name.
This is ... | [
"def",
"mapped_jsontree_class",
"(",
"mapping",
")",
":",
"mapper",
"=",
"mapping",
"if",
"not",
"callable",
"(",
"mapping",
")",
":",
"if",
"not",
"isinstance",
"(",
"mapping",
",",
"collections",
".",
"Mapping",
")",
":",
"raise",
"TypeError",
"(",
"\"Ar... | Return a class which is a jsontree, but with a supplied attribute name
mapping. The mapping argument can be a mapping object
(dict, jsontree, etc.) or it can be a callable which takes a single
argument (the attribute name), and returns a new name.
This is useful in situations where you have a jsont... | [
"Return",
"a",
"class",
"which",
"is",
"a",
"jsontree",
"but",
"with",
"a",
"supplied",
"attribute",
"name",
"mapping",
".",
"The",
"mapping",
"argument",
"can",
"be",
"a",
"mapping",
"object",
"(",
"dict",
"jsontree",
"etc",
".",
")",
"or",
"it",
"can",... | train | https://github.com/dougn/jsontree/blob/e65ebc220528dfc15acb3813ab77c936c1ffc623/jsontree.py#L98-L174 |
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=datetime... | 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=datetime... | [
"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",
"."
] | train | https://github.com/dougn/jsontree/blob/e65ebc220528dfc15acb3813ab77c936c1ffc623/jsontree.py#L233-L240 |
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, obje... | 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, obje... | [
"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"
] | train | https://github.com/dougn/jsontree/blob/e65ebc220528dfc15acb3813ab77c936c1ffc623/jsontree.py#L261-L269 |
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, ob... | 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, ob... | [
"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"
] | train | https://github.com/dougn/jsontree/blob/e65ebc220528dfc15acb3813ab77c936c1ffc623/jsontree.py#L271-L279 |
facelessuser/pyspelling | pyspelling/filters/python.py | PythonFilter.setup | def setup(self):
"""Setup."""
self.comments = self.config['comments']
self.docstrings = self.config['docstrings']
self.strings = self.config['strings']
self.group_comments = self.config['group_comments']
self.string_types, self.wild_string_types = self.eval_string_type(s... | python | def setup(self):
"""Setup."""
self.comments = self.config['comments']
self.docstrings = self.config['docstrings']
self.strings = self.config['strings']
self.group_comments = self.config['group_comments']
self.string_types, self.wild_string_types = self.eval_string_type(s... | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"comments",
"=",
"self",
".",
"config",
"[",
"'comments'",
"]",
"self",
".",
"docstrings",
"=",
"self",
".",
"config",
"[",
"'docstrings'",
"]",
"self",
".",
"strings",
"=",
"self",
".",
"config",
"... | Setup. | [
"Setup",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L115-L123 |
facelessuser/pyspelling | pyspelling/filters/python.py | PythonFilter.validate_options | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'string_types':
if RE_VALID_STRING_TYPES.match(v) is None:
raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v)) | python | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'string_types':
if RE_VALID_STRING_TYPES.match(v) is None:
raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v)) | [
"def",
"validate_options",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"super",
"(",
")",
".",
"validate_options",
"(",
"k",
",",
"v",
")",
"if",
"k",
"==",
"'string_types'",
":",
"if",
"RE_VALID_STRING_TYPES",
".",
"match",
"(",
"v",
")",
"is",
"None... | Validate options. | [
"Validate",
"options",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L125-L131 |
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')
... | 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')
... | [
"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",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L133-L146 |
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')
... | 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')
... | [
"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",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L148-L169 |
facelessuser/pyspelling | pyspelling/filters/python.py | PythonFilter.replace_unicode | def replace_unicode(self, m):
"""Replace escapes."""
groups = m.groupdict()
esc = m.group(0)
if groups.get('fesc'):
value = m.group(0)
elif groups.get('format'):
value = ' '
elif groups.get('special'):
value = BACK_SLASH_TRANSLATION[es... | python | def replace_unicode(self, m):
"""Replace escapes."""
groups = m.groupdict()
esc = m.group(0)
if groups.get('fesc'):
value = m.group(0)
elif groups.get('format'):
value = ' '
elif groups.get('special'):
value = BACK_SLASH_TRANSLATION[es... | [
"def",
"replace_unicode",
"(",
"self",
",",
"m",
")",
":",
"groups",
"=",
"m",
".",
"groupdict",
"(",
")",
"esc",
"=",
"m",
".",
"group",
"(",
"0",
")",
"if",
"groups",
".",
"get",
"(",
"'fesc'",
")",
":",
"value",
"=",
"m",
".",
"group",
"(",
... | Replace escapes. | [
"Replace",
"escapes",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L181-L204 |
facelessuser/pyspelling | pyspelling/filters/python.py | PythonFilter.replace_bytes | def replace_bytes(self, m):
"""Replace escapes."""
esc = m.group(0)
value = esc
if m.group('special'):
value = BACK_SLASH_TRANSLATION[esc]
elif m.group('char'):
try:
value = chr(int(esc[2:], 16))
except Exception:
... | python | def replace_bytes(self, m):
"""Replace escapes."""
esc = m.group(0)
value = esc
if m.group('special'):
value = BACK_SLASH_TRANSLATION[esc]
elif m.group('char'):
try:
value = chr(int(esc[2:], 16))
except Exception:
... | [
"def",
"replace_bytes",
"(",
"self",
",",
"m",
")",
":",
"esc",
"=",
"m",
".",
"group",
"(",
"0",
")",
"value",
"=",
"esc",
"if",
"m",
".",
"group",
"(",
"'special'",
")",
":",
"value",
"=",
"BACK_SLASH_TRANSLATION",
"[",
"esc",
"]",
"elif",
"m",
... | Replace escapes. | [
"Replace",
"escapes",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/python.py#L206-L223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.