repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Lagg/steamodd | steam/items.py | schema._quality_definition | def _quality_definition(self, qid):
""" Returns the ID and localized name of the given quality, can be either ID type """
qualities = self._schema["qualities"]
try:
return qualities[qid]
except KeyError:
qid = self._schema["quality_names"].get(str(qid).lower(), 0... | python | def _quality_definition(self, qid):
""" Returns the ID and localized name of the given quality, can be either ID type """
qualities = self._schema["qualities"]
try:
return qualities[qid]
except KeyError:
qid = self._schema["quality_names"].get(str(qid).lower(), 0... | [
"def",
"_quality_definition",
"(",
"self",
",",
"qid",
")",
":",
"qualities",
"=",
"self",
".",
"_schema",
"[",
"\"qualities\"",
"]",
"try",
":",
"return",
"qualities",
"[",
"qid",
"]",
"except",
"KeyError",
":",
"qid",
"=",
"self",
".",
"_schema",
"[",
... | Returns the ID and localized name of the given quality, can be either ID type | [
"Returns",
"the",
"ID",
"and",
"localized",
"name",
"of",
"the",
"given",
"quality",
"can",
"be",
"either",
"ID",
"type"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L147-L155 | train |
Lagg/steamodd | steam/items.py | schema.attributes | def attributes(self):
""" Returns all attributes in the schema """
attrs = self._schema["attributes"]
return [item_attribute(attr) for attr in sorted(attrs.values(),
key=operator.itemgetter("defindex"))] | python | def attributes(self):
""" Returns all attributes in the schema """
attrs = self._schema["attributes"]
return [item_attribute(attr) for attr in sorted(attrs.values(),
key=operator.itemgetter("defindex"))] | [
"def",
"attributes",
"(",
"self",
")",
":",
"attrs",
"=",
"self",
".",
"_schema",
"[",
"\"attributes\"",
"]",
"return",
"[",
"item_attribute",
"(",
"attr",
")",
"for",
"attr",
"in",
"sorted",
"(",
"attrs",
".",
"values",
"(",
")",
",",
"key",
"=",
"o... | Returns all attributes in the schema | [
"Returns",
"all",
"attributes",
"in",
"the",
"schema"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L158-L162 | train |
Lagg/steamodd | steam/items.py | schema.origin_id_to_name | def origin_id_to_name(self, origin):
""" Returns a localized origin name for a given ID """
try:
oid = int(origin)
except (ValueError, TypeError):
return None
return self.origins.get(oid) | python | def origin_id_to_name(self, origin):
""" Returns a localized origin name for a given ID """
try:
oid = int(origin)
except (ValueError, TypeError):
return None
return self.origins.get(oid) | [
"def",
"origin_id_to_name",
"(",
"self",
",",
"origin",
")",
":",
"try",
":",
"oid",
"=",
"int",
"(",
"origin",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"None",
"return",
"self",
".",
"origins",
".",
"get",
"(",
"oid",
... | Returns a localized origin name for a given ID | [
"Returns",
"a",
"localized",
"origin",
"name",
"for",
"a",
"given",
"ID"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L195-L202 | train |
Lagg/steamodd | steam/items.py | item.attributes | def attributes(self):
""" Returns a list of attributes """
overridden_attrs = self._attributes
sortmap = {"neutral": 1, "positive": 2,
"negative": 3}
sortedattrs = list(overridden_attrs.values())
sortedattrs.sort(key=operator.itemgetter("defindex"))
s... | python | def attributes(self):
""" Returns a list of attributes """
overridden_attrs = self._attributes
sortmap = {"neutral": 1, "positive": 2,
"negative": 3}
sortedattrs = list(overridden_attrs.values())
sortedattrs.sort(key=operator.itemgetter("defindex"))
s... | [
"def",
"attributes",
"(",
"self",
")",
":",
"overridden_attrs",
"=",
"self",
".",
"_attributes",
"sortmap",
"=",
"{",
"\"neutral\"",
":",
"1",
",",
"\"positive\"",
":",
"2",
",",
"\"negative\"",
":",
"3",
"}",
"sortedattrs",
"=",
"list",
"(",
"overridden_a... | Returns a list of attributes | [
"Returns",
"a",
"list",
"of",
"attributes"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L269-L280 | train |
Lagg/steamodd | steam/items.py | item.equipped | def equipped(self):
""" Returns a dict of classes that have the item equipped and in what slot """
equipped = self._item.get("equipped", [])
# WORKAROUND: 0 is probably an off-by-one error
# WORKAROUND: 65535 actually serves a purpose (according to Valve)
return dict([(eq["class... | python | def equipped(self):
""" Returns a dict of classes that have the item equipped and in what slot """
equipped = self._item.get("equipped", [])
# WORKAROUND: 0 is probably an off-by-one error
# WORKAROUND: 65535 actually serves a purpose (according to Valve)
return dict([(eq["class... | [
"def",
"equipped",
"(",
"self",
")",
":",
"equipped",
"=",
"self",
".",
"_item",
".",
"get",
"(",
"\"equipped\"",
",",
"[",
"]",
")",
"# WORKAROUND: 0 is probably an off-by-one error",
"# WORKAROUND: 65535 actually serves a purpose (according to Valve)",
"return",
"dict",... | Returns a dict of classes that have the item equipped and in what slot | [
"Returns",
"a",
"dict",
"of",
"classes",
"that",
"have",
"the",
"item",
"equipped",
"and",
"in",
"what",
"slot"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L306-L312 | train |
Lagg/steamodd | steam/items.py | item.equipable_classes | def equipable_classes(self):
""" Returns a list of classes that _can_ use the item. """
sitem = self._schema_item
return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c] | python | def equipable_classes(self):
""" Returns a list of classes that _can_ use the item. """
sitem = self._schema_item
return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c] | [
"def",
"equipable_classes",
"(",
"self",
")",
":",
"sitem",
"=",
"self",
".",
"_schema_item",
"return",
"[",
"c",
"for",
"c",
"in",
"sitem",
".",
"get",
"(",
"\"used_by_classes\"",
",",
"self",
".",
"equipped",
".",
"keys",
"(",
")",
")",
"if",
"c",
... | Returns a list of classes that _can_ use the item. | [
"Returns",
"a",
"list",
"of",
"classes",
"that",
"_can_",
"use",
"the",
"item",
"."
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L315-L319 | train |
Lagg/steamodd | steam/items.py | item.contents | def contents(self):
""" Returns the item in the container, if there is one.
This will be a standard item object. """
rawitem = self._item.get("contained_item")
if rawitem:
return self.__class__(rawitem, self._schema) | python | def contents(self):
""" Returns the item in the container, if there is one.
This will be a standard item object. """
rawitem = self._item.get("contained_item")
if rawitem:
return self.__class__(rawitem, self._schema) | [
"def",
"contents",
"(",
"self",
")",
":",
"rawitem",
"=",
"self",
".",
"_item",
".",
"get",
"(",
"\"contained_item\"",
")",
"if",
"rawitem",
":",
"return",
"self",
".",
"__class__",
"(",
"rawitem",
",",
"self",
".",
"_schema",
")"
] | Returns the item in the container, if there is one.
This will be a standard item object. | [
"Returns",
"the",
"item",
"in",
"the",
"container",
"if",
"there",
"is",
"one",
".",
"This",
"will",
"be",
"a",
"standard",
"item",
"object",
"."
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L422-L427 | train |
Lagg/steamodd | steam/items.py | item.full_name | def full_name(self):
"""
The full name of the item, generated depending
on things such as its quality, rank, the schema language,
and so on.
"""
qid, quality_str, pretty_quality_str = self.quality
custom_name = self.custom_name
item_name = self.name
... | python | def full_name(self):
"""
The full name of the item, generated depending
on things such as its quality, rank, the schema language,
and so on.
"""
qid, quality_str, pretty_quality_str = self.quality
custom_name = self.custom_name
item_name = self.name
... | [
"def",
"full_name",
"(",
"self",
")",
":",
"qid",
",",
"quality_str",
",",
"pretty_quality_str",
"=",
"self",
".",
"quality",
"custom_name",
"=",
"self",
".",
"custom_name",
"item_name",
"=",
"self",
".",
"name",
"english",
"=",
"(",
"self",
".",
"_languag... | The full name of the item, generated depending
on things such as its quality, rank, the schema language,
and so on. | [
"The",
"full",
"name",
"of",
"the",
"item",
"generated",
"depending",
"on",
"things",
"such",
"as",
"its",
"quality",
"rank",
"the",
"schema",
"language",
"and",
"so",
"on",
"."
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L444-L481 | train |
Lagg/steamodd | steam/items.py | item.kill_eaters | def kill_eaters(self):
"""
Returns a list of tuples containing the proper localized kill eater type strings and their values
according to set/type/value "order"
"""
eaters = {}
ranktypes = self._kill_types
for attr in self:
aname = attr.name.strip()
... | python | def kill_eaters(self):
"""
Returns a list of tuples containing the proper localized kill eater type strings and their values
according to set/type/value "order"
"""
eaters = {}
ranktypes = self._kill_types
for attr in self:
aname = attr.name.strip()
... | [
"def",
"kill_eaters",
"(",
"self",
")",
":",
"eaters",
"=",
"{",
"}",
"ranktypes",
"=",
"self",
".",
"_kill_types",
"for",
"attr",
"in",
"self",
":",
"aname",
"=",
"attr",
".",
"name",
".",
"strip",
"(",
")",
"aid",
"=",
"attr",
".",
"id",
"if",
... | Returns a list of tuples containing the proper localized kill eater type strings and their values
according to set/type/value "order" | [
"Returns",
"a",
"list",
"of",
"tuples",
"containing",
"the",
"proper",
"localized",
"kill",
"eater",
"type",
"strings",
"and",
"their",
"values",
"according",
"to",
"set",
"/",
"type",
"/",
"value",
"order"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L484-L540 | train |
Lagg/steamodd | steam/items.py | item.rank | def rank(self):
"""
Returns the item's rank (if it has one)
as a dict that includes required score, name, and level.
"""
if self._rank != {}:
# Don't bother doing attribute lookups again
return self._rank
try:
# The eater determining ... | python | def rank(self):
"""
Returns the item's rank (if it has one)
as a dict that includes required score, name, and level.
"""
if self._rank != {}:
# Don't bother doing attribute lookups again
return self._rank
try:
# The eater determining ... | [
"def",
"rank",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rank",
"!=",
"{",
"}",
":",
"# Don't bother doing attribute lookups again",
"return",
"self",
".",
"_rank",
"try",
":",
"# The eater determining the rank",
"levelkey",
",",
"typename",
",",
"count",
"=",... | Returns the item's rank (if it has one)
as a dict that includes required score, name, and level. | [
"Returns",
"the",
"item",
"s",
"rank",
"(",
"if",
"it",
"has",
"one",
")",
"as",
"a",
"dict",
"that",
"includes",
"required",
"score",
"name",
"and",
"level",
"."
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L543-L571 | train |
Lagg/steamodd | steam/items.py | item.available_styles | def available_styles(self):
""" Returns a list of all styles defined for the item """
styles = self._schema_item.get("styles", [])
return list(map(operator.itemgetter("name"), styles)) | python | def available_styles(self):
""" Returns a list of all styles defined for the item """
styles = self._schema_item.get("styles", [])
return list(map(operator.itemgetter("name"), styles)) | [
"def",
"available_styles",
"(",
"self",
")",
":",
"styles",
"=",
"self",
".",
"_schema_item",
".",
"get",
"(",
"\"styles\"",
",",
"[",
"]",
")",
"return",
"list",
"(",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"\"name\"",
")",
",",
"styles",
")",... | Returns a list of all styles defined for the item | [
"Returns",
"a",
"list",
"of",
"all",
"styles",
"defined",
"for",
"the",
"item"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L574-L578 | train |
Lagg/steamodd | steam/items.py | item_attribute.formatted_value | def formatted_value(self):
""" Returns a formatted value as a string"""
# TODO: Cleanup all of this, it's just weird and unnatural maths
val = self.value
pval = val
ftype = self.value_type
if ftype == "percentage":
pval = int(round(val * 100))
if... | python | def formatted_value(self):
""" Returns a formatted value as a string"""
# TODO: Cleanup all of this, it's just weird and unnatural maths
val = self.value
pval = val
ftype = self.value_type
if ftype == "percentage":
pval = int(round(val * 100))
if... | [
"def",
"formatted_value",
"(",
"self",
")",
":",
"# TODO: Cleanup all of this, it's just weird and unnatural maths",
"val",
"=",
"self",
".",
"value",
"pval",
"=",
"val",
"ftype",
"=",
"self",
".",
"value_type",
"if",
"ftype",
"==",
"\"percentage\"",
":",
"pval",
... | Returns a formatted value as a string | [
"Returns",
"a",
"formatted",
"value",
"as",
"a",
"string"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L711-L741 | train |
Lagg/steamodd | steam/items.py | item_attribute.formatted_description | def formatted_description(self):
""" Returns a formatted description string (%s* tokens replaced) or None if unavailable """
desc = self.description
if desc:
return desc.replace("%s1", self.formatted_value)
else:
return None | python | def formatted_description(self):
""" Returns a formatted description string (%s* tokens replaced) or None if unavailable """
desc = self.description
if desc:
return desc.replace("%s1", self.formatted_value)
else:
return None | [
"def",
"formatted_description",
"(",
"self",
")",
":",
"desc",
"=",
"self",
".",
"description",
"if",
"desc",
":",
"return",
"desc",
".",
"replace",
"(",
"\"%s1\"",
",",
"self",
".",
"formatted_value",
")",
"else",
":",
"return",
"None"
] | Returns a formatted description string (%s* tokens replaced) or None if unavailable | [
"Returns",
"a",
"formatted",
"description",
"string",
"(",
"%s",
"*",
"tokens",
"replaced",
")",
"or",
"None",
"if",
"unavailable"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L744-L751 | train |
Lagg/steamodd | steam/items.py | item_attribute.value_type | def value_type(self):
""" The attribute's type, note that this is the type of the attribute's
value and not its affect on the item (i.e. negative or positive). See
'type' for that. """
redundantprefix = "value_is_"
vtype = self._attribute.get("description_format")
if vty... | python | def value_type(self):
""" The attribute's type, note that this is the type of the attribute's
value and not its affect on the item (i.e. negative or positive). See
'type' for that. """
redundantprefix = "value_is_"
vtype = self._attribute.get("description_format")
if vty... | [
"def",
"value_type",
"(",
"self",
")",
":",
"redundantprefix",
"=",
"\"value_is_\"",
"vtype",
"=",
"self",
".",
"_attribute",
".",
"get",
"(",
"\"description_format\"",
")",
"if",
"vtype",
"and",
"vtype",
".",
"startswith",
"(",
"redundantprefix",
")",
":",
... | The attribute's type, note that this is the type of the attribute's
value and not its affect on the item (i.e. negative or positive). See
'type' for that. | [
"The",
"attribute",
"s",
"type",
"note",
"that",
"this",
"is",
"the",
"type",
"of",
"the",
"attribute",
"s",
"value",
"and",
"not",
"its",
"affect",
"on",
"the",
"item",
"(",
"i",
".",
"e",
".",
"negative",
"or",
"positive",
")",
".",
"See",
"type",
... | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L819-L829 | train |
Lagg/steamodd | steam/items.py | item_attribute.account_info | def account_info(self):
""" Certain attributes have a user's account information
associated with it such as a gifted or crafted item.
A dict with two keys: 'persona' and 'id64'.
None if the attribute has no account information attached to it. """
account_info = self._attribute.g... | python | def account_info(self):
""" Certain attributes have a user's account information
associated with it such as a gifted or crafted item.
A dict with two keys: 'persona' and 'id64'.
None if the attribute has no account information attached to it. """
account_info = self._attribute.g... | [
"def",
"account_info",
"(",
"self",
")",
":",
"account_info",
"=",
"self",
".",
"_attribute",
".",
"get",
"(",
"\"account_info\"",
")",
"if",
"account_info",
":",
"return",
"{",
"\"persona\"",
":",
"account_info",
".",
"get",
"(",
"\"personaname\"",
",",
"\"... | Certain attributes have a user's account information
associated with it such as a gifted or crafted item.
A dict with two keys: 'persona' and 'id64'.
None if the attribute has no account information attached to it. | [
"Certain",
"attributes",
"have",
"a",
"user",
"s",
"account",
"information",
"associated",
"with",
"it",
"such",
"as",
"a",
"gifted",
"or",
"crafted",
"item",
"."
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L839-L850 | train |
Lagg/steamodd | steam/items.py | asset_item.tags | def tags(self):
""" Returns a dict containing tags and their localized labels as values """
return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])]) | python | def tags(self):
""" Returns a dict containing tags and their localized labels as values """
return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])]) | [
"def",
"tags",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"t",
",",
"self",
".",
"_catalog",
".",
"tags",
".",
"get",
"(",
"t",
",",
"t",
")",
")",
"for",
"t",
"in",
"self",
".",
"_asset",
".",
"get",
"(",
"\"tags\"",
",",
"[",
... | Returns a dict containing tags and their localized labels as values | [
"Returns",
"a",
"dict",
"containing",
"tags",
"and",
"their",
"localized",
"labels",
"as",
"values"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/items.py#L965-L967 | train |
Lagg/steamodd | steam/user.py | profile.vanity | def vanity(self):
""" Returns the user's vanity url if it exists, None otherwise """
purl = self.profile_url.strip('/')
if purl.find("/id/") != -1:
return os.path.basename(purl) | python | def vanity(self):
""" Returns the user's vanity url if it exists, None otherwise """
purl = self.profile_url.strip('/')
if purl.find("/id/") != -1:
return os.path.basename(purl) | [
"def",
"vanity",
"(",
"self",
")",
":",
"purl",
"=",
"self",
".",
"profile_url",
".",
"strip",
"(",
"'/'",
")",
"if",
"purl",
".",
"find",
"(",
"\"/id/\"",
")",
"!=",
"-",
"1",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"purl",
")"
] | Returns the user's vanity url if it exists, None otherwise | [
"Returns",
"the",
"user",
"s",
"vanity",
"url",
"if",
"it",
"exists",
"None",
"otherwise"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L90-L94 | train |
Lagg/steamodd | steam/user.py | profile.creation_date | def creation_date(self):
""" Returns the account creation date as a localtime time.struct_time
struct if public"""
timestamp = self._prof.get("timecreated")
if timestamp:
return time.localtime(timestamp) | python | def creation_date(self):
""" Returns the account creation date as a localtime time.struct_time
struct if public"""
timestamp = self._prof.get("timecreated")
if timestamp:
return time.localtime(timestamp) | [
"def",
"creation_date",
"(",
"self",
")",
":",
"timestamp",
"=",
"self",
".",
"_prof",
".",
"get",
"(",
"\"timecreated\"",
")",
"if",
"timestamp",
":",
"return",
"time",
".",
"localtime",
"(",
"timestamp",
")"
] | Returns the account creation date as a localtime time.struct_time
struct if public | [
"Returns",
"the",
"account",
"creation",
"date",
"as",
"a",
"localtime",
"time",
".",
"struct_time",
"struct",
"if",
"public"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L158-L163 | train |
Lagg/steamodd | steam/user.py | profile.current_game | def current_game(self):
"""
Returns a tuple of 3 elements (each of which may be None if not available):
Current game app ID, server ip:port, misc. extra info (eg. game title)
"""
obj = self._prof
gameid = obj.get("gameid")
gameserverip = obj.get("gameserverip")
... | python | def current_game(self):
"""
Returns a tuple of 3 elements (each of which may be None if not available):
Current game app ID, server ip:port, misc. extra info (eg. game title)
"""
obj = self._prof
gameid = obj.get("gameid")
gameserverip = obj.get("gameserverip")
... | [
"def",
"current_game",
"(",
"self",
")",
":",
"obj",
"=",
"self",
".",
"_prof",
"gameid",
"=",
"obj",
".",
"get",
"(",
"\"gameid\"",
")",
"gameserverip",
"=",
"obj",
".",
"get",
"(",
"\"gameserverip\"",
")",
"gameextrainfo",
"=",
"obj",
".",
"get",
"("... | Returns a tuple of 3 elements (each of which may be None if not available):
Current game app ID, server ip:port, misc. extra info (eg. game title) | [
"Returns",
"a",
"tuple",
"of",
"3",
"elements",
"(",
"each",
"of",
"which",
"may",
"be",
"None",
"if",
"not",
"available",
")",
":",
"Current",
"game",
"app",
"ID",
"server",
"ip",
":",
"port",
"misc",
".",
"extra",
"info",
"(",
"eg",
".",
"game",
... | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L166-L175 | train |
Lagg/steamodd | steam/user.py | profile.level | def level(self):
"""
Returns the the user's profile level, note that this runs a separate
request because the profile level data isn't in the standard player summary
output even though it should be. Which is also why it's not implemented
as a separate class. You won't need this o... | python | def level(self):
"""
Returns the the user's profile level, note that this runs a separate
request because the profile level data isn't in the standard player summary
output even though it should be. Which is also why it's not implemented
as a separate class. You won't need this o... | [
"def",
"level",
"(",
"self",
")",
":",
"level_key",
"=",
"\"player_level\"",
"if",
"level_key",
"in",
"self",
".",
"_api",
"[",
"\"response\"",
"]",
":",
"return",
"self",
".",
"_api",
"[",
"\"response\"",
"]",
"[",
"level_key",
"]",
"try",
":",
"lvl",
... | Returns the the user's profile level, note that this runs a separate
request because the profile level data isn't in the standard player summary
output even though it should be. Which is also why it's not implemented
as a separate class. You won't need this output and not the profile output | [
"Returns",
"the",
"the",
"user",
"s",
"profile",
"level",
"note",
"that",
"this",
"runs",
"a",
"separate",
"request",
"because",
"the",
"profile",
"level",
"data",
"isn",
"t",
"in",
"the",
"standard",
"player",
"summary",
"output",
"even",
"though",
"it",
... | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L208-L226 | train |
Lagg/steamodd | steam/user.py | profile.from_def | def from_def(cls, obj):
""" Builds a profile object from a raw player summary object """
prof = cls(obj["steamid"])
prof._cache = obj
return prof | python | def from_def(cls, obj):
""" Builds a profile object from a raw player summary object """
prof = cls(obj["steamid"])
prof._cache = obj
return prof | [
"def",
"from_def",
"(",
"cls",
",",
"obj",
")",
":",
"prof",
"=",
"cls",
"(",
"obj",
"[",
"\"steamid\"",
"]",
")",
"prof",
".",
"_cache",
"=",
"obj",
"return",
"prof"
] | Builds a profile object from a raw player summary object | [
"Builds",
"a",
"profile",
"object",
"from",
"a",
"raw",
"player",
"summary",
"object"
] | 2e9ced4e7a6dbe3e09d5a648450bafc12b937b95 | https://github.com/Lagg/steamodd/blob/2e9ced4e7a6dbe3e09d5a648450bafc12b937b95/steam/user.py#L229-L234 | train |
michaelbrooks/twitter-monitor | twitter_monitor/listener.py | JsonStreamListener.on_status_withheld | def on_status_withheld(self, status_id, user_id, countries):
"""Called when a status is withheld"""
logger.info('Status %s withheld for user %s', status_id, user_id)
return True | python | def on_status_withheld(self, status_id, user_id, countries):
"""Called when a status is withheld"""
logger.info('Status %s withheld for user %s', status_id, user_id)
return True | [
"def",
"on_status_withheld",
"(",
"self",
",",
"status_id",
",",
"user_id",
",",
"countries",
")",
":",
"logger",
".",
"info",
"(",
"'Status %s withheld for user %s'",
",",
"status_id",
",",
"user_id",
")",
"return",
"True"
] | Called when a status is withheld | [
"Called",
"when",
"a",
"status",
"is",
"withheld"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L91-L94 | train |
michaelbrooks/twitter-monitor | twitter_monitor/listener.py | JsonStreamListener.on_disconnect | def on_disconnect(self, code, stream_name, reason):
"""Called when a disconnect is received"""
logger.error('Disconnect message: %s %s %s', code, stream_name, reason)
return True | python | def on_disconnect(self, code, stream_name, reason):
"""Called when a disconnect is received"""
logger.error('Disconnect message: %s %s %s', code, stream_name, reason)
return True | [
"def",
"on_disconnect",
"(",
"self",
",",
"code",
",",
"stream_name",
",",
"reason",
")",
":",
"logger",
".",
"error",
"(",
"'Disconnect message: %s %s %s'",
",",
"code",
",",
"stream_name",
",",
"reason",
")",
"return",
"True"
] | Called when a disconnect is received | [
"Called",
"when",
"a",
"disconnect",
"is",
"received"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L101-L104 | train |
michaelbrooks/twitter-monitor | twitter_monitor/listener.py | JsonStreamListener.on_error | def on_error(self, status_code):
"""Called when a non-200 status code is returned"""
logger.error('Twitter returned error code %s', status_code)
self.error = status_code
return False | python | def on_error(self, status_code):
"""Called when a non-200 status code is returned"""
logger.error('Twitter returned error code %s', status_code)
self.error = status_code
return False | [
"def",
"on_error",
"(",
"self",
",",
"status_code",
")",
":",
"logger",
".",
"error",
"(",
"'Twitter returned error code %s'",
",",
"status_code",
")",
"self",
".",
"error",
"=",
"status_code",
"return",
"False"
] | Called when a non-200 status code is returned | [
"Called",
"when",
"a",
"non",
"-",
"200",
"status",
"code",
"is",
"returned"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L110-L114 | train |
michaelbrooks/twitter-monitor | twitter_monitor/listener.py | JsonStreamListener.on_exception | def on_exception(self, exception):
"""An exception occurred in the streaming thread"""
logger.error('Exception from stream!', exc_info=True)
self.streaming_exception = exception | python | def on_exception(self, exception):
"""An exception occurred in the streaming thread"""
logger.error('Exception from stream!', exc_info=True)
self.streaming_exception = exception | [
"def",
"on_exception",
"(",
"self",
",",
"exception",
")",
":",
"logger",
".",
"error",
"(",
"'Exception from stream!'",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"streaming_exception",
"=",
"exception"
] | An exception occurred in the streaming thread | [
"An",
"exception",
"occurred",
"in",
"the",
"streaming",
"thread"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L121-L124 | train |
michaelbrooks/twitter-monitor | twitter_monitor/checker.py | TermChecker.check | def check(self):
"""
Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False.
"""
new_tracking_terms = self.update_tracking_terms()
terms_changed = False
# any deleted terms?
if self._tracking_terms_set > new_tracking_t... | python | def check(self):
"""
Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False.
"""
new_tracking_terms = self.update_tracking_terms()
terms_changed = False
# any deleted terms?
if self._tracking_terms_set > new_tracking_t... | [
"def",
"check",
"(",
"self",
")",
":",
"new_tracking_terms",
"=",
"self",
".",
"update_tracking_terms",
"(",
")",
"terms_changed",
"=",
"False",
"# any deleted terms?",
"if",
"self",
".",
"_tracking_terms_set",
">",
"new_tracking_terms",
":",
"logging",
".",
"debu... | Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False. | [
"Checks",
"if",
"the",
"list",
"of",
"tracked",
"terms",
"has",
"changed",
".",
"Returns",
"True",
"if",
"changed",
"otherwise",
"False",
"."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L33-L57 | train |
michaelbrooks/twitter-monitor | twitter_monitor/checker.py | FileTermChecker.update_tracking_terms | def update_tracking_terms(self):
"""
Terms must be one-per-line.
Blank lines will be skipped.
"""
import codecs
with codecs.open(self.filename,"r", encoding='utf8') as input:
# read all the lines
lines = input.readlines()
# build a set... | python | def update_tracking_terms(self):
"""
Terms must be one-per-line.
Blank lines will be skipped.
"""
import codecs
with codecs.open(self.filename,"r", encoding='utf8') as input:
# read all the lines
lines = input.readlines()
# build a set... | [
"def",
"update_tracking_terms",
"(",
"self",
")",
":",
"import",
"codecs",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"filename",
",",
"\"r\"",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"input",
":",
"# read all the lines",
"lines",
"=",
"input",
".... | Terms must be one-per-line.
Blank lines will be skipped. | [
"Terms",
"must",
"be",
"one",
"-",
"per",
"-",
"line",
".",
"Blank",
"lines",
"will",
"be",
"skipped",
"."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L75-L92 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | launch_debugger | def launch_debugger(frame, stream=None):
"""
Interrupt running process, and provide a python prompt for
interactive debugging.
"""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
import code, traceba... | python | def launch_debugger(frame, stream=None):
"""
Interrupt running process, and provide a python prompt for
interactive debugging.
"""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
import code, traceba... | [
"def",
"launch_debugger",
"(",
"frame",
",",
"stream",
"=",
"None",
")",
":",
"d",
"=",
"{",
"'_frame'",
":",
"frame",
"}",
"# Allow access to frame object.",
"d",
".",
"update",
"(",
"frame",
".",
"f_globals",
")",
"# Unless shadowed by global",
"d",
".",
"... | Interrupt running process, and provide a python prompt for
interactive debugging. | [
"Interrupt",
"running",
"process",
"and",
"provide",
"a",
"python",
"prompt",
"for",
"interactive",
"debugging",
"."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L75-L90 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | set_debug_listener | def set_debug_listener(stream):
"""Break into a debugger if receives the SIGUSR1 signal"""
def debugger(sig, frame):
launch_debugger(frame, stream)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, debugger)
else:
logger.warn("Cannot set SIGUSR1 signal for debug mode... | python | def set_debug_listener(stream):
"""Break into a debugger if receives the SIGUSR1 signal"""
def debugger(sig, frame):
launch_debugger(frame, stream)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, debugger)
else:
logger.warn("Cannot set SIGUSR1 signal for debug mode... | [
"def",
"set_debug_listener",
"(",
"stream",
")",
":",
"def",
"debugger",
"(",
"sig",
",",
"frame",
")",
":",
"launch_debugger",
"(",
"frame",
",",
"stream",
")",
"if",
"hasattr",
"(",
"signal",
",",
"'SIGUSR1'",
")",
":",
"signal",
".",
"signal",
"(",
... | Break into a debugger if receives the SIGUSR1 signal | [
"Break",
"into",
"a",
"debugger",
"if",
"receives",
"the",
"SIGUSR1",
"signal"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L93-L102 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | set_terminate_listeners | def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT"""
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | python | def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT"""
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | [
"def",
"set_terminate_listeners",
"(",
"stream",
")",
":",
"def",
"stop",
"(",
"signum",
",",
"frame",
")",
":",
"terminate",
"(",
"stream",
".",
"listener",
")",
"# Installs signal handlers for handling SIGINT and SIGTERM",
"# gracefully.",
"signal",
".",
"signal",
... | Die on SIGTERM or SIGINT | [
"Die",
"on",
"SIGTERM",
"or",
"SIGINT"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L115-L124 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | get_tweepy_auth | def get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret):
"""Make a tweepy auth object"""
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token,... | python | def get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret):
"""Make a tweepy auth object"""
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token,... | [
"def",
"get_tweepy_auth",
"(",
"twitter_api_key",
",",
"twitter_api_secret",
",",
"twitter_access_token",
",",
"twitter_access_token_secret",
")",
":",
"auth",
"=",
"tweepy",
".",
"OAuthHandler",
"(",
"twitter_api_key",
",",
"twitter_api_secret",
")",
"auth",
".",
"se... | Make a tweepy auth object | [
"Make",
"a",
"tweepy",
"auth",
"object"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L127-L134 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | construct_listener | def construct_listener(outfile=None):
"""Create the listener that prints tweets"""
if outfile is not None:
if os.path.exists(outfile):
raise IOError("File %s already exists" % outfile)
outfile = open(outfile, 'wb')
return PrintingListener(out=outfile) | python | def construct_listener(outfile=None):
"""Create the listener that prints tweets"""
if outfile is not None:
if os.path.exists(outfile):
raise IOError("File %s already exists" % outfile)
outfile = open(outfile, 'wb')
return PrintingListener(out=outfile) | [
"def",
"construct_listener",
"(",
"outfile",
"=",
"None",
")",
":",
"if",
"outfile",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"outfile",
")",
":",
"raise",
"IOError",
"(",
"\"File %s already exists\"",
"%",
"outfile",
")",
"... | Create the listener that prints tweets | [
"Create",
"the",
"listener",
"that",
"prints",
"tweets"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L137-L145 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | begin_stream_loop | def begin_stream_loop(stream, poll_interval):
"""Start and maintain the streaming connection..."""
while should_continue():
try:
stream.start_polling(poll_interval)
except Exception as e:
# Infinite restart
logger.error("Exception while polling. Restarting in ... | python | def begin_stream_loop(stream, poll_interval):
"""Start and maintain the streaming connection..."""
while should_continue():
try:
stream.start_polling(poll_interval)
except Exception as e:
# Infinite restart
logger.error("Exception while polling. Restarting in ... | [
"def",
"begin_stream_loop",
"(",
"stream",
",",
"poll_interval",
")",
":",
"while",
"should_continue",
"(",
")",
":",
"try",
":",
"stream",
".",
"start_polling",
"(",
"poll_interval",
")",
"except",
"Exception",
"as",
"e",
":",
"# Infinite restart",
"logger",
... | Start and maintain the streaming connection... | [
"Start",
"and",
"maintain",
"the",
"streaming",
"connection",
"..."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L150-L158 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | start | def start(track_file,
twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret,
poll_interval=15,
unfiltered=False,
languages=None,
debug=False,
outfile=None):
"""Start the stream."""
listener... | python | def start(track_file,
twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret,
poll_interval=15,
unfiltered=False,
languages=None,
debug=False,
outfile=None):
"""Start the stream."""
listener... | [
"def",
"start",
"(",
"track_file",
",",
"twitter_api_key",
",",
"twitter_api_secret",
",",
"twitter_access_token",
",",
"twitter_access_token_secret",
",",
"poll_interval",
"=",
"15",
",",
"unfiltered",
"=",
"False",
",",
"languages",
"=",
"None",
",",
"debug",
"=... | Start the stream. | [
"Start",
"the",
"stream",
"."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L161-L186 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | PrintingListener.on_status | def on_status(self, status):
"""Print out some tweets"""
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate | python | def on_status(self, status):
"""Print out some tweets"""
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate | [
"def",
"on_status",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"out",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"status",
")",
")",
"self",
".",
"out",
".",
"write",
"(",
"os",
".",
"linesep",
")",
"self",
".",
"received",
"+=",
"1",
... | Print out some tweets | [
"Print",
"out",
"some",
"tweets"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L38-L44 | train |
michaelbrooks/twitter-monitor | twitter_monitor/basic_stream.py | PrintingListener.print_status | def print_status(self):
"""Print out the current tweet rate and reset the counter"""
tweets = self.received
now = time.time()
diff = now - self.since
self.since = now
self.received = 0
if diff > 0:
logger.info("Receiving tweets at %s tps", tweets / dif... | python | def print_status(self):
"""Print out the current tweet rate and reset the counter"""
tweets = self.received
now = time.time()
diff = now - self.since
self.since = now
self.received = 0
if diff > 0:
logger.info("Receiving tweets at %s tps", tweets / dif... | [
"def",
"print_status",
"(",
"self",
")",
":",
"tweets",
"=",
"self",
".",
"received",
"now",
"=",
"time",
".",
"time",
"(",
")",
"diff",
"=",
"now",
"-",
"self",
".",
"since",
"self",
".",
"since",
"=",
"now",
"self",
".",
"received",
"=",
"0",
"... | Print out the current tweet rate and reset the counter | [
"Print",
"out",
"the",
"current",
"tweet",
"rate",
"and",
"reset",
"the",
"counter"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L50-L58 | train |
michaelbrooks/twitter-monitor | twitter_monitor/stream.py | DynamicTwitterStream.start_polling | def start_polling(self, interval):
"""
Start polling for term updates and streaming.
"""
interval = float(interval)
self.polling = True
# clear the stored list of terms - we aren't tracking any
self.term_checker.reset()
logger.info("Starting polling for... | python | def start_polling(self, interval):
"""
Start polling for term updates and streaming.
"""
interval = float(interval)
self.polling = True
# clear the stored list of terms - we aren't tracking any
self.term_checker.reset()
logger.info("Starting polling for... | [
"def",
"start_polling",
"(",
"self",
",",
"interval",
")",
":",
"interval",
"=",
"float",
"(",
"interval",
")",
"self",
".",
"polling",
"=",
"True",
"# clear the stored list of terms - we aren't tracking any",
"self",
".",
"term_checker",
".",
"reset",
"(",
")",
... | Start polling for term updates and streaming. | [
"Start",
"polling",
"for",
"term",
"updates",
"and",
"streaming",
"."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L33-L56 | train |
michaelbrooks/twitter-monitor | twitter_monitor/stream.py | DynamicTwitterStream.update_stream | def update_stream(self):
"""
Restarts the stream with the current list of tracking terms.
"""
need_to_restart = False
# If we think we are running, but something has gone wrong in the streaming thread
# Restart it.
if self.stream is not None and not self.stream.... | python | def update_stream(self):
"""
Restarts the stream with the current list of tracking terms.
"""
need_to_restart = False
# If we think we are running, but something has gone wrong in the streaming thread
# Restart it.
if self.stream is not None and not self.stream.... | [
"def",
"update_stream",
"(",
"self",
")",
":",
"need_to_restart",
"=",
"False",
"# If we think we are running, but something has gone wrong in the streaming thread",
"# Restart it.",
"if",
"self",
".",
"stream",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"stream",
... | Restarts the stream with the current list of tracking terms. | [
"Restarts",
"the",
"stream",
"with",
"the",
"current",
"list",
"of",
"tracking",
"terms",
"."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L65-L98 | train |
michaelbrooks/twitter-monitor | twitter_monitor/stream.py | DynamicTwitterStream.start_stream | def start_stream(self):
"""Starts a stream with teh current tracking terms"""
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.l... | python | def start_stream(self):
"""Starts a stream with teh current tracking terms"""
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.l... | [
"def",
"start_stream",
"(",
"self",
")",
":",
"tracking_terms",
"=",
"self",
".",
"term_checker",
".",
"tracking_terms",
"(",
")",
"if",
"len",
"(",
"tracking_terms",
")",
">",
"0",
"or",
"self",
".",
"unfiltered",
":",
"# we have terms to track, so build a new ... | Starts a stream with teh current tracking terms | [
"Starts",
"a",
"stream",
"with",
"teh",
"current",
"tracking",
"terms"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L100-L120 | train |
michaelbrooks/twitter-monitor | twitter_monitor/stream.py | DynamicTwitterStream.stop_stream | def stop_stream(self):
"""
Stops the current stream. Blocks until this is done.
"""
if self.stream is not None:
# There is a streaming thread
logger.warning("Stopping twitter stream...")
self.stream.disconnect()
self.stream = None
... | python | def stop_stream(self):
"""
Stops the current stream. Blocks until this is done.
"""
if self.stream is not None:
# There is a streaming thread
logger.warning("Stopping twitter stream...")
self.stream.disconnect()
self.stream = None
... | [
"def",
"stop_stream",
"(",
"self",
")",
":",
"if",
"self",
".",
"stream",
"is",
"not",
"None",
":",
"# There is a streaming thread",
"logger",
".",
"warning",
"(",
"\"Stopping twitter stream...\"",
")",
"self",
".",
"stream",
".",
"disconnect",
"(",
")",
"self... | Stops the current stream. Blocks until this is done. | [
"Stops",
"the",
"current",
"stream",
".",
"Blocks",
"until",
"this",
"is",
"done",
"."
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L122-L136 | train |
coagulant/django-twitter-tag | twitter_tag/templatetags/twitter_tag.py | BaseTwitterTag.enrich | def enrich(self, tweet):
""" Apply the local presentation logic to the fetched data."""
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %... | python | def enrich(self, tweet):
""" Apply the local presentation logic to the fetched data."""
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %... | [
"def",
"enrich",
"(",
"self",
",",
"tweet",
")",
":",
"tweet",
"=",
"urlize_tweet",
"(",
"expand_tweet_urls",
"(",
"tweet",
")",
")",
"# parses created_at \"Wed Aug 27 13:08:45 +0000 2008\"",
"if",
"settings",
".",
"USE_TZ",
":",
"tweet",
"[",
"'datetime'",
"]",
... | Apply the local presentation logic to the fetched data. | [
"Apply",
"the",
"local",
"presentation",
"logic",
"to",
"the",
"fetched",
"data",
"."
] | 2cb0f46837279e12b1ac250794a71611bac1acdc | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/templatetags/twitter_tag.py#L37-L47 | train |
coagulant/django-twitter-tag | twitter_tag/utils.py | get_user_cache_key | def get_user_cache_key(**kwargs):
""" Generate suitable key to cache twitter tag context
"""
key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
... | python | def get_user_cache_key(**kwargs):
""" Generate suitable key to cache twitter tag context
"""
key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
... | [
"def",
"get_user_cache_key",
"(",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"'get_tweets_%s'",
"%",
"(",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"kwargs",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"sorted",
"(",
"kwargs",
")",
"if",
"kwargs",
"["... | Generate suitable key to cache twitter tag context | [
"Generate",
"suitable",
"key",
"to",
"cache",
"twitter",
"tag",
"context"
] | 2cb0f46837279e12b1ac250794a71611bac1acdc | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L9-L15 | train |
coagulant/django-twitter-tag | twitter_tag/utils.py | get_search_cache_key | def get_search_cache_key(prefix, *args):
""" Generate suitable key to cache twitter tag context
"""
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return key | python | def get_search_cache_key(prefix, *args):
""" Generate suitable key to cache twitter tag context
"""
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return key | [
"def",
"get_search_cache_key",
"(",
"prefix",
",",
"*",
"args",
")",
":",
"key",
"=",
"'%s_%s'",
"%",
"(",
"prefix",
",",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"if",
"arg",
"]",
")",
")",
"not_allowed",
... | Generate suitable key to cache twitter tag context | [
"Generate",
"suitable",
"key",
"to",
"cache",
"twitter",
"tag",
"context"
] | 2cb0f46837279e12b1ac250794a71611bac1acdc | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L18-L24 | train |
coagulant/django-twitter-tag | twitter_tag/utils.py | urlize_tweet | def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
"""
text = tweet.get('html', tweet['text'])
for hash in tweet['entities']['hashtags']:
text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL %... | python | def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
"""
text = tweet.get('html', tweet['text'])
for hash in tweet['entities']['hashtags']:
text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL %... | [
"def",
"urlize_tweet",
"(",
"tweet",
")",
":",
"text",
"=",
"tweet",
".",
"get",
"(",
"'html'",
",",
"tweet",
"[",
"'text'",
"]",
")",
"for",
"hash",
"in",
"tweet",
"[",
"'entities'",
"]",
"[",
"'hashtags'",
"]",
":",
"text",
"=",
"text",
".",
"rep... | Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django. | [
"Turn",
"#hashtag",
"and"
] | 2cb0f46837279e12b1ac250794a71611bac1acdc | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L31-L41 | train |
coagulant/django-twitter-tag | twitter_tag/utils.py | expand_tweet_urls | def expand_tweet_urls(tweet):
""" Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet
"""
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
... | python | def expand_tweet_urls(tweet):
""" Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet
"""
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
... | [
"def",
"expand_tweet_urls",
"(",
"tweet",
")",
":",
"if",
"'retweeted_status'",
"in",
"tweet",
":",
"text",
"=",
"'RT @{user}: {text}'",
".",
"format",
"(",
"user",
"=",
"tweet",
"[",
"'retweeted_status'",
"]",
"[",
"'user'",
"]",
"[",
"'screen_name'",
"]",
... | Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet | [
"Replace",
"shortened",
"URLs",
"with",
"long",
"URLs",
"in",
"the",
"twitter",
"status",
"and",
"add",
"the",
"RT",
"flag",
".",
"Should",
"be",
"used",
"before",
"urlize_tweet"
] | 2cb0f46837279e12b1ac250794a71611bac1acdc | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L44-L59 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | safe_power | def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b | python | def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b | [
"def",
"safe_power",
"(",
"a",
",",
"b",
")",
":",
"if",
"abs",
"(",
"a",
")",
">",
"MAX_POWER",
"or",
"abs",
"(",
"b",
")",
">",
"MAX_POWER",
":",
"raise",
"ValueError",
"(",
"'Number too high!'",
")",
"return",
"a",
"**",
"b"
] | Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b | [
"Same",
"power",
"of",
"a",
"^",
"b",
":",
"param",
"a",
":",
"Number",
"a",
":",
"param",
"b",
":",
"Number",
"b",
":",
"return",
":",
"a",
"^",
"b"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L55-L64 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | rabin_miller | def rabin_miller(p):
"""
Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime
"""
# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function
if p < 2:
return False
if p != 2 ... | python | def rabin_miller(p):
"""
Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime
"""
# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function
if p < 2:
return False
if p != 2 ... | [
"def",
"rabin_miller",
"(",
"p",
")",
":",
"# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function",
"if",
"p",
"<",
"2",
":",
"return",
"False",
"if",
"p",
"!=",
"2",
"and",
"p",
"&",
"1",
"==",
"0",
":",
... | Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime | [
"Performs",
"a",
"rabin",
"-",
"miller",
"primality",
"test"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L67-L91 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | zero_width_split | def zero_width_split(pattern, string):
"""
Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array
"""
splits = list((m.start(), m.end()) for m in regex.finditer(patt... | python | def zero_width_split(pattern, string):
"""
Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array
"""
splits = list((m.start(), m.end()) for m in regex.finditer(patt... | [
"def",
"zero_width_split",
"(",
"pattern",
",",
"string",
")",
":",
"splits",
"=",
"list",
"(",
"(",
"m",
".",
"start",
"(",
")",
",",
"m",
".",
"end",
"(",
")",
")",
"for",
"m",
"in",
"regex",
".",
"finditer",
"(",
"pattern",
",",
"string",
",",... | Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array | [
"Split",
"a",
"string",
"on",
"a",
"regex",
"that",
"only",
"matches",
"zero",
"-",
"width",
"strings"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L308-L319 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | roll_group | def roll_group(group):
"""
Rolls a group of dice in 2d6, 3d10, d12, etc. format
:param group: String of dice group
:return: Array of results
"""
group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE)
num_of_dice = int(group[1]) if group[1] != '' else 1
type_of_dice = int(group[2... | python | def roll_group(group):
"""
Rolls a group of dice in 2d6, 3d10, d12, etc. format
:param group: String of dice group
:return: Array of results
"""
group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE)
num_of_dice = int(group[1]) if group[1] != '' else 1
type_of_dice = int(group[2... | [
"def",
"roll_group",
"(",
"group",
")",
":",
"group",
"=",
"regex",
".",
"match",
"(",
"r'^(\\d*)d(\\d+)$'",
",",
"group",
",",
"regex",
".",
"IGNORECASE",
")",
"num_of_dice",
"=",
"int",
"(",
"group",
"[",
"1",
"]",
")",
"if",
"group",
"[",
"1",
"]"... | Rolls a group of dice in 2d6, 3d10, d12, etc. format
:param group: String of dice group
:return: Array of results | [
"Rolls",
"a",
"group",
"of",
"dice",
"in",
"2d6",
"3d10",
"d12",
"etc",
".",
"format"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L322-L337 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | num_equal | def num_equal(result, operator, comparator):
"""
Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
... | python | def num_equal(result, operator, comparator):
"""
Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
... | [
"def",
"num_equal",
"(",
"result",
",",
"operator",
",",
"comparator",
")",
":",
"if",
"operator",
"==",
"'<'",
":",
"return",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"result",
"if",
"x",
"<",
"comparator",
"]",
")",
"elif",
"operator",
"==",
"'>'",
... | Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
:return: | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"a",
"list",
"that",
"pass",
"a",
"comparison"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L340-L357 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | roll_dice | def roll_dice(roll, *, functions=True, floats=True):
"""
Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string
"""
roll = ''.join(roll.split())
roll = regex.sub(r'(?<=d)%', ... | python | def roll_dice(roll, *, functions=True, floats=True):
"""
Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string
"""
roll = ''.join(roll.split())
roll = regex.sub(r'(?<=d)%', ... | [
"def",
"roll_dice",
"(",
"roll",
",",
"*",
",",
"functions",
"=",
"True",
",",
"floats",
"=",
"True",
")",
":",
"roll",
"=",
"''",
".",
"join",
"(",
"roll",
".",
"split",
"(",
")",
")",
"roll",
"=",
"regex",
".",
"sub",
"(",
"r'(?<=d)%'",
",",
... | Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string | [
"Rolls",
"dice",
"in",
"dice",
"notation",
"with",
"advanced",
"syntax",
"used",
"according",
"to",
"tinyurl",
".",
"com",
"/",
"pydice"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L360-L875 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | SimpleEval.eval | def eval(self, expr):
"""
Evaluates an expression
:param expr: Expression to evaluate
:return: Result of expression
"""
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
# and evaluate:
return self._eval(ast.pa... | python | def eval(self, expr):
"""
Evaluates an expression
:param expr: Expression to evaluate
:return: Result of expression
"""
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
# and evaluate:
return self._eval(ast.pa... | [
"def",
"eval",
"(",
"self",
",",
"expr",
")",
":",
"# set a copy of the expression aside, so we can give nice errors...",
"self",
".",
"expr",
"=",
"expr",
"# and evaluate:",
"return",
"self",
".",
"_eval",
"(",
"ast",
".",
"parse",
"(",
"expr",
".",
"strip",
"(... | Evaluates an expression
:param expr: Expression to evaluate
:return: Result of expression | [
"Evaluates",
"an",
"expression"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L139-L151 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | SimpleEval._eval | def _eval(self, node):
"""
Evaluate a node
:param node: Node to eval
:return: Result of node
"""
try:
handler = self.nodes[type(node)]
except KeyError:
raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__na... | python | def _eval(self, node):
"""
Evaluate a node
:param node: Node to eval
:return: Result of node
"""
try:
handler = self.nodes[type(node)]
except KeyError:
raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__na... | [
"def",
"_eval",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"handler",
"=",
"self",
".",
"nodes",
"[",
"type",
"(",
"node",
")",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Sorry, {0} is not available in this evaluator\"",
".",
"format... | Evaluate a node
:param node: Node to eval
:return: Result of node | [
"Evaluate",
"a",
"node"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L153-L165 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | SimpleEval._eval_num | def _eval_num(self, node):
"""
Evaluate a numerical node
:param node: Node to eval
:return: Result of node
"""
if self.floats:
return node.n
else:
return int(node.n) | python | def _eval_num(self, node):
"""
Evaluate a numerical node
:param node: Node to eval
:return: Result of node
"""
if self.floats:
return node.n
else:
return int(node.n) | [
"def",
"_eval_num",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"floats",
":",
"return",
"node",
".",
"n",
"else",
":",
"return",
"int",
"(",
"node",
".",
"n",
")"
] | Evaluate a numerical node
:param node: Node to eval
:return: Result of node | [
"Evaluate",
"a",
"numerical",
"node"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L167-L177 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | SimpleEval._eval_unaryop | def _eval_unaryop(self, node):
"""
Evaluate a unary operator node (ie. -2, +3)
Currently just supports positive and negative
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.operand)) | python | def _eval_unaryop(self, node):
"""
Evaluate a unary operator node (ie. -2, +3)
Currently just supports positive and negative
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.operand)) | [
"def",
"_eval_unaryop",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"operators",
"[",
"type",
"(",
"node",
".",
"op",
")",
"]",
"(",
"self",
".",
"_eval",
"(",
"node",
".",
"operand",
")",
")"
] | Evaluate a unary operator node (ie. -2, +3)
Currently just supports positive and negative
:param node: Node to eval
:return: Result of node | [
"Evaluate",
"a",
"unary",
"operator",
"node",
"(",
"ie",
".",
"-",
"2",
"+",
"3",
")",
"Currently",
"just",
"supports",
"positive",
"and",
"negative"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L179-L187 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | SimpleEval._eval_binop | def _eval_binop(self, node):
"""
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.left),
self._eval(node.right)) | python | def _eval_binop(self, node):
"""
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.left),
self._eval(node.right)) | [
"def",
"_eval_binop",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"operators",
"[",
"type",
"(",
"node",
".",
"op",
")",
"]",
"(",
"self",
".",
"_eval",
"(",
"node",
".",
"left",
")",
",",
"self",
".",
"_eval",
"(",
"node",
".",
... | Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node | [
"Evaluate",
"a",
"binary",
"operator",
"node",
"(",
"ie",
".",
"2",
"+",
"3",
"5",
"*",
"6",
"3",
"**",
"4",
")"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L189-L197 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | SimpleEval._eval_call | def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... | python | def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... | [
"def",
"_eval_call",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"func",
"=",
"self",
".",
"functions",
"[",
"node",
".",
"func",
".",
"id",
"]",
"except",
"KeyError",
":",
"raise",
"NameError",
"(",
"node",
".",
"func",
".",
"id",
")",
"value"... | Evaluate a function call
:param node: Node to eval
:return: Result of node | [
"Evaluate",
"a",
"function",
"call"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L199-L221 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | DiceBag.roll_dice | def roll_dice(self): # Roll dice with current roll
"""
Rolls dicebag and sets last_roll and last_explanation to roll results
:return: Roll results.
"""
roll = roll_dice(self.roll, floats=self.floats, functions=self.functions)
self._last_roll = roll[0]
self._las... | python | def roll_dice(self): # Roll dice with current roll
"""
Rolls dicebag and sets last_roll and last_explanation to roll results
:return: Roll results.
"""
roll = roll_dice(self.roll, floats=self.floats, functions=self.functions)
self._last_roll = roll[0]
self._las... | [
"def",
"roll_dice",
"(",
"self",
")",
":",
"# Roll dice with current roll",
"roll",
"=",
"roll_dice",
"(",
"self",
".",
"roll",
",",
"floats",
"=",
"self",
".",
"floats",
",",
"functions",
"=",
"self",
".",
"functions",
")",
"self",
".",
"_last_roll",
"=",... | Rolls dicebag and sets last_roll and last_explanation to roll results
:return: Roll results. | [
"Rolls",
"dicebag",
"and",
"sets",
"last_roll",
"and",
"last_explanation",
"to",
"roll",
"results"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L242-L253 | train |
ThePlasmaRailgun/py-rolldice | rolldice/rolldice.py | DiceBag.roll | def roll(self, value):
"""
Setter for roll, verifies the roll is valid
:param value: Roll
:return: None
"""
if type(value) != str: # Make sure dice roll is a str
raise TypeError('Dice roll must be a string in dice notation')
try:
roll_dic... | python | def roll(self, value):
"""
Setter for roll, verifies the roll is valid
:param value: Roll
:return: None
"""
if type(value) != str: # Make sure dice roll is a str
raise TypeError('Dice roll must be a string in dice notation')
try:
roll_dic... | [
"def",
"roll",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"!=",
"str",
":",
"# Make sure dice roll is a str",
"raise",
"TypeError",
"(",
"'Dice roll must be a string in dice notation'",
")",
"try",
":",
"roll_dice",
"(",
"value",
")",
... | Setter for roll, verifies the roll is valid
:param value: Roll
:return: None | [
"Setter",
"for",
"roll",
"verifies",
"the",
"roll",
"is",
"valid"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L273-L287 | train |
alexcouper/captainhook | captainhook/checkers/pdb_checker.py | run | def run(files, temp_folder, arg=''):
"Look for pdb.set_trace() commands in python files."
parser = get_parser()
args = parser.parse_args(arg.split())
py_files = filter_python_files(files)
if args.ignore:
orig_file_list = original_files(py_files, temp_folder)
py_files = set(orig_file... | python | def run(files, temp_folder, arg=''):
"Look for pdb.set_trace() commands in python files."
parser = get_parser()
args = parser.parse_args(arg.split())
py_files = filter_python_files(files)
if args.ignore:
orig_file_list = original_files(py_files, temp_folder)
py_files = set(orig_file... | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
",",
"arg",
"=",
"''",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"arg",
".",
"split",
"(",
")",
")",
"py_files",
"=",
"filter_python_files",
"(",
"f... | Look for pdb.set_trace() commands in python files. | [
"Look",
"for",
"pdb",
".",
"set_trace",
"()",
"commands",
"in",
"python",
"files",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/pdb_checker.py#L15-L26 | train |
alexcouper/captainhook | captainhook/pre_commit.py | checks | def checks():
"""
An iterator of valid checks that are in the installed checkers package.
yields check name, check module
"""
checkers_dir = os.path.dirname(checkers.__file__)
mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])]
for name in mod_names:
mod = impo... | python | def checks():
"""
An iterator of valid checks that are in the installed checkers package.
yields check name, check module
"""
checkers_dir = os.path.dirname(checkers.__file__)
mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])]
for name in mod_names:
mod = impo... | [
"def",
"checks",
"(",
")",
":",
"checkers_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"checkers",
".",
"__file__",
")",
"mod_names",
"=",
"[",
"name",
"for",
"_",
",",
"name",
",",
"_",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"[",
"checkers... | An iterator of valid checks that are in the installed checkers package.
yields check name, check module | [
"An",
"iterator",
"of",
"valid",
"checks",
"that",
"are",
"in",
"the",
"installed",
"checkers",
"package",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L40-L54 | train |
alexcouper/captainhook | captainhook/pre_commit.py | files_to_check | def files_to_check(commit_only):
"""
Validate the commit diff.
Make copies of the staged changes for analysis.
"""
global TEMP_FOLDER
safe_directory = tempfile.mkdtemp()
TEMP_FOLDER = safe_directory
files = get_files(commit_only=commit_only, copy_dest=safe_directory)
try:
... | python | def files_to_check(commit_only):
"""
Validate the commit diff.
Make copies of the staged changes for analysis.
"""
global TEMP_FOLDER
safe_directory = tempfile.mkdtemp()
TEMP_FOLDER = safe_directory
files = get_files(commit_only=commit_only, copy_dest=safe_directory)
try:
... | [
"def",
"files_to_check",
"(",
"commit_only",
")",
":",
"global",
"TEMP_FOLDER",
"safe_directory",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"TEMP_FOLDER",
"=",
"safe_directory",
"files",
"=",
"get_files",
"(",
"commit_only",
"=",
"commit_only",
",",
"copy_dest",
... | Validate the commit diff.
Make copies of the staged changes for analysis. | [
"Validate",
"the",
"commit",
"diff",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L66-L81 | train |
alexcouper/captainhook | captainhook/pre_commit.py | main | def main(commit_only=True):
"""
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
"""
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for name, mod ... | python | def main(commit_only=True):
"""
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
"""
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for name, mod ... | [
"def",
"main",
"(",
"commit_only",
"=",
"True",
")",
":",
"global",
"TEMP_FOLDER",
"exit_code",
"=",
"0",
"hook_checks",
"=",
"HookConfig",
"(",
"get_config_file",
"(",
")",
")",
"with",
"files_to_check",
"(",
"commit_only",
")",
"as",
"files",
":",
"for",
... | Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit | [
"Run",
"the",
"configured",
"code",
"checks",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L84-L123 | train |
alexcouper/captainhook | captainhook/checkers/utils.py | get_files | def get_files(commit_only=True, copy_dest=None):
"Get copies of files for analysis."
if commit_only:
real_files = bash(
"git diff --cached --name-status | "
"grep -v -E '^D' | "
"awk '{ print ( $(NF) ) }' "
).value().strip()
else:
real_files = bash... | python | def get_files(commit_only=True, copy_dest=None):
"Get copies of files for analysis."
if commit_only:
real_files = bash(
"git diff --cached --name-status | "
"grep -v -E '^D' | "
"awk '{ print ( $(NF) ) }' "
).value().strip()
else:
real_files = bash... | [
"def",
"get_files",
"(",
"commit_only",
"=",
"True",
",",
"copy_dest",
"=",
"None",
")",
":",
"if",
"commit_only",
":",
"real_files",
"=",
"bash",
"(",
"\"git diff --cached --name-status | \"",
"\"grep -v -E '^D' | \"",
"\"awk '{ print ( $(NF) ) }' \"",
")",
".",
"val... | Get copies of files for analysis. | [
"Get",
"copies",
"of",
"files",
"for",
"analysis",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L34-L49 | train |
alexcouper/captainhook | captainhook/checkers/utils.py | create_fake_copies | def create_fake_copies(files, destination):
"""
Create copies of the given list of files in the destination given.
Creates copies of the actual files to be committed using
git show :<filename>
Return a list of destination files.
"""
dest_files = []
for filename in files:
leaf_d... | python | def create_fake_copies(files, destination):
"""
Create copies of the given list of files in the destination given.
Creates copies of the actual files to be committed using
git show :<filename>
Return a list of destination files.
"""
dest_files = []
for filename in files:
leaf_d... | [
"def",
"create_fake_copies",
"(",
"files",
",",
"destination",
")",
":",
"dest_files",
"=",
"[",
"]",
"for",
"filename",
"in",
"files",
":",
"leaf_dest_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"os",
".",
"path",
".",
"dirnam... | Create copies of the given list of files in the destination given.
Creates copies of the actual files to be committed using
git show :<filename>
Return a list of destination files. | [
"Create",
"copies",
"of",
"the",
"given",
"list",
"of",
"files",
"in",
"the",
"destination",
"given",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L52-L72 | train |
alexcouper/captainhook | captainhook/checkers/utils.py | filter_python_files | def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if exten... | python | def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if exten... | [
"def",
"filter_python_files",
"(",
"files",
")",
":",
"py_files",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"# If we end in .py, or if we don't have an extension and file says that",
"# we are a python script, then add us to the list",
"extension",
"=",
"os",
".",
"pat... | Get all python files from the list of files. | [
"Get",
"all",
"python",
"files",
"from",
"the",
"list",
"of",
"files",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L75-L91 | train |
alexcouper/captainhook | captainhook/checkers/utils.py | HookConfig.configuration | def configuration(self, plugin):
"""
Get plugin configuration.
Return a tuple of (on|off|default, args)
"""
conf = self.config.get(plugin, "default;").split(';')
if len(conf) == 1:
conf.append('')
return tuple(conf) | python | def configuration(self, plugin):
"""
Get plugin configuration.
Return a tuple of (on|off|default, args)
"""
conf = self.config.get(plugin, "default;").split(';')
if len(conf) == 1:
conf.append('')
return tuple(conf) | [
"def",
"configuration",
"(",
"self",
",",
"plugin",
")",
":",
"conf",
"=",
"self",
".",
"config",
".",
"get",
"(",
"plugin",
",",
"\"default;\"",
")",
".",
"split",
"(",
"';'",
")",
"if",
"len",
"(",
"conf",
")",
"==",
"1",
":",
"conf",
".",
"app... | Get plugin configuration.
Return a tuple of (on|off|default, args) | [
"Get",
"plugin",
"configuration",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L121-L130 | train |
alexcouper/captainhook | captainhook/checkers/frosted_checker.py | run | def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NOQA
except ImportError:
return NO_FROSTED_MSG
py_files = filter_python_files(files)
cmd = 'frosted {0}'.format(' '.join(py_files))
return bash(cmd).value() | python | def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NOQA
except ImportError:
return NO_FROSTED_MSG
py_files = filter_python_files(files)
cmd = 'frosted {0}'.format(' '.join(py_files))
return bash(cmd).value() | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"try",
":",
"import",
"frosted",
"# NOQA",
"except",
"ImportError",
":",
"return",
"NO_FROSTED_MSG",
"py_files",
"=",
"filter_python_files",
"(",
"files",
")",
"cmd",
"=",
"'frosted {0}'",
".",
"format"... | Check frosted errors in the code base. | [
"Check",
"frosted",
"errors",
"in",
"the",
"code",
"base",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/frosted_checker.py#L14-L24 | train |
alexcouper/captainhook | captainhook/checkers/isort_checker.py | run | def run(files, temp_folder):
"""Check isort errors in the code base.
For the --quiet option, at least isort >= 4.1.1 is required.
https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411
"""
try:
import isort # NOQA
except ImportError:
return NO_ISORT_MSG
py_... | python | def run(files, temp_folder):
"""Check isort errors in the code base.
For the --quiet option, at least isort >= 4.1.1 is required.
https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411
"""
try:
import isort # NOQA
except ImportError:
return NO_ISORT_MSG
py_... | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"try",
":",
"import",
"isort",
"# NOQA",
"except",
"ImportError",
":",
"return",
"NO_ISORT_MSG",
"py_files",
"=",
"filter_python_files",
"(",
"files",
")",
"# --quiet because isort >= 4.1 outputs its logo in th... | Check isort errors in the code base.
For the --quiet option, at least isort >= 4.1.1 is required.
https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411 | [
"Check",
"isort",
"errors",
"in",
"the",
"code",
"base",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/isort_checker.py#L13-L28 | train |
alexcouper/captainhook | captainhook/checkers/block_branches.py | run | def run(files, temp_folder, arg=None):
"Check we're not committing to a blocked branch"
parser = get_parser()
argos = parser.parse_args(arg.split())
current_branch = bash('git symbolic-ref HEAD').value()
current_branch = current_branch.replace('refs/heads/', '').strip()
if current_branch in arg... | python | def run(files, temp_folder, arg=None):
"Check we're not committing to a blocked branch"
parser = get_parser()
argos = parser.parse_args(arg.split())
current_branch = bash('git symbolic-ref HEAD').value()
current_branch = current_branch.replace('refs/heads/', '').strip()
if current_branch in arg... | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
",",
"arg",
"=",
"None",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"argos",
"=",
"parser",
".",
"parse_args",
"(",
"arg",
".",
"split",
"(",
")",
")",
"current_branch",
"=",
"bash",
"(",
"'git sy... | Check we're not committing to a blocked branch | [
"Check",
"we",
"re",
"not",
"committing",
"to",
"a",
"blocked",
"branch"
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/block_branches.py#L11-L20 | train |
alexcouper/captainhook | captainhook/checkers/pylint_checker.py | run | def run(files, temp_folder, arg=None):
"Check coding convention of the code base."
try:
import pylint
except ImportError:
return NO_PYLINT_MSG
# set default level of threshold
arg = arg or SCORE
py_files = filter_python_files(files)
if not py_files:
return False
... | python | def run(files, temp_folder, arg=None):
"Check coding convention of the code base."
try:
import pylint
except ImportError:
return NO_PYLINT_MSG
# set default level of threshold
arg = arg or SCORE
py_files = filter_python_files(files)
if not py_files:
return False
... | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
",",
"arg",
"=",
"None",
")",
":",
"try",
":",
"import",
"pylint",
"except",
"ImportError",
":",
"return",
"NO_PYLINT_MSG",
"# set default level of threshold",
"arg",
"=",
"arg",
"or",
"SCORE",
"py_files",
"=",
... | Check coding convention of the code base. | [
"Check",
"coding",
"convention",
"of",
"the",
"code",
"base",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/pylint_checker.py#L17-L42 | train |
alexcouper/captainhook | captainhook/checkers/python3.py | run | def run(files, temp_folder):
"Check to see if python files are py3 compatible"
errors = []
for py_file in filter_python_files(files):
# We only want to show errors if we CAN'T compile to py3.
# but we want to show all the errors at once.
b = bash('python3 -m py_compile {0}'.format(py... | python | def run(files, temp_folder):
"Check to see if python files are py3 compatible"
errors = []
for py_file in filter_python_files(files):
# We only want to show errors if we CAN'T compile to py3.
# but we want to show all the errors at once.
b = bash('python3 -m py_compile {0}'.format(py... | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"py_file",
"in",
"filter_python_files",
"(",
"files",
")",
":",
"# We only want to show errors if we CAN'T compile to py3.",
"# but we want to show all the errors at once.",
"b",
"... | Check to see if python files are py3 compatible | [
"Check",
"to",
"see",
"if",
"python",
"files",
"are",
"py3",
"compatible"
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/python3.py#L9-L19 | train |
alexcouper/captainhook | captainhook/checkers/flake8_checker.py | run | def run(files, temp_folder):
"Check flake8 errors in the code base."
try:
import flake8 # NOQA
except ImportError:
return NO_FLAKE_MSG
try:
from flake8.engine import get_style_guide
except ImportError:
# We're on a new version of flake8
from flake8.api.legacy... | python | def run(files, temp_folder):
"Check flake8 errors in the code base."
try:
import flake8 # NOQA
except ImportError:
return NO_FLAKE_MSG
try:
from flake8.engine import get_style_guide
except ImportError:
# We're on a new version of flake8
from flake8.api.legacy... | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"try",
":",
"import",
"flake8",
"# NOQA",
"except",
"ImportError",
":",
"return",
"NO_FLAKE_MSG",
"try",
":",
"from",
"flake8",
".",
"engine",
"import",
"get_style_guide",
"except",
"ImportError",
":",
... | Check flake8 errors in the code base. | [
"Check",
"flake8",
"errors",
"in",
"the",
"code",
"base",
"."
] | 5593ee8756dfa06959adb4320b4f6308277bb9d3 | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/flake8_checker.py#L45-L67 | train |
bpython/curtsies | examples/tttplaybitboard.py | tictactoe | def tictactoe(w, i, player, opponent, grid=None):
"Put two strategies to a classic battle of wits."
grid = grid or empty_grid
while True:
w.render_to_terminal(w.array_from_text(view(grid)))
if is_won(grid):
print(whose_move(grid), "wins.")
break
if not success... | python | def tictactoe(w, i, player, opponent, grid=None):
"Put two strategies to a classic battle of wits."
grid = grid or empty_grid
while True:
w.render_to_terminal(w.array_from_text(view(grid)))
if is_won(grid):
print(whose_move(grid), "wins.")
break
if not success... | [
"def",
"tictactoe",
"(",
"w",
",",
"i",
",",
"player",
",",
"opponent",
",",
"grid",
"=",
"None",
")",
":",
"grid",
"=",
"grid",
"or",
"empty_grid",
"while",
"True",
":",
"w",
".",
"render_to_terminal",
"(",
"w",
".",
"array_from_text",
"(",
"view",
... | Put two strategies to a classic battle of wits. | [
"Put",
"two",
"strategies",
"to",
"a",
"classic",
"battle",
"of",
"wits",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L40-L52 | train |
bpython/curtsies | examples/tttplaybitboard.py | memo | def memo(f):
"Return a function like f that remembers and reuses results of past calls."
table = {}
def memo_f(*args):
try:
return table[args]
except KeyError:
table[args] = value = f(*args)
return value
return memo_f | python | def memo(f):
"Return a function like f that remembers and reuses results of past calls."
table = {}
def memo_f(*args):
try:
return table[args]
except KeyError:
table[args] = value = f(*args)
return value
return memo_f | [
"def",
"memo",
"(",
"f",
")",
":",
"table",
"=",
"{",
"}",
"def",
"memo_f",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"table",
"[",
"args",
"]",
"except",
"KeyError",
":",
"table",
"[",
"args",
"]",
"=",
"value",
"=",
"f",
"(",
"*",
"... | Return a function like f that remembers and reuses results of past calls. | [
"Return",
"a",
"function",
"like",
"f",
"that",
"remembers",
"and",
"reuses",
"results",
"of",
"past",
"calls",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L60-L69 | train |
bpython/curtsies | examples/tttplaybitboard.py | human_play | def human_play(w, i, grid):
"Just ask for a move."
plaint = ''
prompt = whose_move(grid) + " move? [1-9] "
while True:
w.render_to_terminal(w.array_from_text(view(grid)
+ '\n\n' + plaint + prompt))
key = c = i.next()
try:
... | python | def human_play(w, i, grid):
"Just ask for a move."
plaint = ''
prompt = whose_move(grid) + " move? [1-9] "
while True:
w.render_to_terminal(w.array_from_text(view(grid)
+ '\n\n' + plaint + prompt))
key = c = i.next()
try:
... | [
"def",
"human_play",
"(",
"w",
",",
"i",
",",
"grid",
")",
":",
"plaint",
"=",
"''",
"prompt",
"=",
"whose_move",
"(",
"grid",
")",
"+",
"\" move? [1-9] \"",
"while",
"True",
":",
"w",
".",
"render_to_terminal",
"(",
"w",
".",
"array_from_text",
"(",
"... | Just ask for a move. | [
"Just",
"ask",
"for",
"a",
"move",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L74-L94 | train |
bpython/curtsies | examples/tttplaybitboard.py | max_play | def max_play(w, i, grid):
"Play like Spock, except breaking ties by drunk_value."
return min(successors(grid),
key=lambda succ: (evaluate(succ), drunk_value(succ))) | python | def max_play(w, i, grid):
"Play like Spock, except breaking ties by drunk_value."
return min(successors(grid),
key=lambda succ: (evaluate(succ), drunk_value(succ))) | [
"def",
"max_play",
"(",
"w",
",",
"i",
",",
"grid",
")",
":",
"return",
"min",
"(",
"successors",
"(",
"grid",
")",
",",
"key",
"=",
"lambda",
"succ",
":",
"(",
"evaluate",
"(",
"succ",
")",
",",
"drunk_value",
"(",
"succ",
")",
")",
")"
] | Play like Spock, except breaking ties by drunk_value. | [
"Play",
"like",
"Spock",
"except",
"breaking",
"ties",
"by",
"drunk_value",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L106-L109 | train |
bpython/curtsies | examples/tttplaybitboard.py | drunk_value | def drunk_value(grid):
"Return the expected value to the player if both players play at random."
if is_won(grid): return -1
succs = successors(grid)
return -average(map(drunk_value, succs)) if succs else 0 | python | def drunk_value(grid):
"Return the expected value to the player if both players play at random."
if is_won(grid): return -1
succs = successors(grid)
return -average(map(drunk_value, succs)) if succs else 0 | [
"def",
"drunk_value",
"(",
"grid",
")",
":",
"if",
"is_won",
"(",
"grid",
")",
":",
"return",
"-",
"1",
"succs",
"=",
"successors",
"(",
"grid",
")",
"return",
"-",
"average",
"(",
"map",
"(",
"drunk_value",
",",
"succs",
")",
")",
"if",
"succs",
"... | Return the expected value to the player if both players play at random. | [
"Return",
"the",
"expected",
"value",
"to",
"the",
"player",
"if",
"both",
"players",
"play",
"at",
"random",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L112-L116 | train |
bpython/curtsies | examples/tttplaybitboard.py | evaluate | def evaluate(grid):
"Return the value for the player to move, assuming perfect play."
if is_won(grid): return -1
succs = successors(grid)
return -min(map(evaluate, succs)) if succs else 0 | python | def evaluate(grid):
"Return the value for the player to move, assuming perfect play."
if is_won(grid): return -1
succs = successors(grid)
return -min(map(evaluate, succs)) if succs else 0 | [
"def",
"evaluate",
"(",
"grid",
")",
":",
"if",
"is_won",
"(",
"grid",
")",
":",
"return",
"-",
"1",
"succs",
"=",
"successors",
"(",
"grid",
")",
"return",
"-",
"min",
"(",
"map",
"(",
"evaluate",
",",
"succs",
")",
")",
"if",
"succs",
"else",
"... | Return the value for the player to move, assuming perfect play. | [
"Return",
"the",
"value",
"for",
"the",
"player",
"to",
"move",
"assuming",
"perfect",
"play",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L119-L123 | train |
bpython/curtsies | examples/tttplaybitboard.py | is_won | def is_won(grid):
"Did the latest move win the game?"
p, q = grid
return any(way == (way & q) for way in ways_to_win) | python | def is_won(grid):
"Did the latest move win the game?"
p, q = grid
return any(way == (way & q) for way in ways_to_win) | [
"def",
"is_won",
"(",
"grid",
")",
":",
"p",
",",
"q",
"=",
"grid",
"return",
"any",
"(",
"way",
"==",
"(",
"way",
"&",
"q",
")",
"for",
"way",
"in",
"ways_to_win",
")"
] | Did the latest move win the game? | [
"Did",
"the",
"latest",
"move",
"win",
"the",
"game?"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L139-L142 | train |
bpython/curtsies | examples/tttplaybitboard.py | apply_move | def apply_move(grid, move):
"Try to move: return a new grid, or None if illegal."
p, q = grid
bit = 1 << move
return (q, p | bit) if 0 == (bit & (p | q)) else None | python | def apply_move(grid, move):
"Try to move: return a new grid, or None if illegal."
p, q = grid
bit = 1 << move
return (q, p | bit) if 0 == (bit & (p | q)) else None | [
"def",
"apply_move",
"(",
"grid",
",",
"move",
")",
":",
"p",
",",
"q",
"=",
"grid",
"bit",
"=",
"1",
"<<",
"move",
"return",
"(",
"q",
",",
"p",
"|",
"bit",
")",
"if",
"0",
"==",
"(",
"bit",
"&",
"(",
"p",
"|",
"q",
")",
")",
"else",
"No... | Try to move: return a new grid, or None if illegal. | [
"Try",
"to",
"move",
":",
"return",
"a",
"new",
"grid",
"or",
"None",
"if",
"illegal",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L161-L165 | train |
bpython/curtsies | examples/tttplaybitboard.py | player_marks | def player_marks(grid):
"Return two results: the player's mark and their opponent's."
p, q = grid
return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX' | python | def player_marks(grid):
"Return two results: the player's mark and their opponent's."
p, q = grid
return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX' | [
"def",
"player_marks",
"(",
"grid",
")",
":",
"p",
",",
"q",
"=",
"grid",
"return",
"'XO'",
"if",
"sum",
"(",
"player_bits",
"(",
"p",
")",
")",
"==",
"sum",
"(",
"player_bits",
"(",
"q",
")",
")",
"else",
"'OX'"
] | Return two results: the player's mark and their opponent's. | [
"Return",
"two",
"results",
":",
"the",
"player",
"s",
"mark",
"and",
"their",
"opponent",
"s",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L181-L184 | train |
bpython/curtsies | examples/tttplaybitboard.py | view | def view(grid):
"Show a grid human-readably."
p_mark, q_mark = player_marks(grid)
return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.'
for by_p, by_q in zip(*map(player_bits, grid))) | python | def view(grid):
"Show a grid human-readably."
p_mark, q_mark = player_marks(grid)
return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.'
for by_p, by_q in zip(*map(player_bits, grid))) | [
"def",
"view",
"(",
"grid",
")",
":",
"p_mark",
",",
"q_mark",
"=",
"player_marks",
"(",
"grid",
")",
"return",
"grid_format",
"%",
"tuple",
"(",
"p_mark",
"if",
"by_p",
"else",
"q_mark",
"if",
"by_q",
"else",
"'.'",
"for",
"by_p",
",",
"by_q",
"in",
... | Show a grid human-readably. | [
"Show",
"a",
"grid",
"human",
"-",
"readably",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L189-L193 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | read_sdpa_out | def read_sdpa_out(filename, solutionmatrix=False, status=False,
sdp=None):
"""Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solu... | python | def read_sdpa_out(filename, solutionmatrix=False, status=False,
sdp=None):
"""Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solu... | [
"def",
"read_sdpa_out",
"(",
"filename",
",",
"solutionmatrix",
"=",
"False",
",",
"status",
"=",
"False",
",",
"sdp",
"=",
"None",
")",
":",
"primal",
"=",
"None",
"dual",
"=",
"None",
"x_mat",
"=",
"None",
"y_mat",
"=",
"None",
"status_string",
"=",
... | Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solutionmatrix: bool.
:param status: Optional parameter for retrieving the status.
:type status:... | [
"Helper",
"function",
"to",
"parse",
"the",
"output",
"file",
"of",
"SDPA",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L47-L119 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | solve_with_sdpa | def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | python | def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | [
"def",
"solve_with_sdpa",
"(",
"sdp",
",",
"solverparameters",
"=",
"None",
")",
":",
"solverexecutable",
"=",
"detect_sdpa",
"(",
"solverparameters",
")",
"if",
"solverexecutable",
"is",
"None",
":",
"raise",
"OSError",
"(",
"\"SDPA is not in the path or the executab... | Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:type solverparameters: dict of str.
:returns: tuple of... | [
"Helper",
"function",
"to",
"write",
"out",
"the",
"SDP",
"problem",
"to",
"a",
"temporary",
"file",
"call",
"the",
"solver",
"and",
"parse",
"the",
"output",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L148-L191 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | convert_row_to_sdpa_index | def convert_row_to_sdpa_index(block_struct, row_offsets, row):
"""Helper function to map to sparse SDPA index values.
"""
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i... | python | def convert_row_to_sdpa_index(block_struct, row_offsets, row):
"""Helper function to map to sparse SDPA index values.
"""
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i... | [
"def",
"convert_row_to_sdpa_index",
"(",
"block_struct",
",",
"row_offsets",
",",
"row",
")",
":",
"block_index",
"=",
"bisect_left",
"(",
"row_offsets",
"[",
"1",
":",
"]",
",",
"row",
"+",
"1",
")",
"width",
"=",
"block_struct",
"[",
"block_index",
"]",
... | Helper function to map to sparse SDPA index values. | [
"Helper",
"function",
"to",
"map",
"to",
"sparse",
"SDPA",
"index",
"values",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L194-L201 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | write_to_sdpa | def write_to_sdpa(sdp, filename):
"""Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str.
"""
# Coefficient matrices
row_offsets ... | python | def write_to_sdpa(sdp, filename):
"""Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str.
"""
# Coefficient matrices
row_offsets ... | [
"def",
"write_to_sdpa",
"(",
"sdp",
",",
"filename",
")",
":",
"# Coefficient matrices",
"row_offsets",
"=",
"[",
"0",
"]",
"cumulative_sum",
"=",
"0",
"for",
"block_size",
"in",
"sdp",
".",
"block_struct",
":",
"cumulative_sum",
"+=",
"block_size",
"**",
"2",... | Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str. | [
"Write",
"the",
"SDP",
"relaxation",
"to",
"SDPA",
"format",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L204-L273 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | convert_to_human_readable | def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the mo... | python | def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the mo... | [
"def",
"convert_to_human_readable",
"(",
"sdp",
")",
":",
"objective",
"=",
"\"\"",
"indices_in_objective",
"=",
"[",
"]",
"for",
"i",
",",
"tmp",
"in",
"enumerate",
"(",
"sdp",
".",
"obj_facvar",
")",
":",
"candidates",
"=",
"[",
"key",
"for",
"key",
",... | Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the moment matrix | [
"Convert",
"the",
"SDP",
"relaxation",
"to",
"a",
"human",
"-",
"readable",
"format",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L276-L341 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/sdpa_utils.py | write_to_human_readable | def write_to_human_readable(sdp, filename):
"""Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str.
"""
objective, matrix = convert_to_human_readable(sdp)... | python | def write_to_human_readable(sdp, filename):
"""Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str.
"""
objective, matrix = convert_to_human_readable(sdp)... | [
"def",
"write_to_human_readable",
"(",
"sdp",
",",
"filename",
")",
":",
"objective",
",",
"matrix",
"=",
"convert_to_human_readable",
"(",
"sdp",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"\"Objective:\"",
"+",
"obje... | Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str. | [
"Write",
"the",
"SDP",
"relaxation",
"to",
"a",
"human",
"-",
"readable",
"format",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L344-L359 | train |
bpython/curtsies | examples/initial_input_with_cursor.py | main | def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | python | def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | [
"def",
"main",
"(",
")",
":",
"with",
"Input",
"(",
")",
"as",
"input_generator",
":",
"def",
"extra_bytes_callback",
"(",
"string",
")",
":",
"print",
"(",
"'got extra bytes'",
",",
"repr",
"(",
"string",
")",
")",
"print",
"(",
"'type:'",
",",
"type",
... | Ideally we shouldn't lose the first second of events | [
"Ideally",
"we",
"shouldn",
"t",
"lose",
"the",
"first",
"second",
"of",
"events"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/initial_input_with_cursor.py#L5-L16 | train |
kmn/coincheck | coincheck/utils.py | make_header | def make_header(url,
access_key=None,
secret_key=None):
''' create request header function
:param url: URL for the new :class:`Request` object.
'''
nonce = nounce()
url = url
message = nonce + url
signature = hmac.new(secret_key.encode('utf-8'), message.enc... | python | def make_header(url,
access_key=None,
secret_key=None):
''' create request header function
:param url: URL for the new :class:`Request` object.
'''
nonce = nounce()
url = url
message = nonce + url
signature = hmac.new(secret_key.encode('utf-8'), message.enc... | [
"def",
"make_header",
"(",
"url",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"nonce",
"=",
"nounce",
"(",
")",
"url",
"=",
"url",
"message",
"=",
"nonce",
"+",
"url",
"signature",
"=",
"hmac",
".",
"new",
"(",
"secret_k... | create request header function
:param url: URL for the new :class:`Request` object. | [
"create",
"request",
"header",
"function",
":",
"param",
"url",
":",
"URL",
"for",
"the",
"new",
":",
"class",
":",
"Request",
"object",
"."
] | 4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc | https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/utils.py#L14-L29 | train |
bpython/curtsies | curtsies/input.py | Input.unget_bytes | def unget_bytes(self, string):
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object"""
self.unprocessed_bytes.extend(string[i:i + 1]
for i in range(len(string))) | python | def unget_bytes(self, string):
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object"""
self.unprocessed_bytes.extend(string[i:i + 1]
for i in range(len(string))) | [
"def",
"unget_bytes",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"unprocessed_bytes",
".",
"extend",
"(",
"string",
"[",
"i",
":",
"i",
"+",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
")",
")"
] | Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object | [
"Adds",
"bytes",
"to",
"be",
"internal",
"buffer",
"to",
"be",
"read"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L120-L127 | train |
bpython/curtsies | curtsies/input.py | Input._wait_for_read_ready_or_timeout | def _wait_for_read_ready_or_timeout(self, timeout):
"""Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a ... | python | def _wait_for_read_ready_or_timeout(self, timeout):
"""Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a ... | [
"def",
"_wait_for_read_ready_or_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"remaining_timeout",
"=",
"timeout",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"(",
"rs",
",",
"_",
",",
"_",
")",
"=",
"select",
".",
... | Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a SIGTSTP
triggered by dsusp has been received | [
"Returns",
"tuple",
"of",
"whether",
"stdin",
"is",
"ready",
"to",
"read",
"and",
"an",
"event",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L129-L162 | train |
bpython/curtsies | curtsies/input.py | Input.send | def send(self, timeout=None):
"""Returns an event or None if no events occur before timeout."""
if self.sigint_event and is_main_thread():
with ReplacedSigIntHandler(self.sigint_handler):
return self._send(timeout)
else:
return self._send(timeout) | python | def send(self, timeout=None):
"""Returns an event or None if no events occur before timeout."""
if self.sigint_event and is_main_thread():
with ReplacedSigIntHandler(self.sigint_handler):
return self._send(timeout)
else:
return self._send(timeout) | [
"def",
"send",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"sigint_event",
"and",
"is_main_thread",
"(",
")",
":",
"with",
"ReplacedSigIntHandler",
"(",
"self",
".",
"sigint_handler",
")",
":",
"return",
"self",
".",
"_send",
"... | Returns an event or None if no events occur before timeout. | [
"Returns",
"an",
"event",
"or",
"None",
"if",
"no",
"events",
"occur",
"before",
"timeout",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L164-L170 | train |
bpython/curtsies | curtsies/input.py | Input._nonblocking_read | def _nonblocking_read(self):
"""Returns the number of characters read and adds them to self.unprocessed_bytes"""
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
... | python | def _nonblocking_read(self):
"""Returns the number of characters read and adds them to self.unprocessed_bytes"""
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
... | [
"def",
"_nonblocking_read",
"(",
"self",
")",
":",
"with",
"Nonblocking",
"(",
"self",
".",
"in_stream",
")",
":",
"if",
"PY3",
":",
"try",
":",
"data",
"=",
"os",
".",
"read",
"(",
"self",
".",
"in_stream",
".",
"fileno",
"(",
")",
",",
"READ_SIZE",... | Returns the number of characters read and adds them to self.unprocessed_bytes | [
"Returns",
"the",
"number",
"of",
"characters",
"read",
"and",
"adds",
"them",
"to",
"self",
".",
"unprocessed_bytes"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L245-L265 | train |
bpython/curtsies | curtsies/input.py | Input.event_trigger | def event_trigger(self, event_type):
"""Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(**kwargs):
self.queued_events.append(event_ty... | python | def event_trigger(self, event_type):
"""Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(**kwargs):
self.queued_events.append(event_ty... | [
"def",
"event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"def",
"callback",
"(",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"queued_events",
".",
"append",
"(",
"event_type",
"(",
"*",
"*",
"kwargs",
")",
")",
"return",
"callback"
] | Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested. | [
"Returns",
"a",
"callback",
"that",
"creates",
"events",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L267-L274 | train |
bpython/curtsies | curtsies/input.py | Input.scheduled_event_trigger | def scheduled_event_trigger(self, event_type):
"""Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(when, **kwargs):
s... | python | def scheduled_event_trigger(self, event_type):
"""Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(when, **kwargs):
s... | [
"def",
"scheduled_event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"def",
"callback",
"(",
"when",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"queued_scheduled_events",
".",
"append",
"(",
"(",
"when",
",",
"event_type",
"(",
"when",
"=",
"... | Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested. | [
"Returns",
"a",
"callback",
"that",
"schedules",
"events",
"for",
"the",
"future",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L276-L283 | train |
bpython/curtsies | curtsies/input.py | Input.threadsafe_event_trigger | def threadsafe_event_trigger(self, event_type):
"""Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the ev... | python | def threadsafe_event_trigger(self, event_type):
"""Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the ev... | [
"def",
"threadsafe_event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"readfd",
",",
"writefd",
"=",
"os",
".",
"pipe",
"(",
")",
"self",
".",
"readers",
".",
"append",
"(",
"readfd",
")",
"def",
"callback",
"(",
"*",
"*",
"kwargs",
")",
":",
... | Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the event to a queue
that will be checked on the next eve... | [
"Returns",
"a",
"callback",
"to",
"creates",
"events",
"interrupting",
"current",
"event",
"requests",
"."
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L285-L299 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/solver_common.py | solve_sdp | def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.... | python | def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.... | [
"def",
"solve_sdp",
"(",
"sdp",
",",
"solver",
"=",
"None",
",",
"solverparameters",
"=",
"None",
")",
":",
"solvers",
"=",
"autodetect_solvers",
"(",
"solverparameters",
")",
"solver",
"=",
"solver",
".",
"lower",
"(",
")",
"if",
"solver",
"is",
"not",
... | Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`.
:param solver: The solver to be called, eit... | [
"Call",
"a",
"solver",
"on",
"the",
"SDP",
"relaxation",
".",
"Upon",
"successful",
"solution",
"it",
"returns",
"the",
"primal",
"and",
"dual",
"objective",
"values",
"along",
"with",
"the",
"solution",
"matrices",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L46-L140 | train |
peterwittek/ncpol2sdpa | ncpol2sdpa/solver_common.py | find_solution_ranks | def find_solution_ranks(sdp, xmat=None, baselevel=0):
"""Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided... | python | def find_solution_ranks(sdp, xmat=None, baselevel=0):
"""Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided... | [
"def",
"find_solution_ranks",
"(",
"sdp",
",",
"xmat",
"=",
"None",
",",
"baselevel",
"=",
"0",
")",
":",
"if",
"sdp",
".",
"status",
"==",
"\"unsolved\"",
"and",
"xmat",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"The SDP relaxation is unsolved and no pr... | Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided, the solution is extracted
from the sdp ob... | [
"Helper",
"function",
"to",
"detect",
"rank",
"loop",
"in",
"the",
"solution",
"matrix",
"."
] | bce75d524d0b9d0093f32e3a0a5611f8589351a7 | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L143-L181 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.