repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
icq-bot/python-icq-bot | example/util.py | random_choice | def random_choice(sequence):
""" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. """
return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence) | python | def random_choice(sequence):
""" Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. """
return random.choice(tuple(sequence) if isinstance(sequence, set) else sequence) | [
"def",
"random_choice",
"(",
"sequence",
")",
":",
"return",
"random",
".",
"choice",
"(",
"tuple",
"(",
"sequence",
")",
"if",
"isinstance",
"(",
"sequence",
",",
"set",
")",
"else",
"sequence",
")"
] | Same as :meth:`random.choice`, but also supports :class:`set` type to be passed as sequence. | [
"Same",
"as",
":",
"meth",
":",
"random",
".",
"choice",
"but",
"also",
"supports",
":",
"class",
":",
"set",
"type",
"to",
"be",
"passed",
"as",
"sequence",
"."
] | train | https://github.com/icq-bot/python-icq-bot/blob/1d278cc91f8eba5481bb8d70f80fc74160a40c8b/example/util.py#L36-L38 |
torchbox/wagtail-markdown | wagtailmarkdown/utils.py | render_markdown | def render_markdown(text, context=None):
"""
Turn markdown into HTML.
"""
if context is None or not isinstance(context, dict):
context = {}
markdown_html = _transform_markdown_into_html(text)
sanitised_markdown_html = _sanitise_markdown_html(markdown_html)
return mark_safe(sanitised_... | python | def render_markdown(text, context=None):
"""
Turn markdown into HTML.
"""
if context is None or not isinstance(context, dict):
context = {}
markdown_html = _transform_markdown_into_html(text)
sanitised_markdown_html = _sanitise_markdown_html(markdown_html)
return mark_safe(sanitised_... | [
"def",
"render_markdown",
"(",
"text",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"context",
",",
"dict",
")",
":",
"context",
"=",
"{",
"}",
"markdown_html",
"=",
"_transform_markdown_into_html",
... | Turn markdown into HTML. | [
"Turn",
"markdown",
"into",
"HTML",
"."
] | train | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/utils.py#L22-L30 |
torchbox/wagtail-markdown | wagtailmarkdown/utils.py | render | def render(text, context=None):
"""
Depreceated call to render_markdown().
"""
warning = (
"wagtailmarkdown.utils.render() is deprecated. Use "
"wagtailmarkdown.utils.render_markdown() instead."
)
warnings.warn(warning, WagtailMarkdownDeprecationWarning, stacklevel=2)
return ... | python | def render(text, context=None):
"""
Depreceated call to render_markdown().
"""
warning = (
"wagtailmarkdown.utils.render() is deprecated. Use "
"wagtailmarkdown.utils.render_markdown() instead."
)
warnings.warn(warning, WagtailMarkdownDeprecationWarning, stacklevel=2)
return ... | [
"def",
"render",
"(",
"text",
",",
"context",
"=",
"None",
")",
":",
"warning",
"=",
"(",
"\"wagtailmarkdown.utils.render() is deprecated. Use \"",
"\"wagtailmarkdown.utils.render_markdown() instead.\"",
")",
"warnings",
".",
"warn",
"(",
"warning",
",",
"WagtailMarkdownD... | Depreceated call to render_markdown(). | [
"Depreceated",
"call",
"to",
"render_markdown",
"()",
"."
] | train | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/utils.py#L154-L163 |
torchbox/wagtail-markdown | wagtailmarkdown/mdx/tables/__init__.py | TableProcessor.run | def run(self, parent, blocks):
""" Parse a table block and build table. """
block = blocks.pop(0).split('\n')
header = block[0].strip()
seperator = block[1].strip()
rows = block[2:]
# Get format type (bordered by pipes or not)
border = False
if hea... | python | def run(self, parent, blocks):
""" Parse a table block and build table. """
block = blocks.pop(0).split('\n')
header = block[0].strip()
seperator = block[1].strip()
rows = block[2:]
# Get format type (bordered by pipes or not)
border = False
if hea... | [
"def",
"run",
"(",
"self",
",",
"parent",
",",
"blocks",
")",
":",
"block",
"=",
"blocks",
".",
"pop",
"(",
"0",
")",
".",
"split",
"(",
"'\\n'",
")",
"header",
"=",
"block",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"seperator",
"=",
"block",
"["... | Parse a table block and build table. | [
"Parse",
"a",
"table",
"block",
"and",
"build",
"table",
"."
] | train | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L33-L61 |
torchbox/wagtail-markdown | wagtailmarkdown/mdx/tables/__init__.py | TableProcessor._build_row | def _build_row(self, row, parent, align, border):
""" Given a row of text, build table cells. """
tr = etree.SubElement(parent, 'tr')
tag = 'td'
if parent.tag == 'thead':
tag = 'th'
cells = self._split_row(row, border)
# We use align here rather than ce... | python | def _build_row(self, row, parent, align, border):
""" Given a row of text, build table cells. """
tr = etree.SubElement(parent, 'tr')
tag = 'td'
if parent.tag == 'thead':
tag = 'th'
cells = self._split_row(row, border)
# We use align here rather than ce... | [
"def",
"_build_row",
"(",
"self",
",",
"row",
",",
"parent",
",",
"align",
",",
"border",
")",
":",
"tr",
"=",
"etree",
".",
"SubElement",
"(",
"parent",
",",
"'tr'",
")",
"tag",
"=",
"'td'",
"if",
"parent",
".",
"tag",
"==",
"'thead'",
":",
"tag",... | Given a row of text, build table cells. | [
"Given",
"a",
"row",
"of",
"text",
"build",
"table",
"cells",
"."
] | train | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L63-L79 |
torchbox/wagtail-markdown | wagtailmarkdown/mdx/tables/__init__.py | TableProcessor._split_row | def _split_row(self, row, border):
""" split a row of text into list of cells. """
if border:
if row.startswith('|'):
row = row[1:]
if row.endswith('|'):
row = row[:-1]
return row.split('|') | python | def _split_row(self, row, border):
""" split a row of text into list of cells. """
if border:
if row.startswith('|'):
row = row[1:]
if row.endswith('|'):
row = row[:-1]
return row.split('|') | [
"def",
"_split_row",
"(",
"self",
",",
"row",
",",
"border",
")",
":",
"if",
"border",
":",
"if",
"row",
".",
"startswith",
"(",
"'|'",
")",
":",
"row",
"=",
"row",
"[",
"1",
":",
"]",
"if",
"row",
".",
"endswith",
"(",
"'|'",
")",
":",
"row",
... | split a row of text into list of cells. | [
"split",
"a",
"row",
"of",
"text",
"into",
"list",
"of",
"cells",
"."
] | train | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L81-L88 |
torchbox/wagtail-markdown | wagtailmarkdown/mdx/tables/__init__.py | TableExtension.extendMarkdown | def extendMarkdown(self, md, md_globals):
""" Add an instance of TableProcessor to BlockParser. """
md.parser.blockprocessors.add('table',
TableProcessor(md.parser),
'<hashheader') | python | def extendMarkdown(self, md, md_globals):
""" Add an instance of TableProcessor to BlockParser. """
md.parser.blockprocessors.add('table',
TableProcessor(md.parser),
'<hashheader') | [
"def",
"extendMarkdown",
"(",
"self",
",",
"md",
",",
"md_globals",
")",
":",
"md",
".",
"parser",
".",
"blockprocessors",
".",
"add",
"(",
"'table'",
",",
"TableProcessor",
"(",
"md",
".",
"parser",
")",
",",
"'<hashheader'",
")"
] | Add an instance of TableProcessor to BlockParser. | [
"Add",
"an",
"instance",
"of",
"TableProcessor",
"to",
"BlockParser",
"."
] | train | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L94-L98 |
kottenator/django-compressor-toolkit | compressor_toolkit/precompilers.py | get_all_static | def get_all_static():
"""
Get all the static files directories found by ``STATICFILES_FINDERS``
:return: set of paths (top-level folders only)
"""
static_dirs = set()
for finder in settings.STATICFILES_FINDERS:
finder = finders.get_finder(finder)
if hasattr(finder, 'storages')... | python | def get_all_static():
"""
Get all the static files directories found by ``STATICFILES_FINDERS``
:return: set of paths (top-level folders only)
"""
static_dirs = set()
for finder in settings.STATICFILES_FINDERS:
finder = finders.get_finder(finder)
if hasattr(finder, 'storages')... | [
"def",
"get_all_static",
"(",
")",
":",
"static_dirs",
"=",
"set",
"(",
")",
"for",
"finder",
"in",
"settings",
".",
"STATICFILES_FINDERS",
":",
"finder",
"=",
"finders",
".",
"get_finder",
"(",
"finder",
")",
"if",
"hasattr",
"(",
"finder",
",",
"'storage... | Get all the static files directories found by ``STATICFILES_FINDERS``
:return: set of paths (top-level folders only) | [
"Get",
"all",
"the",
"static",
"files",
"directories",
"found",
"by",
"STATICFILES_FINDERS"
] | train | https://github.com/kottenator/django-compressor-toolkit/blob/e7bfdaa354e9c9189db0e4ba4fa049045adad91b/compressor_toolkit/precompilers.py#L13-L31 |
kottenator/django-compressor-toolkit | compressor_toolkit/precompilers.py | BaseCompiler.input | def input(self, **kwargs):
"""
Specify temporary input file extension.
Browserify requires explicit file extension (".js" or ".json" by default).
https://github.com/substack/node-browserify/issues/1469
"""
if self.infile is None and "{infile}" in self.command:
... | python | def input(self, **kwargs):
"""
Specify temporary input file extension.
Browserify requires explicit file extension (".js" or ".json" by default).
https://github.com/substack/node-browserify/issues/1469
"""
if self.infile is None and "{infile}" in self.command:
... | [
"def",
"input",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"infile",
"is",
"None",
"and",
"\"{infile}\"",
"in",
"self",
".",
"command",
":",
"if",
"self",
".",
"filename",
"is",
"None",
":",
"self",
".",
"infile",
"=",
"Name... | Specify temporary input file extension.
Browserify requires explicit file extension (".js" or ".json" by default).
https://github.com/substack/node-browserify/issues/1469 | [
"Specify",
"temporary",
"input",
"file",
"extension",
"."
] | train | https://github.com/kottenator/django-compressor-toolkit/blob/e7bfdaa354e9c9189db0e4ba4fa049045adad91b/compressor_toolkit/precompilers.py#L38-L53 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | graph_hash | def graph_hash(obj):
'''this hashes all types to a hash without colissions. python's hashing algorithms are not cross type compatable but hashing tuples with the type as the first element seems to do the trick'''
obj_type = type(obj)
try:
# this works for hashables
return hash((obj_type, obj... | python | def graph_hash(obj):
'''this hashes all types to a hash without colissions. python's hashing algorithms are not cross type compatable but hashing tuples with the type as the first element seems to do the trick'''
obj_type = type(obj)
try:
# this works for hashables
return hash((obj_type, obj... | [
"def",
"graph_hash",
"(",
"obj",
")",
":",
"obj_type",
"=",
"type",
"(",
"obj",
")",
"try",
":",
"# this works for hashables",
"return",
"hash",
"(",
"(",
"obj_type",
",",
"obj",
")",
")",
"except",
":",
"# this works for object containers since graphdb",
"# wan... | this hashes all types to a hash without colissions. python's hashing algorithms are not cross type compatable but hashing tuples with the type as the first element seems to do the trick | [
"this",
"hashes",
"all",
"types",
"to",
"a",
"hash",
"without",
"colissions",
".",
"python",
"s",
"hashing",
"algorithms",
"are",
"not",
"cross",
"type",
"compatable",
"but",
"hashing",
"tuples",
"with",
"the",
"type",
"as",
"the",
"first",
"element",
"seems... | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L13-L23 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.store_item | def store_item(self, item):
''' use this function to store a python object in the database '''
assert not isinstance(item, RamGraphDBNode)
item_hash = graph_hash(item)
if item_hash not in self.nodes:
self.nodes[item_hash] = RamGraphDBNode(item)
return self.nodes[item_... | python | def store_item(self, item):
''' use this function to store a python object in the database '''
assert not isinstance(item, RamGraphDBNode)
item_hash = graph_hash(item)
if item_hash not in self.nodes:
self.nodes[item_hash] = RamGraphDBNode(item)
return self.nodes[item_... | [
"def",
"store_item",
"(",
"self",
",",
"item",
")",
":",
"assert",
"not",
"isinstance",
"(",
"item",
",",
"RamGraphDBNode",
")",
"item_hash",
"=",
"graph_hash",
"(",
"item",
")",
"if",
"item_hash",
"not",
"in",
"self",
".",
"nodes",
":",
"self",
".",
"... | use this function to store a python object in the database | [
"use",
"this",
"function",
"to",
"store",
"a",
"python",
"object",
"in",
"the",
"database"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L155-L161 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.store_relation | def store_relation(self, src, name, dst):
''' use this to store a relation between two objects '''
self.__require_string__(name)
#print('storing relation', src, name, dst)
# make sure both items are stored
self.store_item(src).link(name, self.store_item(dst)) | python | def store_relation(self, src, name, dst):
''' use this to store a relation between two objects '''
self.__require_string__(name)
#print('storing relation', src, name, dst)
# make sure both items are stored
self.store_item(src).link(name, self.store_item(dst)) | [
"def",
"store_relation",
"(",
"self",
",",
"src",
",",
"name",
",",
"dst",
")",
":",
"self",
".",
"__require_string__",
"(",
"name",
")",
"#print('storing relation', src, name, dst)",
"# make sure both items are stored",
"self",
".",
"store_item",
"(",
"src",
")",
... | use this to store a relation between two objects | [
"use",
"this",
"to",
"store",
"a",
"relation",
"between",
"two",
"objects"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L203-L208 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.delete_relation | def delete_relation(self, src, relation, target):
''' can be both used as (src, relation, dest) for a single relation or
(src, relation) to delete all relations of that type from the src '''
self.__require_string__(relation)
if src in self and target in self:
self._get_it... | python | def delete_relation(self, src, relation, target):
''' can be both used as (src, relation, dest) for a single relation or
(src, relation) to delete all relations of that type from the src '''
self.__require_string__(relation)
if src in self and target in self:
self._get_it... | [
"def",
"delete_relation",
"(",
"self",
",",
"src",
",",
"relation",
",",
"target",
")",
":",
"self",
".",
"__require_string__",
"(",
"relation",
")",
"if",
"src",
"in",
"self",
"and",
"target",
"in",
"self",
":",
"self",
".",
"_get_item_node",
"(",
"src"... | can be both used as (src, relation, dest) for a single relation or
(src, relation) to delete all relations of that type from the src | [
"can",
"be",
"both",
"used",
"as",
"(",
"src",
"relation",
"dest",
")",
"for",
"a",
"single",
"relation",
"or",
"(",
"src",
"relation",
")",
"to",
"delete",
"all",
"relations",
"of",
"that",
"type",
"from",
"the",
"src"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L216-L221 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.delete_item | def delete_item(self, item):
''' removes an item from the db '''
for relation, dst in self.relations_of(item, True):
self.delete_relation(item, relation, dst)
#print(item, relation, dst)
for src, relation in self.relations_to(item, True):
self.delete_relation(... | python | def delete_item(self, item):
''' removes an item from the db '''
for relation, dst in self.relations_of(item, True):
self.delete_relation(item, relation, dst)
#print(item, relation, dst)
for src, relation in self.relations_to(item, True):
self.delete_relation(... | [
"def",
"delete_item",
"(",
"self",
",",
"item",
")",
":",
"for",
"relation",
",",
"dst",
"in",
"self",
".",
"relations_of",
"(",
"item",
",",
"True",
")",
":",
"self",
".",
"delete_relation",
"(",
"item",
",",
"relation",
",",
"dst",
")",
"#print(item,... | removes an item from the db | [
"removes",
"an",
"item",
"from",
"the",
"db"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L223-L235 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.relations_of | def relations_of(self, target, include_object=False):
''' list all relations the originate from target '''
relations = (target if isinstance(target, RamGraphDBNode) else self._get_item_node(target)).outgoing
if include_object:
for k in relations:
for v in relations[k]... | python | def relations_of(self, target, include_object=False):
''' list all relations the originate from target '''
relations = (target if isinstance(target, RamGraphDBNode) else self._get_item_node(target)).outgoing
if include_object:
for k in relations:
for v in relations[k]... | [
"def",
"relations_of",
"(",
"self",
",",
"target",
",",
"include_object",
"=",
"False",
")",
":",
"relations",
"=",
"(",
"target",
"if",
"isinstance",
"(",
"target",
",",
"RamGraphDBNode",
")",
"else",
"self",
".",
"_get_item_node",
"(",
"target",
")",
")"... | list all relations the originate from target | [
"list",
"all",
"relations",
"the",
"originate",
"from",
"target"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L241-L250 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.relations_to | def relations_to(self, target, include_object=False):
''' list all relations pointing at an object '''
relations = self._get_item_node(target).incoming
if include_object:
for k in relations:
for v in relations[k]:
if hasattr(v, 'obj'): # filter dea... | python | def relations_to(self, target, include_object=False):
''' list all relations pointing at an object '''
relations = self._get_item_node(target).incoming
if include_object:
for k in relations:
for v in relations[k]:
if hasattr(v, 'obj'): # filter dea... | [
"def",
"relations_to",
"(",
"self",
",",
"target",
",",
"include_object",
"=",
"False",
")",
":",
"relations",
"=",
"self",
".",
"_get_item_node",
"(",
"target",
")",
".",
"incoming",
"if",
"include_object",
":",
"for",
"k",
"in",
"relations",
":",
"for",
... | list all relations pointing at an object | [
"list",
"all",
"relations",
"pointing",
"at",
"an",
"object"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L252-L261 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.show_objects | def show_objects(self):
''' display the entire of objects with their (id, value, node) '''
for key in self.nodes:
node = self.nodes[key]
value = node.obj
print(key, '-', repr(value), '-', node) | python | def show_objects(self):
''' display the entire of objects with their (id, value, node) '''
for key in self.nodes:
node = self.nodes[key]
value = node.obj
print(key, '-', repr(value), '-', node) | [
"def",
"show_objects",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"nodes",
":",
"node",
"=",
"self",
".",
"nodes",
"[",
"key",
"]",
"value",
"=",
"node",
".",
"obj",
"print",
"(",
"key",
",",
"'-'",
",",
"repr",
"(",
"value",
")",
... | display the entire of objects with their (id, value, node) | [
"display",
"the",
"entire",
"of",
"objects",
"with",
"their",
"(",
"id",
"value",
"node",
")"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L276-L281 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.list_relations | def list_relations(self):
''' list every relation in the database as (src, relation, dst) '''
for node in self.iter_nodes():
for relation, target in self.relations_of(node.obj, True):
yield node.obj, relation, target | python | def list_relations(self):
''' list every relation in the database as (src, relation, dst) '''
for node in self.iter_nodes():
for relation, target in self.relations_of(node.obj, True):
yield node.obj, relation, target | [
"def",
"list_relations",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"iter_nodes",
"(",
")",
":",
"for",
"relation",
",",
"target",
"in",
"self",
".",
"relations_of",
"(",
"node",
".",
"obj",
",",
"True",
")",
":",
"yield",
"node",
".",
... | list every relation in the database as (src, relation, dst) | [
"list",
"every",
"relation",
"in",
"the",
"database",
"as",
"(",
"src",
"relation",
"dst",
")"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L283-L287 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | RamGraphDB.show_relations | def show_relations(self):
''' display every relation in the database as (src, relation, dst) '''
for src_node in self.iter_nodes():
for relation in src_node.outgoing:
for dst_node in src_node.outgoing[relation]:
print(repr(src_node.obj), '-', relation, '-'... | python | def show_relations(self):
''' display every relation in the database as (src, relation, dst) '''
for src_node in self.iter_nodes():
for relation in src_node.outgoing:
for dst_node in src_node.outgoing[relation]:
print(repr(src_node.obj), '-', relation, '-'... | [
"def",
"show_relations",
"(",
"self",
")",
":",
"for",
"src_node",
"in",
"self",
".",
"iter_nodes",
"(",
")",
":",
"for",
"relation",
"in",
"src_node",
".",
"outgoing",
":",
"for",
"dst_node",
"in",
"src_node",
".",
"outgoing",
"[",
"relation",
"]",
":",... | display every relation in the database as (src, relation, dst) | [
"display",
"every",
"relation",
"in",
"the",
"database",
"as",
"(",
"src",
"relation",
"dst",
")"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L289-L294 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | VList.where | def where(self, relation, filter_fn):
''' use this to filter VLists, simply provide a filter function and what relation to apply it to '''
assert type(relation).__name__ in {'str','unicode'}, 'where needs the first arg to be a string'
assert callable(filter_fn), 'filter_fn needs to be callable'
... | python | def where(self, relation, filter_fn):
''' use this to filter VLists, simply provide a filter function and what relation to apply it to '''
assert type(relation).__name__ in {'str','unicode'}, 'where needs the first arg to be a string'
assert callable(filter_fn), 'filter_fn needs to be callable'
... | [
"def",
"where",
"(",
"self",
",",
"relation",
",",
"filter_fn",
")",
":",
"assert",
"type",
"(",
"relation",
")",
".",
"__name__",
"in",
"{",
"'str'",
",",
"'unicode'",
"}",
",",
"'where needs the first arg to be a string'",
"assert",
"callable",
"(",
"filter_... | use this to filter VLists, simply provide a filter function and what relation to apply it to | [
"use",
"this",
"to",
"filter",
"VLists",
"simply",
"provide",
"a",
"filter",
"function",
"and",
"what",
"relation",
"to",
"apply",
"it",
"to"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L349-L353 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | VList._where | def _where(self, filter_fn):
''' use this to filter VLists, simply provide a filter function to filter the current found objects '''
assert callable(filter_fn), 'filter_fn needs to be callable'
return VList(i for i in self if filter_fn(i())) | python | def _where(self, filter_fn):
''' use this to filter VLists, simply provide a filter function to filter the current found objects '''
assert callable(filter_fn), 'filter_fn needs to be callable'
return VList(i for i in self if filter_fn(i())) | [
"def",
"_where",
"(",
"self",
",",
"filter_fn",
")",
":",
"assert",
"callable",
"(",
"filter_fn",
")",
",",
"'filter_fn needs to be callable'",
"return",
"VList",
"(",
"i",
"for",
"i",
"in",
"self",
"if",
"filter_fn",
"(",
"i",
"(",
")",
")",
")"
] | use this to filter VLists, simply provide a filter function to filter the current found objects | [
"use",
"this",
"to",
"filter",
"VLists",
"simply",
"provide",
"a",
"filter",
"function",
"to",
"filter",
"the",
"current",
"found",
"objects"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L355-L358 |
CodyKochmann/graphdb | graphdb/RamGraphDB.py | VList._where | def _where(self, **kwargs):
'''use this to filter VLists with kv pairs'''
out = self
for k,v in kwargs.items():
out = out.where(k, lambda i:i==v)
return out | python | def _where(self, **kwargs):
'''use this to filter VLists with kv pairs'''
out = self
for k,v in kwargs.items():
out = out.where(k, lambda i:i==v)
return out | [
"def",
"_where",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"out",
"=",
"out",
".",
"where",
"(",
"k",
",",
"lambda",
"i",
":",
"i",
"==",
"v",
")",... | use this to filter VLists with kv pairs | [
"use",
"this",
"to",
"filter",
"VLists",
"with",
"kv",
"pairs"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L362-L367 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB._create_file | def _create_file(path=''):
''' creates a file at the given path and sets the permissions to user only read/write '''
from os.path import isfile
if not isfile(path): # only do the following if the file doesn't exist yet
from os import chmod
from stat import S_IRUSR, S_IWUS... | python | def _create_file(path=''):
''' creates a file at the given path and sets the permissions to user only read/write '''
from os.path import isfile
if not isfile(path): # only do the following if the file doesn't exist yet
from os import chmod
from stat import S_IRUSR, S_IWUS... | [
"def",
"_create_file",
"(",
"path",
"=",
"''",
")",
":",
"from",
"os",
".",
"path",
"import",
"isfile",
"if",
"not",
"isfile",
"(",
"path",
")",
":",
"# only do the following if the file doesn't exist yet",
"from",
"os",
"import",
"chmod",
"from",
"stat",
"imp... | creates a file at the given path and sets the permissions to user only read/write | [
"creates",
"a",
"file",
"at",
"the",
"given",
"path",
"and",
"sets",
"the",
"permissions",
"to",
"user",
"only",
"read",
"/",
"write"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L174-L182 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.store_item | def store_item(self, item):
''' use this function to store a python object in the database '''
#print('storing item', item)
item_id = self._id_of(item)
#print('item_id', item_id)
if item_id is None:
#print('storing item', item)
blob = self.serialize(item)
... | python | def store_item(self, item):
''' use this function to store a python object in the database '''
#print('storing item', item)
item_id = self._id_of(item)
#print('item_id', item_id)
if item_id is None:
#print('storing item', item)
blob = self.serialize(item)
... | [
"def",
"store_item",
"(",
"self",
",",
"item",
")",
":",
"#print('storing item', item)",
"item_id",
"=",
"self",
".",
"_id_of",
"(",
"item",
")",
"#print('item_id', item_id)",
"if",
"item_id",
"is",
"None",
":",
"#print('storing item', item)",
"blob",
"=",
"self",... | use this function to store a python object in the database | [
"use",
"this",
"function",
"to",
"store",
"a",
"python",
"object",
"in",
"the",
"database"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L197-L210 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.delete_item | def delete_item(self, item):
''' removes an item from the db '''
for relation in self.relations_of(item):
self.delete_relation(item, relation)
for origin, relation in self.relations_to(item, True):
self.delete_relation(origin, relation, item)
with self._write_lock... | python | def delete_item(self, item):
''' removes an item from the db '''
for relation in self.relations_of(item):
self.delete_relation(item, relation)
for origin, relation in self.relations_to(item, True):
self.delete_relation(origin, relation, item)
with self._write_lock... | [
"def",
"delete_item",
"(",
"self",
",",
"item",
")",
":",
"for",
"relation",
"in",
"self",
".",
"relations_of",
"(",
"item",
")",
":",
"self",
".",
"delete_relation",
"(",
"item",
",",
"relation",
")",
"for",
"origin",
",",
"relation",
"in",
"self",
".... | removes an item from the db | [
"removes",
"an",
"item",
"from",
"the",
"db"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L212-L222 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.store_relation | def store_relation(self, src, name, dst):
''' use this to store a relation between two objects '''
self.__require_string__(name)
#print('storing relation', src, name, dst)
# make sure both items are stored
self.store_item(src)
self.store_item(dst)
with self._write... | python | def store_relation(self, src, name, dst):
''' use this to store a relation between two objects '''
self.__require_string__(name)
#print('storing relation', src, name, dst)
# make sure both items are stored
self.store_item(src)
self.store_item(dst)
with self._write... | [
"def",
"store_relation",
"(",
"self",
",",
"src",
",",
"name",
",",
"dst",
")",
":",
"self",
".",
"__require_string__",
"(",
"name",
")",
"#print('storing relation', src, name, dst)",
"# make sure both items are stored",
"self",
".",
"store_item",
"(",
"src",
")",
... | use this to store a relation between two objects | [
"use",
"this",
"to",
"store",
"a",
"relation",
"between",
"two",
"objects"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L270-L284 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB._delete_single_relation | def _delete_single_relation(self, src, relation, dst):
''' deletes a single relation between objects '''
self.__require_string__(relation)
src_id = self._id_of(src)
dst_id = self._id_of(dst)
with self._write_lock:
self._execute('''
DELETE from relation... | python | def _delete_single_relation(self, src, relation, dst):
''' deletes a single relation between objects '''
self.__require_string__(relation)
src_id = self._id_of(src)
dst_id = self._id_of(dst)
with self._write_lock:
self._execute('''
DELETE from relation... | [
"def",
"_delete_single_relation",
"(",
"self",
",",
"src",
",",
"relation",
",",
"dst",
")",
":",
"self",
".",
"__require_string__",
"(",
"relation",
")",
"src_id",
"=",
"self",
".",
"_id_of",
"(",
"src",
")",
"dst_id",
"=",
"self",
".",
"_id_of",
"(",
... | deletes a single relation between objects | [
"deletes",
"a",
"single",
"relation",
"between",
"objects"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L286-L295 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.delete_relation | def delete_relation(self, src, relation, *targets):
''' can be both used as (src, relation, dest) for a single relation or
(src, relation) to delete all relations of that type from the src '''
self.__require_string__(relation)
if len(targets):
for i in targets:
... | python | def delete_relation(self, src, relation, *targets):
''' can be both used as (src, relation, dest) for a single relation or
(src, relation) to delete all relations of that type from the src '''
self.__require_string__(relation)
if len(targets):
for i in targets:
... | [
"def",
"delete_relation",
"(",
"self",
",",
"src",
",",
"relation",
",",
"*",
"targets",
")",
":",
"self",
".",
"__require_string__",
"(",
"relation",
")",
"if",
"len",
"(",
"targets",
")",
":",
"for",
"i",
"in",
"targets",
":",
"self",
".",
"_delete_s... | can be both used as (src, relation, dest) for a single relation or
(src, relation) to delete all relations of that type from the src | [
"can",
"be",
"both",
"used",
"as",
"(",
"src",
"relation",
"dest",
")",
"for",
"a",
"single",
"relation",
"or",
"(",
"src",
"relation",
")",
"to",
"delete",
"all",
"relations",
"of",
"that",
"type",
"from",
"the",
"src"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L297-L307 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.find | def find(self, target, relation):
''' returns back all elements the target has a relation to '''
query = 'select ob1.code from objects as ob1, objects as ob2, relations where relations.dst=ob1.id and relations.name=? and relations.src=ob2.id and ob2.code=?' # src is id not source :/
for i in sel... | python | def find(self, target, relation):
''' returns back all elements the target has a relation to '''
query = 'select ob1.code from objects as ob1, objects as ob2, relations where relations.dst=ob1.id and relations.name=? and relations.src=ob2.id and ob2.code=?' # src is id not source :/
for i in sel... | [
"def",
"find",
"(",
"self",
",",
"target",
",",
"relation",
")",
":",
"query",
"=",
"'select ob1.code from objects as ob1, objects as ob2, relations where relations.dst=ob1.id and relations.name=? and relations.src=ob2.id and ob2.code=?'",
"# src is id not source :/",
"for",
"i",
"in... | returns back all elements the target has a relation to | [
"returns",
"back",
"all",
"elements",
"the",
"target",
"has",
"a",
"relation",
"to"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L309-L313 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.relations_of | def relations_of(self, target, include_object=False):
''' list all relations the originate from target '''
if include_object:
_ = self._execute('''
select relations.name, ob2.code from relations, objects as ob1, objects as ob2 where relations.src=ob1.id and ob2.id=relations.d... | python | def relations_of(self, target, include_object=False):
''' list all relations the originate from target '''
if include_object:
_ = self._execute('''
select relations.name, ob2.code from relations, objects as ob1, objects as ob2 where relations.src=ob1.id and ob2.id=relations.d... | [
"def",
"relations_of",
"(",
"self",
",",
"target",
",",
"include_object",
"=",
"False",
")",
":",
"if",
"include_object",
":",
"_",
"=",
"self",
".",
"_execute",
"(",
"'''\n select relations.name, ob2.code from relations, objects as ob1, objects as ob2 where ... | list all relations the originate from target | [
"list",
"all",
"relations",
"the",
"originate",
"from",
"target"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L315-L329 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.relations_to | def relations_to(self, target, include_object=False):
''' list all relations pointing at an object '''
if include_object:
_ = self._execute('''
select name, (select code from objects where id=src) from relations where dst=?
''', (self._id_of(target),))
... | python | def relations_to(self, target, include_object=False):
''' list all relations pointing at an object '''
if include_object:
_ = self._execute('''
select name, (select code from objects where id=src) from relations where dst=?
''', (self._id_of(target),))
... | [
"def",
"relations_to",
"(",
"self",
",",
"target",
",",
"include_object",
"=",
"False",
")",
":",
"if",
"include_object",
":",
"_",
"=",
"self",
".",
"_execute",
"(",
"'''\n select name, (select code from objects where id=src) from relations where dst=?\n ... | list all relations pointing at an object | [
"list",
"all",
"relations",
"pointing",
"at",
"an",
"object"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L331-L344 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.connections_of | def connections_of(self, target):
''' generate tuples containing (relation, object_that_applies) '''
return gen.chain( ((r,i) for i in self.find(target,r)) for r in self.relations_of(target) ) | python | def connections_of(self, target):
''' generate tuples containing (relation, object_that_applies) '''
return gen.chain( ((r,i) for i in self.find(target,r)) for r in self.relations_of(target) ) | [
"def",
"connections_of",
"(",
"self",
",",
"target",
")",
":",
"return",
"gen",
".",
"chain",
"(",
"(",
"(",
"r",
",",
"i",
")",
"for",
"i",
"in",
"self",
".",
"find",
"(",
"target",
",",
"r",
")",
")",
"for",
"r",
"in",
"self",
".",
"relations... | generate tuples containing (relation, object_that_applies) | [
"generate",
"tuples",
"containing",
"(",
"relation",
"object_that_applies",
")"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L346-L348 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.list_objects | def list_objects(self):
''' list the entire of objects with their (id, serialized_form, actual_value) '''
for i in self._execute('select * from objects'):
_id, code = i
yield _id, code, self.deserialize(code) | python | def list_objects(self):
''' list the entire of objects with their (id, serialized_form, actual_value) '''
for i in self._execute('select * from objects'):
_id, code = i
yield _id, code, self.deserialize(code) | [
"def",
"list_objects",
"(",
"self",
")",
":",
"for",
"i",
"in",
"self",
".",
"_execute",
"(",
"'select * from objects'",
")",
":",
"_id",
",",
"code",
"=",
"i",
"yield",
"_id",
",",
"code",
",",
"self",
".",
"deserialize",
"(",
"code",
")"
] | list the entire of objects with their (id, serialized_form, actual_value) | [
"list",
"the",
"entire",
"of",
"objects",
"with",
"their",
"(",
"id",
"serialized_form",
"actual_value",
")"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L350-L354 |
CodyKochmann/graphdb | graphdb/SQLiteGraphDB.py | SQLiteGraphDB.list_relations | def list_relations(self):
''' list every relation in the database as (src, relation, dst) '''
_ = self._execute('select * from relations').fetchall()
for i in _:
#print(i)
src, name, dst = i
src = self.deserialize(
next(self._execute('select co... | python | def list_relations(self):
''' list every relation in the database as (src, relation, dst) '''
_ = self._execute('select * from relations').fetchall()
for i in _:
#print(i)
src, name, dst = i
src = self.deserialize(
next(self._execute('select co... | [
"def",
"list_relations",
"(",
"self",
")",
":",
"_",
"=",
"self",
".",
"_execute",
"(",
"'select * from relations'",
")",
".",
"fetchall",
"(",
")",
"for",
"i",
"in",
"_",
":",
"#print(i)",
"src",
",",
"name",
",",
"dst",
"=",
"i",
"src",
"=",
"self"... | list every relation in the database as (src, relation, dst) | [
"list",
"every",
"relation",
"in",
"the",
"database",
"as",
"(",
"src",
"relation",
"dst",
")"
] | train | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L366-L378 |
keredson/peewee-db-evolve | peeweedbevolve.py | calc_changes | def calc_changes(db, ignore_tables=None):
migrator = None # expose eventually?
if migrator is None:
migrator = auto_detect_migrator(db)
existing_tables = [unicode(t) for t in db.get_tables()]
existing_indexes = {table:get_indexes_by_table(db, table) for table in existing_tables}
existing_columns_by_table... | python | def calc_changes(db, ignore_tables=None):
migrator = None # expose eventually?
if migrator is None:
migrator = auto_detect_migrator(db)
existing_tables = [unicode(t) for t in db.get_tables()]
existing_indexes = {table:get_indexes_by_table(db, table) for table in existing_tables}
existing_columns_by_table... | [
"def",
"calc_changes",
"(",
"db",
",",
"ignore_tables",
"=",
"None",
")",
":",
"migrator",
"=",
"None",
"# expose eventually?",
"if",
"migrator",
"is",
"None",
":",
"migrator",
"=",
"auto_detect_migrator",
"(",
"db",
")",
"existing_tables",
"=",
"[",
"unicode"... | to_run += calc_perms_changes($schema_tables, noop) unless $check_perms_for.empty? | [
"to_run",
"+",
"=",
"calc_perms_changes",
"(",
"$schema_tables",
"noop",
")",
"unless",
"$check_perms_for",
".",
"empty?"
] | train | https://github.com/keredson/peewee-db-evolve/blob/0cc4dc33935f01e2c2b4b8778a4a0ee10de22023/peeweedbevolve.py#L604-L676 |
StorjOld/pyp2p | pyp2p/sock.py | Sock.set_keep_alive | def set_keep_alive(self, sock, after_idle_sec=5, interval_sec=60,
max_fails=5):
"""
This function instructs the TCP socket to send a heart beat every n
seconds to detect dead connections. It's the TCP equivalent of the
IRC ping-pong protocol and allows for better c... | python | def set_keep_alive(self, sock, after_idle_sec=5, interval_sec=60,
max_fails=5):
"""
This function instructs the TCP socket to send a heart beat every n
seconds to detect dead connections. It's the TCP equivalent of the
IRC ping-pong protocol and allows for better c... | [
"def",
"set_keep_alive",
"(",
"self",
",",
"sock",
",",
"after_idle_sec",
"=",
"5",
",",
"interval_sec",
"=",
"60",
",",
"max_fails",
"=",
"5",
")",
":",
"# OSX",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Darwin\"",
":",
"# scraped from /usr/incl... | This function instructs the TCP socket to send a heart beat every n
seconds to detect dead connections. It's the TCP equivalent of the
IRC ping-pong protocol and allows for better cleanup / detection
of dead TCP connections.
It activates after 1 second (after_idle_sec) of idleness, then... | [
"This",
"function",
"instructs",
"the",
"TCP",
"socket",
"to",
"send",
"a",
"heart",
"beat",
"every",
"n",
"seconds",
"to",
"detect",
"dead",
"connections",
".",
"It",
"s",
"the",
"TCP",
"equivalent",
"of",
"the",
"IRC",
"ping",
"-",
"pong",
"protocol",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/sock.py#L99-L128 |
StorjOld/pyp2p | pyp2p/sock.py | Sock.parse_buf | def parse_buf(self, encoding="unicode"):
"""
Since TCP is a stream-orientated protocol, responses aren't guaranteed
to be complete when they arrive. The buffer stores all the data and
this function splits the data into replies based on the new line
delimiter.
"""
... | python | def parse_buf(self, encoding="unicode"):
"""
Since TCP is a stream-orientated protocol, responses aren't guaranteed
to be complete when they arrive. The buffer stores all the data and
this function splits the data into replies based on the new line
delimiter.
"""
... | [
"def",
"parse_buf",
"(",
"self",
",",
"encoding",
"=",
"\"unicode\"",
")",
":",
"buf_len",
"=",
"len",
"(",
"self",
".",
"buf",
")",
"replies",
"=",
"[",
"]",
"reply",
"=",
"b\"\"",
"chop",
"=",
"0",
"skip",
"=",
"0",
"i",
"=",
"0",
"buf_len",
"=... | Since TCP is a stream-orientated protocol, responses aren't guaranteed
to be complete when they arrive. The buffer stores all the data and
this function splits the data into replies based on the new line
delimiter. | [
"Since",
"TCP",
"is",
"a",
"stream",
"-",
"orientated",
"protocol",
"responses",
"aren",
"t",
"guaranteed",
"to",
"be",
"complete",
"when",
"they",
"arrive",
".",
"The",
"buffer",
"stores",
"all",
"the",
"data",
"and",
"this",
"function",
"splits",
"the",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/sock.py#L221-L267 |
StorjOld/pyp2p | pyp2p/sock.py | Sock.get_chunks | def get_chunks(self, fixed_limit=None, encoding="unicode"):
"""
This is the function which handles retrieving new data chunks. It's
main logic is avoiding a recv call blocking forever and halting
the program flow. To do this, it manages errors and keeps an eye
on the buffer to av... | python | def get_chunks(self, fixed_limit=None, encoding="unicode"):
"""
This is the function which handles retrieving new data chunks. It's
main logic is avoiding a recv call blocking forever and halting
the program flow. To do this, it manages errors and keeps an eye
on the buffer to av... | [
"def",
"get_chunks",
"(",
"self",
",",
"fixed_limit",
"=",
"None",
",",
"encoding",
"=",
"\"unicode\"",
")",
":",
"# Socket is disconnected.",
"if",
"not",
"self",
".",
"connected",
":",
"return",
"# Recv chunks until network buffer is empty.",
"repeat",
"=",
"1",
... | This is the function which handles retrieving new data chunks. It's
main logic is avoiding a recv call blocking forever and halting
the program flow. To do this, it manages errors and keeps an eye
on the buffer to avoid overflows and DoS attacks.
http://stackoverflow.com/questions/16745... | [
"This",
"is",
"the",
"function",
"which",
"handles",
"retrieving",
"new",
"data",
"chunks",
".",
"It",
"s",
"main",
"logic",
"is",
"avoiding",
"a",
"recv",
"call",
"blocking",
"forever",
"and",
"halting",
"the",
"program",
"flow",
".",
"To",
"do",
"this",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/sock.py#L270-L369 |
StorjOld/pyp2p | pyp2p/net.py | Net.validate_node | def validate_node(self, node_ip, node_port=None, same_nodes=1):
self.debug_print("Validating: " + node_ip)
# Is this a valid IP?
if not is_ip_valid(node_ip) or node_ip == "0.0.0.0":
self.debug_print("Invalid node ip in validate node")
return 0
# Is this ... | python | def validate_node(self, node_ip, node_port=None, same_nodes=1):
self.debug_print("Validating: " + node_ip)
# Is this a valid IP?
if not is_ip_valid(node_ip) or node_ip == "0.0.0.0":
self.debug_print("Invalid node ip in validate node")
return 0
# Is this ... | [
"def",
"validate_node",
"(",
"self",
",",
"node_ip",
",",
"node_port",
"=",
"None",
",",
"same_nodes",
"=",
"1",
")",
":",
"self",
".",
"debug_print",
"(",
"\"Validating: \"",
"+",
"node_ip",
")",
"# Is this a valid IP?\r",
"if",
"not",
"is_ip_valid",
"(",
"... | Don't accept connections from self to passive server
or connections to already connected nodes. | [
"Don",
"t",
"accept",
"connections",
"from",
"self",
"to",
"passive",
"server",
"or",
"connections",
"to",
"already",
"connected",
"nodes",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L330-L373 |
StorjOld/pyp2p | pyp2p/net.py | Net.bootstrap | def bootstrap(self):
"""
When the software is first started, it needs to retrieve
a list of nodes to connect to the network to. This function
asks the server for N nodes which consists of at least N
passive nodes and N simultaneous nodes. The simultaneous
nodes are ... | python | def bootstrap(self):
"""
When the software is first started, it needs to retrieve
a list of nodes to connect to the network to. This function
asks the server for N nodes which consists of at least N
passive nodes and N simultaneous nodes. The simultaneous
nodes are ... | [
"def",
"bootstrap",
"(",
"self",
")",
":",
"# Disable bootstrap.\r",
"if",
"not",
"self",
".",
"enable_bootstrap",
":",
"return",
"None",
"# Avoid raping the rendezvous server.\r",
"t",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"last_bootstrap",
"is... | When the software is first started, it needs to retrieve
a list of nodes to connect to the network to. This function
asks the server for N nodes which consists of at least N
passive nodes and N simultaneous nodes. The simultaneous
nodes are prioritized if the node_type for the machin... | [
"When",
"the",
"software",
"is",
"first",
"started",
"it",
"needs",
"to",
"retrieve",
"a",
"list",
"of",
"nodes",
"to",
"connect",
"to",
"the",
"network",
"to",
".",
"This",
"function",
"asks",
"the",
"server",
"for",
"N",
"nodes",
"which",
"consists",
"... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L481-L560 |
StorjOld/pyp2p | pyp2p/net.py | Net.advertise | def advertise(self):
"""
This function tells the rendezvous server that our node is ready to
accept connections from other nodes on the P2P network that run the
bootstrap function. It's only used when net_type == p2p
"""
# Advertise is disabled.
if not se... | python | def advertise(self):
"""
This function tells the rendezvous server that our node is ready to
accept connections from other nodes on the P2P network that run the
bootstrap function. It's only used when net_type == p2p
"""
# Advertise is disabled.
if not se... | [
"def",
"advertise",
"(",
"self",
")",
":",
"# Advertise is disabled.\r",
"if",
"not",
"self",
".",
"enable_advertise",
":",
"self",
".",
"debug_print",
"(",
"\"Advertise is disbled!\"",
")",
"return",
"None",
"# Direct net server is reserved for direct connections only.\r",... | This function tells the rendezvous server that our node is ready to
accept connections from other nodes on the P2P network that run the
bootstrap function. It's only used when net_type == p2p | [
"This",
"function",
"tells",
"the",
"rendezvous",
"server",
"that",
"our",
"node",
"is",
"ready",
"to",
"accept",
"connections",
"from",
"other",
"nodes",
"on",
"the",
"P2P",
"network",
"that",
"run",
"the",
"bootstrap",
"function",
".",
"It",
"s",
"only",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L562-L613 |
StorjOld/pyp2p | pyp2p/net.py | Net.determine_node | def determine_node(self):
"""
Determines the type of node based on a combination of forwarding
reachability and NAT type.
"""
# Manually set node_type as simultaneous.
if self.node_type == "simultaneous":
if self.nat_type != "unknown":
... | python | def determine_node(self):
"""
Determines the type of node based on a combination of forwarding
reachability and NAT type.
"""
# Manually set node_type as simultaneous.
if self.node_type == "simultaneous":
if self.nat_type != "unknown":
... | [
"def",
"determine_node",
"(",
"self",
")",
":",
"# Manually set node_type as simultaneous.\r",
"if",
"self",
".",
"node_type",
"==",
"\"simultaneous\"",
":",
"if",
"self",
".",
"nat_type",
"!=",
"\"unknown\"",
":",
"return",
"\"simultaneous\"",
"# Get IP of binding inte... | Determines the type of node based on a combination of forwarding
reachability and NAT type. | [
"Determines",
"the",
"type",
"of",
"node",
"based",
"on",
"a",
"combination",
"of",
"forwarding",
"reachability",
"and",
"NAT",
"type",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L615-L697 |
StorjOld/pyp2p | pyp2p/net.py | Net.start | def start(self):
"""
This function determines node and NAT type, saves connectivity details,
and starts any needed servers to be a part of the network. This is
usually the first function called after initialising the Net class.
"""
self.debug_print("Starting netwo... | python | def start(self):
"""
This function determines node and NAT type, saves connectivity details,
and starts any needed servers to be a part of the network. This is
usually the first function called after initialising the Net class.
"""
self.debug_print("Starting netwo... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"debug_print",
"(",
"\"Starting networking.\"",
")",
"self",
".",
"debug_print",
"(",
"\"Make sure to iterate over replies if you need\"",
"\" connection alive management!\"",
")",
"# Register a cnt + c handler\r",
"signal",... | This function determines node and NAT type, saves connectivity details,
and starts any needed servers to be a part of the network. This is
usually the first function called after initialising the Net class. | [
"This",
"function",
"determines",
"node",
"and",
"NAT",
"type",
"saves",
"connectivity",
"details",
"and",
"starts",
"any",
"needed",
"servers",
"to",
"be",
"a",
"part",
"of",
"the",
"network",
".",
"This",
"is",
"usually",
"the",
"first",
"function",
"calle... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L710-L795 |
StorjOld/pyp2p | pyp2p/net.py | Net.stop | def stop(self, signum=None, frame=None):
self.debug_print("Stopping networking.")
if self.passive is not None:
try:
self.passive.shutdown(1)
except:
pass
self.passive.close()
self.passive = None
if self.... | python | def stop(self, signum=None, frame=None):
self.debug_print("Stopping networking.")
if self.passive is not None:
try:
self.passive.shutdown(1)
except:
pass
self.passive.close()
self.passive = None
if self.... | [
"def",
"stop",
"(",
"self",
",",
"signum",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"self",
".",
"debug_print",
"(",
"\"Stopping networking.\"",
")",
"if",
"self",
".",
"passive",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"passive",
... | Just let the threads timeout by themselves.
Otherwise mutex deadlocks could occur.
for unl_thread in self.unl.unl_threads:
unl_thread.exit() | [
"Just",
"let",
"the",
"threads",
"timeout",
"by",
"themselves",
".",
"Otherwise",
"mutex",
"deadlocks",
"could",
"occur",
".",
"for",
"unl_thread",
"in",
"self",
".",
"unl",
".",
"unl_threads",
":",
"unl_thread",
".",
"exit",
"()"
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L797-L822 |
StorjOld/pyp2p | pyp2p/rendezvous_server.py | RendezvousProtocol.send_remote_port | def send_remote_port(self):
"""
Sends the remote port mapped for the connection.
This port is surprisingly often the same as the locally
bound port for an endpoint because a lot of NAT types
preserve the port.
"""
msg = "REMOTE TCP %s" % (str(self.transport... | python | def send_remote_port(self):
"""
Sends the remote port mapped for the connection.
This port is surprisingly often the same as the locally
bound port for an endpoint because a lot of NAT types
preserve the port.
"""
msg = "REMOTE TCP %s" % (str(self.transport... | [
"def",
"send_remote_port",
"(",
"self",
")",
":",
"msg",
"=",
"\"REMOTE TCP %s\"",
"%",
"(",
"str",
"(",
"self",
".",
"transport",
".",
"getPeer",
"(",
")",
".",
"port",
")",
")",
"self",
".",
"send_line",
"(",
"msg",
")"
] | Sends the remote port mapped for the connection.
This port is surprisingly often the same as the locally
bound port for an endpoint because a lot of NAT types
preserve the port. | [
"Sends",
"the",
"remote",
"port",
"mapped",
"for",
"the",
"connection",
".",
"This",
"port",
"is",
"surprisingly",
"often",
"the",
"same",
"as",
"the",
"locally",
"bound",
"port",
"for",
"an",
"endpoint",
"because",
"a",
"lot",
"of",
"NAT",
"types",
"prese... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L76-L84 |
StorjOld/pyp2p | pyp2p/rendezvous_server.py | RendezvousProtocol.cleanup_candidates | def cleanup_candidates(self, node_ip):
"""
Removes old TCP hole punching candidates for a
designated node if a certain amount of time has passed
since they last connected.
"""
if node_ip in self.factory.candidates:
old_candidates = []
for c... | python | def cleanup_candidates(self, node_ip):
"""
Removes old TCP hole punching candidates for a
designated node if a certain amount of time has passed
since they last connected.
"""
if node_ip in self.factory.candidates:
old_candidates = []
for c... | [
"def",
"cleanup_candidates",
"(",
"self",
",",
"node_ip",
")",
":",
"if",
"node_ip",
"in",
"self",
".",
"factory",
".",
"candidates",
":",
"old_candidates",
"=",
"[",
"]",
"for",
"candidate",
"in",
"self",
".",
"factory",
".",
"candidates",
"[",
"node_ip",... | Removes old TCP hole punching candidates for a
designated node if a certain amount of time has passed
since they last connected. | [
"Removes",
"old",
"TCP",
"hole",
"punching",
"candidates",
"for",
"a",
"designated",
"node",
"if",
"a",
"certain",
"amount",
"of",
"time",
"has",
"passed",
"since",
"they",
"last",
"connected",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L108-L122 |
StorjOld/pyp2p | pyp2p/rendezvous_server.py | RendezvousProtocol.propogate_candidates | def propogate_candidates(self, node_ip):
"""
Used to progate new candidates to passive simultaneous
nodes.
"""
if node_ip in self.factory.candidates:
old_candidates = []
for candidate in self.factory.candidates[node_ip]:
# Not con... | python | def propogate_candidates(self, node_ip):
"""
Used to progate new candidates to passive simultaneous
nodes.
"""
if node_ip in self.factory.candidates:
old_candidates = []
for candidate in self.factory.candidates[node_ip]:
# Not con... | [
"def",
"propogate_candidates",
"(",
"self",
",",
"node_ip",
")",
":",
"if",
"node_ip",
"in",
"self",
".",
"factory",
".",
"candidates",
":",
"old_candidates",
"=",
"[",
"]",
"for",
"candidate",
"in",
"self",
".",
"factory",
".",
"candidates",
"[",
"node_ip... | Used to progate new candidates to passive simultaneous
nodes. | [
"Used",
"to",
"progate",
"new",
"candidates",
"to",
"passive",
"simultaneous",
"nodes",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L124-L149 |
StorjOld/pyp2p | pyp2p/rendezvous_server.py | RendezvousProtocol.synchronize_simultaneous | def synchronize_simultaneous(self, node_ip):
"""
Because adjacent mappings for certain NAT types can
be stolen by other connections, the purpose of this
function is to ensure the last connection by a passive
simultaneous node is recent compared to the time for
a can... | python | def synchronize_simultaneous(self, node_ip):
"""
Because adjacent mappings for certain NAT types can
be stolen by other connections, the purpose of this
function is to ensure the last connection by a passive
simultaneous node is recent compared to the time for
a can... | [
"def",
"synchronize_simultaneous",
"(",
"self",
",",
"node_ip",
")",
":",
"for",
"candidate",
"in",
"self",
".",
"factory",
".",
"candidates",
"[",
"node_ip",
"]",
":",
"# Only if candidate is connected.\r",
"if",
"not",
"candidate",
"[",
"\"con\"",
"]",
".",
... | Because adjacent mappings for certain NAT types can
be stolen by other connections, the purpose of this
function is to ensure the last connection by a passive
simultaneous node is recent compared to the time for
a candidate to increase the chance that the precited
mappings r... | [
"Because",
"adjacent",
"mappings",
"for",
"certain",
"NAT",
"types",
"can",
"be",
"stolen",
"by",
"other",
"connections",
"the",
"purpose",
"of",
"this",
"function",
"is",
"to",
"ensure",
"the",
"last",
"connection",
"by",
"a",
"passive",
"simultaneous",
"node... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L151-L177 |
StorjOld/pyp2p | pyp2p/rendezvous_server.py | RendezvousProtocol.connectionLost | def connectionLost(self, reason):
"""
Mostly handles clean-up of node + candidate structures.
Avoids memory exhaustion for a large number of connections.
"""
try:
self.connected = False
if debug:
print(self.log_entry("CLOSED =", "no... | python | def connectionLost(self, reason):
"""
Mostly handles clean-up of node + candidate structures.
Avoids memory exhaustion for a large number of connections.
"""
try:
self.connected = False
if debug:
print(self.log_entry("CLOSED =", "no... | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
")",
":",
"try",
":",
"self",
".",
"connected",
"=",
"False",
"if",
"debug",
":",
"print",
"(",
"self",
".",
"log_entry",
"(",
"\"CLOSED =\"",
",",
"\"none\"",
")",
")",
"# Every five minutes: cleanup\r",
... | Mostly handles clean-up of node + candidate structures.
Avoids memory exhaustion for a large number of connections. | [
"Mostly",
"handles",
"clean",
"-",
"up",
"of",
"node",
"+",
"candidate",
"structures",
".",
"Avoids",
"memory",
"exhaustion",
"for",
"a",
"large",
"number",
"of",
"connections",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L197-L261 |
StorjOld/pyp2p | pyp2p/ipgetter.py | IPgetter.get_external_ip | def get_external_ip(self):
"""
This function gets your IP from a random server
"""
random.shuffle(self.server_list)
myip = ''
for server in self.server_list[:3]:
myip = self.fetch(server)
if myip != '':
return myip
... | python | def get_external_ip(self):
"""
This function gets your IP from a random server
"""
random.shuffle(self.server_list)
myip = ''
for server in self.server_list[:3]:
myip = self.fetch(server)
if myip != '':
return myip
... | [
"def",
"get_external_ip",
"(",
"self",
")",
":",
"random",
".",
"shuffle",
"(",
"self",
".",
"server_list",
")",
"myip",
"=",
"''",
"for",
"server",
"in",
"self",
".",
"server_list",
"[",
":",
"3",
"]",
":",
"myip",
"=",
"self",
".",
"fetch",
"(",
... | This function gets your IP from a random server | [
"This",
"function",
"gets",
"your",
"IP",
"from",
"a",
"random",
"server"
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/ipgetter.py#L109-L122 |
StorjOld/pyp2p | pyp2p/ipgetter.py | IPgetter.fetch | def fetch(self, server):
"""
This function gets your IP from a specific server
"""
t = None
socket_default_timeout = socket.getdefaulttimeout()
opener = urllib.build_opener()
opener.addheaders = [('User-agent',
"Mozilla/5.0 (X... | python | def fetch(self, server):
"""
This function gets your IP from a specific server
"""
t = None
socket_default_timeout = socket.getdefaulttimeout()
opener = urllib.build_opener()
opener.addheaders = [('User-agent',
"Mozilla/5.0 (X... | [
"def",
"fetch",
"(",
"self",
",",
"server",
")",
":",
"t",
"=",
"None",
"socket_default_timeout",
"=",
"socket",
".",
"getdefaulttimeout",
"(",
")",
"opener",
"=",
"urllib",
".",
"build_opener",
"(",
")",
"opener",
".",
"addheaders",
"=",
"[",
"(",
"'Use... | This function gets your IP from a specific server | [
"This",
"function",
"gets",
"your",
"IP",
"from",
"a",
"specific",
"server"
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/ipgetter.py#L129-L187 |
StorjOld/pyp2p | pyp2p/unl.py | UNL.connect_handler | def connect_handler(self, their_unl, events, force_master, hairpin, nonce):
# Figure out who should make the connection.
our_unl = self.value.encode("ascii")
their_unl = their_unl.encode("ascii")
master = self.is_master(their_unl)
"""
Master defines who connects i... | python | def connect_handler(self, their_unl, events, force_master, hairpin, nonce):
# Figure out who should make the connection.
our_unl = self.value.encode("ascii")
their_unl = their_unl.encode("ascii")
master = self.is_master(their_unl)
"""
Master defines who connects i... | [
"def",
"connect_handler",
"(",
"self",
",",
"their_unl",
",",
"events",
",",
"force_master",
",",
"hairpin",
",",
"nonce",
")",
":",
"# Figure out who should make the connection.\r",
"our_unl",
"=",
"self",
".",
"value",
".",
"encode",
"(",
"\"ascii\"",
")",
"th... | Master defines who connects if either side can. It's used to
eliminate having multiple connections with the same host. | [
"Master",
"defines",
"who",
"connects",
"if",
"either",
"side",
"can",
".",
"It",
"s",
"used",
"to",
"eliminate",
"having",
"multiple",
"connections",
"with",
"the",
"same",
"host",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/unl.py#L239-L373 |
StorjOld/pyp2p | pyp2p/unl.py | UNL.connect | def connect(self, their_unl, events, force_master=1, hairpin=1,
nonce="0" * 64):
"""
A new thread is spawned because many of the connection techniques
rely on sleep to determine connection outcome or to synchronise hole
punching techniques. If the sleep is in its own... | python | def connect(self, their_unl, events, force_master=1, hairpin=1,
nonce="0" * 64):
"""
A new thread is spawned because many of the connection techniques
rely on sleep to determine connection outcome or to synchronise hole
punching techniques. If the sleep is in its own... | [
"def",
"connect",
"(",
"self",
",",
"their_unl",
",",
"events",
",",
"force_master",
"=",
"1",
",",
"hairpin",
"=",
"1",
",",
"nonce",
"=",
"\"0\"",
"*",
"64",
")",
":",
"parms",
"=",
"(",
"their_unl",
",",
"events",
",",
"force_master",
",",
"hairpi... | A new thread is spawned because many of the connection techniques
rely on sleep to determine connection outcome or to synchronise hole
punching techniques. If the sleep is in its own thread it won't
block main execution. | [
"A",
"new",
"thread",
"is",
"spawned",
"because",
"many",
"of",
"the",
"connection",
"techniques",
"rely",
"on",
"sleep",
"to",
"determine",
"connection",
"outcome",
"or",
"to",
"synchronise",
"hole",
"punching",
"techniques",
".",
"If",
"the",
"sleep",
"is",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/unl.py#L375-L386 |
StorjOld/pyp2p | pyp2p/sys_clock.py | SysClock.calculate_clock_skew | def calculate_clock_skew(self):
"""
Computer average and standard deviation
using all the data points.
"""
n = self.statx_n(self.data_points)
"""
Required to be able to compute the standard
deviation.
"""
if n < 1:
return Decim... | python | def calculate_clock_skew(self):
"""
Computer average and standard deviation
using all the data points.
"""
n = self.statx_n(self.data_points)
"""
Required to be able to compute the standard
deviation.
"""
if n < 1:
return Decim... | [
"def",
"calculate_clock_skew",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"statx_n",
"(",
"self",
".",
"data_points",
")",
"\"\"\"\n Required to be able to compute the standard\n deviation.\n \"\"\"",
"if",
"n",
"<",
"1",
":",
"return",
"Decimal"... | Computer average and standard deviation
using all the data points. | [
"Computer",
"average",
"and",
"standard",
"deviation",
"using",
"all",
"the",
"data",
"points",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/sys_clock.py#L66-L132 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.attend_fight | def attend_fight(self, mappings, node_ip, predictions, ntp):
"""
This function is for starting and managing a fight
once the details are known. It also handles the
task of returning any valid connections (if any) that
may be returned from threads in the simultaneous_fight fu... | python | def attend_fight(self, mappings, node_ip, predictions, ntp):
"""
This function is for starting and managing a fight
once the details are known. It also handles the
task of returning any valid connections (if any) that
may be returned from threads in the simultaneous_fight fu... | [
"def",
"attend_fight",
"(",
"self",
",",
"mappings",
",",
"node_ip",
",",
"predictions",
",",
"ntp",
")",
":",
"# Bind listen server socket.\r",
"mappings",
"=",
"self",
".",
"add_listen_sock",
"(",
"mappings",
")",
"log",
".",
"debug",
"(",
"mappings",
")",
... | This function is for starting and managing a fight
once the details are known. It also handles the
task of returning any valid connections (if any) that
may be returned from threads in the simultaneous_fight function. | [
"This",
"function",
"is",
"for",
"starting",
"and",
"managing",
"a",
"fight",
"once",
"the",
"details",
"are",
"known",
".",
"It",
"also",
"handles",
"the",
"task",
"of",
"returning",
"any",
"valid",
"connections",
"(",
"if",
"any",
")",
"that",
"may",
"... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L139-L209 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.sequential_connect | def sequential_connect(self):
"""
Sequential connect is designed to return a connection to the
Rendezvous Server but it does so in a way that the local port
ranges (both for the server and used for subsequent hole
punching) are allocated sequentially and predictably. This is... | python | def sequential_connect(self):
"""
Sequential connect is designed to return a connection to the
Rendezvous Server but it does so in a way that the local port
ranges (both for the server and used for subsequent hole
punching) are allocated sequentially and predictably. This is... | [
"def",
"sequential_connect",
"(",
"self",
")",
":",
"# Connect to rendezvous server.\r",
"try",
":",
"mappings",
"=",
"sequential_bind",
"(",
"self",
".",
"mapping_no",
"+",
"1",
",",
"self",
".",
"interface",
")",
"con",
"=",
"self",
".",
"server_connect",
"(... | Sequential connect is designed to return a connection to the
Rendezvous Server but it does so in a way that the local port
ranges (both for the server and used for subsequent hole
punching) are allocated sequentially and predictably. This is
because Delta+1 type NATs only preserve th... | [
"Sequential",
"connect",
"is",
"designed",
"to",
"return",
"a",
"connection",
"to",
"the",
"Rendezvous",
"Server",
"but",
"it",
"does",
"so",
"in",
"a",
"way",
"that",
"the",
"local",
"port",
"ranges",
"(",
"both",
"for",
"the",
"server",
"and",
"used",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L211-L251 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.simultaneous_listen | def simultaneous_listen(self):
"""
This function is called by passive simultaneous nodes who
wish to establish themself as such. It sets up a connection
to the Rendezvous Server to monitor for new hole punching requests.
"""
# Close socket.
if self.server... | python | def simultaneous_listen(self):
"""
This function is called by passive simultaneous nodes who
wish to establish themself as such. It sets up a connection
to the Rendezvous Server to monitor for new hole punching requests.
"""
# Close socket.
if self.server... | [
"def",
"simultaneous_listen",
"(",
"self",
")",
":",
"# Close socket.\r",
"if",
"self",
".",
"server_con",
"is",
"not",
"None",
":",
"self",
".",
"server_con",
".",
"s",
".",
"close",
"(",
")",
"self",
".",
"server_con",
"=",
"None",
"# Reset predictions + m... | This function is called by passive simultaneous nodes who
wish to establish themself as such. It sets up a connection
to the Rendezvous Server to monitor for new hole punching requests. | [
"This",
"function",
"is",
"called",
"by",
"passive",
"simultaneous",
"nodes",
"who",
"wish",
"to",
"establish",
"themself",
"as",
"such",
".",
"It",
"sets",
"up",
"a",
"connection",
"to",
"the",
"Rendezvous",
"Server",
"to",
"monitor",
"for",
"new",
"hole",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L253-L286 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.predict_mappings | def predict_mappings(self, mappings):
"""
This function is used to predict the remote ports that a NAT
will map a local connection to. It requires the NAT type to
be determined before use. Current support for preserving and
delta type mapping behaviour.
"""
... | python | def predict_mappings(self, mappings):
"""
This function is used to predict the remote ports that a NAT
will map a local connection to. It requires the NAT type to
be determined before use. Current support for preserving and
delta type mapping behaviour.
"""
... | [
"def",
"predict_mappings",
"(",
"self",
",",
"mappings",
")",
":",
"if",
"self",
".",
"nat_type",
"not",
"in",
"self",
".",
"predictable_nats",
":",
"msg",
"=",
"\"Can't predict mappings for non-predictable NAT type.\"",
"raise",
"Exception",
"(",
"msg",
")",
"for... | This function is used to predict the remote ports that a NAT
will map a local connection to. It requires the NAT type to
be determined before use. Current support for preserving and
delta type mapping behaviour. | [
"This",
"function",
"is",
"used",
"to",
"predict",
"the",
"remote",
"ports",
"that",
"a",
"NAT",
"will",
"map",
"a",
"local",
"connection",
"to",
".",
"It",
"requires",
"the",
"NAT",
"type",
"to",
"be",
"determined",
"before",
"use",
".",
"Current",
"sup... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L298-L330 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.throw_punch | def throw_punch(self, args, tries=1):
"""
Attempt to open a hole by TCP hole punching. This
function is called by the simultaneous fight function
and its the code that handles doing the actual hole
punching / connecting.
"""
# Parse arguments.
if... | python | def throw_punch(self, args, tries=1):
"""
Attempt to open a hole by TCP hole punching. This
function is called by the simultaneous fight function
and its the code that handles doing the actual hole
punching / connecting.
"""
# Parse arguments.
if... | [
"def",
"throw_punch",
"(",
"self",
",",
"args",
",",
"tries",
"=",
"1",
")",
":",
"# Parse arguments.\r",
"if",
"len",
"(",
"args",
")",
"!=",
"3",
":",
"return",
"0",
"sock",
",",
"node_ip",
",",
"remote_port",
"=",
"args",
"if",
"sock",
"is",
"None... | Attempt to open a hole by TCP hole punching. This
function is called by the simultaneous fight function
and its the code that handles doing the actual hole
punching / connecting. | [
"Attempt",
"to",
"open",
"a",
"hole",
"by",
"TCP",
"hole",
"punching",
".",
"This",
"function",
"is",
"called",
"by",
"the",
"simultaneous",
"fight",
"function",
"and",
"its",
"the",
"code",
"that",
"handles",
"doing",
"the",
"actual",
"hole",
"punching",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L332-L396 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.simultaneous_fight | def simultaneous_fight(self, my_mappings, node_ip, predictions, origin_ntp):
"""
TCP hole punching algorithm. It uses network time servers to
synchronize two nodes to connect to each other on their
predicted remote ports at the exact same time.
One thing to note is how sen... | python | def simultaneous_fight(self, my_mappings, node_ip, predictions, origin_ntp):
"""
TCP hole punching algorithm. It uses network time servers to
synchronize two nodes to connect to each other on their
predicted remote ports at the exact same time.
One thing to note is how sen... | [
"def",
"simultaneous_fight",
"(",
"self",
",",
"my_mappings",
",",
"node_ip",
",",
"predictions",
",",
"origin_ntp",
")",
":",
"# Get current network time accurate to\r",
"# ~50 ms over WAN (apparently.)\r",
"p",
"=",
"request_priority_execution",
"(",
")",
"log",
".",
... | TCP hole punching algorithm. It uses network time servers to
synchronize two nodes to connect to each other on their
predicted remote ports at the exact same time.
One thing to note is how sensitive TCP hole punching is to
timing. To open a successful connection both sides need to
... | [
"TCP",
"hole",
"punching",
"algorithm",
".",
"It",
"uses",
"network",
"time",
"servers",
"to",
"synchronize",
"two",
"nodes",
"to",
"connect",
"to",
"each",
"other",
"on",
"their",
"predicted",
"remote",
"ports",
"at",
"the",
"exact",
"same",
"time",
".",
... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L398-L498 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.simultaneous_challenge | def simultaneous_challenge(self, node_ip, node_port, proto):
"""
Used by active simultaneous nodes to attempt to initiate
a simultaneous open to a compatible node after retrieving
its details from bootstrapping. The function advertises
itself as a potential candidate to the ... | python | def simultaneous_challenge(self, node_ip, node_port, proto):
"""
Used by active simultaneous nodes to attempt to initiate
a simultaneous open to a compatible node after retrieving
its details from bootstrapping. The function advertises
itself as a potential candidate to the ... | [
"def",
"simultaneous_challenge",
"(",
"self",
",",
"node_ip",
",",
"node_port",
",",
"proto",
")",
":",
"parts",
"=",
"self",
".",
"sequential_connect",
"(",
")",
"if",
"parts",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"\"Sequential connect failed\"",
")... | Used by active simultaneous nodes to attempt to initiate
a simultaneous open to a compatible node after retrieving
its details from bootstrapping. The function advertises
itself as a potential candidate to the server for the
designated node_ip. It also waits for a response from the
... | [
"Used",
"by",
"active",
"simultaneous",
"nodes",
"to",
"attempt",
"to",
"initiate",
"a",
"simultaneous",
"open",
"to",
"a",
"compatible",
"node",
"after",
"retrieving",
"its",
"details",
"from",
"bootstrapping",
".",
"The",
"function",
"advertises",
"itself",
"a... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L501-L542 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.parse_remote_port | def parse_remote_port(self, reply):
"""
Parses a remote port from a Rendezvous Server's
response.
"""
remote_port = re.findall("^REMOTE (TCP|UDP) ([0-9]+)$", reply)
if not len(remote_port):
remote_port = 0
else:
remote_port = int... | python | def parse_remote_port(self, reply):
"""
Parses a remote port from a Rendezvous Server's
response.
"""
remote_port = re.findall("^REMOTE (TCP|UDP) ([0-9]+)$", reply)
if not len(remote_port):
remote_port = 0
else:
remote_port = int... | [
"def",
"parse_remote_port",
"(",
"self",
",",
"reply",
")",
":",
"remote_port",
"=",
"re",
".",
"findall",
"(",
"\"^REMOTE (TCP|UDP) ([0-9]+)$\"",
",",
"reply",
")",
"if",
"not",
"len",
"(",
"remote_port",
")",
":",
"remote_port",
"=",
"0",
"else",
":",
"r... | Parses a remote port from a Rendezvous Server's
response. | [
"Parses",
"a",
"remote",
"port",
"from",
"a",
"Rendezvous",
"Server",
"s",
"response",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L544-L557 |
StorjOld/pyp2p | pyp2p/rendezvous_client.py | RendezvousClient.determine_nat | def determine_nat(self, return_instantly=1):
"""
This function can predict 4 types of NATS.
(Not adequately tested yet.)
1. Preserving.
Source port == remote port
2. Delta.
Remote port == source port + delta.
3. Delta+1
Same as delta but d... | python | def determine_nat(self, return_instantly=1):
"""
This function can predict 4 types of NATS.
(Not adequately tested yet.)
1. Preserving.
Source port == remote port
2. Delta.
Remote port == source port + delta.
3. Delta+1
Same as delta but d... | [
"def",
"determine_nat",
"(",
"self",
",",
"return_instantly",
"=",
"1",
")",
":",
"# Already set.\r",
"if",
"self",
".",
"nat_type",
"!=",
"\"unknown\"",
":",
"return",
"self",
".",
"nat_type",
"nat_type",
"=",
"\"random\"",
"# Check collision ration.\r",
"if",
... | This function can predict 4 types of NATS.
(Not adequately tested yet.)
1. Preserving.
Source port == remote port
2. Delta.
Remote port == source port + delta.
3. Delta+1
Same as delta but delta is only preserved when
the source port increments by ... | [
"This",
"function",
"can",
"predict",
"4",
"types",
"of",
"NATS",
".",
"(",
"Not",
"adequately",
"tested",
"yet",
".",
")",
"1",
".",
"Preserving",
".",
"Source",
"port",
"==",
"remote",
"port",
"2",
".",
"Delta",
".",
"Remote",
"port",
"==",
"source",... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L643-L786 |
StorjOld/pyp2p | pyp2p/lib.py | get_unused_port | def get_unused_port(port=None):
"""Checks if port is already in use."""
if port is None or port < 1024 or port > 65535:
port = random.randint(1024, 65535)
assert(1024 <= port <= 65535)
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('', ... | python | def get_unused_port(port=None):
"""Checks if port is already in use."""
if port is None or port < 1024 or port > 65535:
port = random.randint(1024, 65535)
assert(1024 <= port <= 65535)
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('', ... | [
"def",
"get_unused_port",
"(",
"port",
"=",
"None",
")",
":",
"if",
"port",
"is",
"None",
"or",
"port",
"<",
"1024",
"or",
"port",
">",
"65535",
":",
"port",
"=",
"random",
".",
"randint",
"(",
"1024",
",",
"65535",
")",
"assert",
"(",
"1024",
"<="... | Checks if port is already in use. | [
"Checks",
"if",
"port",
"is",
"already",
"in",
"use",
"."
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/lib.py#L27-L41 |
StorjOld/pyp2p | pyp2p/lib.py | get_lan_ip | def get_lan_ip(interface="default"):
if sys.version_info < (3, 0, 0):
if type(interface) == str:
interface = unicode(interface)
else:
if type(interface) == bytes:
interface = interface.decode("utf-8")
# Get ID of interface that handles WAN stuff.
default_gateway ... | python | def get_lan_ip(interface="default"):
if sys.version_info < (3, 0, 0):
if type(interface) == str:
interface = unicode(interface)
else:
if type(interface) == bytes:
interface = interface.decode("utf-8")
# Get ID of interface that handles WAN stuff.
default_gateway ... | [
"def",
"get_lan_ip",
"(",
"interface",
"=",
"\"default\"",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
",",
"0",
")",
":",
"if",
"type",
"(",
"interface",
")",
"==",
"str",
":",
"interface",
"=",
"unicode",
"(",
"interface",
... | Execution may reach here if the host is using
virtual interfaces on Linux and there are no gateways
which suggests the host is a VPS or server. In this
case | [
"Execution",
"may",
"reach",
"here",
"if",
"the",
"host",
"is",
"using",
"virtual",
"interfaces",
"on",
"Linux",
"and",
"there",
"are",
"no",
"gateways",
"which",
"suggests",
"the",
"host",
"is",
"a",
"VPS",
"or",
"server",
".",
"In",
"this",
"case"
] | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/lib.py#L179-L218 |
StorjOld/pyp2p | pyp2p/lib.py | get_wan_ip | def get_wan_ip(n=0):
"""
That IP module sucks. Occasionally it returns an IP address behind
cloudflare which probably happens when cloudflare tries to proxy your web
request because it thinks you're trying to DoS. It's better if we just run
our own infrastructure.
"""
if n == 2:
try... | python | def get_wan_ip(n=0):
"""
That IP module sucks. Occasionally it returns an IP address behind
cloudflare which probably happens when cloudflare tries to proxy your web
request because it thinks you're trying to DoS. It's better if we just run
our own infrastructure.
"""
if n == 2:
try... | [
"def",
"get_wan_ip",
"(",
"n",
"=",
"0",
")",
":",
"if",
"n",
"==",
"2",
":",
"try",
":",
"ip",
"=",
"myip",
"(",
")",
"ip",
"=",
"extract_ip",
"(",
"ip",
")",
"if",
"is_ip_valid",
"(",
"ip",
")",
":",
"return",
"ip",
"except",
"Exception",
"as... | That IP module sucks. Occasionally it returns an IP address behind
cloudflare which probably happens when cloudflare tries to proxy your web
request because it thinks you're trying to DoS. It's better if we just run
our own infrastructure. | [
"That",
"IP",
"module",
"sucks",
".",
"Occasionally",
"it",
"returns",
"an",
"IP",
"address",
"behind",
"cloudflare",
"which",
"probably",
"happens",
"when",
"cloudflare",
"tries",
"to",
"proxy",
"your",
"web",
"request",
"because",
"it",
"thinks",
"you",
"re"... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/lib.py#L378-L414 |
StorjOld/pyp2p | pyp2p/nat_pmp.py | get_gateway_addr | def get_gateway_addr():
"""Use netifaces to get the gateway address, if we can't import it then
fall back to a hack to obtain the current gateway automatically, since
Python has no interface to sysctl().
This may or may not be the gateway we should be contacting.
It does not guara... | python | def get_gateway_addr():
"""Use netifaces to get the gateway address, if we can't import it then
fall back to a hack to obtain the current gateway automatically, since
Python has no interface to sysctl().
This may or may not be the gateway we should be contacting.
It does not guara... | [
"def",
"get_gateway_addr",
"(",
")",
":",
"try",
":",
"import",
"netifaces",
"return",
"netifaces",
".",
"gateways",
"(",
")",
"[",
"\"default\"",
"]",
"[",
"netifaces",
".",
"AF_INET",
"]",
"[",
"0",
"]",
"except",
"ImportError",
":",
"shell_command",
"="... | Use netifaces to get the gateway address, if we can't import it then
fall back to a hack to obtain the current gateway automatically, since
Python has no interface to sysctl().
This may or may not be the gateway we should be contacting.
It does not guarantee correct results.
... | [
"Use",
"netifaces",
"to",
"get",
"the",
"gateway",
"address",
"if",
"we",
"can",
"t",
"import",
"it",
"then",
"fall",
"back",
"to",
"a",
"hack",
"to",
"obtain",
"the",
"current",
"gateway",
"automatically",
"since",
"Python",
"has",
"no",
"interface",
"to"... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/nat_pmp.py#L246-L279 |
StorjOld/pyp2p | pyp2p/nat_pmp.py | get_gateway_socket | def get_gateway_socket(gateway):
"""Takes a gateway address string and returns a non-blocking UDP
socket to communicate with its NAT-PMP implementation on
NATPMP_PORT.
e.g. addr = get_gateway_socket('10.0.1.1')
"""
if not gateway:
raise NATPMPNetworkError(NATPMP_... | python | def get_gateway_socket(gateway):
"""Takes a gateway address string and returns a non-blocking UDP
socket to communicate with its NAT-PMP implementation on
NATPMP_PORT.
e.g. addr = get_gateway_socket('10.0.1.1')
"""
if not gateway:
raise NATPMPNetworkError(NATPMP_... | [
"def",
"get_gateway_socket",
"(",
"gateway",
")",
":",
"if",
"not",
"gateway",
":",
"raise",
"NATPMPNetworkError",
"(",
"NATPMP_GATEWAY_NO_VALID_GATEWAY",
",",
"error_str",
"(",
"NATPMP_GATEWAY_NO_VALID_GATEWAY",
")",
")",
"response_socket",
"=",
"socket",
".",
"socke... | Takes a gateway address string and returns a non-blocking UDP
socket to communicate with its NAT-PMP implementation on
NATPMP_PORT.
e.g. addr = get_gateway_socket('10.0.1.1') | [
"Takes",
"a",
"gateway",
"address",
"string",
"and",
"returns",
"a",
"non",
"-",
"blocking",
"UDP",
"socket",
"to",
"communicate",
"with",
"its",
"NAT",
"-",
"PMP",
"implementation",
"on",
"NATPMP_PORT",
".",
"e",
".",
"g",
".",
"addr",
"=",
"get_gateway_s... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/nat_pmp.py#L292-L305 |
StorjOld/pyp2p | pyp2p/nat_pmp.py | get_public_address | def get_public_address(gateway_ip=None, retry=9):
"""A high-level function that returns the public interface IP of
the current host by querying the NAT-PMP gateway. IP is
returned as string.
Takes two possible keyword arguments:
gateway_ip - the IP to the NAT-PMP comp... | python | def get_public_address(gateway_ip=None, retry=9):
"""A high-level function that returns the public interface IP of
the current host by querying the NAT-PMP gateway. IP is
returned as string.
Takes two possible keyword arguments:
gateway_ip - the IP to the NAT-PMP comp... | [
"def",
"get_public_address",
"(",
"gateway_ip",
"=",
"None",
",",
"retry",
"=",
"9",
")",
":",
"if",
"gateway_ip",
"is",
"None",
":",
"gateway_ip",
"=",
"get_gateway_addr",
"(",
")",
"addr_request",
"=",
"PublicAddressRequest",
"(",
")",
"addr_response",
"=",
... | A high-level function that returns the public interface IP of
the current host by querying the NAT-PMP gateway. IP is
returned as string.
Takes two possible keyword arguments:
gateway_ip - the IP to the NAT-PMP compatible gateway.
Defaults to usin... | [
"A",
"high",
"-",
"level",
"function",
"that",
"returns",
"the",
"public",
"interface",
"IP",
"of",
"the",
"current",
"host",
"by",
"querying",
"the",
"NAT",
"-",
"PMP",
"gateway",
".",
"IP",
"is",
"returned",
"as",
"string",
".",
"Takes",
"two",
"possib... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/nat_pmp.py#L308-L335 |
StorjOld/pyp2p | pyp2p/nat_pmp.py | map_tcp_port | def map_tcp_port(public_port, private_port, lifetime=3600, gateway_ip=None,
retry=9, use_exception=True):
"""A high-level wrapper to map_port() that requests a mapping
for a public TCP port on the NAT to a private TCP port on this host.
Returns the complete response on success.
... | python | def map_tcp_port(public_port, private_port, lifetime=3600, gateway_ip=None,
retry=9, use_exception=True):
"""A high-level wrapper to map_port() that requests a mapping
for a public TCP port on the NAT to a private TCP port on this host.
Returns the complete response on success.
... | [
"def",
"map_tcp_port",
"(",
"public_port",
",",
"private_port",
",",
"lifetime",
"=",
"3600",
",",
"gateway_ip",
"=",
"None",
",",
"retry",
"=",
"9",
",",
"use_exception",
"=",
"True",
")",
":",
"return",
"map_port",
"(",
"NATPMP_PROTOCOL_TCP",
",",
"public_... | A high-level wrapper to map_port() that requests a mapping
for a public TCP port on the NAT to a private TCP port on this host.
Returns the complete response on success.
public_port - the public port of the mapping requested
private_port - the private port of the mappi... | [
"A",
"high",
"-",
"level",
"wrapper",
"to",
"map_port",
"()",
"that",
"requests",
"a",
"mapping",
"for",
"a",
"public",
"TCP",
"port",
"on",
"the",
"NAT",
"to",
"a",
"private",
"TCP",
"port",
"on",
"this",
"host",
".",
"Returns",
"the",
"complete",
"re... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/nat_pmp.py#L338-L358 |
StorjOld/pyp2p | pyp2p/nat_pmp.py | map_udp_port | def map_udp_port(public_port, private_port, lifetime=3600, gateway_ip=None,
retry=9, use_exception=True):
"""A high-level wrapper to map_port() that requests a mapping for
a public UDP port on the NAT to a private UDP port on this host.
Returns the complete response on success.
... | python | def map_udp_port(public_port, private_port, lifetime=3600, gateway_ip=None,
retry=9, use_exception=True):
"""A high-level wrapper to map_port() that requests a mapping for
a public UDP port on the NAT to a private UDP port on this host.
Returns the complete response on success.
... | [
"def",
"map_udp_port",
"(",
"public_port",
",",
"private_port",
",",
"lifetime",
"=",
"3600",
",",
"gateway_ip",
"=",
"None",
",",
"retry",
"=",
"9",
",",
"use_exception",
"=",
"True",
")",
":",
"return",
"map_port",
"(",
"NATPMP_PROTOCOL_UDP",
",",
"public_... | A high-level wrapper to map_port() that requests a mapping for
a public UDP port on the NAT to a private UDP port on this host.
Returns the complete response on success.
public_port - the public port of the mapping requested
private_port - the private port of the mappi... | [
"A",
"high",
"-",
"level",
"wrapper",
"to",
"map_port",
"()",
"that",
"requests",
"a",
"mapping",
"for",
"a",
"public",
"UDP",
"port",
"on",
"the",
"NAT",
"to",
"a",
"private",
"UDP",
"port",
"on",
"this",
"host",
".",
"Returns",
"the",
"complete",
"re... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/nat_pmp.py#L361-L381 |
StorjOld/pyp2p | pyp2p/nat_pmp.py | map_port | def map_port(protocol, public_port, private_port, lifetime=3600,
gateway_ip=None, retry=9, use_exception=True):
"""A function to map public_port to private_port of protocol.
Returns the complete response on success.
protocol - NATPMP_PROTOCOL_UDP or NATPMP_PROTOCOL_TCP
... | python | def map_port(protocol, public_port, private_port, lifetime=3600,
gateway_ip=None, retry=9, use_exception=True):
"""A function to map public_port to private_port of protocol.
Returns the complete response on success.
protocol - NATPMP_PROTOCOL_UDP or NATPMP_PROTOCOL_TCP
... | [
"def",
"map_port",
"(",
"protocol",
",",
"public_port",
",",
"private_port",
",",
"lifetime",
"=",
"3600",
",",
"gateway_ip",
"=",
"None",
",",
"retry",
"=",
"9",
",",
"use_exception",
"=",
"True",
")",
":",
"if",
"protocol",
"not",
"in",
"[",
"NATPMP_PR... | A function to map public_port to private_port of protocol.
Returns the complete response on success.
protocol - NATPMP_PROTOCOL_UDP or NATPMP_PROTOCOL_TCP
public_port - the public port of the mapping requested
private_port - the private port of the mapping request... | [
"A",
"function",
"to",
"map",
"public_port",
"to",
"private_port",
"of",
"protocol",
".",
"Returns",
"the",
"complete",
"response",
"on",
"success",
".",
"protocol",
"-",
"NATPMP_PROTOCOL_UDP",
"or",
"NATPMP_PROTOCOL_TCP",
"public_port",
"-",
"the",
"public",
"por... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/nat_pmp.py#L384-L418 |
StorjOld/pyp2p | pyp2p/upnp.py | UPnP.forward_port | def forward_port(self, proto, src_port, dest_ip, dest_port=None):
"""
Creates a new mapping for the default gateway to forward ports.
Source port is from the perspective of the original client.
For example, if a client tries to connect to us on port 80,
the source port is port 80... | python | def forward_port(self, proto, src_port, dest_ip, dest_port=None):
"""
Creates a new mapping for the default gateway to forward ports.
Source port is from the perspective of the original client.
For example, if a client tries to connect to us on port 80,
the source port is port 80... | [
"def",
"forward_port",
"(",
"self",
",",
"proto",
",",
"src_port",
",",
"dest_ip",
",",
"dest_port",
"=",
"None",
")",
":",
"proto",
"=",
"proto",
".",
"upper",
"(",
")",
"valid_protos",
"=",
"[",
"\"TCP\"",
",",
"\"UDP\"",
"]",
"if",
"proto",
"not",
... | Creates a new mapping for the default gateway to forward ports.
Source port is from the perspective of the original client.
For example, if a client tries to connect to us on port 80,
the source port is port 80. The destination port isn't
necessarily 80, however. We might wish to run our... | [
"Creates",
"a",
"new",
"mapping",
"for",
"the",
"default",
"gateway",
"to",
"forward",
"ports",
".",
"Source",
"port",
"is",
"from",
"the",
"perspective",
"of",
"the",
"original",
"client",
".",
"For",
"example",
"if",
"a",
"client",
"tries",
"to",
"connec... | train | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/upnp.py#L159-L238 |
gawel/aiocron | aiocron/__init__.py | Cron.start | def start(self):
"""Start scheduling"""
self.stop()
self.initialize()
self.handle = self.loop.call_at(self.get_next(), self.call_next) | python | def start(self):
"""Start scheduling"""
self.stop()
self.initialize()
self.handle = self.loop.call_at(self.get_next(), self.call_next) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"initialize",
"(",
")",
"self",
".",
"handle",
"=",
"self",
".",
"loop",
".",
"call_at",
"(",
"self",
".",
"get_next",
"(",
")",
",",
"self",
".",
"call_next",
")"... | Start scheduling | [
"Start",
"scheduling"
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L43-L47 |
gawel/aiocron | aiocron/__init__.py | Cron.stop | def stop(self):
"""Stop scheduling"""
if self.handle is not None:
self.handle.cancel()
self.handle = self.future = self.croniter = None | python | def stop(self):
"""Stop scheduling"""
if self.handle is not None:
self.handle.cancel()
self.handle = self.future = self.croniter = None | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
"is",
"not",
"None",
":",
"self",
".",
"handle",
".",
"cancel",
"(",
")",
"self",
".",
"handle",
"=",
"self",
".",
"future",
"=",
"self",
".",
"croniter",
"=",
"None"
] | Stop scheduling | [
"Stop",
"scheduling"
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L49-L53 |
gawel/aiocron | aiocron/__init__.py | Cron.next | def next(self, *args):
"""yield from .next()"""
self.initialize()
self.future = asyncio.Future(loop=self.loop)
self.handle = self.loop.call_at(self.get_next(), self.call_func, *args)
return self.future | python | def next(self, *args):
"""yield from .next()"""
self.initialize()
self.future = asyncio.Future(loop=self.loop)
self.handle = self.loop.call_at(self.get_next(), self.call_func, *args)
return self.future | [
"def",
"next",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"initialize",
"(",
")",
"self",
".",
"future",
"=",
"asyncio",
".",
"Future",
"(",
"loop",
"=",
"self",
".",
"loop",
")",
"self",
".",
"handle",
"=",
"self",
".",
"loop",
".",
... | yield from .next() | [
"yield",
"from",
".",
"next",
"()"
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L56-L61 |
gawel/aiocron | aiocron/__init__.py | Cron.initialize | def initialize(self):
"""Initialize croniter and related times"""
if self.croniter is None:
self.time = time.time()
self.datetime = datetime.now(self.tz)
self.loop_time = self.loop.time()
self.croniter = croniter(self.spec, start_time=self.datetime) | python | def initialize(self):
"""Initialize croniter and related times"""
if self.croniter is None:
self.time = time.time()
self.datetime = datetime.now(self.tz)
self.loop_time = self.loop.time()
self.croniter = croniter(self.spec, start_time=self.datetime) | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"croniter",
"is",
"None",
":",
"self",
".",
"time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"datetime",
"=",
"datetime",
".",
"now",
"(",
"self",
".",
"tz",
")",
"self",
".",... | Initialize croniter and related times | [
"Initialize",
"croniter",
"and",
"related",
"times"
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L63-L69 |
gawel/aiocron | aiocron/__init__.py | Cron.get_next | def get_next(self):
"""Return next iteration time related to loop time"""
return self.loop_time + (self.croniter.get_next(float) - self.time) | python | def get_next(self):
"""Return next iteration time related to loop time"""
return self.loop_time + (self.croniter.get_next(float) - self.time) | [
"def",
"get_next",
"(",
"self",
")",
":",
"return",
"self",
".",
"loop_time",
"+",
"(",
"self",
".",
"croniter",
".",
"get_next",
"(",
"float",
")",
"-",
"self",
".",
"time",
")"
] | Return next iteration time related to loop time | [
"Return",
"next",
"iteration",
"time",
"related",
"to",
"loop",
"time"
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L71-L73 |
gawel/aiocron | aiocron/__init__.py | Cron.call_next | def call_next(self):
"""Set next hop in the loop. Call task"""
if self.handle is not None:
self.handle.cancel()
next_time = self.get_next()
self.handle = self.loop.call_at(next_time, self.call_next)
self.call_func() | python | def call_next(self):
"""Set next hop in the loop. Call task"""
if self.handle is not None:
self.handle.cancel()
next_time = self.get_next()
self.handle = self.loop.call_at(next_time, self.call_next)
self.call_func() | [
"def",
"call_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
"is",
"not",
"None",
":",
"self",
".",
"handle",
".",
"cancel",
"(",
")",
"next_time",
"=",
"self",
".",
"get_next",
"(",
")",
"self",
".",
"handle",
"=",
"self",
".",
"loop",
... | Set next hop in the loop. Call task | [
"Set",
"next",
"hop",
"in",
"the",
"loop",
".",
"Call",
"task"
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L75-L81 |
gawel/aiocron | aiocron/__init__.py | Cron.call_func | def call_func(self, *args, **kwargs):
"""Called. Take care of exceptions using gather"""
asyncio.gather(
self.cron(*args, **kwargs),
loop=self.loop, return_exceptions=True
).add_done_callback(self.set_result) | python | def call_func(self, *args, **kwargs):
"""Called. Take care of exceptions using gather"""
asyncio.gather(
self.cron(*args, **kwargs),
loop=self.loop, return_exceptions=True
).add_done_callback(self.set_result) | [
"def",
"call_func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"asyncio",
".",
"gather",
"(",
"self",
".",
"cron",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"loop",
"=",
"self",
".",
"loop",
",",
"return_exceptio... | Called. Take care of exceptions using gather | [
"Called",
".",
"Take",
"care",
"of",
"exceptions",
"using",
"gather"
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L83-L88 |
gawel/aiocron | aiocron/__init__.py | Cron.set_result | def set_result(self, result):
"""Set future's result if needed (can be an exception).
Else raise if needed."""
result = result.result()[0]
if self.future is not None:
if isinstance(result, Exception):
self.future.set_exception(result)
else:
... | python | def set_result(self, result):
"""Set future's result if needed (can be an exception).
Else raise if needed."""
result = result.result()[0]
if self.future is not None:
if isinstance(result, Exception):
self.future.set_exception(result)
else:
... | [
"def",
"set_result",
"(",
"self",
",",
"result",
")",
":",
"result",
"=",
"result",
".",
"result",
"(",
")",
"[",
"0",
"]",
"if",
"self",
".",
"future",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"result",
",",
"Exception",
")",
":",
"self"... | Set future's result if needed (can be an exception).
Else raise if needed. | [
"Set",
"future",
"s",
"result",
"if",
"needed",
"(",
"can",
"be",
"an",
"exception",
")",
".",
"Else",
"raise",
"if",
"needed",
"."
] | train | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L90-L101 |
nicolas-van/docker-compose-wait | timeparse.py | timeparse | def timeparse(sval):
"""Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Arguments:
- `sval`: the stri... | python | def timeparse(sval):
"""Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Arguments:
- `sval`: the stri... | [
"def",
"timeparse",
"(",
"sval",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'\\s*'",
"+",
"TIMEFORMAT",
"+",
"r'\\s*$'",
",",
"sval",
",",
"re",
".",
"I",
")",
"if",
"not",
"match",
"or",
"not",
"match",
".",
"group",
"(",
"0",
")",
".",
... | Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Arguments:
- `sval`: the string value to parse
>>> ti... | [
"Parse",
"a",
"time",
"expression",
"returning",
"it",
"as",
"a",
"number",
"of",
"seconds",
".",
"If",
"possible",
"the",
"return",
"value",
"will",
"be",
"an",
"int",
";",
"if",
"this",
"is",
"not",
"possible",
"the",
"return",
"will",
"be",
"a",
"fl... | train | https://github.com/nicolas-van/docker-compose-wait/blob/86dab5c9f306ec73a7f9199ba244b47791e1ac73/timeparse.py#L68-L88 |
ppannuto/python-titlecase | titlecase/__init__.py | titlecase | def titlecase(text, callback=None, small_first_last=True):
"""
Titlecases input text
This filter changes all words to Title Caps, and attempts to be clever
about *un*capitalizing SMALL words like a/an/the in the input.
The list of "SMALL words" which are not capped comes from
the New York Time... | python | def titlecase(text, callback=None, small_first_last=True):
"""
Titlecases input text
This filter changes all words to Title Caps, and attempts to be clever
about *un*capitalizing SMALL words like a/an/the in the input.
The list of "SMALL words" which are not capped comes from
the New York Time... | [
"def",
"titlecase",
"(",
"text",
",",
"callback",
"=",
"None",
",",
"small_first_last",
"=",
"True",
")",
":",
"lines",
"=",
"re",
".",
"split",
"(",
"'[\\r\\n]+'",
",",
"text",
")",
"processed",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"all... | Titlecases input text
This filter changes all words to Title Caps, and attempts to be clever
about *un*capitalizing SMALL words like a/an/the in the input.
The list of "SMALL words" which are not capped comes from
the New York Times Manual of Style, plus 'vs' and 'v'. | [
"Titlecases",
"input",
"text"
] | train | https://github.com/ppannuto/python-titlecase/blob/9000878d917f88030807b1bcdc04a0c37f7001ee/titlecase/__init__.py#L66-L162 |
ppannuto/python-titlecase | titlecase/__init__.py | cmd | def cmd():
'''Handler for command line invocation'''
# Try to handle any reasonable thing thrown at this.
# Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout
# and treat any subsequent arguments as a space separated string to
# be titlecased (so it still works if people forget quote... | python | def cmd():
'''Handler for command line invocation'''
# Try to handle any reasonable thing thrown at this.
# Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout
# and treat any subsequent arguments as a space separated string to
# be titlecased (so it still works if people forget quote... | [
"def",
"cmd",
"(",
")",
":",
"# Try to handle any reasonable thing thrown at this.",
"# Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout",
"# and treat any subsequent arguments as a space separated string to",
"# be titlecased (so it still works if people forget quotes)",
"parser"... | Handler for command line invocation | [
"Handler",
"for",
"command",
"line",
"invocation"
] | train | https://github.com/ppannuto/python-titlecase/blob/9000878d917f88030807b1bcdc04a0c37f7001ee/titlecase/__init__.py#L165-L206 |
sobolevn/flake8-eradicate | flake8_eradicate.py | Checker.add_options | def add_options(cls, parser: OptionManager) -> None:
"""
``flake8`` api method to register new plugin options.
See :class:`.Configuration` docs for detailed options reference.
Arguments:
parser: ``flake8`` option parser instance.
"""
parser.add_option(
... | python | def add_options(cls, parser: OptionManager) -> None:
"""
``flake8`` api method to register new plugin options.
See :class:`.Configuration` docs for detailed options reference.
Arguments:
parser: ``flake8`` option parser instance.
"""
parser.add_option(
... | [
"def",
"add_options",
"(",
"cls",
",",
"parser",
":",
"OptionManager",
")",
"->",
"None",
":",
"parser",
".",
"add_option",
"(",
"'--eradicate-aggressive'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"(",
"'Enables aggressive mode for eradicate; '",
"'this ma... | ``flake8`` api method to register new plugin options.
See :class:`.Configuration` docs for detailed options reference.
Arguments:
parser: ``flake8`` option parser instance. | [
"flake8",
"api",
"method",
"to",
"register",
"new",
"plugin",
"options",
"."
] | train | https://github.com/sobolevn/flake8-eradicate/blob/0d992fae5dd3bd9014d79291a4f08b6da17d3031/flake8_eradicate.py#L52-L71 |
sobolevn/flake8-eradicate | flake8_eradicate.py | Checker.run | def run(self) -> Generator[Tuple[int, int, str, type], None, None]:
"""
Runs the checker.
``fix_file()`` only mutates the buffer object.
It is the only way to find out if some error happened.
"""
if self.filename != STDIN:
buffer = StringIO()
opti... | python | def run(self) -> Generator[Tuple[int, int, str, type], None, None]:
"""
Runs the checker.
``fix_file()`` only mutates the buffer object.
It is the only way to find out if some error happened.
"""
if self.filename != STDIN:
buffer = StringIO()
opti... | [
"def",
"run",
"(",
"self",
")",
"->",
"Generator",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"str",
",",
"type",
"]",
",",
"None",
",",
"None",
"]",
":",
"if",
"self",
".",
"filename",
"!=",
"STDIN",
":",
"buffer",
"=",
"StringIO",
"(",
")",
"... | Runs the checker.
``fix_file()`` only mutates the buffer object.
It is the only way to find out if some error happened. | [
"Runs",
"the",
"checker",
"."
] | train | https://github.com/sobolevn/flake8-eradicate/blob/0d992fae5dd3bd9014d79291a4f08b6da17d3031/flake8_eradicate.py#L78-L92 |
ssanderson/interface | interface/utils.py | unique | def unique(g):
"""
Yield values yielded by ``g``, removing any duplicates.
Example
-------
>>> list(unique(iter([1, 3, 1, 2, 3])))
[1, 3, 2]
"""
yielded = set()
for value in g:
if value not in yielded:
yield value
yielded.add(value) | python | def unique(g):
"""
Yield values yielded by ``g``, removing any duplicates.
Example
-------
>>> list(unique(iter([1, 3, 1, 2, 3])))
[1, 3, 2]
"""
yielded = set()
for value in g:
if value not in yielded:
yield value
yielded.add(value) | [
"def",
"unique",
"(",
"g",
")",
":",
"yielded",
"=",
"set",
"(",
")",
"for",
"value",
"in",
"g",
":",
"if",
"value",
"not",
"in",
"yielded",
":",
"yield",
"value",
"yielded",
".",
"add",
"(",
"value",
")"
] | Yield values yielded by ``g``, removing any duplicates.
Example
-------
>>> list(unique(iter([1, 3, 1, 2, 3])))
[1, 3, 2] | [
"Yield",
"values",
"yielded",
"by",
"g",
"removing",
"any",
"duplicates",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/utils.py#L6-L19 |
ssanderson/interface | interface/interface.py | static_get_type_attr | def static_get_type_attr(t, name):
"""
Get a type attribute statically, circumventing the descriptor protocol.
"""
for type_ in t.mro():
try:
return vars(type_)[name]
except KeyError:
pass
raise AttributeError(name) | python | def static_get_type_attr(t, name):
"""
Get a type attribute statically, circumventing the descriptor protocol.
"""
for type_ in t.mro():
try:
return vars(type_)[name]
except KeyError:
pass
raise AttributeError(name) | [
"def",
"static_get_type_attr",
"(",
"t",
",",
"name",
")",
":",
"for",
"type_",
"in",
"t",
".",
"mro",
"(",
")",
":",
"try",
":",
"return",
"vars",
"(",
"type_",
")",
"[",
"name",
"]",
"except",
"KeyError",
":",
"pass",
"raise",
"AttributeError",
"("... | Get a type attribute statically, circumventing the descriptor protocol. | [
"Get",
"a",
"type",
"attribute",
"statically",
"circumventing",
"the",
"descriptor",
"protocol",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L37-L46 |
ssanderson/interface | interface/interface.py | _conflicting_defaults | def _conflicting_defaults(typename, conflicts):
"""Format an error message for conflicting default implementations.
Parameters
----------
typename : str
Name of the type for which we're producing an error.
conflicts : dict[str -> list[Interface]]
Map from strings to interfaces provi... | python | def _conflicting_defaults(typename, conflicts):
"""Format an error message for conflicting default implementations.
Parameters
----------
typename : str
Name of the type for which we're producing an error.
conflicts : dict[str -> list[Interface]]
Map from strings to interfaces provi... | [
"def",
"_conflicting_defaults",
"(",
"typename",
",",
"conflicts",
")",
":",
"message",
"=",
"\"\\nclass {C} received conflicting default implementations:\"",
".",
"format",
"(",
"C",
"=",
"typename",
",",
")",
"for",
"attrname",
",",
"interfaces",
"in",
"conflicts",
... | Format an error message for conflicting default implementations.
Parameters
----------
typename : str
Name of the type for which we're producing an error.
conflicts : dict[str -> list[Interface]]
Map from strings to interfaces providing a default with that name.
Returns
-------... | [
"Format",
"an",
"error",
"message",
"for",
"conflicting",
"default",
"implementations",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L49-L77 |
ssanderson/interface | interface/interface.py | InterfaceMeta._diff_signatures | def _diff_signatures(self, type_):
"""
Diff our method signatures against the methods provided by type_.
Parameters
----------
type_ : type
The type to check.
Returns
-------
missing, mistyped, mismatched : list[str], dict[str -> type], dict[s... | python | def _diff_signatures(self, type_):
"""
Diff our method signatures against the methods provided by type_.
Parameters
----------
type_ : type
The type to check.
Returns
-------
missing, mistyped, mismatched : list[str], dict[str -> type], dict[s... | [
"def",
"_diff_signatures",
"(",
"self",
",",
"type_",
")",
":",
"missing",
"=",
"[",
"]",
"mistyped",
"=",
"{",
"}",
"mismatched",
"=",
"{",
"}",
"for",
"name",
",",
"iface_sig",
"in",
"self",
".",
"_signatures",
".",
"items",
"(",
")",
":",
"try",
... | Diff our method signatures against the methods provided by type_.
Parameters
----------
type_ : type
The type to check.
Returns
-------
missing, mistyped, mismatched : list[str], dict[str -> type], dict[str -> signature] # noqa
``missing`` is a l... | [
"Diff",
"our",
"method",
"signatures",
"against",
"the",
"methods",
"provided",
"by",
"type_",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L116-L153 |
ssanderson/interface | interface/interface.py | InterfaceMeta.verify | def verify(self, type_):
"""
Check whether a type implements ``self``.
Parameters
----------
type_ : type
The type to check.
Raises
------
TypeError
If ``type_`` doesn't conform to our interface.
Returns
-------
... | python | def verify(self, type_):
"""
Check whether a type implements ``self``.
Parameters
----------
type_ : type
The type to check.
Raises
------
TypeError
If ``type_`` doesn't conform to our interface.
Returns
-------
... | [
"def",
"verify",
"(",
"self",
",",
"type_",
")",
":",
"raw_missing",
",",
"mistyped",
",",
"mismatched",
"=",
"self",
".",
"_diff_signatures",
"(",
"type_",
")",
"# See if we have defaults for missing methods.",
"missing",
"=",
"[",
"]",
"defaults_to_use",
"=",
... | Check whether a type implements ``self``.
Parameters
----------
type_ : type
The type to check.
Raises
------
TypeError
If ``type_`` doesn't conform to our interface.
Returns
-------
None | [
"Check",
"whether",
"a",
"type",
"implements",
"self",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L155-L187 |
ssanderson/interface | interface/interface.py | InterfaceMeta._invalid_implementation | def _invalid_implementation(self, t, missing, mistyped, mismatched):
"""
Make a TypeError explaining why ``t`` doesn't implement our interface.
"""
assert missing or mistyped or mismatched, "Implementation wasn't invalid."
message = "\nclass {C} failed to implement interface {I}... | python | def _invalid_implementation(self, t, missing, mistyped, mismatched):
"""
Make a TypeError explaining why ``t`` doesn't implement our interface.
"""
assert missing or mistyped or mismatched, "Implementation wasn't invalid."
message = "\nclass {C} failed to implement interface {I}... | [
"def",
"_invalid_implementation",
"(",
"self",
",",
"t",
",",
"missing",
",",
"mistyped",
",",
"mismatched",
")",
":",
"assert",
"missing",
"or",
"mistyped",
"or",
"mismatched",
",",
"\"Implementation wasn't invalid.\"",
"message",
"=",
"\"\\nclass {C} failed to imple... | Make a TypeError explaining why ``t`` doesn't implement our interface. | [
"Make",
"a",
"TypeError",
"explaining",
"why",
"t",
"doesn",
"t",
"implement",
"our",
"interface",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L189-L231 |
ssanderson/interface | interface/interface.py | Interface.from_class | def from_class(cls, existing_class, subset=None, name=None):
"""Create an interface from an existing class.
Parameters
----------
existing_class : type
The type from which to extract an interface.
subset : list[str], optional
List of methods that should b... | python | def from_class(cls, existing_class, subset=None, name=None):
"""Create an interface from an existing class.
Parameters
----------
existing_class : type
The type from which to extract an interface.
subset : list[str], optional
List of methods that should b... | [
"def",
"from_class",
"(",
"cls",
",",
"existing_class",
",",
"subset",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"existing_class",
".",
"__name__",
"+",
"'Interface'",
"if",
"subset",
"is",
"None",
"... | Create an interface from an existing class.
Parameters
----------
existing_class : type
The type from which to extract an interface.
subset : list[str], optional
List of methods that should be included in the interface.
Default is to use all attribute... | [
"Create",
"an",
"interface",
"from",
"an",
"existing",
"class",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L319-L348 |
ssanderson/interface | interface/typecheck.py | compatible | def compatible(impl_sig, iface_sig):
"""
Check whether ``impl_sig`` is compatible with ``iface_sig``.
Parameters
----------
impl_sig : inspect.Signature
The signature of the implementation function.
iface_sig : inspect.Signature
The signature of the interface function.
In g... | python | def compatible(impl_sig, iface_sig):
"""
Check whether ``impl_sig`` is compatible with ``iface_sig``.
Parameters
----------
impl_sig : inspect.Signature
The signature of the implementation function.
iface_sig : inspect.Signature
The signature of the interface function.
In g... | [
"def",
"compatible",
"(",
"impl_sig",
",",
"iface_sig",
")",
":",
"return",
"all",
"(",
"[",
"positionals_compatible",
"(",
"takewhile",
"(",
"is_positional",
",",
"impl_sig",
".",
"parameters",
".",
"values",
"(",
")",
")",
",",
"takewhile",
"(",
"is_positi... | Check whether ``impl_sig`` is compatible with ``iface_sig``.
Parameters
----------
impl_sig : inspect.Signature
The signature of the implementation function.
iface_sig : inspect.Signature
The signature of the interface function.
In general, an implementation is compatible with an i... | [
"Check",
"whether",
"impl_sig",
"is",
"compatible",
"with",
"iface_sig",
"."
] | train | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/typecheck.py#L10-L49 |
ml31415/numpy-groupies | numpy_groupies/benchmarks/simple.py | aggregate_group_loop | def aggregate_group_loop(*args, **kwargs):
"""wraps func in lambda which prevents aggregate_numpy from
recognising and optimising it. Instead it groups and loops."""
func = kwargs['func']
del kwargs['func']
return aggregate_np(*args, func=lambda x: func(x), **kwargs) | python | def aggregate_group_loop(*args, **kwargs):
"""wraps func in lambda which prevents aggregate_numpy from
recognising and optimising it. Instead it groups and loops."""
func = kwargs['func']
del kwargs['func']
return aggregate_np(*args, func=lambda x: func(x), **kwargs) | [
"def",
"aggregate_group_loop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"kwargs",
"[",
"'func'",
"]",
"del",
"kwargs",
"[",
"'func'",
"]",
"return",
"aggregate_np",
"(",
"*",
"args",
",",
"func",
"=",
"lambda",
"x",
":",
"fun... | wraps func in lambda which prevents aggregate_numpy from
recognising and optimising it. Instead it groups and loops. | [
"wraps",
"func",
"in",
"lambda",
"which",
"prevents",
"aggregate_numpy",
"from",
"recognising",
"and",
"optimising",
"it",
".",
"Instead",
"it",
"groups",
"and",
"loops",
"."
] | train | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/benchmarks/simple.py#L14-L19 |
ml31415/numpy-groupies | numpy_groupies/aggregate_numba.py | step_count | def step_count(group_idx):
"""Return the amount of index changes within group_idx."""
cmp_pos = 0
steps = 1
if len(group_idx) < 1:
return 0
for i in range(len(group_idx)):
if group_idx[cmp_pos] != group_idx[i]:
cmp_pos = i
steps += 1
return steps | python | def step_count(group_idx):
"""Return the amount of index changes within group_idx."""
cmp_pos = 0
steps = 1
if len(group_idx) < 1:
return 0
for i in range(len(group_idx)):
if group_idx[cmp_pos] != group_idx[i]:
cmp_pos = i
steps += 1
return steps | [
"def",
"step_count",
"(",
"group_idx",
")",
":",
"cmp_pos",
"=",
"0",
"steps",
"=",
"1",
"if",
"len",
"(",
"group_idx",
")",
"<",
"1",
":",
"return",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"group_idx",
")",
")",
":",
"if",
"group_idx",
... | Return the amount of index changes within group_idx. | [
"Return",
"the",
"amount",
"of",
"index",
"changes",
"within",
"group_idx",
"."
] | train | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L445-L455 |
ml31415/numpy-groupies | numpy_groupies/aggregate_numba.py | step_indices | def step_indices(group_idx):
"""Return the edges of areas within group_idx, which are filled with the same value."""
ilen = step_count(group_idx) + 1
indices = np.empty(ilen, np.int64)
indices[0] = 0
indices[-1] = group_idx.size
cmp_pos = 0
ri = 1
for i in range(len(group_idx)):
... | python | def step_indices(group_idx):
"""Return the edges of areas within group_idx, which are filled with the same value."""
ilen = step_count(group_idx) + 1
indices = np.empty(ilen, np.int64)
indices[0] = 0
indices[-1] = group_idx.size
cmp_pos = 0
ri = 1
for i in range(len(group_idx)):
... | [
"def",
"step_indices",
"(",
"group_idx",
")",
":",
"ilen",
"=",
"step_count",
"(",
"group_idx",
")",
"+",
"1",
"indices",
"=",
"np",
".",
"empty",
"(",
"ilen",
",",
"np",
".",
"int64",
")",
"indices",
"[",
"0",
"]",
"=",
"0",
"indices",
"[",
"-",
... | Return the edges of areas within group_idx, which are filled with the same value. | [
"Return",
"the",
"edges",
"of",
"areas",
"within",
"group_idx",
"which",
"are",
"filled",
"with",
"the",
"same",
"value",
"."
] | train | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L459-L472 |
ml31415/numpy-groupies | numpy_groupies/aggregate_numba.py | AggregateOp.callable | def callable(cls, nans=False, reverse=False, scalar=False):
""" Compile a jitted function doing the hard part of the job """
_valgetter = cls._valgetter_scalar if scalar else cls._valgetter
valgetter = nb.njit(_valgetter)
outersetter = nb.njit(cls._outersetter)
_cls_inner = nb.n... | python | def callable(cls, nans=False, reverse=False, scalar=False):
""" Compile a jitted function doing the hard part of the job """
_valgetter = cls._valgetter_scalar if scalar else cls._valgetter
valgetter = nb.njit(_valgetter)
outersetter = nb.njit(cls._outersetter)
_cls_inner = nb.n... | [
"def",
"callable",
"(",
"cls",
",",
"nans",
"=",
"False",
",",
"reverse",
"=",
"False",
",",
"scalar",
"=",
"False",
")",
":",
"_valgetter",
"=",
"cls",
".",
"_valgetter_scalar",
"if",
"scalar",
"else",
"cls",
".",
"_valgetter",
"valgetter",
"=",
"nb",
... | Compile a jitted function doing the hard part of the job | [
"Compile",
"a",
"jitted",
"function",
"doing",
"the",
"hard",
"part",
"of",
"the",
"job"
] | train | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L91-L119 |
ml31415/numpy-groupies | numpy_groupies/aggregate_numba.py | AggregateGeneric.callable | def callable(self, nans=False):
"""Compile a jitted function and loop it over the sorted data."""
jitfunc = nb.njit(self.func, nogil=True)
def _loop(sortidx, group_idx, a, ret):
size = len(ret)
group_idx_srt = group_idx[sortidx]
a_srt = a[sortidx]
... | python | def callable(self, nans=False):
"""Compile a jitted function and loop it over the sorted data."""
jitfunc = nb.njit(self.func, nogil=True)
def _loop(sortidx, group_idx, a, ret):
size = len(ret)
group_idx_srt = group_idx[sortidx]
a_srt = a[sortidx]
... | [
"def",
"callable",
"(",
"self",
",",
"nans",
"=",
"False",
")",
":",
"jitfunc",
"=",
"nb",
".",
"njit",
"(",
"self",
".",
"func",
",",
"nogil",
"=",
"True",
")",
"def",
"_loop",
"(",
"sortidx",
",",
"group_idx",
",",
"a",
",",
"ret",
")",
":",
... | Compile a jitted function and loop it over the sorted data. | [
"Compile",
"a",
"jitted",
"function",
"and",
"loop",
"it",
"over",
"the",
"sorted",
"data",
"."
] | train | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L208-L226 |
ml31415/numpy-groupies | numpy_groupies/utils.py | get_aliasing | def get_aliasing(*extra):
"""The assembles the dict mapping strings and functions to the list of
supported function names:
e.g. alias['add'] = 'sum' and alias[sorted] = 'sort'
This funciton should only be called during import.
"""
alias = dict((k, k) for k in funcs_common)
alias.upd... | python | def get_aliasing(*extra):
"""The assembles the dict mapping strings and functions to the list of
supported function names:
e.g. alias['add'] = 'sum' and alias[sorted] = 'sort'
This funciton should only be called during import.
"""
alias = dict((k, k) for k in funcs_common)
alias.upd... | [
"def",
"get_aliasing",
"(",
"*",
"extra",
")",
":",
"alias",
"=",
"dict",
"(",
"(",
"k",
",",
"k",
")",
"for",
"k",
"in",
"funcs_common",
")",
"alias",
".",
"update",
"(",
"_alias_str",
")",
"alias",
".",
"update",
"(",
"(",
"fn",
",",
"fn",
")",... | The assembles the dict mapping strings and functions to the list of
supported function names:
e.g. alias['add'] = 'sum' and alias[sorted] = 'sort'
This funciton should only be called during import. | [
"The",
"assembles",
"the",
"dict",
"mapping",
"strings",
"and",
"functions",
"to",
"the",
"list",
"of",
"supported",
"function",
"names",
":",
"e",
".",
"g",
".",
"alias",
"[",
"add",
"]",
"=",
"sum",
"and",
"alias",
"[",
"sorted",
"]",
"=",
"sort",
... | train | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils.py#L95-L113 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.