id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1,900 | 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):
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 cells to ensure every row
# contains the same numb... | [
"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",
"."
] | 6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6 | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L63-L79 |
1,901 | 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):
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",
"."
] | 6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6 | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L81-L88 |
1,902 | 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):
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",
"."
] | 6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6 | https://github.com/torchbox/wagtail-markdown/blob/6e1c4457049b68e8bc7eb5a3b19830bff58dc6a6/wagtailmarkdown/mdx/tables/__init__.py#L94-L98 |
1,903 | 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():
static_dirs = set()
for finder in settings.STATICFILES_FINDERS:
finder = finders.get_finder(finder)
if hasattr(finder, 'storages'):
for storage in finder.storages.values():
static_dirs.add(storage.location)
if hasattr(finder, 'storage'... | [
"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"
] | e7bfdaa354e9c9189db0e4ba4fa049045adad91b | https://github.com/kottenator/django-compressor-toolkit/blob/e7bfdaa354e9c9189db0e4ba4fa049045adad91b/compressor_toolkit/precompilers.py#L13-L31 |
1,904 | 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):
if self.infile is None and "{infile}" in self.command:
if self.filename is None:
self.infile = NamedTemporaryFile(mode='wb', suffix=self.infile_ext)
self.infile.write(self.content.encode(self.default_encoding))
self.infile.fl... | [
"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",
"."
] | e7bfdaa354e9c9189db0e4ba4fa049045adad91b | https://github.com/kottenator/django-compressor-toolkit/blob/e7bfdaa354e9c9189db0e4ba4fa049045adad91b/compressor_toolkit/precompilers.py#L38-L53 |
1,905 | 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... | 8c18830db4beda30204f5fd4450bc96eb39b0feb | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L13-L23 |
1,906 | 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"
] | 8c18830db4beda30204f5fd4450bc96eb39b0feb | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L349-L353 |
1,907 | 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"
] | 8c18830db4beda30204f5fd4450bc96eb39b0feb | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L355-L358 |
1,908 | 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"
] | 8c18830db4beda30204f5fd4450bc96eb39b0feb | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/RamGraphDB.py#L362-L367 |
1,909 | 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"
] | 8c18830db4beda30204f5fd4450bc96eb39b0feb | https://github.com/CodyKochmann/graphdb/blob/8c18830db4beda30204f5fd4450bc96eb39b0feb/graphdb/SQLiteGraphDB.py#L309-L313 |
1,910 | 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"):
buf_len = len(self.buf)
replies = []
reply = b""
chop = 0
skip = 0
i = 0
buf_len = len(self.buf)
for i in range(0, buf_len):
ch = self.buf[i:i + 1]
if skip:
skip -= 1
... | [
"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",
... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/sock.py#L221-L267 |
1,911 | 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"):
# Socket is disconnected.
if not self.connected:
return
# Recv chunks until network buffer is empty.
repeat = 1
wait = 0.2
chunk_no = 0
max_buf = self.max_buf
max_chunks = self.max_ch... | [
"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",
... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/sock.py#L270-L369 |
1,912 | 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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L330-L373 |
1,913 | 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):
# Disable bootstrap.
if not self.enable_bootstrap:
return None
# Avoid raping the rendezvous server.
t = time.time()
if self.last_bootstrap is not None:
if t - self.last_bootstrap <= rendezvous_interval:
self.... | [
"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",
"... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L481-L560 |
1,914 | 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):
# Advertise is disabled.
if not self.enable_advertise:
self.debug_print("Advertise is disbled!")
return None
# Direct net server is reserved for direct connections only.
if self.net_type == "direct" and self.node_type == "passive":
... | [
"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",
... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L562-L613 |
1,915 | 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):
# Manually set node_type as simultaneous.
if self.node_type == "simultaneous":
if self.nat_type != "unknown":
return "simultaneous"
# Get IP of binding interface.
unspecific_bind = ["0.0.0.0", "127.0.0.1", "localhost"]
... | [
"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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L615-L697 |
1,916 | 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):
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
signal.signal(signal.SIGINT, self.stop)
# Save WAN IP.
... | [
"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... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/net.py#L710-L795 |
1,917 | 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):
msg = "REMOTE TCP %s" % (str(self.transport.getPeer().port))
self.send_line(msg) | [
"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... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L76-L84 |
1,918 | 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):
if node_ip in self.factory.candidates:
old_candidates = []
for candidate in self.factory.candidates[node_ip]:
elapsed = int(time.time() - candidate["time"])
if elapsed > self.challege_timeout:
... | [
"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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L108-L122 |
1,919 | 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):
if node_ip in self.factory.candidates:
old_candidates = []
for candidate in self.factory.candidates[node_ip]:
# Not connected.
if not candidate["con"].connected:
continue
... | [
"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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L124-L149 |
1,920 | 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):
for candidate in self.factory.candidates[node_ip]:
# Only if candidate is connected.
if not candidate["con"].connected:
continue
# Synchronise simultaneous node.
if candidate["time"] -\
... | [
"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... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L151-L177 |
1,921 | 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):
try:
self.connected = False
if debug:
print(self.log_entry("CLOSED =", "none"))
# Every five minutes: cleanup
t = time.time()
if time.time() - self.factory.last_cleanup >= self.cleanup:
... | [
"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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_server.py#L197-L261 |
1,922 | 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):
random.shuffle(self.server_list)
myip = ''
for server in self.server_list[:3]:
myip = self.fetch(server)
if myip != '':
return myip
else:
continue
return '' | [
"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"
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/ipgetter.py#L109-L122 |
1,923 | 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):
t = None
socket_default_timeout = socket.getdefaulttimeout()
opener = urllib.build_opener()
opener.addheaders = [('User-agent',
"Mozilla/5.0 (X11; Linux x86_64; rv:24.0)"
" Gecko/20100101 Firefox/2... | [
"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"
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/ipgetter.py#L129-L187 |
1,924 | 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):
parms = (their_unl, events, force_master, hairpin, nonce)
t = Thread(target=self.connect_handler, args=parms)
t.start()
self.unl_threads.append(t) | [
"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",
... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/unl.py#L375-L386 |
1,925 | 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):
n = self.statx_n(self.data_points)
"""
Required to be able to compute the standard
deviation.
"""
if n < 1:
return Decimal("0")
avg = self.statx_avg(self.data_points)
sdev = self.statx_sdev(self.data_points)
... | [
"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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/sys_clock.py#L66-L132 |
1,926 | 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):
# Close socket.
if self.server_con is not None:
self.server_con.s.close()
self.server_con = None
# Reset predictions + mappings.
self.mappings = None
self.predictions = None
# Connect to rendezvous 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",
... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L253-L286 |
1,927 | 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):
if self.nat_type not in self.predictable_nats:
msg = "Can't predict mappings for non-predictable NAT type."
raise Exception(msg)
for mapping in mappings:
mapping["bound"] = mapping["sock"].getsockname()[1]
if... | [
"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... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L298-L330 |
1,928 | 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):
remote_port = re.findall("^REMOTE (TCP|UDP) ([0-9]+)$", reply)
if not len(remote_port):
remote_port = 0
else:
remote_port = int(remote_port[0][1])
if remote_port < 1 or remote_port > 65535:
remote_port... | [
"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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/rendezvous_client.py#L544-L557 |
1,929 | 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):
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(('', port)) # Try to open port
except so... | [
"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",
"."
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/lib.py#L27-L41 |
1,930 | 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"
] | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/lib.py#L179-L218 |
1,931 | 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):
if n == 2:
try:
ip = myip()
ip = extract_ip(ip)
if is_ip_valid(ip):
return ip
except Exception as e:
print(str(e))
return None
# Fail-safe: use centralized server for IP lookup.
from pyp2p.net i... | [
"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"... | 7024208c3af20511496a652ff212f54c420e0464 | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/lib.py#L378-L414 |
1,932 | 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):
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"
] | 949870b2f7fe1e10e4220f3243c9d4237255d203 | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L63-L69 |
1,933 | 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 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"
] | 949870b2f7fe1e10e4220f3243c9d4237255d203 | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L71-L73 |
1,934 | 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):
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"
] | 949870b2f7fe1e10e4220f3243c9d4237255d203 | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L75-L81 |
1,935 | 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):
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"
] | 949870b2f7fe1e10e4220f3243c9d4237255d203 | https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L83-L88 |
1,936 | 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"
] | 9000878d917f88030807b1bcdc04a0c37f7001ee | https://github.com/ppannuto/python-titlecase/blob/9000878d917f88030807b1bcdc04a0c37f7001ee/titlecase/__init__.py#L165-L206 |
1,937 | 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:
parser.add_option(
'--eradicate-aggressive',
default=False,
help=(
'Enables aggressive mode for eradicate; '
'this may result in false positives'
),
action='store_true... | [
"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",
"."
] | 0d992fae5dd3bd9014d79291a4f08b6da17d3031 | https://github.com/sobolevn/flake8-eradicate/blob/0d992fae5dd3bd9014d79291a4f08b6da17d3031/flake8_eradicate.py#L52-L71 |
1,938 | 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]:
if self.filename != STDIN:
buffer = StringIO()
options = _Options(aggressive=self.options.eradicate_aggressive)
fix_file(self.filename, options, buffer)
traceback = buffer.getvalue()
... | [
"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",
"."
] | 0d992fae5dd3bd9014d79291a4f08b6da17d3031 | https://github.com/sobolevn/flake8-eradicate/blob/0d992fae5dd3bd9014d79291a4f08b6da17d3031/flake8_eradicate.py#L78-L92 |
1,939 | 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):
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",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/utils.py#L6-L19 |
1,940 | 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):
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",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L37-L46 |
1,941 | 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):
message = "\nclass {C} received conflicting default implementations:".format(
C=typename,
)
for attrname, interfaces in conflicts.items():
message += dedent(
"""
The following interfaces provided default implementations... | [
"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",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L49-L77 |
1,942 | 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_):
missing = []
mistyped = {}
mismatched = {}
for name, iface_sig in self._signatures.items():
try:
# Don't invoke the descriptor protocol here so that we get
# staticmethod/classmethod/property objects instead o... | [
"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_",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L116-L153 |
1,943 | 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_):
raw_missing, mistyped, mismatched = self._diff_signatures(type_)
# See if we have defaults for missing methods.
missing = []
defaults_to_use = {}
for name in raw_missing:
try:
defaults_to_use[name] = self._defaults[name].imple... | [
"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",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L155-L187 |
1,944 | 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):
assert missing or mistyped or mismatched, "Implementation wasn't invalid."
message = "\nclass {C} failed to implement interface {I}:".format(
C=getname(t),
I=getname(self),
)
if missing:
... | [
"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",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L189-L231 |
1,945 | 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):
if name is None:
name = existing_class.__name__ + 'Interface'
if subset is None:
subset = set(dir(existing_class)) - TRIVIAL_CLASS_ATTRIBUTES
return InterfaceMeta(
name,
(Interface,),
... | [
"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",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/interface.py#L319-L348 |
1,946 | 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):
return all([
positionals_compatible(
takewhile(is_positional, impl_sig.parameters.values()),
takewhile(is_positional, iface_sig.parameters.values()),
),
keywords_compatible(
valfilter(complement(is_positional), impl_sig... | [
"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",
"."
] | b1dabab8556848fd473e388e28399886321b6127 | https://github.com/ssanderson/interface/blob/b1dabab8556848fd473e388e28399886321b6127/interface/typecheck.py#L10-L49 |
1,947 | 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):
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",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L445-L455 |
1,948 | 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):
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)):
if group_idx[cmp_pos] != group_idx[i]:
cmp_pos = i
indices[ri] = i
... | [
"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",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L459-L472 |
1,949 | 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):
_valgetter = cls._valgetter_scalar if scalar else cls._valgetter
valgetter = nb.njit(_valgetter)
outersetter = nb.njit(cls._outersetter)
_cls_inner = nb.njit(cls._inner)
if nans:
def _inner(ri, val, ret, cou... | [
"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"
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L91-L119 |
1,950 | 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):
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]
indices = step_indices(group_idx_srt)
for i in range(len(ind... | [
"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",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numba.py#L208-L226 |
1,951 | ml31415/numpy-groupies | numpy_groupies/utils.py | get_func | def get_func(func, aliasing, implementations):
""" Return the key of a found implementation or the func itself """
try:
func_str = aliasing[func]
except KeyError:
if callable(func):
return func
else:
if func_str in implementations:
return func_str
... | python | def get_func(func, aliasing, implementations):
try:
func_str = aliasing[func]
except KeyError:
if callable(func):
return func
else:
if func_str in implementations:
return func_str
if func_str.startswith('nan') and \
func_str[3:] in func... | [
"def",
"get_func",
"(",
"func",
",",
"aliasing",
",",
"implementations",
")",
":",
"try",
":",
"func_str",
"=",
"aliasing",
"[",
"func",
"]",
"except",
"KeyError",
":",
"if",
"callable",
"(",
"func",
")",
":",
"return",
"func",
"else",
":",
"if",
"func... | Return the key of a found implementation or the func itself | [
"Return",
"the",
"key",
"of",
"a",
"found",
"implementation",
"or",
"the",
"func",
"itself"
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils.py#L118-L134 |
1,952 | ml31415/numpy-groupies | numpy_groupies/utils_numpy.py | minimum_dtype | def minimum_dtype(x, dtype=np.bool_):
"""returns the "most basic" dtype which represents `x` properly, which
provides at least the same value range as the specified dtype."""
def check_type(x, dtype):
try:
converted = dtype.type(x)
except (ValueError, OverflowError):
... | python | def minimum_dtype(x, dtype=np.bool_):
def check_type(x, dtype):
try:
converted = dtype.type(x)
except (ValueError, OverflowError):
return False
# False if some overflow has happened
return converted == x or np.isnan(x)
def type_loop(x, dtype, dtype_dict, ... | [
"def",
"minimum_dtype",
"(",
"x",
",",
"dtype",
"=",
"np",
".",
"bool_",
")",
":",
"def",
"check_type",
"(",
"x",
",",
"dtype",
")",
":",
"try",
":",
"converted",
"=",
"dtype",
".",
"type",
"(",
"x",
")",
"except",
"(",
"ValueError",
",",
"Overflow... | returns the "most basic" dtype which represents `x` properly, which
provides at least the same value range as the specified dtype. | [
"returns",
"the",
"most",
"basic",
"dtype",
"which",
"represents",
"x",
"properly",
"which",
"provides",
"at",
"least",
"the",
"same",
"value",
"range",
"as",
"the",
"specified",
"dtype",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/utils_numpy.py#L60-L90 |
1,953 | ml31415/numpy-groupies | numpy_groupies/aggregate_numpy.py | _array | def _array(group_idx, a, size, fill_value, dtype=None):
"""groups a into separate arrays, keeping the order intact."""
if fill_value is not None and not (np.isscalar(fill_value) or
len(fill_value) == 0):
raise ValueError("fill_value must be None, a scalar or an emp... | python | def _array(group_idx, a, size, fill_value, dtype=None):
if fill_value is not None and not (np.isscalar(fill_value) or
len(fill_value) == 0):
raise ValueError("fill_value must be None, a scalar or an empty "
"sequence")
order_group_idx = np.... | [
"def",
"_array",
"(",
"group_idx",
",",
"a",
",",
"size",
",",
"fill_value",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"fill_value",
"is",
"not",
"None",
"and",
"not",
"(",
"np",
".",
"isscalar",
"(",
"fill_value",
")",
"or",
"len",
"(",
"fill_value... | groups a into separate arrays, keeping the order intact. | [
"groups",
"a",
"into",
"separate",
"arrays",
"keeping",
"the",
"order",
"intact",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L188-L200 |
1,954 | ml31415/numpy-groupies | numpy_groupies/aggregate_numpy.py | _generic_callable | def _generic_callable(group_idx, a, size, fill_value, dtype=None,
func=lambda g: g, **kwargs):
"""groups a by inds, and then applies foo to each group in turn, placing
the results in an array."""
groups = _array(group_idx, a, size, ())
ret = np.full(size, fill_value, dtype=dtype or... | python | def _generic_callable(group_idx, a, size, fill_value, dtype=None,
func=lambda g: g, **kwargs):
groups = _array(group_idx, a, size, ())
ret = np.full(size, fill_value, dtype=dtype or np.float64)
for i, grp in enumerate(groups):
if np.ndim(grp) == 1 and len(grp) > 0:
... | [
"def",
"_generic_callable",
"(",
"group_idx",
",",
"a",
",",
"size",
",",
"fill_value",
",",
"dtype",
"=",
"None",
",",
"func",
"=",
"lambda",
"g",
":",
"g",
",",
"*",
"*",
"kwargs",
")",
":",
"groups",
"=",
"_array",
"(",
"group_idx",
",",
"a",
",... | groups a by inds, and then applies foo to each group in turn, placing
the results in an array. | [
"groups",
"a",
"by",
"inds",
"and",
"then",
"applies",
"foo",
"to",
"each",
"group",
"in",
"turn",
"placing",
"the",
"results",
"in",
"an",
"array",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L203-L213 |
1,955 | ml31415/numpy-groupies | numpy_groupies/aggregate_numpy.py | _cumsum | def _cumsum(group_idx, a, size, fill_value=None, dtype=None):
"""
N to N aggregate operation of cumsum. Perform cumulative sum for each group.
group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1])
a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8])
_cumsum(group_idx, a, ... | python | def _cumsum(group_idx, a, size, fill_value=None, dtype=None):
sortidx = np.argsort(group_idx, kind='mergesort')
invsortidx = np.argsort(sortidx, kind='mergesort')
group_idx_srt = group_idx[sortidx]
a_srt = a[sortidx]
a_srt_cumsum = np.cumsum(a_srt, dtype=dtype)
increasing = np.arange(len(a), d... | [
"def",
"_cumsum",
"(",
"group_idx",
",",
"a",
",",
"size",
",",
"fill_value",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"sortidx",
"=",
"np",
".",
"argsort",
"(",
"group_idx",
",",
"kind",
"=",
"'mergesort'",
")",
"invsortidx",
"=",
"np",
"."... | N to N aggregate operation of cumsum. Perform cumulative sum for each group.
group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1])
a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8])
_cumsum(group_idx, a, np.max(group_idx) + 1)
>>> array([ 3, 4, 5, 6, 15, 9, 15, 22, 7, ... | [
"N",
"to",
"N",
"aggregate",
"operation",
"of",
"cumsum",
".",
"Perform",
"cumulative",
"sum",
"for",
"each",
"group",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L216-L235 |
1,956 | ml31415/numpy-groupies | numpy_groupies/aggregate_numpy.py | _fill_untouched | def _fill_untouched(idx, ret, fill_value):
"""any elements of ret not indexed by idx are set to fill_value."""
untouched = np.ones_like(ret, dtype=bool)
untouched[idx] = False
ret[untouched] = fill_value | python | def _fill_untouched(idx, ret, fill_value):
untouched = np.ones_like(ret, dtype=bool)
untouched[idx] = False
ret[untouched] = fill_value | [
"def",
"_fill_untouched",
"(",
"idx",
",",
"ret",
",",
"fill_value",
")",
":",
"untouched",
"=",
"np",
".",
"ones_like",
"(",
"ret",
",",
"dtype",
"=",
"bool",
")",
"untouched",
"[",
"idx",
"]",
"=",
"False",
"ret",
"[",
"untouched",
"]",
"=",
"fill_... | any elements of ret not indexed by idx are set to fill_value. | [
"any",
"elements",
"of",
"ret",
"not",
"indexed",
"by",
"idx",
"are",
"set",
"to",
"fill_value",
"."
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy.py#L296-L300 |
1,957 | ml31415/numpy-groupies | numpy_groupies/aggregate_numpy_ufunc.py | _prod | def _prod(group_idx, a, size, fill_value, dtype=None):
"""Same as aggregate_numpy.py"""
dtype = minimum_dtype_scalar(fill_value, dtype, a)
ret = np.full(size, fill_value, dtype=dtype)
if fill_value != 1:
ret[group_idx] = 1 # product should start from 1
np.multiply.at(ret, group_idx, a)
... | python | def _prod(group_idx, a, size, fill_value, dtype=None):
dtype = minimum_dtype_scalar(fill_value, dtype, a)
ret = np.full(size, fill_value, dtype=dtype)
if fill_value != 1:
ret[group_idx] = 1 # product should start from 1
np.multiply.at(ret, group_idx, a)
return ret | [
"def",
"_prod",
"(",
"group_idx",
",",
"a",
",",
"size",
",",
"fill_value",
",",
"dtype",
"=",
"None",
")",
":",
"dtype",
"=",
"minimum_dtype_scalar",
"(",
"fill_value",
",",
"dtype",
",",
"a",
")",
"ret",
"=",
"np",
".",
"full",
"(",
"size",
",",
... | Same as aggregate_numpy.py | [
"Same",
"as",
"aggregate_numpy",
".",
"py"
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_numpy_ufunc.py#L50-L57 |
1,958 | ml31415/numpy-groupies | numpy_groupies/aggregate_weave.py | c_func | def c_func(funcname, reverse=False, nans=False, scalar=False):
""" Fill c_funcs with constructed code from the templates """
varnames = ['group_idx', 'a', 'ret', 'counter']
codebase = c_base_reverse if reverse else c_base
iteration = c_iter_scalar[funcname] if scalar else c_iter[funcname]
if scalar:... | python | def c_func(funcname, reverse=False, nans=False, scalar=False):
varnames = ['group_idx', 'a', 'ret', 'counter']
codebase = c_base_reverse if reverse else c_base
iteration = c_iter_scalar[funcname] if scalar else c_iter[funcname]
if scalar:
varnames.remove('a')
return codebase % dict(init=c_in... | [
"def",
"c_func",
"(",
"funcname",
",",
"reverse",
"=",
"False",
",",
"nans",
"=",
"False",
",",
"scalar",
"=",
"False",
")",
":",
"varnames",
"=",
"[",
"'group_idx'",
",",
"'a'",
",",
"'ret'",
",",
"'counter'",
"]",
"codebase",
"=",
"c_base_reverse",
"... | Fill c_funcs with constructed code from the templates | [
"Fill",
"c_funcs",
"with",
"constructed",
"code",
"from",
"the",
"templates"
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_weave.py#L154-L163 |
1,959 | ml31415/numpy-groupies | numpy_groupies/aggregate_weave.py | step_indices | def step_indices(group_idx):
""" Get the edges of areas within group_idx, which are filled
with the same value
"""
ilen = step_count(group_idx) + 1
indices = np.empty(ilen, int)
indices[0] = 0
indices[-1] = group_idx.size
inline(c_step_indices, ['group_idx', 'indices'], define_macro... | python | def step_indices(group_idx):
ilen = step_count(group_idx) + 1
indices = np.empty(ilen, int)
indices[0] = 0
indices[-1] = group_idx.size
inline(c_step_indices, ['group_idx', 'indices'], define_macros=c_macros, extra_compile_args=c_args)
return indices | [
"def",
"step_indices",
"(",
"group_idx",
")",
":",
"ilen",
"=",
"step_count",
"(",
"group_idx",
")",
"+",
"1",
"indices",
"=",
"np",
".",
"empty",
"(",
"ilen",
",",
"int",
")",
"indices",
"[",
"0",
"]",
"=",
"0",
"indices",
"[",
"-",
"1",
"]",
"=... | Get the edges of areas within group_idx, which are filled
with the same value | [
"Get",
"the",
"edges",
"of",
"areas",
"within",
"group_idx",
"which",
"are",
"filled",
"with",
"the",
"same",
"value"
] | 0911e9c59b14e11319e82d0876056ad2a17e6568 | https://github.com/ml31415/numpy-groupies/blob/0911e9c59b14e11319e82d0876056ad2a17e6568/numpy_groupies/aggregate_weave.py#L212-L221 |
1,960 | takuti/flurs | flurs/utils/projection.py | RandomProjection.__create_proj_mat | def __create_proj_mat(self, size):
"""Create a random projection matrix
[1] D. Achlioptas. Database-friendly random projections: Johnson-Lindenstrauss with binary coins.
[2] P. Li, et al. Very sparse random projections.
http://scikit-learn.org/stable/modules/random_projection.html#spar... | python | def __create_proj_mat(self, size):
# [1]
# return np.random.choice([-np.sqrt(3), 0, np.sqrt(3)], size=size, p=[1 / 6, 2 / 3, 1 / 6])
# [2]
s = 1 / self.density
return np.random.choice([-np.sqrt(s / self.k), 0, np.sqrt(s / self.k)],
size=size,
... | [
"def",
"__create_proj_mat",
"(",
"self",
",",
"size",
")",
":",
"# [1]",
"# return np.random.choice([-np.sqrt(3), 0, np.sqrt(3)], size=size, p=[1 / 6, 2 / 3, 1 / 6])",
"# [2]",
"s",
"=",
"1",
"/",
"self",
".",
"density",
"return",
"np",
".",
"random",
".",
"choice",
"... | Create a random projection matrix
[1] D. Achlioptas. Database-friendly random projections: Johnson-Lindenstrauss with binary coins.
[2] P. Li, et al. Very sparse random projections.
http://scikit-learn.org/stable/modules/random_projection.html#sparse-random-projection | [
"Create",
"a",
"random",
"projection",
"matrix"
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/projection.py#L72-L88 |
1,961 | takuti/flurs | flurs/datasets/movielens.py | load_ratings | def load_ratings(data_home, size):
"""Load all samples in the dataset.
"""
if size == '100k':
with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines()))
elif size == '1m':
with ... | python | def load_ratings(data_home, size):
if size == '100k':
with open(os.path.join(data_home, 'u.data'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: list(map(int, l.rstrip().split('\t'))), f.readlines()))
elif size == '1m':
with open(os.path.join(data_home, 'ratings.dat'), enco... | [
"def",
"load_ratings",
"(",
"data_home",
",",
"size",
")",
":",
"if",
"size",
"==",
"'100k'",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_home",
",",
"'u.data'",
")",
",",
"encoding",
"=",
"'ISO-8859-1'",
")",
"as",
"f",
":",... | Load all samples in the dataset. | [
"Load",
"all",
"samples",
"in",
"the",
"dataset",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L127-L148 |
1,962 | takuti/flurs | flurs/utils/feature_hash.py | n_feature_hash | def n_feature_hash(feature, dims, seeds):
"""N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns:
numpy 1d a... | python | def n_feature_hash(feature, dims, seeds):
vec = np.zeros(sum(dims))
offset = 0
for seed, dim in zip(seeds, dims):
vec[offset:(offset + dim)] = feature_hash(feature, dim, seed)
offset += dim
return vec | [
"def",
"n_feature_hash",
"(",
"feature",
",",
"dims",
",",
"seeds",
")",
":",
"vec",
"=",
"np",
".",
"zeros",
"(",
"sum",
"(",
"dims",
")",
")",
"offset",
"=",
"0",
"for",
"seed",
",",
"dim",
"in",
"zip",
"(",
"seeds",
",",
"dims",
")",
":",
"v... | N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns:
numpy 1d array: n-hot-encoded feature vector for `s`. | [
"N",
"-",
"hot",
"-",
"encoded",
"feature",
"hashing",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/feature_hash.py#L5-L24 |
1,963 | takuti/flurs | flurs/utils/feature_hash.py | feature_hash | def feature_hash(feature, dim, seed=123):
"""Feature hashing.
Args:
feature (str): Target feature represented as string.
dim (int): Number of dimensions for a hash value.
seed (float): Seed of a MurmurHash3 hash function.
Returns:
numpy 1d array: one-hot-encoded feature vec... | python | def feature_hash(feature, dim, seed=123):
vec = np.zeros(dim)
i = mmh3.hash(feature, seed) % dim
vec[i] = 1
return vec | [
"def",
"feature_hash",
"(",
"feature",
",",
"dim",
",",
"seed",
"=",
"123",
")",
":",
"vec",
"=",
"np",
".",
"zeros",
"(",
"dim",
")",
"i",
"=",
"mmh3",
".",
"hash",
"(",
"feature",
",",
"seed",
")",
"%",
"dim",
"vec",
"[",
"i",
"]",
"=",
"1"... | Feature hashing.
Args:
feature (str): Target feature represented as string.
dim (int): Number of dimensions for a hash value.
seed (float): Seed of a MurmurHash3 hash function.
Returns:
numpy 1d array: one-hot-encoded feature vector for `s`. | [
"Feature",
"hashing",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/feature_hash.py#L27-L42 |
1,964 | takuti/flurs | flurs/utils/metric.py | count_true_positive | def count_true_positive(truth, recommend):
"""Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives.
"""
tp = 0
... | python | def count_true_positive(truth, recommend):
tp = 0
for r in recommend:
if r in truth:
tp += 1
return tp | [
"def",
"count_true_positive",
"(",
"truth",
",",
"recommend",
")",
":",
"tp",
"=",
"0",
"for",
"r",
"in",
"recommend",
":",
"if",
"r",
"in",
"truth",
":",
"tp",
"+=",
"1",
"return",
"tp"
] | Count number of true positives from given sets of samples.
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
int: Number of true positives. | [
"Count",
"number",
"of",
"true",
"positives",
"from",
"given",
"sets",
"of",
"samples",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/utils/metric.py#L4-L19 |
1,965 | takuti/flurs | flurs/base.py | RecommenderMixin.initialize | def initialize(self, *args):
"""Initialize a recommender by resetting stored users and items.
"""
# number of observed users
self.n_user = 0
# store user data
self.users = {}
# number of observed items
self.n_item = 0
# store item data
s... | python | def initialize(self, *args):
# number of observed users
self.n_user = 0
# store user data
self.users = {}
# number of observed items
self.n_item = 0
# store item data
self.items = {} | [
"def",
"initialize",
"(",
"self",
",",
"*",
"args",
")",
":",
"# number of observed users",
"self",
".",
"n_user",
"=",
"0",
"# store user data",
"self",
".",
"users",
"=",
"{",
"}",
"# number of observed items",
"self",
".",
"n_item",
"=",
"0",
"# store item ... | Initialize a recommender by resetting stored users and items. | [
"Initialize",
"a",
"recommender",
"by",
"resetting",
"stored",
"users",
"and",
"items",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L11-L24 |
1,966 | takuti/flurs | flurs/base.py | RecommenderMixin.register_user | def register_user(self, user):
"""For new users, append their information into the dictionaries.
Args:
user (User): User.
"""
self.users[user.index] = {'known_items': set()}
self.n_user += 1 | python | def register_user(self, user):
self.users[user.index] = {'known_items': set()}
self.n_user += 1 | [
"def",
"register_user",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"users",
"[",
"user",
".",
"index",
"]",
"=",
"{",
"'known_items'",
":",
"set",
"(",
")",
"}",
"self",
".",
"n_user",
"+=",
"1"
] | For new users, append their information into the dictionaries.
Args:
user (User): User. | [
"For",
"new",
"users",
"append",
"their",
"information",
"into",
"the",
"dictionaries",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L45-L53 |
1,967 | takuti/flurs | flurs/base.py | RecommenderMixin.scores2recos | def scores2recos(self, scores, candidates, rev=False):
"""Get recommendation list for a user u_index based on scores.
Args:
scores (numpy array; (n_target_items,)):
Scores for the target items. Smaller score indicates a promising item.
candidates (numpy array; (#... | python | def scores2recos(self, scores, candidates, rev=False):
sorted_indices = np.argsort(scores)
if rev:
sorted_indices = sorted_indices[::-1]
return candidates[sorted_indices], scores[sorted_indices] | [
"def",
"scores2recos",
"(",
"self",
",",
"scores",
",",
"candidates",
",",
"rev",
"=",
"False",
")",
":",
"sorted_indices",
"=",
"np",
".",
"argsort",
"(",
"scores",
")",
"if",
"rev",
":",
"sorted_indices",
"=",
"sorted_indices",
"[",
":",
":",
"-",
"1... | Get recommendation list for a user u_index based on scores.
Args:
scores (numpy array; (n_target_items,)):
Scores for the target items. Smaller score indicates a promising item.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are con... | [
"Get",
"recommendation",
"list",
"for",
"a",
"user",
"u_index",
"based",
"on",
"scores",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/base.py#L115-L133 |
1,968 | takuti/flurs | flurs/evaluator.py | Evaluator.fit | def fit(self, train_events, test_events, n_epoch=1):
"""Train a model using the first 30% positive events to avoid cold-start.
Evaluation of this batch training is done by using the next 20% positive events.
After the batch SGD training, the models are incrementally updated by using the 20% tes... | python | def fit(self, train_events, test_events, n_epoch=1):
# make initial status for batch training
for e in train_events:
self.__validate(e)
self.rec.users[e.user.index]['known_items'].add(e.item.index)
self.item_buffer.append(e.item.index)
# for batch evaluation,... | [
"def",
"fit",
"(",
"self",
",",
"train_events",
",",
"test_events",
",",
"n_epoch",
"=",
"1",
")",
":",
"# make initial status for batch training",
"for",
"e",
"in",
"train_events",
":",
"self",
".",
"__validate",
"(",
"e",
")",
"self",
".",
"rec",
".",
"u... | Train a model using the first 30% positive events to avoid cold-start.
Evaluation of this batch training is done by using the next 20% positive events.
After the batch SGD training, the models are incrementally updated by using the 20% test events.
Args:
train_events (list of Event... | [
"Train",
"a",
"model",
"using",
"the",
"first",
"30%",
"positive",
"events",
"to",
"avoid",
"cold",
"-",
"start",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L35-L64 |
1,969 | takuti/flurs | flurs/evaluator.py | Evaluator.__batch_update | def __batch_update(self, train_events, test_events, n_epoch):
"""Batch update called by the fitting method.
Args:
train_events (list of Event): Positive training events.
test_events (list of Event): Test events.
n_epoch (int): Number of epochs for the batch training.... | python | def __batch_update(self, train_events, test_events, n_epoch):
for epoch in range(n_epoch):
# SGD requires us to shuffle events in each iteration
# * if n_epoch == 1
# => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
if n_... | [
"def",
"__batch_update",
"(",
"self",
",",
"train_events",
",",
"test_events",
",",
"n_epoch",
")",
":",
"for",
"epoch",
"in",
"range",
"(",
"n_epoch",
")",
":",
"# SGD requires us to shuffle events in each iteration",
"# * if n_epoch == 1",
"# => shuffle is not require... | Batch update called by the fitting method.
Args:
train_events (list of Event): Positive training events.
test_events (list of Event): Test events.
n_epoch (int): Number of epochs for the batch training. | [
"Batch",
"update",
"called",
"by",
"the",
"fitting",
"method",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L126-L149 |
1,970 | takuti/flurs | flurs/evaluator.py | Evaluator.__batch_evaluate | def __batch_evaluate(self, test_events):
"""Evaluate the current model by using the given test events.
Args:
test_events (list of Event): Current model is evaluated by these events.
Returns:
float: Mean Percentile Rank for the test set.
"""
percentiles ... | python | def __batch_evaluate(self, test_events):
percentiles = np.zeros(len(test_events))
all_items = set(self.item_buffer)
for i, e in enumerate(test_events):
# check if the data allows users to interact the same items repeatedly
unobserved = all_items
if not self.... | [
"def",
"__batch_evaluate",
"(",
"self",
",",
"test_events",
")",
":",
"percentiles",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"test_events",
")",
")",
"all_items",
"=",
"set",
"(",
"self",
".",
"item_buffer",
")",
"for",
"i",
",",
"e",
"in",
"enumerat... | Evaluate the current model by using the given test events.
Args:
test_events (list of Event): Current model is evaluated by these events.
Returns:
float: Mean Percentile Rank for the test set. | [
"Evaluate",
"the",
"current",
"model",
"by",
"using",
"the",
"given",
"test",
"events",
"."
] | a998fc180b45db7eaf38dbbbf8125a93100b8a8c | https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/evaluator.py#L151-L180 |
1,971 | linkedin/asciietch | asciietch/graph.py | Grapher._scale_x_values | def _scale_x_values(self, values, max_width):
'''Scale X values to new width'''
if type(values) == dict:
values = self._scale_x_values_timestamps(values=values, max_width=max_width)
adjusted_values = list(values)
if len(adjusted_values) > max_width:
def get_pos... | python | def _scale_x_values(self, values, max_width):
'''Scale X values to new width'''
if type(values) == dict:
values = self._scale_x_values_timestamps(values=values, max_width=max_width)
adjusted_values = list(values)
if len(adjusted_values) > max_width:
def get_pos... | [
"def",
"_scale_x_values",
"(",
"self",
",",
"values",
",",
"max_width",
")",
":",
"if",
"type",
"(",
"values",
")",
"==",
"dict",
":",
"values",
"=",
"self",
".",
"_scale_x_values_timestamps",
"(",
"values",
"=",
"values",
",",
"max_width",
"=",
"max_width... | Scale X values to new width | [
"Scale",
"X",
"values",
"to",
"new",
"width"
] | 33499e9b1c5226c04078d08a210ef657c630291c | https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L11-L25 |
1,972 | linkedin/asciietch | asciietch/graph.py | Grapher._scale_x_values_timestamps | def _scale_x_values_timestamps(self, values, max_width):
'''Scale X values to new width based on timestamps'''
first_timestamp = float(values[0][0])
last_timestamp = float(values[-1][0])
step_size = (last_timestamp - first_timestamp) / max_width
values_by_column = [[] for i in r... | python | def _scale_x_values_timestamps(self, values, max_width):
'''Scale X values to new width based on timestamps'''
first_timestamp = float(values[0][0])
last_timestamp = float(values[-1][0])
step_size = (last_timestamp - first_timestamp) / max_width
values_by_column = [[] for i in r... | [
"def",
"_scale_x_values_timestamps",
"(",
"self",
",",
"values",
",",
"max_width",
")",
":",
"first_timestamp",
"=",
"float",
"(",
"values",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"last_timestamp",
"=",
"float",
"(",
"values",
"[",
"-",
"1",
"]",
"[",
"0",... | Scale X values to new width based on timestamps | [
"Scale",
"X",
"values",
"to",
"new",
"width",
"based",
"on",
"timestamps"
] | 33499e9b1c5226c04078d08a210ef657c630291c | https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L27-L44 |
1,973 | linkedin/asciietch | asciietch/graph.py | Grapher._scale_y_values | def _scale_y_values(self, values, new_min, new_max, scale_old_from_zero=True):
'''
Take values and transmute them into a new range
'''
# Scale Y values - Create a scaled list of values to use for the visual graph
scaled_values = []
y_min_value = min(values)
if sca... | python | def _scale_y_values(self, values, new_min, new_max, scale_old_from_zero=True):
'''
Take values and transmute them into a new range
'''
# Scale Y values - Create a scaled list of values to use for the visual graph
scaled_values = []
y_min_value = min(values)
if sca... | [
"def",
"_scale_y_values",
"(",
"self",
",",
"values",
",",
"new_min",
",",
"new_max",
",",
"scale_old_from_zero",
"=",
"True",
")",
":",
"# Scale Y values - Create a scaled list of values to use for the visual graph",
"scaled_values",
"=",
"[",
"]",
"y_min_value",
"=",
... | Take values and transmute them into a new range | [
"Take",
"values",
"and",
"transmute",
"them",
"into",
"a",
"new",
"range"
] | 33499e9b1c5226c04078d08a210ef657c630291c | https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L46-L62 |
1,974 | linkedin/asciietch | asciietch/graph.py | Grapher._assign_ascii_character | def _assign_ascii_character(self, y_prev, y, y_next): # noqa for complexity
'''Assign the character to be placed into the graph'''
char = '?'
if y_next > y and y_prev > y:
char = '-'
elif y_next < y and y_prev < y:
char = '-'
e... | python | def _assign_ascii_character(self, y_prev, y, y_next): # noqa for complexity
'''Assign the character to be placed into the graph'''
char = '?'
if y_next > y and y_prev > y:
char = '-'
elif y_next < y and y_prev < y:
char = '-'
e... | [
"def",
"_assign_ascii_character",
"(",
"self",
",",
"y_prev",
",",
"y",
",",
"y_next",
")",
":",
"# noqa for complexity",
"char",
"=",
"'?'",
"if",
"y_next",
">",
"y",
"and",
"y_prev",
">",
"y",
":",
"char",
"=",
"'-'",
"elif",
"y_next",
"<",
"y",
"and... | Assign the character to be placed into the graph | [
"Assign",
"the",
"character",
"to",
"be",
"placed",
"into",
"the",
"graph"
] | 33499e9b1c5226c04078d08a210ef657c630291c | https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L97-L120 |
1,975 | linkedin/asciietch | asciietch/graph.py | Grapher.asciigraph | def asciigraph(self, values=None, max_height=None, max_width=None, label=False):
'''
Accepts a list of y values and returns an ascii graph
Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example.
'''
... | python | def asciigraph(self, values=None, max_height=None, max_width=None, label=False):
'''
Accepts a list of y values and returns an ascii graph
Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example.
'''
... | [
"def",
"asciigraph",
"(",
"self",
",",
"values",
"=",
"None",
",",
"max_height",
"=",
"None",
",",
"max_width",
"=",
"None",
",",
"label",
"=",
"False",
")",
":",
"result",
"=",
"''",
"border_fill_char",
"=",
"'*'",
"start_ctime",
"=",
"None",
"end_ctime... | Accepts a list of y values and returns an ascii graph
Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example. | [
"Accepts",
"a",
"list",
"of",
"y",
"values",
"and",
"returns",
"an",
"ascii",
"graph",
"Optionally",
"values",
"can",
"also",
"be",
"a",
"dictionary",
"with",
"a",
"key",
"of",
"timestamp",
"and",
"a",
"value",
"of",
"value",
".",
"InGraphs",
"returns",
... | 33499e9b1c5226c04078d08a210ef657c630291c | https://github.com/linkedin/asciietch/blob/33499e9b1c5226c04078d08a210ef657c630291c/asciietch/graph.py#L133-L192 |
1,976 | HPAC/matchpy | matchpy/functions.py | replace | def replace(expression: Expression, position: Sequence[int], replacement: Replacement) -> Replacement:
r"""Replaces the subexpression of `expression` at the given `position` with the given `replacement`.
The original `expression` itself is not modified, but a modified copy is returned. If the replacement
i... | python | def replace(expression: Expression, position: Sequence[int], replacement: Replacement) -> Replacement:
r"""Replaces the subexpression of `expression` at the given `position` with the given `replacement`.
The original `expression` itself is not modified, but a modified copy is returned. If the replacement
i... | [
"def",
"replace",
"(",
"expression",
":",
"Expression",
",",
"position",
":",
"Sequence",
"[",
"int",
"]",
",",
"replacement",
":",
"Replacement",
")",
"->",
"Replacement",
":",
"if",
"len",
"(",
"position",
")",
"==",
"0",
":",
"return",
"replacement",
... | r"""Replaces the subexpression of `expression` at the given `position` with the given `replacement`.
The original `expression` itself is not modified, but a modified copy is returned. If the replacement
is a list of expressions, it will be expanded into the list of operands of the respective operation:
>>... | [
"r",
"Replaces",
"the",
"subexpression",
"of",
"expression",
"at",
"the",
"given",
"position",
"with",
"the",
"given",
"replacement",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/functions.py#L96-L135 |
1,977 | HPAC/matchpy | matchpy/matching/bipartite.py | BipartiteGraph.find_matching | def find_matching(self) -> Dict[TLeft, TRight]:
"""Finds a matching in the bipartite graph.
This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.
Returns:
A dictionary where each edge of the matching is represented by a key-v... | python | def find_matching(self) -> Dict[TLeft, TRight]:
# The directed graph is represented as a dictionary of edges
# The key is the tail of all edges which are represented by the value
# The value is a set of heads for the all edges originating from the tail (key)
# In addition, the graph stor... | [
"def",
"find_matching",
"(",
"self",
")",
"->",
"Dict",
"[",
"TLeft",
",",
"TRight",
"]",
":",
"# The directed graph is represented as a dictionary of edges",
"# The key is the tail of all edges which are represented by the value",
"# The value is a set of heads for the all edges origi... | Finds a matching in the bipartite graph.
This is done using the Hopcroft-Karp algorithm with an implementation from the
`hopcroftkarp` package.
Returns:
A dictionary where each edge of the matching is represented by a key-value pair
with the key being from the left part... | [
"Finds",
"a",
"matching",
"in",
"the",
"bipartite",
"graph",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L144-L174 |
1,978 | HPAC/matchpy | matchpy/matching/bipartite.py | BipartiteGraph.without_nodes | def without_nodes(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
"""Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed."""
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 != edge[0] and n2 != edge[1]) | python | def without_nodes(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 != edge[0] and n2 != edge[1]) | [
"def",
"without_nodes",
"(",
"self",
",",
"edge",
":",
"Edge",
")",
"->",
"'BipartiteGraph[TLeft, TRight, TEdgeValue]'",
":",
"return",
"BipartiteGraph",
"(",
"(",
"(",
"n1",
",",
"n2",
")",
",",
"v",
")",
"for",
"(",
"n1",
",",
"n2",
")",
",",
"v",
"i... | Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed. | [
"Returns",
"a",
"copy",
"of",
"this",
"bipartite",
"graph",
"with",
"the",
"given",
"edge",
"and",
"its",
"adjacent",
"nodes",
"removed",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L176-L178 |
1,979 | HPAC/matchpy | matchpy/matching/bipartite.py | BipartiteGraph.without_edge | def without_edge(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
"""Returns a copy of this bipartite graph with the given edge removed."""
return BipartiteGraph((e2, v) for e2, v in self._edges.items() if edge != e2) | python | def without_edge(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
return BipartiteGraph((e2, v) for e2, v in self._edges.items() if edge != e2) | [
"def",
"without_edge",
"(",
"self",
",",
"edge",
":",
"Edge",
")",
"->",
"'BipartiteGraph[TLeft, TRight, TEdgeValue]'",
":",
"return",
"BipartiteGraph",
"(",
"(",
"e2",
",",
"v",
")",
"for",
"e2",
",",
"v",
"in",
"self",
".",
"_edges",
".",
"items",
"(",
... | Returns a copy of this bipartite graph with the given edge removed. | [
"Returns",
"a",
"copy",
"of",
"this",
"bipartite",
"graph",
"with",
"the",
"given",
"edge",
"removed",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L180-L182 |
1,980 | HPAC/matchpy | matchpy/matching/bipartite.py | BipartiteGraph.limited_to | def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
"""Returns the induced subgraph where only the nodes from the given sets are included."""
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right) | python | def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right) | [
"def",
"limited_to",
"(",
"self",
",",
"left",
":",
"Set",
"[",
"TLeft",
"]",
",",
"right",
":",
"Set",
"[",
"TRight",
"]",
")",
"->",
"'BipartiteGraph[TLeft, TRight, TEdgeValue]'",
":",
"return",
"BipartiteGraph",
"(",
"(",
"(",
"n1",
",",
"n2",
")",
",... | Returns the induced subgraph where only the nodes from the given sets are included. | [
"Returns",
"the",
"induced",
"subgraph",
"where",
"only",
"the",
"nodes",
"from",
"the",
"given",
"sets",
"are",
"included",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L184-L186 |
1,981 | HPAC/matchpy | matchpy/expressions/functions.py | is_constant | def is_constant(expression):
"""Check if the given expression is constant, i.e. it does not contain Wildcards."""
if isinstance(expression, Wildcard):
return False
if isinstance(expression, Expression):
return expression.is_constant
if isinstance(expression, Operation):
return al... | python | def is_constant(expression):
if isinstance(expression, Wildcard):
return False
if isinstance(expression, Expression):
return expression.is_constant
if isinstance(expression, Operation):
return all(is_constant(o) for o in op_iter(expression))
return True | [
"def",
"is_constant",
"(",
"expression",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"Wildcard",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"expression",
",",
"Expression",
")",
":",
"return",
"expression",
".",
"is_constant",
"if",
"isi... | Check if the given expression is constant, i.e. it does not contain Wildcards. | [
"Check",
"if",
"the",
"given",
"expression",
"is",
"constant",
"i",
".",
"e",
".",
"it",
"does",
"not",
"contain",
"Wildcards",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L15-L23 |
1,982 | HPAC/matchpy | matchpy/expressions/functions.py | get_head | def get_head(expression):
"""Returns the given expression's head."""
if isinstance(expression, Wildcard):
if isinstance(expression, SymbolWildcard):
return expression.symbol_type
return None
return type(expression) | python | def get_head(expression):
if isinstance(expression, Wildcard):
if isinstance(expression, SymbolWildcard):
return expression.symbol_type
return None
return type(expression) | [
"def",
"get_head",
"(",
"expression",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"Wildcard",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"SymbolWildcard",
")",
":",
"return",
"expression",
".",
"symbol_type",
"return",
"None",
"return",
... | Returns the given expression's head. | [
"Returns",
"the",
"given",
"expression",
"s",
"head",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L42-L48 |
1,983 | HPAC/matchpy | matchpy/expressions/functions.py | match_head | def match_head(subject, pattern):
"""Checks if the head of subject matches the pattern's head."""
if isinstance(pattern, Pattern):
pattern = pattern.expression
pattern_head = get_head(pattern)
if pattern_head is None:
return True
if issubclass(pattern_head, OneIdentityOperation):
... | python | def match_head(subject, pattern):
if isinstance(pattern, Pattern):
pattern = pattern.expression
pattern_head = get_head(pattern)
if pattern_head is None:
return True
if issubclass(pattern_head, OneIdentityOperation):
return True
subject_head = get_head(subject)
assert sub... | [
"def",
"match_head",
"(",
"subject",
",",
"pattern",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"Pattern",
")",
":",
"pattern",
"=",
"pattern",
".",
"expression",
"pattern_head",
"=",
"get_head",
"(",
"pattern",
")",
"if",
"pattern_head",
"is",
"No... | Checks if the head of subject matches the pattern's head. | [
"Checks",
"if",
"the",
"head",
"of",
"subject",
"matches",
"the",
"pattern",
"s",
"head",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L51-L62 |
1,984 | HPAC/matchpy | matchpy/expressions/functions.py | is_anonymous | def is_anonymous(expression):
"""Returns True iff the expression does not contain any variables."""
if hasattr(expression, 'variable_name') and expression.variable_name:
return False
if isinstance(expression, Operation):
return all(is_anonymous(o) for o in op_iter(expression))
return Tru... | python | def is_anonymous(expression):
if hasattr(expression, 'variable_name') and expression.variable_name:
return False
if isinstance(expression, Operation):
return all(is_anonymous(o) for o in op_iter(expression))
return True | [
"def",
"is_anonymous",
"(",
"expression",
")",
":",
"if",
"hasattr",
"(",
"expression",
",",
"'variable_name'",
")",
"and",
"expression",
".",
"variable_name",
":",
"return",
"False",
"if",
"isinstance",
"(",
"expression",
",",
"Operation",
")",
":",
"return",... | Returns True iff the expression does not contain any variables. | [
"Returns",
"True",
"iff",
"the",
"expression",
"does",
"not",
"contain",
"any",
"variables",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L85-L91 |
1,985 | HPAC/matchpy | matchpy/expressions/functions.py | contains_variables_from_set | def contains_variables_from_set(expression, variables):
"""Returns True iff the expression contains any of the variables from the given set."""
if hasattr(expression, 'variable_name') and expression.variable_name in variables:
return True
if isinstance(expression, Operation):
return any(cont... | python | def contains_variables_from_set(expression, variables):
if hasattr(expression, 'variable_name') and expression.variable_name in variables:
return True
if isinstance(expression, Operation):
return any(contains_variables_from_set(o, variables) for o in op_iter(expression))
return False | [
"def",
"contains_variables_from_set",
"(",
"expression",
",",
"variables",
")",
":",
"if",
"hasattr",
"(",
"expression",
",",
"'variable_name'",
")",
"and",
"expression",
".",
"variable_name",
"in",
"variables",
":",
"return",
"True",
"if",
"isinstance",
"(",
"e... | Returns True iff the expression contains any of the variables from the given set. | [
"Returns",
"True",
"iff",
"the",
"expression",
"contains",
"any",
"of",
"the",
"variables",
"from",
"the",
"given",
"set",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L94-L100 |
1,986 | HPAC/matchpy | matchpy/expressions/functions.py | get_variables | def get_variables(expression, variables=None):
"""Returns the set of variable names in the given expression."""
if variables is None:
variables = set()
if hasattr(expression, 'variable_name') and expression.variable_name is not None:
variables.add(expression.variable_name)
if isinstance(... | python | def get_variables(expression, variables=None):
if variables is None:
variables = set()
if hasattr(expression, 'variable_name') and expression.variable_name is not None:
variables.add(expression.variable_name)
if isinstance(expression, Operation):
for operand in op_iter(expression):
... | [
"def",
"get_variables",
"(",
"expression",
",",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"set",
"(",
")",
"if",
"hasattr",
"(",
"expression",
",",
"'variable_name'",
")",
"and",
"expression",
".",
"variabl... | Returns the set of variable names in the given expression. | [
"Returns",
"the",
"set",
"of",
"variable",
"names",
"in",
"the",
"given",
"expression",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L103-L112 |
1,987 | HPAC/matchpy | matchpy/expressions/functions.py | rename_variables | def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression:
"""Rename the variables in the expression according to the given dictionary.
Args:
expression:
The expression in which the variables are renamed.
renaming:
The renaming dictionary. Maps... | python | def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression:
if isinstance(expression, Operation):
if hasattr(expression, 'variable_name'):
variable_name = renaming.get(expression.variable_name, expression.variable_name)
return create_operation_expression(
... | [
"def",
"rename_variables",
"(",
"expression",
":",
"Expression",
",",
"renaming",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"Expression",
":",
"if",
"isinstance",
"(",
"expression",
",",
"Operation",
")",
":",
"if",
"hasattr",
"(",
"expression",... | Rename the variables in the expression according to the given dictionary.
Args:
expression:
The expression in which the variables are renamed.
renaming:
The renaming dictionary. Maps old variable names to new ones.
Variable names not occuring in the dictionary ar... | [
"Rename",
"the",
"variables",
"in",
"the",
"expression",
"according",
"to",
"the",
"given",
"dictionary",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L115-L139 |
1,988 | HPAC/matchpy | matchpy/utils.py | fixed_integer_vector_iter | def fixed_integer_vector_iter(max_vector: Tuple[int, ...], vector_sum: int) -> Iterator[Tuple[int, ...]]:
"""
Return an iterator over the integer vectors which
- are componentwise less than or equal to *max_vector*, and
- are non-negative, and where
- the sum of their components is exactly *vector_... | python | def fixed_integer_vector_iter(max_vector: Tuple[int, ...], vector_sum: int) -> Iterator[Tuple[int, ...]]:
if vector_sum < 0:
raise ValueError("Vector sum must not be negative")
if len(max_vector) == 0:
if vector_sum == 0:
yield tuple()
return
total = sum(max_vector)
i... | [
"def",
"fixed_integer_vector_iter",
"(",
"max_vector",
":",
"Tuple",
"[",
"int",
",",
"...",
"]",
",",
"vector_sum",
":",
"int",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"int",
",",
"...",
"]",
"]",
":",
"if",
"vector_sum",
"<",
"0",
":",
"raise",
"... | Return an iterator over the integer vectors which
- are componentwise less than or equal to *max_vector*, and
- are non-negative, and where
- the sum of their components is exactly *vector_sum*.
The iterator yields the vectors in lexicographical order.
Examples:
List all vectors that are... | [
"Return",
"an",
"iterator",
"over",
"the",
"integer",
"vectors",
"which"
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L30-L75 |
1,989 | HPAC/matchpy | matchpy/utils.py | commutative_sequence_variable_partition_iter | def commutative_sequence_variable_partition_iter(values: Multiset, variables: List[VariableWithCount]
) -> Iterator[Dict[str, Multiset]]:
"""Yield all possible variable substitutions for given values and variables.
.. note::
The results are not yielded i... | python | def commutative_sequence_variable_partition_iter(values: Multiset, variables: List[VariableWithCount]
) -> Iterator[Dict[str, Multiset]]:
if len(variables) == 1:
yield from _commutative_single_variable_partiton_iter(values, variables[0])
return
ge... | [
"def",
"commutative_sequence_variable_partition_iter",
"(",
"values",
":",
"Multiset",
",",
"variables",
":",
"List",
"[",
"VariableWithCount",
"]",
")",
"->",
"Iterator",
"[",
"Dict",
"[",
"str",
",",
"Multiset",
"]",
"]",
":",
"if",
"len",
"(",
"variables",
... | Yield all possible variable substitutions for given values and variables.
.. note::
The results are not yielded in any particular order because the algorithm uses dictionaries. Dictionaries until
Python 3.6 do not keep track of the insertion order.
Example:
For a subject like ``fc(a,... | [
"Yield",
"all",
"possible",
"variable",
"substitutions",
"for",
"given",
"values",
"and",
"variables",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L173-L232 |
1,990 | HPAC/matchpy | matchpy/utils.py | generator_chain | def generator_chain(initial_data: T, *factories: Callable[[T], Iterator[T]]) -> Iterator[T]:
"""Chain multiple generators together by passing results from one to the next.
This helper function allows to create a chain of generator where each generator is constructed by a factory that
gets the data yielded ... | python | def generator_chain(initial_data: T, *factories: Callable[[T], Iterator[T]]) -> Iterator[T]:
generator_count = len(factories)
if generator_count == 0:
yield initial_data
return
generators = [None] * generator_count # type: List[Optional[Iterator[T]]]
next_data = initial_data
generat... | [
"def",
"generator_chain",
"(",
"initial_data",
":",
"T",
",",
"*",
"factories",
":",
"Callable",
"[",
"[",
"T",
"]",
",",
"Iterator",
"[",
"T",
"]",
"]",
")",
"->",
"Iterator",
"[",
"T",
"]",
":",
"generator_count",
"=",
"len",
"(",
"factories",
")",... | Chain multiple generators together by passing results from one to the next.
This helper function allows to create a chain of generator where each generator is constructed by a factory that
gets the data yielded by the previous generator. So each generator can generate new data dependant on the data
yielded... | [
"Chain",
"multiple",
"generators",
"together",
"by",
"passing",
"results",
"from",
"one",
"to",
"the",
"next",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/utils.py#L477-L532 |
1,991 | HPAC/matchpy | matchpy/expressions/substitution.py | Substitution.try_add_variable | def try_add_variable(self, variable_name: str, replacement: VariableReplacement) -> None:
"""Try to add the variable with its replacement to the substitution.
This considers an existing replacement and will only succeed if the new replacement
can be merged with the old replacement. Merging can ... | python | def try_add_variable(self, variable_name: str, replacement: VariableReplacement) -> None:
if variable_name not in self:
self[variable_name] = replacement.copy() if isinstance(replacement, Multiset) else replacement
else:
existing_value = self[variable_name]
if isinst... | [
"def",
"try_add_variable",
"(",
"self",
",",
"variable_name",
":",
"str",
",",
"replacement",
":",
"VariableReplacement",
")",
"->",
"None",
":",
"if",
"variable_name",
"not",
"in",
"self",
":",
"self",
"[",
"variable_name",
"]",
"=",
"replacement",
".",
"co... | Try to add the variable with its replacement to the substitution.
This considers an existing replacement and will only succeed if the new replacement
can be merged with the old replacement. Merging can occur if either the two replacements
are equivalent. Replacements can also be merged if the o... | [
"Try",
"to",
"add",
"the",
"variable",
"with",
"its",
"replacement",
"to",
"the",
"substitution",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L32-L77 |
1,992 | HPAC/matchpy | matchpy/expressions/substitution.py | Substitution.union_with_variable | def union_with_variable(self, variable: str, replacement: VariableReplacement) -> 'Substitution':
"""Try to create a new substitution with the given variable added.
See :meth:`try_add_variable` for a version of this method that modifies the substitution
in place.
Args:
vari... | python | def union_with_variable(self, variable: str, replacement: VariableReplacement) -> 'Substitution':
new_subst = Substitution(self)
new_subst.try_add_variable(variable, replacement)
return new_subst | [
"def",
"union_with_variable",
"(",
"self",
",",
"variable",
":",
"str",
",",
"replacement",
":",
"VariableReplacement",
")",
"->",
"'Substitution'",
":",
"new_subst",
"=",
"Substitution",
"(",
"self",
")",
"new_subst",
".",
"try_add_variable",
"(",
"variable",
"... | Try to create a new substitution with the given variable added.
See :meth:`try_add_variable` for a version of this method that modifies the substitution
in place.
Args:
variable_name:
The name of the variable to add.
replacement:
The subs... | [
"Try",
"to",
"create",
"a",
"new",
"substitution",
"with",
"the",
"given",
"variable",
"added",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L79-L101 |
1,993 | HPAC/matchpy | matchpy/expressions/substitution.py | Substitution.extract_substitution | def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool:
"""Extract the variable substitution for the given pattern and subject.
This assumes that subject and pattern already match when being considered as linear.
Also, they both must be :ter... | python | def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool:
if getattr(pattern, 'variable_name', False):
try:
self.try_add_variable(pattern.variable_name, subject)
except ValueError:
return False
... | [
"def",
"extract_substitution",
"(",
"self",
",",
"subject",
":",
"'expressions.Expression'",
",",
"pattern",
":",
"'expressions.Expression'",
")",
"->",
"bool",
":",
"if",
"getattr",
"(",
"pattern",
",",
"'variable_name'",
",",
"False",
")",
":",
"try",
":",
"... | Extract the variable substitution for the given pattern and subject.
This assumes that subject and pattern already match when being considered as linear.
Also, they both must be :term:`syntactic`, as sequence variables cannot be handled here.
All that this method does is checking whether all th... | [
"Extract",
"the",
"variable",
"substitution",
"for",
"the",
"given",
"pattern",
"and",
"subject",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L103-L164 |
1,994 | HPAC/matchpy | matchpy/expressions/substitution.py | Substitution.union | def union(self, *others: 'Substitution') -> 'Substitution':
"""Try to merge the substitutions.
If a variable occurs in multiple substitutions, try to merge the replacements.
See :meth:`union_with_variable` to see how replacements are merged.
Does not modify any of the original substitu... | python | def union(self, *others: 'Substitution') -> 'Substitution':
new_subst = Substitution(self)
for other in others:
for variable_name, replacement in other.items():
new_subst.try_add_variable(variable_name, replacement)
return new_subst | [
"def",
"union",
"(",
"self",
",",
"*",
"others",
":",
"'Substitution'",
")",
"->",
"'Substitution'",
":",
"new_subst",
"=",
"Substitution",
"(",
"self",
")",
"for",
"other",
"in",
"others",
":",
"for",
"variable_name",
",",
"replacement",
"in",
"other",
".... | Try to merge the substitutions.
If a variable occurs in multiple substitutions, try to merge the replacements.
See :meth:`union_with_variable` to see how replacements are merged.
Does not modify any of the original substitutions.
Example:
>>> subst1 = Substitution({'x': Multi... | [
"Try",
"to",
"merge",
"the",
"substitutions",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L166-L197 |
1,995 | HPAC/matchpy | matchpy/expressions/substitution.py | Substitution.rename | def rename(self, renaming: Dict[str, str]) -> 'Substitution':
"""Return a copy of the substitution with renamed variables.
Example:
Rename the variable *x* to *y*:
>>> subst = Substitution({'x': a})
>>> subst.rename({'x': 'y'})
{'y': Symbol('a')}
... | python | def rename(self, renaming: Dict[str, str]) -> 'Substitution':
return Substitution((renaming.get(name, name), value) for name, value in self.items()) | [
"def",
"rename",
"(",
"self",
",",
"renaming",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"'Substitution'",
":",
"return",
"Substitution",
"(",
"(",
"renaming",
".",
"get",
"(",
"name",
",",
"name",
")",
",",
"value",
")",
"for",
"name",
... | Return a copy of the substitution with renamed variables.
Example:
Rename the variable *x* to *y*:
>>> subst = Substitution({'x': a})
>>> subst.rename({'x': 'y'})
{'y': Symbol('a')}
Args:
renaming:
A dictionary mapping old v... | [
"Return",
"a",
"copy",
"of",
"the",
"substitution",
"with",
"renamed",
"variables",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/substitution.py#L199-L218 |
1,996 | HPAC/matchpy | matchpy/matching/syntactic.py | _get_symbol_wildcard_label | def _get_symbol_wildcard_label(state: '_State', symbol: Symbol) -> Type[Symbol]:
"""Return the transition target for the given symbol type from the the given state or None if it does not exist."""
return next((t for t in state.keys() if is_symbol_wildcard(t) and isinstance(symbol, t)), None) | python | def _get_symbol_wildcard_label(state: '_State', symbol: Symbol) -> Type[Symbol]:
return next((t for t in state.keys() if is_symbol_wildcard(t) and isinstance(symbol, t)), None) | [
"def",
"_get_symbol_wildcard_label",
"(",
"state",
":",
"'_State'",
",",
"symbol",
":",
"Symbol",
")",
"->",
"Type",
"[",
"Symbol",
"]",
":",
"return",
"next",
"(",
"(",
"t",
"for",
"t",
"in",
"state",
".",
"keys",
"(",
")",
"if",
"is_symbol_wildcard",
... | Return the transition target for the given symbol type from the the given state or None if it does not exist. | [
"Return",
"the",
"transition",
"target",
"for",
"the",
"given",
"symbol",
"type",
"from",
"the",
"the",
"given",
"state",
"or",
"None",
"if",
"it",
"does",
"not",
"exist",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L50-L52 |
1,997 | HPAC/matchpy | matchpy/matching/syntactic.py | _term_str | def _term_str(term: TermAtom) -> str: # pragma: no cover
"""Return a string representation of a term atom."""
if is_operation(term):
return term.name + '('
elif is_symbol_wildcard(term):
return '*{!s}'.format(term.__name__)
elif isinstance(term, Wildcard):
return '*{!s}{!s}'.for... | python | def _term_str(term: TermAtom) -> str: # pragma: no cover
if is_operation(term):
return term.name + '('
elif is_symbol_wildcard(term):
return '*{!s}'.format(term.__name__)
elif isinstance(term, Wildcard):
return '*{!s}{!s}'.format(term.min_count, (not term.fixed_size) and '+' or '')
... | [
"def",
"_term_str",
"(",
"term",
":",
"TermAtom",
")",
"->",
"str",
":",
"# pragma: no cover",
"if",
"is_operation",
"(",
"term",
")",
":",
"return",
"term",
".",
"name",
"+",
"'('",
"elif",
"is_symbol_wildcard",
"(",
"term",
")",
":",
"return",
"'*{!s}'",... | Return a string representation of a term atom. | [
"Return",
"a",
"string",
"representation",
"of",
"a",
"term",
"atom",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L200-L211 |
1,998 | HPAC/matchpy | matchpy/matching/syntactic.py | FlatTerm.merged | def merged(cls, *flatterms: 'FlatTerm') -> 'FlatTerm':
"""Concatenate the given flatterms to a single flatterm.
Args:
*flatterms:
The flatterms which are concatenated.
Returns:
The concatenated flatterms.
"""
return cls(cls._combined_wild... | python | def merged(cls, *flatterms: 'FlatTerm') -> 'FlatTerm':
return cls(cls._combined_wildcards_iter(sum(flatterms, cls.empty()))) | [
"def",
"merged",
"(",
"cls",
",",
"*",
"flatterms",
":",
"'FlatTerm'",
")",
"->",
"'FlatTerm'",
":",
"return",
"cls",
"(",
"cls",
".",
"_combined_wildcards_iter",
"(",
"sum",
"(",
"flatterms",
",",
"cls",
".",
"empty",
"(",
")",
")",
")",
")"
] | Concatenate the given flatterms to a single flatterm.
Args:
*flatterms:
The flatterms which are concatenated.
Returns:
The concatenated flatterms. | [
"Concatenate",
"the",
"given",
"flatterms",
"to",
"a",
"single",
"flatterm",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L146-L156 |
1,999 | HPAC/matchpy | matchpy/matching/syntactic.py | FlatTerm._flatterm_iter | def _flatterm_iter(cls, expression: Expression) -> Iterator[TermAtom]:
"""Generator that yields the atoms of the expressions in prefix notation with operation end markers."""
if isinstance(expression, Operation):
yield type(expression)
for operand in op_iter(expression):
... | python | def _flatterm_iter(cls, expression: Expression) -> Iterator[TermAtom]:
if isinstance(expression, Operation):
yield type(expression)
for operand in op_iter(expression):
yield from cls._flatterm_iter(operand)
yield OPERATION_END
elif isinstance(expressio... | [
"def",
"_flatterm_iter",
"(",
"cls",
",",
"expression",
":",
"Expression",
")",
"->",
"Iterator",
"[",
"TermAtom",
"]",
":",
"if",
"isinstance",
"(",
"expression",
",",
"Operation",
")",
":",
"yield",
"type",
"(",
"expression",
")",
"for",
"operand",
"in",... | Generator that yields the atoms of the expressions in prefix notation with operation end markers. | [
"Generator",
"that",
"yields",
"the",
"atoms",
"of",
"the",
"expressions",
"in",
"prefix",
"notation",
"with",
"operation",
"end",
"markers",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L159-L171 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.