repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
bitesofcode/projexui | projexui/widgets/xorbcolumnnavigator.py | XOrbColumnNavigatorBox.acceptColumn | def acceptColumn(self):
"""
Accepts the current item as the current column.
"""
self.navigator().hide()
self.lineEdit().setText(self.navigator().currentSchemaPath())
self.emitSchemaColumnChanged(self.navigator().currentColumn()) | python | def acceptColumn(self):
"""
Accepts the current item as the current column.
"""
self.navigator().hide()
self.lineEdit().setText(self.navigator().currentSchemaPath())
self.emitSchemaColumnChanged(self.navigator().currentColumn()) | [
"def",
"acceptColumn",
"(",
"self",
")",
":",
"self",
".",
"navigator",
"(",
")",
".",
"hide",
"(",
")",
"self",
".",
"lineEdit",
"(",
")",
".",
"setText",
"(",
"self",
".",
"navigator",
"(",
")",
".",
"currentSchemaPath",
"(",
")",
")",
"self",
".",
"emitSchemaColumnChanged",
"(",
"self",
".",
"navigator",
"(",
")",
".",
"currentColumn",
"(",
")",
")"
] | Accepts the current item as the current column. | [
"Accepts",
"the",
"current",
"item",
"as",
"the",
"current",
"column",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbcolumnnavigator.py#L270-L276 | train |
bitesofcode/projexui | projexui/widgets/xorbcolumnnavigator.py | XOrbColumnNavigatorBox.showPopup | def showPopup(self):
"""
Displays the popup associated with this navigator.
"""
nav = self.navigator()
nav.move(self.mapToGlobal(QPoint(0, self.height())))
nav.resize(400, 250)
nav.show() | python | def showPopup(self):
"""
Displays the popup associated with this navigator.
"""
nav = self.navigator()
nav.move(self.mapToGlobal(QPoint(0, self.height())))
nav.resize(400, 250)
nav.show() | [
"def",
"showPopup",
"(",
"self",
")",
":",
"nav",
"=",
"self",
".",
"navigator",
"(",
")",
"nav",
".",
"move",
"(",
"self",
".",
"mapToGlobal",
"(",
"QPoint",
"(",
"0",
",",
"self",
".",
"height",
"(",
")",
")",
")",
")",
"nav",
".",
"resize",
"(",
"400",
",",
"250",
")",
"nav",
".",
"show",
"(",
")"
] | Displays the popup associated with this navigator. | [
"Displays",
"the",
"popup",
"associated",
"with",
"this",
"navigator",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbcolumnnavigator.py#L428-L436 | train |
kimdhamilton/merkle-proofs | merkleproof/hash_functions.py | sha256 | def sha256(content):
"""Finds the sha256 hash of the content."""
if isinstance(content, str):
content = content.encode('utf-8')
return hashlib.sha256(content).hexdigest() | python | def sha256(content):
"""Finds the sha256 hash of the content."""
if isinstance(content, str):
content = content.encode('utf-8')
return hashlib.sha256(content).hexdigest() | [
"def",
"sha256",
"(",
"content",
")",
":",
"if",
"isinstance",
"(",
"content",
",",
"str",
")",
":",
"content",
"=",
"content",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"hashlib",
".",
"sha256",
"(",
"content",
")",
".",
"hexdigest",
"(",
")"
] | Finds the sha256 hash of the content. | [
"Finds",
"the",
"sha256",
"hash",
"of",
"the",
"content",
"."
] | 77551cc65f72b50ac203f10a5069cb1a5b3ffb49 | https://github.com/kimdhamilton/merkle-proofs/blob/77551cc65f72b50ac203f10a5069cb1a5b3ffb49/merkleproof/hash_functions.py#L9-L13 | train |
whiteclover/dbpy | db/connection.py | Connection.cursor | def cursor(self, as_dict=False):
"""Gets the cursor by type , if ``as_dict is ture, make a dict sql connection cursor"""
self.ensure_connect()
ctype = self.real_ctype(as_dict)
return self._connect.cursor(ctype) | python | def cursor(self, as_dict=False):
"""Gets the cursor by type , if ``as_dict is ture, make a dict sql connection cursor"""
self.ensure_connect()
ctype = self.real_ctype(as_dict)
return self._connect.cursor(ctype) | [
"def",
"cursor",
"(",
"self",
",",
"as_dict",
"=",
"False",
")",
":",
"self",
".",
"ensure_connect",
"(",
")",
"ctype",
"=",
"self",
".",
"real_ctype",
"(",
"as_dict",
")",
"return",
"self",
".",
"_connect",
".",
"cursor",
"(",
"ctype",
")"
] | Gets the cursor by type , if ``as_dict is ture, make a dict sql connection cursor | [
"Gets",
"the",
"cursor",
"by",
"type",
"if",
"as_dict",
"is",
"ture",
"make",
"a",
"dict",
"sql",
"connection",
"cursor"
] | 3d9ce85f55cfb39cced22081e525f79581b26b3a | https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/connection.py#L57-L61 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client_service.py | RTMCurrentTeam.members | def members(self):
"""Gets members of current team
Returns:
list of User
Throws:
RTMServiceError when request failed
"""
resp = self._rtm_client.get('v1/current_team.members?all=true')
if resp.is_fail():
raise RTMServiceError(
'Failed to get members of current team',
resp
)
return resp.data['result'] | python | def members(self):
"""Gets members of current team
Returns:
list of User
Throws:
RTMServiceError when request failed
"""
resp = self._rtm_client.get('v1/current_team.members?all=true')
if resp.is_fail():
raise RTMServiceError(
'Failed to get members of current team',
resp
)
return resp.data['result'] | [
"def",
"members",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_rtm_client",
".",
"get",
"(",
"'v1/current_team.members?all=true'",
")",
"if",
"resp",
".",
"is_fail",
"(",
")",
":",
"raise",
"RTMServiceError",
"(",
"'Failed to get members of current team'",
",",
"resp",
")",
"return",
"resp",
".",
"data",
"[",
"'result'",
"]"
] | Gets members of current team
Returns:
list of User
Throws:
RTMServiceError when request failed | [
"Gets",
"members",
"of",
"current",
"team"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L33-L48 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client_service.py | RTMCurrentTeam.channels | def channels(self):
"""Gets channels of current team
Returns:
list of Channel
Throws:
RTMServiceError when request failed
"""
resp = self._rtm_client.get('v1/current_team.channels')
if resp.is_fail():
raise RTMServiceError(
'Failed to get channels of current team',
resp
)
return resp.data['result'] | python | def channels(self):
"""Gets channels of current team
Returns:
list of Channel
Throws:
RTMServiceError when request failed
"""
resp = self._rtm_client.get('v1/current_team.channels')
if resp.is_fail():
raise RTMServiceError(
'Failed to get channels of current team',
resp
)
return resp.data['result'] | [
"def",
"channels",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_rtm_client",
".",
"get",
"(",
"'v1/current_team.channels'",
")",
"if",
"resp",
".",
"is_fail",
"(",
")",
":",
"raise",
"RTMServiceError",
"(",
"'Failed to get channels of current team'",
",",
"resp",
")",
"return",
"resp",
".",
"data",
"[",
"'result'",
"]"
] | Gets channels of current team
Returns:
list of Channel
Throws:
RTMServiceError when request failed | [
"Gets",
"channels",
"of",
"current",
"team"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L50-L65 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client_service.py | RTMUser.info | def info(self, user_id):
"""Gets user information by user id
Args:
user_id(int): the id of user
Returns:
User
Throws:
RTMServiceError when request failed
"""
resp = self._rtm_client.get('v1/user.info?user_id={}'.format(user_id))
if resp.is_fail():
raise RTMServiceError('Failed to get user information', resp)
return resp.data['result'] | python | def info(self, user_id):
"""Gets user information by user id
Args:
user_id(int): the id of user
Returns:
User
Throws:
RTMServiceError when request failed
"""
resp = self._rtm_client.get('v1/user.info?user_id={}'.format(user_id))
if resp.is_fail():
raise RTMServiceError('Failed to get user information', resp)
return resp.data['result'] | [
"def",
"info",
"(",
"self",
",",
"user_id",
")",
":",
"resp",
"=",
"self",
".",
"_rtm_client",
".",
"get",
"(",
"'v1/user.info?user_id={}'",
".",
"format",
"(",
"user_id",
")",
")",
"if",
"resp",
".",
"is_fail",
"(",
")",
":",
"raise",
"RTMServiceError",
"(",
"'Failed to get user information'",
",",
"resp",
")",
"return",
"resp",
".",
"data",
"[",
"'result'",
"]"
] | Gets user information by user id
Args:
user_id(int): the id of user
Returns:
User
Throws:
RTMServiceError when request failed | [
"Gets",
"user",
"information",
"by",
"user",
"id"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L69-L85 | train |
bearyinnovative/bearychat.py | bearychat/rtm_client_service.py | RTMChannel.info | def info(self, channel_id):
"""Gets channel information by channel id
Args:
channel_id(int): the id of channel
Returns:
Channel
Throws:
RTMServiceError when request failed
"""
resource = 'v1/channel.info?channel_id={}'.format(channel_id)
resp = self._rtm_client.get(resource)
if resp.is_fail():
raise RTMServiceError("Failed to get channel information", resp)
return resp.data['result'] | python | def info(self, channel_id):
"""Gets channel information by channel id
Args:
channel_id(int): the id of channel
Returns:
Channel
Throws:
RTMServiceError when request failed
"""
resource = 'v1/channel.info?channel_id={}'.format(channel_id)
resp = self._rtm_client.get(resource)
if resp.is_fail():
raise RTMServiceError("Failed to get channel information", resp)
return resp.data['result'] | [
"def",
"info",
"(",
"self",
",",
"channel_id",
")",
":",
"resource",
"=",
"'v1/channel.info?channel_id={}'",
".",
"format",
"(",
"channel_id",
")",
"resp",
"=",
"self",
".",
"_rtm_client",
".",
"get",
"(",
"resource",
")",
"if",
"resp",
".",
"is_fail",
"(",
")",
":",
"raise",
"RTMServiceError",
"(",
"\"Failed to get channel information\"",
",",
"resp",
")",
"return",
"resp",
".",
"data",
"[",
"'result'",
"]"
] | Gets channel information by channel id
Args:
channel_id(int): the id of channel
Returns:
Channel
Throws:
RTMServiceError when request failed | [
"Gets",
"channel",
"information",
"by",
"channel",
"id"
] | 6c7af2d215c2ff7135bb5af66ca333d0ea1089fd | https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L89-L106 | train |
jschaf/ideone-api | ideone/__init__.py | Ideone._transform_to_dict | def _transform_to_dict(result):
"""
Transform the array from Ideone into a Python dictionary.
"""
result_dict = {}
property_list = result.item
for item in property_list:
result_dict[item.key[0]] = item.value[0]
return result_dict | python | def _transform_to_dict(result):
"""
Transform the array from Ideone into a Python dictionary.
"""
result_dict = {}
property_list = result.item
for item in property_list:
result_dict[item.key[0]] = item.value[0]
return result_dict | [
"def",
"_transform_to_dict",
"(",
"result",
")",
":",
"result_dict",
"=",
"{",
"}",
"property_list",
"=",
"result",
".",
"item",
"for",
"item",
"in",
"property_list",
":",
"result_dict",
"[",
"item",
".",
"key",
"[",
"0",
"]",
"]",
"=",
"item",
".",
"value",
"[",
"0",
"]",
"return",
"result_dict"
] | Transform the array from Ideone into a Python dictionary. | [
"Transform",
"the",
"array",
"from",
"Ideone",
"into",
"a",
"Python",
"dictionary",
"."
] | 2e97767071d5be53c1d435f755b425a6dd8f2514 | https://github.com/jschaf/ideone-api/blob/2e97767071d5be53c1d435f755b425a6dd8f2514/ideone/__init__.py#L40-L48 | train |
jschaf/ideone-api | ideone/__init__.py | Ideone._collapse_language_array | def _collapse_language_array(language_array):
"""
Convert the Ideone language list into a Python dictionary.
"""
language_dict = {}
for language in language_array.item:
key = language.key[0]
value = language.value[0]
language_dict[key] = value
return language_dict | python | def _collapse_language_array(language_array):
"""
Convert the Ideone language list into a Python dictionary.
"""
language_dict = {}
for language in language_array.item:
key = language.key[0]
value = language.value[0]
language_dict[key] = value
return language_dict | [
"def",
"_collapse_language_array",
"(",
"language_array",
")",
":",
"language_dict",
"=",
"{",
"}",
"for",
"language",
"in",
"language_array",
".",
"item",
":",
"key",
"=",
"language",
".",
"key",
"[",
"0",
"]",
"value",
"=",
"language",
".",
"value",
"[",
"0",
"]",
"language_dict",
"[",
"key",
"]",
"=",
"value",
"return",
"language_dict"
] | Convert the Ideone language list into a Python dictionary. | [
"Convert",
"the",
"Ideone",
"language",
"list",
"into",
"a",
"Python",
"dictionary",
"."
] | 2e97767071d5be53c1d435f755b425a6dd8f2514 | https://github.com/jschaf/ideone-api/blob/2e97767071d5be53c1d435f755b425a6dd8f2514/ideone/__init__.py#L62-L72 | train |
jschaf/ideone-api | ideone/__init__.py | Ideone._translate_language_name | def _translate_language_name(self, language_name):
"""
Translate a human readable langauge name into its Ideone
integer representation.
Keyword Arguments
-----------------
* langauge_name: a string of the language (e.g. "c++")
Returns
-------
An integer representation of the language.
Notes
-----
We use a local cache of languages if available, else we grab
the list of languages from Ideone. We test for a string match
by comparing prefixes because Ideone includes the language
compiler name and version number. Both strings are converted
to lower case before the comparison.
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object._translate_language_name('ada')
7
"""
languages = self.languages()
language_id = None
# Check for exact match first including the whole version
# string
for ideone_index, ideone_language in languages.items():
if ideone_language.lower() == language_name.lower():
return ideone_index
# Check for a match of just the language name without any
# version information
simple_languages = dict((k,v.split('(')[0].strip())
for (k,v) in languages.items())
for ideone_index, simple_name in simple_languages.items():
if simple_name.lower() == language_name.lower():
return ideone_index
# Give up, but first find a similar name, suggest it and error
# out
language_choices = languages.values() + simple_languages.values()
similar_choices = difflib.get_close_matches(language_name,
language_choices,
n=3,
cutoff=0.3)
# Add quotes and delimit with strings for easier to read
# output
similar_choices_string = ", ".join(["'" + s + "'"
for s in similar_choices])
error_string = ("Couldn't match '%s' to an Ideone accepted language.\n"
"Did you mean one of the following: %s")
raise IdeoneError(error_string % (language_name, similar_choices_string)) | python | def _translate_language_name(self, language_name):
"""
Translate a human readable langauge name into its Ideone
integer representation.
Keyword Arguments
-----------------
* langauge_name: a string of the language (e.g. "c++")
Returns
-------
An integer representation of the language.
Notes
-----
We use a local cache of languages if available, else we grab
the list of languages from Ideone. We test for a string match
by comparing prefixes because Ideone includes the language
compiler name and version number. Both strings are converted
to lower case before the comparison.
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object._translate_language_name('ada')
7
"""
languages = self.languages()
language_id = None
# Check for exact match first including the whole version
# string
for ideone_index, ideone_language in languages.items():
if ideone_language.lower() == language_name.lower():
return ideone_index
# Check for a match of just the language name without any
# version information
simple_languages = dict((k,v.split('(')[0].strip())
for (k,v) in languages.items())
for ideone_index, simple_name in simple_languages.items():
if simple_name.lower() == language_name.lower():
return ideone_index
# Give up, but first find a similar name, suggest it and error
# out
language_choices = languages.values() + simple_languages.values()
similar_choices = difflib.get_close_matches(language_name,
language_choices,
n=3,
cutoff=0.3)
# Add quotes and delimit with strings for easier to read
# output
similar_choices_string = ", ".join(["'" + s + "'"
for s in similar_choices])
error_string = ("Couldn't match '%s' to an Ideone accepted language.\n"
"Did you mean one of the following: %s")
raise IdeoneError(error_string % (language_name, similar_choices_string)) | [
"def",
"_translate_language_name",
"(",
"self",
",",
"language_name",
")",
":",
"languages",
"=",
"self",
".",
"languages",
"(",
")",
"language_id",
"=",
"None",
"# Check for exact match first including the whole version",
"# string",
"for",
"ideone_index",
",",
"ideone_language",
"in",
"languages",
".",
"items",
"(",
")",
":",
"if",
"ideone_language",
".",
"lower",
"(",
")",
"==",
"language_name",
".",
"lower",
"(",
")",
":",
"return",
"ideone_index",
"# Check for a match of just the language name without any",
"# version information",
"simple_languages",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
".",
"split",
"(",
"'('",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"languages",
".",
"items",
"(",
")",
")",
"for",
"ideone_index",
",",
"simple_name",
"in",
"simple_languages",
".",
"items",
"(",
")",
":",
"if",
"simple_name",
".",
"lower",
"(",
")",
"==",
"language_name",
".",
"lower",
"(",
")",
":",
"return",
"ideone_index",
"# Give up, but first find a similar name, suggest it and error",
"# out",
"language_choices",
"=",
"languages",
".",
"values",
"(",
")",
"+",
"simple_languages",
".",
"values",
"(",
")",
"similar_choices",
"=",
"difflib",
".",
"get_close_matches",
"(",
"language_name",
",",
"language_choices",
",",
"n",
"=",
"3",
",",
"cutoff",
"=",
"0.3",
")",
"# Add quotes and delimit with strings for easier to read",
"# output",
"similar_choices_string",
"=",
"\", \"",
".",
"join",
"(",
"[",
"\"'\"",
"+",
"s",
"+",
"\"'\"",
"for",
"s",
"in",
"similar_choices",
"]",
")",
"error_string",
"=",
"(",
"\"Couldn't match '%s' to an Ideone accepted language.\\n\"",
"\"Did you mean one of the following: %s\"",
")",
"raise",
"IdeoneError",
"(",
"error_string",
"%",
"(",
"language_name",
",",
"similar_choices_string",
")",
")"
] | Translate a human readable langauge name into its Ideone
integer representation.
Keyword Arguments
-----------------
* langauge_name: a string of the language (e.g. "c++")
Returns
-------
An integer representation of the language.
Notes
-----
We use a local cache of languages if available, else we grab
the list of languages from Ideone. We test for a string match
by comparing prefixes because Ideone includes the language
compiler name and version number. Both strings are converted
to lower case before the comparison.
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object._translate_language_name('ada')
7 | [
"Translate",
"a",
"human",
"readable",
"langauge",
"name",
"into",
"its",
"Ideone",
"integer",
"representation",
"."
] | 2e97767071d5be53c1d435f755b425a6dd8f2514 | https://github.com/jschaf/ideone-api/blob/2e97767071d5be53c1d435f755b425a6dd8f2514/ideone/__init__.py#L74-L137 | train |
jschaf/ideone-api | ideone/__init__.py | Ideone.create_submission | def create_submission(self, source_code, language_name=None, language_id=None,
std_input="", run=True, private=False):
"""
Create a submission and upload it to Ideone.
Keyword Arguments
-----------------
* source_code: a string of the programs source code
* language_name: the human readable language string (e.g. 'python')
* language_id: the ID of the programming language
* std_input: the string to pass to the program on stdin
* run: a boolean flag to signifying if Ideone should compile and
run the program
* private: a boolean flag signifying the code is private
Returns
-------
A dictionary with the keys error and link. The link is the
unique id of the program. The URL of the submission is
http://ideone.com/LINK.
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.create_submission('print(42)', language_name='python')
{'error': 'OK',
'link' : 'LsSbo'}
"""
language_id = language_id or self._translate_language_name(language_name)
result = self.client.service.createSubmission(self.user, self.password,
source_code, language_id,
std_input, run, private)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
return result_dict | python | def create_submission(self, source_code, language_name=None, language_id=None,
std_input="", run=True, private=False):
"""
Create a submission and upload it to Ideone.
Keyword Arguments
-----------------
* source_code: a string of the programs source code
* language_name: the human readable language string (e.g. 'python')
* language_id: the ID of the programming language
* std_input: the string to pass to the program on stdin
* run: a boolean flag to signifying if Ideone should compile and
run the program
* private: a boolean flag signifying the code is private
Returns
-------
A dictionary with the keys error and link. The link is the
unique id of the program. The URL of the submission is
http://ideone.com/LINK.
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.create_submission('print(42)', language_name='python')
{'error': 'OK',
'link' : 'LsSbo'}
"""
language_id = language_id or self._translate_language_name(language_name)
result = self.client.service.createSubmission(self.user, self.password,
source_code, language_id,
std_input, run, private)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
return result_dict | [
"def",
"create_submission",
"(",
"self",
",",
"source_code",
",",
"language_name",
"=",
"None",
",",
"language_id",
"=",
"None",
",",
"std_input",
"=",
"\"\"",
",",
"run",
"=",
"True",
",",
"private",
"=",
"False",
")",
":",
"language_id",
"=",
"language_id",
"or",
"self",
".",
"_translate_language_name",
"(",
"language_name",
")",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"createSubmission",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"source_code",
",",
"language_id",
",",
"std_input",
",",
"run",
",",
"private",
")",
"result_dict",
"=",
"Ideone",
".",
"_transform_to_dict",
"(",
"result",
")",
"Ideone",
".",
"_handle_error",
"(",
"result_dict",
")",
"return",
"result_dict"
] | Create a submission and upload it to Ideone.
Keyword Arguments
-----------------
* source_code: a string of the programs source code
* language_name: the human readable language string (e.g. 'python')
* language_id: the ID of the programming language
* std_input: the string to pass to the program on stdin
* run: a boolean flag to signifying if Ideone should compile and
run the program
* private: a boolean flag signifying the code is private
Returns
-------
A dictionary with the keys error and link. The link is the
unique id of the program. The URL of the submission is
http://ideone.com/LINK.
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.create_submission('print(42)', language_name='python')
{'error': 'OK',
'link' : 'LsSbo'} | [
"Create",
"a",
"submission",
"and",
"upload",
"it",
"to",
"Ideone",
"."
] | 2e97767071d5be53c1d435f755b425a6dd8f2514 | https://github.com/jschaf/ideone-api/blob/2e97767071d5be53c1d435f755b425a6dd8f2514/ideone/__init__.py#L141-L179 | train |
jschaf/ideone-api | ideone/__init__.py | Ideone.submission_status | def submission_status(self, link):
"""
Given the unique link of a submission, returns its current
status.
Keyword Arguments
-----------------
* link: the unique id string of a submission
Returns
-------
A dictionary of the error, the result code and the status
code.
Notes
-----
Status specifies the stage of execution.
* status < 0 means the program awaits compilation
* status == 0 means the program is done
* status == 1 means the program is being compiled
* status == 3 means the program is running
Result specifies how the program finished.
* result == 0 means not running, the program was submitted
with run=False
* result == 11 means compilation error
* result == 12 means runtime error
* result == 13 means timelimit exceeded
* result == 15 means success
* result == 17 means memory limit exceeded
* result == 19 means illegal system call
* result == 20 means Ideone internal error, submit a bug report
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.submission_status('LsSbo')
{'error': 'OK',
'result': 15,
'status': 0}
"""
result = self.client.service.getSubmissionStatus(self.user, self.password, link)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
return result_dict | python | def submission_status(self, link):
"""
Given the unique link of a submission, returns its current
status.
Keyword Arguments
-----------------
* link: the unique id string of a submission
Returns
-------
A dictionary of the error, the result code and the status
code.
Notes
-----
Status specifies the stage of execution.
* status < 0 means the program awaits compilation
* status == 0 means the program is done
* status == 1 means the program is being compiled
* status == 3 means the program is running
Result specifies how the program finished.
* result == 0 means not running, the program was submitted
with run=False
* result == 11 means compilation error
* result == 12 means runtime error
* result == 13 means timelimit exceeded
* result == 15 means success
* result == 17 means memory limit exceeded
* result == 19 means illegal system call
* result == 20 means Ideone internal error, submit a bug report
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.submission_status('LsSbo')
{'error': 'OK',
'result': 15,
'status': 0}
"""
result = self.client.service.getSubmissionStatus(self.user, self.password, link)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
return result_dict | [
"def",
"submission_status",
"(",
"self",
",",
"link",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"getSubmissionStatus",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"link",
")",
"result_dict",
"=",
"Ideone",
".",
"_transform_to_dict",
"(",
"result",
")",
"Ideone",
".",
"_handle_error",
"(",
"result_dict",
")",
"return",
"result_dict"
] | Given the unique link of a submission, returns its current
status.
Keyword Arguments
-----------------
* link: the unique id string of a submission
Returns
-------
A dictionary of the error, the result code and the status
code.
Notes
-----
Status specifies the stage of execution.
* status < 0 means the program awaits compilation
* status == 0 means the program is done
* status == 1 means the program is being compiled
* status == 3 means the program is running
Result specifies how the program finished.
* result == 0 means not running, the program was submitted
with run=False
* result == 11 means compilation error
* result == 12 means runtime error
* result == 13 means timelimit exceeded
* result == 15 means success
* result == 17 means memory limit exceeded
* result == 19 means illegal system call
* result == 20 means Ideone internal error, submit a bug report
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.submission_status('LsSbo')
{'error': 'OK',
'result': 15,
'status': 0} | [
"Given",
"the",
"unique",
"link",
"of",
"a",
"submission",
"returns",
"its",
"current",
"status",
"."
] | 2e97767071d5be53c1d435f755b425a6dd8f2514 | https://github.com/jschaf/ideone-api/blob/2e97767071d5be53c1d435f755b425a6dd8f2514/ideone/__init__.py#L181-L234 | train |
jschaf/ideone-api | ideone/__init__.py | Ideone.submission_details | def submission_details(self, link, with_source=True,
with_input=True, with_output=True,
with_stderr=True, with_compilation_info=True):
"""
Return a dictionary of requested details about a submission
with the id of link.
Keyword Arguments
-----------------
* link: the unique string ID of a submission
* with_source: should we request the source code
* with_input: request the program input
* with_output: request the program output
* with_stderr: request the error output
* with_compilation_info: request compilation flags
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.submission_details('LsSbo')
{'cmpinfo': ,
'date': "2011-04-18 15:24:14",
'error': "OK",
'input': "",
'langId': 116,
'langName': "Python 3",
'langVersion': "python-3.1.2",
'memory': 5852,
'output': 42,
'public': True,
'result': 15,
'signal': 0,
'source': "print(42)",
'status': 0,
'stderr': "",
'time': 0.02}
"""
result = self.client.service.getSubmissionDetails(self.user, self.password,
link,
with_source, with_input,
with_output, with_stderr,
with_compilation_info)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
return result_dict | python | def submission_details(self, link, with_source=True,
with_input=True, with_output=True,
with_stderr=True, with_compilation_info=True):
"""
Return a dictionary of requested details about a submission
with the id of link.
Keyword Arguments
-----------------
* link: the unique string ID of a submission
* with_source: should we request the source code
* with_input: request the program input
* with_output: request the program output
* with_stderr: request the error output
* with_compilation_info: request compilation flags
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.submission_details('LsSbo')
{'cmpinfo': ,
'date': "2011-04-18 15:24:14",
'error': "OK",
'input': "",
'langId': 116,
'langName': "Python 3",
'langVersion': "python-3.1.2",
'memory': 5852,
'output': 42,
'public': True,
'result': 15,
'signal': 0,
'source': "print(42)",
'status': 0,
'stderr': "",
'time': 0.02}
"""
result = self.client.service.getSubmissionDetails(self.user, self.password,
link,
with_source, with_input,
with_output, with_stderr,
with_compilation_info)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
return result_dict | [
"def",
"submission_details",
"(",
"self",
",",
"link",
",",
"with_source",
"=",
"True",
",",
"with_input",
"=",
"True",
",",
"with_output",
"=",
"True",
",",
"with_stderr",
"=",
"True",
",",
"with_compilation_info",
"=",
"True",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"getSubmissionDetails",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"link",
",",
"with_source",
",",
"with_input",
",",
"with_output",
",",
"with_stderr",
",",
"with_compilation_info",
")",
"result_dict",
"=",
"Ideone",
".",
"_transform_to_dict",
"(",
"result",
")",
"Ideone",
".",
"_handle_error",
"(",
"result_dict",
")",
"return",
"result_dict"
] | Return a dictionary of requested details about a submission
with the id of link.
Keyword Arguments
-----------------
* link: the unique string ID of a submission
* with_source: should we request the source code
* with_input: request the program input
* with_output: request the program output
* with_stderr: request the error output
* with_compilation_info: request compilation flags
Examples
--------
>>> ideone_object = Ideone('username', 'password')
>>> ideone_object.submission_details('LsSbo')
{'cmpinfo': ,
'date': "2011-04-18 15:24:14",
'error': "OK",
'input': "",
'langId': 116,
'langName': "Python 3",
'langVersion': "python-3.1.2",
'memory': 5852,
'output': 42,
'public': True,
'result': 15,
'signal': 0,
'source': "print(42)",
'status': 0,
'stderr': "",
'time': 0.02} | [
"Return",
"a",
"dictionary",
"of",
"requested",
"details",
"about",
"a",
"submission",
"with",
"the",
"id",
"of",
"link",
"."
] | 2e97767071d5be53c1d435f755b425a6dd8f2514 | https://github.com/jschaf/ideone-api/blob/2e97767071d5be53c1d435f755b425a6dd8f2514/ideone/__init__.py#L236-L283 | train |
jschaf/ideone-api | ideone/__init__.py | Ideone.languages | def languages(self):
"""
Get a list of supported languages and cache it.
Examples
--------
>>> ideone_object.languages()
{'error': 'OK',
'languages': {1: "C++ (gcc-4.3.4)",
2: "Pascal (gpc) (gpc 20070904)",
...
...
...
125: "Falcon (falcon-0.9.6.6)"}}
"""
if self._language_dict is None:
result = self.client.service.getLanguages(self.user, self.password)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
languages = result_dict['languages']
result_dict['languages'] = Ideone._collapse_language_array(languages)
self._language_dict = result_dict['languages']
return self._language_dict | python | def languages(self):
"""
Get a list of supported languages and cache it.
Examples
--------
>>> ideone_object.languages()
{'error': 'OK',
'languages': {1: "C++ (gcc-4.3.4)",
2: "Pascal (gpc) (gpc 20070904)",
...
...
...
125: "Falcon (falcon-0.9.6.6)"}}
"""
if self._language_dict is None:
result = self.client.service.getLanguages(self.user, self.password)
result_dict = Ideone._transform_to_dict(result)
Ideone._handle_error(result_dict)
languages = result_dict['languages']
result_dict['languages'] = Ideone._collapse_language_array(languages)
self._language_dict = result_dict['languages']
return self._language_dict | [
"def",
"languages",
"(",
"self",
")",
":",
"if",
"self",
".",
"_language_dict",
"is",
"None",
":",
"result",
"=",
"self",
".",
"client",
".",
"service",
".",
"getLanguages",
"(",
"self",
".",
"user",
",",
"self",
".",
"password",
")",
"result_dict",
"=",
"Ideone",
".",
"_transform_to_dict",
"(",
"result",
")",
"Ideone",
".",
"_handle_error",
"(",
"result_dict",
")",
"languages",
"=",
"result_dict",
"[",
"'languages'",
"]",
"result_dict",
"[",
"'languages'",
"]",
"=",
"Ideone",
".",
"_collapse_language_array",
"(",
"languages",
")",
"self",
".",
"_language_dict",
"=",
"result_dict",
"[",
"'languages'",
"]",
"return",
"self",
".",
"_language_dict"
] | Get a list of supported languages and cache it.
Examples
--------
>>> ideone_object.languages()
{'error': 'OK',
'languages': {1: "C++ (gcc-4.3.4)",
2: "Pascal (gpc) (gpc 20070904)",
...
...
...
125: "Falcon (falcon-0.9.6.6)"}} | [
"Get",
"a",
"list",
"of",
"supported",
"languages",
"and",
"cache",
"it",
"."
] | 2e97767071d5be53c1d435f755b425a6dd8f2514 | https://github.com/jschaf/ideone-api/blob/2e97767071d5be53c1d435f755b425a6dd8f2514/ideone/__init__.py#L285-L309 | train |
dmerejkowsky/replacer | replacer.py | is_binary | def is_binary(filename):
""" Returns True if the file is binary
"""
with open(filename, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False | python | def is_binary(filename):
""" Returns True if the file is binary
"""
with open(filename, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False | [
"def",
"is_binary",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"data",
"=",
"fp",
".",
"read",
"(",
"1024",
")",
"if",
"not",
"data",
":",
"return",
"False",
"if",
"b'\\0'",
"in",
"data",
":",
"return",
"True",
"return",
"False"
] | Returns True if the file is binary | [
"Returns",
"True",
"if",
"the",
"file",
"is",
"binary"
] | 8dc16f297d0ff3a6ee2fa3c0d77789a6859b0f6a | https://github.com/dmerejkowsky/replacer/blob/8dc16f297d0ff3a6ee2fa3c0d77789a6859b0f6a/replacer.py#L55-L65 | train |
dmerejkowsky/replacer | replacer.py | walk_files | def walk_files(args, root, directory, action):
"""
Recusively go do the subdirectories of the directory,
calling the action on each file
"""
for entry in os.listdir(directory):
if is_hidden(args, entry):
continue
if is_excluded_directory(args, entry):
continue
if is_in_default_excludes(entry):
continue
if not is_included(args, entry):
continue
if is_excluded(args, entry, directory):
continue
entry = os.path.join(directory, entry)
if os.path.isdir(entry):
walk_files(args, root, entry, action)
if os.path.isfile(entry):
if is_binary(entry):
continue
action(entry) | python | def walk_files(args, root, directory, action):
"""
Recusively go do the subdirectories of the directory,
calling the action on each file
"""
for entry in os.listdir(directory):
if is_hidden(args, entry):
continue
if is_excluded_directory(args, entry):
continue
if is_in_default_excludes(entry):
continue
if not is_included(args, entry):
continue
if is_excluded(args, entry, directory):
continue
entry = os.path.join(directory, entry)
if os.path.isdir(entry):
walk_files(args, root, entry, action)
if os.path.isfile(entry):
if is_binary(entry):
continue
action(entry) | [
"def",
"walk_files",
"(",
"args",
",",
"root",
",",
"directory",
",",
"action",
")",
":",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"if",
"is_hidden",
"(",
"args",
",",
"entry",
")",
":",
"continue",
"if",
"is_excluded_directory",
"(",
"args",
",",
"entry",
")",
":",
"continue",
"if",
"is_in_default_excludes",
"(",
"entry",
")",
":",
"continue",
"if",
"not",
"is_included",
"(",
"args",
",",
"entry",
")",
":",
"continue",
"if",
"is_excluded",
"(",
"args",
",",
"entry",
",",
"directory",
")",
":",
"continue",
"entry",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"entry",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"entry",
")",
":",
"walk_files",
"(",
"args",
",",
"root",
",",
"entry",
",",
"action",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"entry",
")",
":",
"if",
"is_binary",
"(",
"entry",
")",
":",
"continue",
"action",
"(",
"entry",
")"
] | Recusively go do the subdirectories of the directory,
calling the action on each file | [
"Recusively",
"go",
"do",
"the",
"subdirectories",
"of",
"the",
"directory",
"calling",
"the",
"action",
"on",
"each",
"file"
] | 8dc16f297d0ff3a6ee2fa3c0d77789a6859b0f6a | https://github.com/dmerejkowsky/replacer/blob/8dc16f297d0ff3a6ee2fa3c0d77789a6859b0f6a/replacer.py#L110-L133 | train |
dmerejkowsky/replacer | replacer.py | main | def main(args=None):
"""
manages options when called from command line
"""
parser = ArgumentParser(usage=__usage__)
parser.add_argument("--no-skip-hidden", action="store_false",
dest="skip_hidden",
help="Do not skip hidden files. "
"Use this if you know what you are doing...")
parser.add_argument("--include", dest="includes", action="append",
help="Only replace in files matching theses patterns")
parser.add_argument("--exclude", dest="excludes", action="append",
help="Ignore files matching theses patterns")
parser.add_argument("--backup",
action="store_true", dest="backup",
help="Create a backup for each file. "
"By default, files are modified in place")
parser.add_argument("--go",
action="store_true", dest="go",
help="Perform changes rather than just printing then")
parser.add_argument("--dry-run", "-n",
action="store_false", dest="go",
help="Do not change anything. This is the default")
parser.add_argument("--color", choices=["always", "never", "auto"],
help="When to colorize the output. "
"Default: when output is a tty")
parser.add_argument("--no-color", action="store_false", dest="color",
help="Do not colorize output")
parser.add_argument("--quiet", "-q", action="store_true", dest="quiet",
help="Do not produce any output")
parser.add_argument("pattern")
parser.add_argument("replacement")
parser.add_argument("paths", nargs="*")
parser.set_defaults(
includes=list(),
excludes=list(),
skip_hidden=True,
backup=False,
go=False,
color="auto",
quiet=False,
)
args = parser.parse_args(args=args)
setup_colors(args)
repl_main(args) | python | def main(args=None):
"""
manages options when called from command line
"""
parser = ArgumentParser(usage=__usage__)
parser.add_argument("--no-skip-hidden", action="store_false",
dest="skip_hidden",
help="Do not skip hidden files. "
"Use this if you know what you are doing...")
parser.add_argument("--include", dest="includes", action="append",
help="Only replace in files matching theses patterns")
parser.add_argument("--exclude", dest="excludes", action="append",
help="Ignore files matching theses patterns")
parser.add_argument("--backup",
action="store_true", dest="backup",
help="Create a backup for each file. "
"By default, files are modified in place")
parser.add_argument("--go",
action="store_true", dest="go",
help="Perform changes rather than just printing then")
parser.add_argument("--dry-run", "-n",
action="store_false", dest="go",
help="Do not change anything. This is the default")
parser.add_argument("--color", choices=["always", "never", "auto"],
help="When to colorize the output. "
"Default: when output is a tty")
parser.add_argument("--no-color", action="store_false", dest="color",
help="Do not colorize output")
parser.add_argument("--quiet", "-q", action="store_true", dest="quiet",
help="Do not produce any output")
parser.add_argument("pattern")
parser.add_argument("replacement")
parser.add_argument("paths", nargs="*")
parser.set_defaults(
includes=list(),
excludes=list(),
skip_hidden=True,
backup=False,
go=False,
color="auto",
quiet=False,
)
args = parser.parse_args(args=args)
setup_colors(args)
repl_main(args) | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"usage",
"=",
"__usage__",
")",
"parser",
".",
"add_argument",
"(",
"\"--no-skip-hidden\"",
",",
"action",
"=",
"\"store_false\"",
",",
"dest",
"=",
"\"skip_hidden\"",
",",
"help",
"=",
"\"Do not skip hidden files. \"",
"\"Use this if you know what you are doing...\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--include\"",
",",
"dest",
"=",
"\"includes\"",
",",
"action",
"=",
"\"append\"",
",",
"help",
"=",
"\"Only replace in files matching theses patterns\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--exclude\"",
",",
"dest",
"=",
"\"excludes\"",
",",
"action",
"=",
"\"append\"",
",",
"help",
"=",
"\"Ignore files matching theses patterns\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--backup\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"backup\"",
",",
"help",
"=",
"\"Create a backup for each file. \"",
"\"By default, files are modified in place\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--go\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"go\"",
",",
"help",
"=",
"\"Perform changes rather than just printing then\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--dry-run\"",
",",
"\"-n\"",
",",
"action",
"=",
"\"store_false\"",
",",
"dest",
"=",
"\"go\"",
",",
"help",
"=",
"\"Do not change anything. This is the default\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--color\"",
",",
"choices",
"=",
"[",
"\"always\"",
",",
"\"never\"",
",",
"\"auto\"",
"]",
",",
"help",
"=",
"\"When to colorize the output. \"",
"\"Default: when output is a tty\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--no-color\"",
",",
"action",
"=",
"\"store_false\"",
",",
"dest",
"=",
"\"color\"",
",",
"help",
"=",
"\"Do not colorize output\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--quiet\"",
",",
"\"-q\"",
",",
"action",
"=",
"\"store_true\"",
",",
"dest",
"=",
"\"quiet\"",
",",
"help",
"=",
"\"Do not produce any output\"",
")",
"parser",
".",
"add_argument",
"(",
"\"pattern\"",
")",
"parser",
".",
"add_argument",
"(",
"\"replacement\"",
")",
"parser",
".",
"add_argument",
"(",
"\"paths\"",
",",
"nargs",
"=",
"\"*\"",
")",
"parser",
".",
"set_defaults",
"(",
"includes",
"=",
"list",
"(",
")",
",",
"excludes",
"=",
"list",
"(",
")",
",",
"skip_hidden",
"=",
"True",
",",
"backup",
"=",
"False",
",",
"go",
"=",
"False",
",",
"color",
"=",
"\"auto\"",
",",
"quiet",
"=",
"False",
",",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
"=",
"args",
")",
"setup_colors",
"(",
"args",
")",
"repl_main",
"(",
"args",
")"
] | manages options when called from command line | [
"manages",
"options",
"when",
"called",
"from",
"command",
"line"
] | 8dc16f297d0ff3a6ee2fa3c0d77789a6859b0f6a | https://github.com/dmerejkowsky/replacer/blob/8dc16f297d0ff3a6ee2fa3c0d77789a6859b0f6a/replacer.py#L253-L300 | train |
bitesofcode/projexui | projexui/windows/xdkwindow/xdkitem.py | XdkEntryItem.load | def load( self ):
"""
Loads this item.
"""
if self._loaded:
return
self._loaded = True
self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless)
if not self.isFolder():
return
path = self.filepath()
if not os.path.isdir(path):
path = os.path.dirname(path)
for name in os.listdir(path):
# ignore 'hidden' folders
if name.startswith('_') and not name.startswith('__'):
continue
# ignore special cases (only want modules for this)
if '-' in name:
continue
# use the index or __init__ information
if name in ('index.html', '__init__.html'):
self._url = 'file:///%s/%s' % (path, name)
continue
# otherwise, load a childitem
filepath = os.path.join(path, name)
folder = os.path.isdir(filepath)
XdkEntryItem(self, filepath, folder=folder) | python | def load( self ):
"""
Loads this item.
"""
if self._loaded:
return
self._loaded = True
self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless)
if not self.isFolder():
return
path = self.filepath()
if not os.path.isdir(path):
path = os.path.dirname(path)
for name in os.listdir(path):
# ignore 'hidden' folders
if name.startswith('_') and not name.startswith('__'):
continue
# ignore special cases (only want modules for this)
if '-' in name:
continue
# use the index or __init__ information
if name in ('index.html', '__init__.html'):
self._url = 'file:///%s/%s' % (path, name)
continue
# otherwise, load a childitem
filepath = os.path.join(path, name)
folder = os.path.isdir(filepath)
XdkEntryItem(self, filepath, folder=folder) | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"_loaded",
":",
"return",
"self",
".",
"_loaded",
"=",
"True",
"self",
".",
"setChildIndicatorPolicy",
"(",
"self",
".",
"DontShowIndicatorWhenChildless",
")",
"if",
"not",
"self",
".",
"isFolder",
"(",
")",
":",
"return",
"path",
"=",
"self",
".",
"filepath",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"# ignore 'hidden' folders\r",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
"and",
"not",
"name",
".",
"startswith",
"(",
"'__'",
")",
":",
"continue",
"# ignore special cases (only want modules for this)\r",
"if",
"'-'",
"in",
"name",
":",
"continue",
"# use the index or __init__ information\r",
"if",
"name",
"in",
"(",
"'index.html'",
",",
"'__init__.html'",
")",
":",
"self",
".",
"_url",
"=",
"'file:///%s/%s'",
"%",
"(",
"path",
",",
"name",
")",
"continue",
"# otherwise, load a childitem\r",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"folder",
"=",
"os",
".",
"path",
".",
"isdir",
"(",
"filepath",
")",
"XdkEntryItem",
"(",
"self",
",",
"filepath",
",",
"folder",
"=",
"folder",
")"
] | Loads this item. | [
"Loads",
"this",
"item",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkitem.py#L122-L156 | train |
stephenmcd/sphinx-me | sphinx_me.py | get_version | def get_version(module):
"""
Attempts to read a version attribute from the given module that
could be specified via several different names and formats.
"""
version_names = ["__version__", "get_version", "version"]
version_names.extend([name.upper() for name in version_names])
for name in version_names:
try:
version = getattr(module, name)
except AttributeError:
continue
if callable(version):
version = version()
try:
version = ".".join([str(i) for i in version.__iter__()])
except AttributeError:
pass
return version | python | def get_version(module):
"""
Attempts to read a version attribute from the given module that
could be specified via several different names and formats.
"""
version_names = ["__version__", "get_version", "version"]
version_names.extend([name.upper() for name in version_names])
for name in version_names:
try:
version = getattr(module, name)
except AttributeError:
continue
if callable(version):
version = version()
try:
version = ".".join([str(i) for i in version.__iter__()])
except AttributeError:
pass
return version | [
"def",
"get_version",
"(",
"module",
")",
":",
"version_names",
"=",
"[",
"\"__version__\"",
",",
"\"get_version\"",
",",
"\"version\"",
"]",
"version_names",
".",
"extend",
"(",
"[",
"name",
".",
"upper",
"(",
")",
"for",
"name",
"in",
"version_names",
"]",
")",
"for",
"name",
"in",
"version_names",
":",
"try",
":",
"version",
"=",
"getattr",
"(",
"module",
",",
"name",
")",
"except",
"AttributeError",
":",
"continue",
"if",
"callable",
"(",
"version",
")",
":",
"version",
"=",
"version",
"(",
")",
"try",
":",
"version",
"=",
"\".\"",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"version",
".",
"__iter__",
"(",
")",
"]",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"version"
] | Attempts to read a version attribute from the given module that
could be specified via several different names and formats. | [
"Attempts",
"to",
"read",
"a",
"version",
"attribute",
"from",
"the",
"given",
"module",
"that",
"could",
"be",
"specified",
"via",
"several",
"different",
"names",
"and",
"formats",
"."
] | 9f51a04d58a90834a787246ce475a564b4f9e5ee | https://github.com/stephenmcd/sphinx-me/blob/9f51a04d58a90834a787246ce475a564b4f9e5ee/sphinx_me.py#L66-L84 | train |
stephenmcd/sphinx-me | sphinx_me.py | get_setup_attribute | def get_setup_attribute(attribute, setup_path):
"""
Runs the project's setup.py script in a process with an arg that
will print out the value for a particular attribute such as author
or version, and returns the value.
"""
args = ["python", setup_path, "--%s" % attribute]
return Popen(args, stdout=PIPE).communicate()[0].decode('utf-8').strip() | python | def get_setup_attribute(attribute, setup_path):
"""
Runs the project's setup.py script in a process with an arg that
will print out the value for a particular attribute such as author
or version, and returns the value.
"""
args = ["python", setup_path, "--%s" % attribute]
return Popen(args, stdout=PIPE).communicate()[0].decode('utf-8').strip() | [
"def",
"get_setup_attribute",
"(",
"attribute",
",",
"setup_path",
")",
":",
"args",
"=",
"[",
"\"python\"",
",",
"setup_path",
",",
"\"--%s\"",
"%",
"attribute",
"]",
"return",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")"
] | Runs the project's setup.py script in a process with an arg that
will print out the value for a particular attribute such as author
or version, and returns the value. | [
"Runs",
"the",
"project",
"s",
"setup",
".",
"py",
"script",
"in",
"a",
"process",
"with",
"an",
"arg",
"that",
"will",
"print",
"out",
"the",
"value",
"for",
"a",
"particular",
"attribute",
"such",
"as",
"author",
"or",
"version",
"and",
"returns",
"the",
"value",
"."
] | 9f51a04d58a90834a787246ce475a564b4f9e5ee | https://github.com/stephenmcd/sphinx-me/blob/9f51a04d58a90834a787246ce475a564b4f9e5ee/sphinx_me.py#L87-L94 | train |
chaoss/grimoirelab-perceval-puppet | perceval/backends/puppet/puppetforge.py | PuppetForge.fetch_items | def fetch_items(self, category, **kwargs):
"""Fetch the modules
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Fetching modules from %s", str(from_date))
from_date_ts = datetime_to_utc(from_date).timestamp()
nmodules = 0
stop_fetching = False
raw_pages = self.client.modules()
for raw_modules in raw_pages:
modules = [mod for mod in self.parse_json(raw_modules)]
for module in modules:
# Check timestamps to stop fetching more modules
# because modules fetched sorted by 'updated_at'
# from newest to oldest.
updated_at_ts = self.metadata_updated_on(module)
if from_date_ts > updated_at_ts:
stop_fetching = True
break
owner = module['owner']['username']
name = module['name']
module['releases'] = self.__fetch_and_parse_releases(owner, name)
module['owner_data'] = self.__get_or_fetch_owner(owner)
yield module
nmodules += 1
if stop_fetching:
break
logger.info("Fetch process completed: %s modules fetched", nmodules) | python | def fetch_items(self, category, **kwargs):
"""Fetch the modules
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Fetching modules from %s", str(from_date))
from_date_ts = datetime_to_utc(from_date).timestamp()
nmodules = 0
stop_fetching = False
raw_pages = self.client.modules()
for raw_modules in raw_pages:
modules = [mod for mod in self.parse_json(raw_modules)]
for module in modules:
# Check timestamps to stop fetching more modules
# because modules fetched sorted by 'updated_at'
# from newest to oldest.
updated_at_ts = self.metadata_updated_on(module)
if from_date_ts > updated_at_ts:
stop_fetching = True
break
owner = module['owner']['username']
name = module['name']
module['releases'] = self.__fetch_and_parse_releases(owner, name)
module['owner_data'] = self.__get_or_fetch_owner(owner)
yield module
nmodules += 1
if stop_fetching:
break
logger.info("Fetch process completed: %s modules fetched", nmodules) | [
"def",
"fetch_items",
"(",
"self",
",",
"category",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
"[",
"'from_date'",
"]",
"logger",
".",
"info",
"(",
"\"Fetching modules from %s\"",
",",
"str",
"(",
"from_date",
")",
")",
"from_date_ts",
"=",
"datetime_to_utc",
"(",
"from_date",
")",
".",
"timestamp",
"(",
")",
"nmodules",
"=",
"0",
"stop_fetching",
"=",
"False",
"raw_pages",
"=",
"self",
".",
"client",
".",
"modules",
"(",
")",
"for",
"raw_modules",
"in",
"raw_pages",
":",
"modules",
"=",
"[",
"mod",
"for",
"mod",
"in",
"self",
".",
"parse_json",
"(",
"raw_modules",
")",
"]",
"for",
"module",
"in",
"modules",
":",
"# Check timestamps to stop fetching more modules",
"# because modules fetched sorted by 'updated_at'",
"# from newest to oldest.",
"updated_at_ts",
"=",
"self",
".",
"metadata_updated_on",
"(",
"module",
")",
"if",
"from_date_ts",
">",
"updated_at_ts",
":",
"stop_fetching",
"=",
"True",
"break",
"owner",
"=",
"module",
"[",
"'owner'",
"]",
"[",
"'username'",
"]",
"name",
"=",
"module",
"[",
"'name'",
"]",
"module",
"[",
"'releases'",
"]",
"=",
"self",
".",
"__fetch_and_parse_releases",
"(",
"owner",
",",
"name",
")",
"module",
"[",
"'owner_data'",
"]",
"=",
"self",
".",
"__get_or_fetch_owner",
"(",
"owner",
")",
"yield",
"module",
"nmodules",
"+=",
"1",
"if",
"stop_fetching",
":",
"break",
"logger",
".",
"info",
"(",
"\"Fetch process completed: %s modules fetched\"",
",",
"nmodules",
")"
] | Fetch the modules
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items | [
"Fetch",
"the",
"modules"
] | 4b215df2e8045ce3d6538e532e8b5c660ebed7ea | https://github.com/chaoss/grimoirelab-perceval-puppet/blob/4b215df2e8045ce3d6538e532e8b5c660ebed7ea/perceval/backends/puppet/puppetforge.py#L91-L134 | train |
chaoss/grimoirelab-perceval-puppet | perceval/backends/puppet/puppetforge.py | PuppetForge.parse_json | def parse_json(raw_json):
"""Parse a Puppet forge JSON stream.
The method parses a JSON stream and returns a list
with the parsed data.
:param raw_json: JSON string to parse
:returns: a list with the parsed data
"""
result = json.loads(raw_json)
if 'results' in result:
result = result['results']
return result | python | def parse_json(raw_json):
"""Parse a Puppet forge JSON stream.
The method parses a JSON stream and returns a list
with the parsed data.
:param raw_json: JSON string to parse
:returns: a list with the parsed data
"""
result = json.loads(raw_json)
if 'results' in result:
result = result['results']
return result | [
"def",
"parse_json",
"(",
"raw_json",
")",
":",
"result",
"=",
"json",
".",
"loads",
"(",
"raw_json",
")",
"if",
"'results'",
"in",
"result",
":",
"result",
"=",
"result",
"[",
"'results'",
"]",
"return",
"result"
] | Parse a Puppet forge JSON stream.
The method parses a JSON stream and returns a list
with the parsed data.
:param raw_json: JSON string to parse
:returns: a list with the parsed data | [
"Parse",
"a",
"Puppet",
"forge",
"JSON",
"stream",
"."
] | 4b215df2e8045ce3d6538e532e8b5c660ebed7ea | https://github.com/chaoss/grimoirelab-perceval-puppet/blob/4b215df2e8045ce3d6538e532e8b5c660ebed7ea/perceval/backends/puppet/puppetforge.py#L185-L200 | train |
chaoss/grimoirelab-perceval-puppet | perceval/backends/puppet/puppetforge.py | PuppetForgeClient.modules | def modules(self):
"""Fetch modules pages."""
resource = self.RMODULES
params = {
self.PLIMIT: self.max_items,
self.PSORT_BY: self.VLATEST_RELEASE
}
for page in self._fetch(resource, params):
yield page | python | def modules(self):
"""Fetch modules pages."""
resource = self.RMODULES
params = {
self.PLIMIT: self.max_items,
self.PSORT_BY: self.VLATEST_RELEASE
}
for page in self._fetch(resource, params):
yield page | [
"def",
"modules",
"(",
"self",
")",
":",
"resource",
"=",
"self",
".",
"RMODULES",
"params",
"=",
"{",
"self",
".",
"PLIMIT",
":",
"self",
".",
"max_items",
",",
"self",
".",
"PSORT_BY",
":",
"self",
".",
"VLATEST_RELEASE",
"}",
"for",
"page",
"in",
"self",
".",
"_fetch",
"(",
"resource",
",",
"params",
")",
":",
"yield",
"page"
] | Fetch modules pages. | [
"Fetch",
"modules",
"pages",
"."
] | 4b215df2e8045ce3d6538e532e8b5c660ebed7ea | https://github.com/chaoss/grimoirelab-perceval-puppet/blob/4b215df2e8045ce3d6538e532e8b5c660ebed7ea/perceval/backends/puppet/puppetforge.py#L264-L275 | train |
chaoss/grimoirelab-perceval-puppet | perceval/backends/puppet/puppetforge.py | PuppetForgeClient.releases | def releases(self, owner, module):
"""Fetch the releases of a module."""
resource = self.RRELEASES
params = {
self.PMODULE: owner + '-' + module,
self.PLIMIT: self.max_items,
self.PSHOW_DELETED: 'true',
self.PSORT_BY: self.VRELEASE_DATE,
}
for page in self._fetch(resource, params):
yield page | python | def releases(self, owner, module):
"""Fetch the releases of a module."""
resource = self.RRELEASES
params = {
self.PMODULE: owner + '-' + module,
self.PLIMIT: self.max_items,
self.PSHOW_DELETED: 'true',
self.PSORT_BY: self.VRELEASE_DATE,
}
for page in self._fetch(resource, params):
yield page | [
"def",
"releases",
"(",
"self",
",",
"owner",
",",
"module",
")",
":",
"resource",
"=",
"self",
".",
"RRELEASES",
"params",
"=",
"{",
"self",
".",
"PMODULE",
":",
"owner",
"+",
"'-'",
"+",
"module",
",",
"self",
".",
"PLIMIT",
":",
"self",
".",
"max_items",
",",
"self",
".",
"PSHOW_DELETED",
":",
"'true'",
",",
"self",
".",
"PSORT_BY",
":",
"self",
".",
"VRELEASE_DATE",
",",
"}",
"for",
"page",
"in",
"self",
".",
"_fetch",
"(",
"resource",
",",
"params",
")",
":",
"yield",
"page"
] | Fetch the releases of a module. | [
"Fetch",
"the",
"releases",
"of",
"a",
"module",
"."
] | 4b215df2e8045ce3d6538e532e8b5c660ebed7ea | https://github.com/chaoss/grimoirelab-perceval-puppet/blob/4b215df2e8045ce3d6538e532e8b5c660ebed7ea/perceval/backends/puppet/puppetforge.py#L277-L290 | train |
kimdhamilton/merkle-proofs | merkleproof/MerkleTree.py | MerkleTree.reset_tree | def reset_tree(self):
"""
Resets the current tree to empty.
"""
self.tree = {}
self.tree['leaves'] = []
self.tree['levels'] = []
self.tree['is_ready'] = False | python | def reset_tree(self):
"""
Resets the current tree to empty.
"""
self.tree = {}
self.tree['leaves'] = []
self.tree['levels'] = []
self.tree['is_ready'] = False | [
"def",
"reset_tree",
"(",
"self",
")",
":",
"self",
".",
"tree",
"=",
"{",
"}",
"self",
".",
"tree",
"[",
"'leaves'",
"]",
"=",
"[",
"]",
"self",
".",
"tree",
"[",
"'levels'",
"]",
"=",
"[",
"]",
"self",
".",
"tree",
"[",
"'is_ready'",
"]",
"=",
"False"
] | Resets the current tree to empty. | [
"Resets",
"the",
"current",
"tree",
"to",
"empty",
"."
] | 77551cc65f72b50ac203f10a5069cb1a5b3ffb49 | https://github.com/kimdhamilton/merkle-proofs/blob/77551cc65f72b50ac203f10a5069cb1a5b3ffb49/merkleproof/MerkleTree.py#L25-L32 | train |
kimdhamilton/merkle-proofs | merkleproof/MerkleTree.py | MerkleTree.add_leaves | def add_leaves(self, values_array, do_hash=False):
"""
Add leaves to the tree.
Similar to chainpoint merkle tree library, this accepts hash values as an array of Buffers or hex strings.
:param values_array: array of values to add
:param do_hash: whether to hash the values before inserting
"""
self.tree['is_ready'] = False
[self._add_leaf(value, do_hash) for value in values_array] | python | def add_leaves(self, values_array, do_hash=False):
"""
Add leaves to the tree.
Similar to chainpoint merkle tree library, this accepts hash values as an array of Buffers or hex strings.
:param values_array: array of values to add
:param do_hash: whether to hash the values before inserting
"""
self.tree['is_ready'] = False
[self._add_leaf(value, do_hash) for value in values_array] | [
"def",
"add_leaves",
"(",
"self",
",",
"values_array",
",",
"do_hash",
"=",
"False",
")",
":",
"self",
".",
"tree",
"[",
"'is_ready'",
"]",
"=",
"False",
"[",
"self",
".",
"_add_leaf",
"(",
"value",
",",
"do_hash",
")",
"for",
"value",
"in",
"values_array",
"]"
] | Add leaves to the tree.
Similar to chainpoint merkle tree library, this accepts hash values as an array of Buffers or hex strings.
:param values_array: array of values to add
:param do_hash: whether to hash the values before inserting | [
"Add",
"leaves",
"to",
"the",
"tree",
"."
] | 77551cc65f72b50ac203f10a5069cb1a5b3ffb49 | https://github.com/kimdhamilton/merkle-proofs/blob/77551cc65f72b50ac203f10a5069cb1a5b3ffb49/merkleproof/MerkleTree.py#L43-L52 | train |
kimdhamilton/merkle-proofs | merkleproof/MerkleTree.py | MerkleTree.make_tree | def make_tree(self):
"""
Generates the merkle tree.
"""
self.tree['is_ready'] = False
leaf_count = len(self.tree['leaves'])
if leaf_count > 0:
# skip this whole process if there are no leaves added to the tree
self._unshift(self.tree['levels'], self.tree['leaves'])
while len(self.tree['levels'][0]) > 1:
self._unshift(self.tree['levels'], self._calculate_next_level())
self.tree['is_ready'] = True | python | def make_tree(self):
"""
Generates the merkle tree.
"""
self.tree['is_ready'] = False
leaf_count = len(self.tree['leaves'])
if leaf_count > 0:
# skip this whole process if there are no leaves added to the tree
self._unshift(self.tree['levels'], self.tree['leaves'])
while len(self.tree['levels'][0]) > 1:
self._unshift(self.tree['levels'], self._calculate_next_level())
self.tree['is_ready'] = True | [
"def",
"make_tree",
"(",
"self",
")",
":",
"self",
".",
"tree",
"[",
"'is_ready'",
"]",
"=",
"False",
"leaf_count",
"=",
"len",
"(",
"self",
".",
"tree",
"[",
"'leaves'",
"]",
")",
"if",
"leaf_count",
">",
"0",
":",
"# skip this whole process if there are no leaves added to the tree",
"self",
".",
"_unshift",
"(",
"self",
".",
"tree",
"[",
"'levels'",
"]",
",",
"self",
".",
"tree",
"[",
"'leaves'",
"]",
")",
"while",
"len",
"(",
"self",
".",
"tree",
"[",
"'levels'",
"]",
"[",
"0",
"]",
")",
">",
"1",
":",
"self",
".",
"_unshift",
"(",
"self",
".",
"tree",
"[",
"'levels'",
"]",
",",
"self",
".",
"_calculate_next_level",
"(",
")",
")",
"self",
".",
"tree",
"[",
"'is_ready'",
"]",
"=",
"True"
] | Generates the merkle tree. | [
"Generates",
"the",
"merkle",
"tree",
"."
] | 77551cc65f72b50ac203f10a5069cb1a5b3ffb49 | https://github.com/kimdhamilton/merkle-proofs/blob/77551cc65f72b50ac203f10a5069cb1a5b3ffb49/merkleproof/MerkleTree.py#L80-L91 | train |
johnnoone/aioconsul | aioconsul/common/util.py | duration_to_timedelta | def duration_to_timedelta(obj):
"""Converts duration to timedelta
>>> duration_to_timedelta("10m")
>>> datetime.timedelta(0, 600)
"""
matches = DURATION_PATTERN.search(obj)
matches = matches.groupdict(default="0")
matches = {k: int(v) for k, v in matches.items()}
return timedelta(**matches) | python | def duration_to_timedelta(obj):
"""Converts duration to timedelta
>>> duration_to_timedelta("10m")
>>> datetime.timedelta(0, 600)
"""
matches = DURATION_PATTERN.search(obj)
matches = matches.groupdict(default="0")
matches = {k: int(v) for k, v in matches.items()}
return timedelta(**matches) | [
"def",
"duration_to_timedelta",
"(",
"obj",
")",
":",
"matches",
"=",
"DURATION_PATTERN",
".",
"search",
"(",
"obj",
")",
"matches",
"=",
"matches",
".",
"groupdict",
"(",
"default",
"=",
"\"0\"",
")",
"matches",
"=",
"{",
"k",
":",
"int",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"matches",
".",
"items",
"(",
")",
"}",
"return",
"timedelta",
"(",
"*",
"*",
"matches",
")"
] | Converts duration to timedelta
>>> duration_to_timedelta("10m")
>>> datetime.timedelta(0, 600) | [
"Converts",
"duration",
"to",
"timedelta"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/common/util.py#L39-L48 | train |
johnnoone/aioconsul | aioconsul/common/util.py | timedelta_to_duration | def timedelta_to_duration(obj):
"""Converts timedelta to duration
>>> timedelta_to_duration(datetime.timedelta(0, 600))
>>> "10m"
"""
minutes, hours, days = 0, 0, 0
seconds = int(obj.total_seconds())
if seconds > 59:
minutes = seconds // 60
seconds = seconds % 60
if minutes > 59:
hours = minutes // 60
minutes = minutes % 60
if hours > 23:
days = hours // 24
hours = hours % 24
response = []
if days:
response.append('%sd' % days)
if hours:
response.append('%sh' % hours)
if minutes:
response.append('%sm' % minutes)
if seconds or not response:
response.append('%ss' % seconds)
return "".join(response) | python | def timedelta_to_duration(obj):
"""Converts timedelta to duration
>>> timedelta_to_duration(datetime.timedelta(0, 600))
>>> "10m"
"""
minutes, hours, days = 0, 0, 0
seconds = int(obj.total_seconds())
if seconds > 59:
minutes = seconds // 60
seconds = seconds % 60
if minutes > 59:
hours = minutes // 60
minutes = minutes % 60
if hours > 23:
days = hours // 24
hours = hours % 24
response = []
if days:
response.append('%sd' % days)
if hours:
response.append('%sh' % hours)
if minutes:
response.append('%sm' % minutes)
if seconds or not response:
response.append('%ss' % seconds)
return "".join(response) | [
"def",
"timedelta_to_duration",
"(",
"obj",
")",
":",
"minutes",
",",
"hours",
",",
"days",
"=",
"0",
",",
"0",
",",
"0",
"seconds",
"=",
"int",
"(",
"obj",
".",
"total_seconds",
"(",
")",
")",
"if",
"seconds",
">",
"59",
":",
"minutes",
"=",
"seconds",
"//",
"60",
"seconds",
"=",
"seconds",
"%",
"60",
"if",
"minutes",
">",
"59",
":",
"hours",
"=",
"minutes",
"//",
"60",
"minutes",
"=",
"minutes",
"%",
"60",
"if",
"hours",
">",
"23",
":",
"days",
"=",
"hours",
"//",
"24",
"hours",
"=",
"hours",
"%",
"24",
"response",
"=",
"[",
"]",
"if",
"days",
":",
"response",
".",
"append",
"(",
"'%sd'",
"%",
"days",
")",
"if",
"hours",
":",
"response",
".",
"append",
"(",
"'%sh'",
"%",
"hours",
")",
"if",
"minutes",
":",
"response",
".",
"append",
"(",
"'%sm'",
"%",
"minutes",
")",
"if",
"seconds",
"or",
"not",
"response",
":",
"response",
".",
"append",
"(",
"'%ss'",
"%",
"seconds",
")",
"return",
"\"\"",
".",
"join",
"(",
"response",
")"
] | Converts timedelta to duration
>>> timedelta_to_duration(datetime.timedelta(0, 600))
>>> "10m" | [
"Converts",
"timedelta",
"to",
"duration"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/common/util.py#L51-L77 | train |
talkincode/txradius | txradius/ext/ikuai.py | create_dm_pkg | def create_dm_pkg(secret,username):
''' create ikuai dm message'''
secret = tools.EncodeString(secret)
username = tools.EncodeString(username)
pkg_format = '>HHHH32sHH32s'
pkg_vals = [
IK_RAD_PKG_VER,
IK_RAD_PKG_AUTH,
IK_RAD_PKG_USR_PWD_TAG,
len(secret),
secret.ljust(32,'\x00'),
IK_RAD_PKG_CMD_ARGS_TAG,
len(username),
username.ljust(32,'\x00')
]
return struct.pack(pkg_format,*pkg_vals) | python | def create_dm_pkg(secret,username):
''' create ikuai dm message'''
secret = tools.EncodeString(secret)
username = tools.EncodeString(username)
pkg_format = '>HHHH32sHH32s'
pkg_vals = [
IK_RAD_PKG_VER,
IK_RAD_PKG_AUTH,
IK_RAD_PKG_USR_PWD_TAG,
len(secret),
secret.ljust(32,'\x00'),
IK_RAD_PKG_CMD_ARGS_TAG,
len(username),
username.ljust(32,'\x00')
]
return struct.pack(pkg_format,*pkg_vals) | [
"def",
"create_dm_pkg",
"(",
"secret",
",",
"username",
")",
":",
"secret",
"=",
"tools",
".",
"EncodeString",
"(",
"secret",
")",
"username",
"=",
"tools",
".",
"EncodeString",
"(",
"username",
")",
"pkg_format",
"=",
"'>HHHH32sHH32s'",
"pkg_vals",
"=",
"[",
"IK_RAD_PKG_VER",
",",
"IK_RAD_PKG_AUTH",
",",
"IK_RAD_PKG_USR_PWD_TAG",
",",
"len",
"(",
"secret",
")",
",",
"secret",
".",
"ljust",
"(",
"32",
",",
"'\\x00'",
")",
",",
"IK_RAD_PKG_CMD_ARGS_TAG",
",",
"len",
"(",
"username",
")",
",",
"username",
".",
"ljust",
"(",
"32",
",",
"'\\x00'",
")",
"]",
"return",
"struct",
".",
"pack",
"(",
"pkg_format",
",",
"*",
"pkg_vals",
")"
] | create ikuai dm message | [
"create",
"ikuai",
"dm",
"message"
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/ext/ikuai.py#L20-L35 | train |
bitesofcode/projexui | projexui/widgets/xscintillaedit/xscintillaedit.py | XScintillaEdit.clearBreakpoints | def clearBreakpoints( self ):
"""
Clears the file of all the breakpoints.
"""
self.markerDeleteAll(self._breakpointMarker)
if ( not self.signalsBlocked() ):
self.breakpointsChanged.emit() | python | def clearBreakpoints( self ):
"""
Clears the file of all the breakpoints.
"""
self.markerDeleteAll(self._breakpointMarker)
if ( not self.signalsBlocked() ):
self.breakpointsChanged.emit() | [
"def",
"clearBreakpoints",
"(",
"self",
")",
":",
"self",
".",
"markerDeleteAll",
"(",
"self",
".",
"_breakpointMarker",
")",
"if",
"(",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
")",
":",
"self",
".",
"breakpointsChanged",
".",
"emit",
"(",
")"
] | Clears the file of all the breakpoints. | [
"Clears",
"the",
"file",
"of",
"all",
"the",
"breakpoints",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xscintillaedit/xscintillaedit.py#L127-L134 | train |
bitesofcode/projexui | projexui/widgets/xscintillaedit/xscintillaedit.py | XScintillaEdit.unindentSelection | def unindentSelection( self ):
"""
Unindents the current selected text.
"""
sel = self.getSelection()
for line in range(sel[0], sel[2] + 1):
self.unindent(line) | python | def unindentSelection( self ):
"""
Unindents the current selected text.
"""
sel = self.getSelection()
for line in range(sel[0], sel[2] + 1):
self.unindent(line) | [
"def",
"unindentSelection",
"(",
"self",
")",
":",
"sel",
"=",
"self",
".",
"getSelection",
"(",
")",
"for",
"line",
"in",
"range",
"(",
"sel",
"[",
"0",
"]",
",",
"sel",
"[",
"2",
"]",
"+",
"1",
")",
":",
"self",
".",
"unindent",
"(",
"line",
")"
] | Unindents the current selected text. | [
"Unindents",
"the",
"current",
"selected",
"text",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xscintillaedit/xscintillaedit.py#L742-L749 | train |
starling-lab/rnlp | rnlp/textprocessing.py | _removePunctuation | def _removePunctuation(text_string):
"""
Removes punctuation symbols from a string.
:param text_string: A string.
:type text_string: str.
:returns: The input ``text_string`` with punctuation symbols removed.
:rtype: str.
>>> from rnlp.textprocessing import __removePunctuation
>>> example = 'Hello, World!'
>>> __removePunctuation(example)
'Hello World'
"""
try:
return text_string.translate(None, _punctuation)
except TypeError:
return text_string.translate(str.maketrans('', '', _punctuation)) | python | def _removePunctuation(text_string):
"""
Removes punctuation symbols from a string.
:param text_string: A string.
:type text_string: str.
:returns: The input ``text_string`` with punctuation symbols removed.
:rtype: str.
>>> from rnlp.textprocessing import __removePunctuation
>>> example = 'Hello, World!'
>>> __removePunctuation(example)
'Hello World'
"""
try:
return text_string.translate(None, _punctuation)
except TypeError:
return text_string.translate(str.maketrans('', '', _punctuation)) | [
"def",
"_removePunctuation",
"(",
"text_string",
")",
":",
"try",
":",
"return",
"text_string",
".",
"translate",
"(",
"None",
",",
"_punctuation",
")",
"except",
"TypeError",
":",
"return",
"text_string",
".",
"translate",
"(",
"str",
".",
"maketrans",
"(",
"''",
",",
"''",
",",
"_punctuation",
")",
")"
] | Removes punctuation symbols from a string.
:param text_string: A string.
:type text_string: str.
:returns: The input ``text_string`` with punctuation symbols removed.
:rtype: str.
>>> from rnlp.textprocessing import __removePunctuation
>>> example = 'Hello, World!'
>>> __removePunctuation(example)
'Hello World' | [
"Removes",
"punctuation",
"symbols",
"from",
"a",
"string",
"."
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/textprocessing.py#L49-L67 | train |
starling-lab/rnlp | rnlp/textprocessing.py | _removeStopwords | def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.lower() not in _stopwords:
output_list.append(word)
return output_list | python | def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.lower() not in _stopwords:
output_list.append(word)
return output_list | [
"def",
"_removeStopwords",
"(",
"text_list",
")",
":",
"output_list",
"=",
"[",
"]",
"for",
"word",
"in",
"text_list",
":",
"if",
"word",
".",
"lower",
"(",
")",
"not",
"in",
"_stopwords",
":",
"output_list",
".",
"append",
"(",
"word",
")",
"return",
"output_list"
] | Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list | [
"Removes",
"stopwords",
"contained",
"in",
"a",
"list",
"of",
"words",
"."
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/textprocessing.py#L70-L87 | train |
starling-lab/rnlp | rnlp/textprocessing.py | getBlocks | def getBlocks(sentences, n):
"""
Get blocks of n sentences together.
:param sentences: List of strings where each string is a sentence.
:type sentences: list
:param n: Maximum blocksize for sentences, i.e. a block will be composed of
``n`` sentences.
:type n: int.
:returns: Blocks of n sentences.
:rtype: list-of-lists
.. code-block:: python
import rnlp
example = "Hello there. How are you? I am fine."
sentences = rnlp.getSentences(example)
# ['Hello there', 'How are you', 'I am fine']
blocks = rnlp.getBlocks(sentences, 2)
# with 1: [['Hello there'], ['How are you'], ['I am fine']]
# with 2: [['Hello there', 'How are you'], ['I am fine']]
# with 3: [['Hello there', 'How are you', 'I am fine']]
"""
blocks = []
for i in range(0, len(sentences), n):
blocks.append(sentences[i:(i+n)])
return blocks | python | def getBlocks(sentences, n):
"""
Get blocks of n sentences together.
:param sentences: List of strings where each string is a sentence.
:type sentences: list
:param n: Maximum blocksize for sentences, i.e. a block will be composed of
``n`` sentences.
:type n: int.
:returns: Blocks of n sentences.
:rtype: list-of-lists
.. code-block:: python
import rnlp
example = "Hello there. How are you? I am fine."
sentences = rnlp.getSentences(example)
# ['Hello there', 'How are you', 'I am fine']
blocks = rnlp.getBlocks(sentences, 2)
# with 1: [['Hello there'], ['How are you'], ['I am fine']]
# with 2: [['Hello there', 'How are you'], ['I am fine']]
# with 3: [['Hello there', 'How are you', 'I am fine']]
"""
blocks = []
for i in range(0, len(sentences), n):
blocks.append(sentences[i:(i+n)])
return blocks | [
"def",
"getBlocks",
"(",
"sentences",
",",
"n",
")",
":",
"blocks",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"sentences",
")",
",",
"n",
")",
":",
"blocks",
".",
"append",
"(",
"sentences",
"[",
"i",
":",
"(",
"i",
"+",
"n",
")",
"]",
")",
"return",
"blocks"
] | Get blocks of n sentences together.
:param sentences: List of strings where each string is a sentence.
:type sentences: list
:param n: Maximum blocksize for sentences, i.e. a block will be composed of
``n`` sentences.
:type n: int.
:returns: Blocks of n sentences.
:rtype: list-of-lists
.. code-block:: python
import rnlp
example = "Hello there. How are you? I am fine."
sentences = rnlp.getSentences(example)
# ['Hello there', 'How are you', 'I am fine']
blocks = rnlp.getBlocks(sentences, 2)
# with 1: [['Hello there'], ['How are you'], ['I am fine']]
# with 2: [['Hello there', 'How are you'], ['I am fine']]
# with 3: [['Hello there', 'How are you', 'I am fine']] | [
"Get",
"blocks",
"of",
"n",
"sentences",
"together",
"."
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/textprocessing.py#L90-L120 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.__destroyLockedView | def __destroyLockedView(self):
"""
Destroys the locked view from this widget.
"""
if self._lockedView:
self._lockedView.close()
self._lockedView.deleteLater()
self._lockedView = None | python | def __destroyLockedView(self):
"""
Destroys the locked view from this widget.
"""
if self._lockedView:
self._lockedView.close()
self._lockedView.deleteLater()
self._lockedView = None | [
"def",
"__destroyLockedView",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lockedView",
":",
"self",
".",
"_lockedView",
".",
"close",
"(",
")",
"self",
".",
"_lockedView",
".",
"deleteLater",
"(",
")",
"self",
".",
"_lockedView",
"=",
"None"
] | Destroys the locked view from this widget. | [
"Destroys",
"the",
"locked",
"view",
"from",
"this",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L185-L192 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.clear | def clear(self):
"""
Removes all the items from this tree widget. This will go through
and also destroy any XTreeWidgetItems prior to the model clearing
its references.
"""
# go through and properly destroy all the items for this tree
for item in self.traverseItems():
if isinstance(item, XTreeWidgetItem):
item.destroy()
super(XTreeWidget, self).clear() | python | def clear(self):
"""
Removes all the items from this tree widget. This will go through
and also destroy any XTreeWidgetItems prior to the model clearing
its references.
"""
# go through and properly destroy all the items for this tree
for item in self.traverseItems():
if isinstance(item, XTreeWidgetItem):
item.destroy()
super(XTreeWidget, self).clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"# go through and properly destroy all the items for this tree\r",
"for",
"item",
"in",
"self",
".",
"traverseItems",
"(",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"XTreeWidgetItem",
")",
":",
"item",
".",
"destroy",
"(",
")",
"super",
"(",
"XTreeWidget",
",",
"self",
")",
".",
"clear",
"(",
")"
] | Removes all the items from this tree widget. This will go through
and also destroy any XTreeWidgetItems prior to the model clearing
its references. | [
"Removes",
"all",
"the",
"items",
"from",
"this",
"tree",
"widget",
".",
"This",
"will",
"go",
"through",
"and",
"also",
"destroy",
"any",
"XTreeWidgetItems",
"prior",
"to",
"the",
"model",
"clearing",
"its",
"references",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L401-L412 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.exportAs | def exportAs(self, action):
"""
Prompts the user to export the information for this tree based on the
available exporters.
"""
plugin = self.exporter(unwrapVariant(action.data()))
if not plugin:
return False
ftypes = '{0} (*{1});;All Files (*.*)'.format(plugin.name(),
plugin.filetype())
filename = QtGui.QFileDialog.getSaveFileName(self.window(),
'Export Data',
'',
ftypes)
if type(filename) == tuple:
filename = filename[0]
if filename:
return self.export(nativestring(filename), exporter=plugin)
return False | python | def exportAs(self, action):
"""
Prompts the user to export the information for this tree based on the
available exporters.
"""
plugin = self.exporter(unwrapVariant(action.data()))
if not plugin:
return False
ftypes = '{0} (*{1});;All Files (*.*)'.format(plugin.name(),
plugin.filetype())
filename = QtGui.QFileDialog.getSaveFileName(self.window(),
'Export Data',
'',
ftypes)
if type(filename) == tuple:
filename = filename[0]
if filename:
return self.export(nativestring(filename), exporter=plugin)
return False | [
"def",
"exportAs",
"(",
"self",
",",
"action",
")",
":",
"plugin",
"=",
"self",
".",
"exporter",
"(",
"unwrapVariant",
"(",
"action",
".",
"data",
"(",
")",
")",
")",
"if",
"not",
"plugin",
":",
"return",
"False",
"ftypes",
"=",
"'{0} (*{1});;All Files (*.*)'",
".",
"format",
"(",
"plugin",
".",
"name",
"(",
")",
",",
"plugin",
".",
"filetype",
"(",
")",
")",
"filename",
"=",
"QtGui",
".",
"QFileDialog",
".",
"getSaveFileName",
"(",
"self",
".",
"window",
"(",
")",
",",
"'Export Data'",
",",
"''",
",",
"ftypes",
")",
"if",
"type",
"(",
"filename",
")",
"==",
"tuple",
":",
"filename",
"=",
"filename",
"[",
"0",
"]",
"if",
"filename",
":",
"return",
"self",
".",
"export",
"(",
"nativestring",
"(",
"filename",
")",
",",
"exporter",
"=",
"plugin",
")",
"return",
"False"
] | Prompts the user to export the information for this tree based on the
available exporters. | [
"Prompts",
"the",
"user",
"to",
"export",
"the",
"information",
"for",
"this",
"tree",
"based",
"on",
"the",
"available",
"exporters",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L740-L761 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.headerHideColumn | def headerHideColumn( self ):
"""
Hides the current column set by the header index.
"""
self.setColumnHidden(self._headerIndex, True)
# ensure we at least have 1 column visible
found = False
for col in range(self.columnCount()):
if ( not self.isColumnHidden(col) ):
found = True
break
if ( not found ):
self.setColumnHidden(0, False) | python | def headerHideColumn( self ):
"""
Hides the current column set by the header index.
"""
self.setColumnHidden(self._headerIndex, True)
# ensure we at least have 1 column visible
found = False
for col in range(self.columnCount()):
if ( not self.isColumnHidden(col) ):
found = True
break
if ( not found ):
self.setColumnHidden(0, False) | [
"def",
"headerHideColumn",
"(",
"self",
")",
":",
"self",
".",
"setColumnHidden",
"(",
"self",
".",
"_headerIndex",
",",
"True",
")",
"# ensure we at least have 1 column visible\r",
"found",
"=",
"False",
"for",
"col",
"in",
"range",
"(",
"self",
".",
"columnCount",
"(",
")",
")",
":",
"if",
"(",
"not",
"self",
".",
"isColumnHidden",
"(",
"col",
")",
")",
":",
"found",
"=",
"True",
"break",
"if",
"(",
"not",
"found",
")",
":",
"self",
".",
"setColumnHidden",
"(",
"0",
",",
"False",
")"
] | Hides the current column set by the header index. | [
"Hides",
"the",
"current",
"column",
"set",
"by",
"the",
"header",
"index",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L967-L981 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.headerSortAscending | def headerSortAscending( self ):
"""
Sorts the column at the current header index by ascending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.AscendingOrder) | python | def headerSortAscending( self ):
"""
Sorts the column at the current header index by ascending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.AscendingOrder) | [
"def",
"headerSortAscending",
"(",
"self",
")",
":",
"self",
".",
"setSortingEnabled",
"(",
"True",
")",
"self",
".",
"sortByColumn",
"(",
"self",
".",
"_headerIndex",
",",
"QtCore",
".",
"Qt",
".",
"AscendingOrder",
")"
] | Sorts the column at the current header index by ascending order. | [
"Sorts",
"the",
"column",
"at",
"the",
"current",
"header",
"index",
"by",
"ascending",
"order",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1000-L1005 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.headerSortDescending | def headerSortDescending( self ):
"""
Sorts the column at the current header index by descending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.DescendingOrder) | python | def headerSortDescending( self ):
"""
Sorts the column at the current header index by descending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.DescendingOrder) | [
"def",
"headerSortDescending",
"(",
"self",
")",
":",
"self",
".",
"setSortingEnabled",
"(",
"True",
")",
"self",
".",
"sortByColumn",
"(",
"self",
".",
"_headerIndex",
",",
"QtCore",
".",
"Qt",
".",
"DescendingOrder",
")"
] | Sorts the column at the current header index by descending order. | [
"Sorts",
"the",
"column",
"at",
"the",
"current",
"header",
"index",
"by",
"descending",
"order",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1007-L1012 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.highlightByAlternate | def highlightByAlternate(self):
"""
Sets the palette highlighting for this tree widget to use a darker
version of the alternate color vs. the standard highlighting.
"""
palette = QtGui.QApplication.palette()
palette.setColor(palette.HighlightedText, palette.color(palette.Text))
clr = palette.color(palette.AlternateBase)
palette.setColor(palette.Highlight, clr.darker(110))
self.setPalette(palette) | python | def highlightByAlternate(self):
"""
Sets the palette highlighting for this tree widget to use a darker
version of the alternate color vs. the standard highlighting.
"""
palette = QtGui.QApplication.palette()
palette.setColor(palette.HighlightedText, palette.color(palette.Text))
clr = palette.color(palette.AlternateBase)
palette.setColor(palette.Highlight, clr.darker(110))
self.setPalette(palette) | [
"def",
"highlightByAlternate",
"(",
"self",
")",
":",
"palette",
"=",
"QtGui",
".",
"QApplication",
".",
"palette",
"(",
")",
"palette",
".",
"setColor",
"(",
"palette",
".",
"HighlightedText",
",",
"palette",
".",
"color",
"(",
"palette",
".",
"Text",
")",
")",
"clr",
"=",
"palette",
".",
"color",
"(",
"palette",
".",
"AlternateBase",
")",
"palette",
".",
"setColor",
"(",
"palette",
".",
"Highlight",
",",
"clr",
".",
"darker",
"(",
"110",
")",
")",
"self",
".",
"setPalette",
"(",
"palette",
")"
] | Sets the palette highlighting for this tree widget to use a darker
version of the alternate color vs. the standard highlighting. | [
"Sets",
"the",
"palette",
"highlighting",
"for",
"this",
"tree",
"widget",
"to",
"use",
"a",
"darker",
"version",
"of",
"the",
"alternate",
"color",
"vs",
".",
"the",
"standard",
"highlighting",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1028-L1038 | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | XTreeWidget.smartResizeColumnsToContents | def smartResizeColumnsToContents( self ):
"""
Resizes the columns to the contents based on the user preferences.
"""
self.blockSignals(True)
self.setUpdatesEnabled(False)
header = self.header()
header.blockSignals(True)
columns = range(self.columnCount())
sizes = [self.columnWidth(c) for c in columns]
header.resizeSections(header.ResizeToContents)
for col in columns:
width = self.columnWidth(col)
if ( width < sizes[col] ):
self.setColumnWidth(col, sizes[col])
header.blockSignals(False)
self.setUpdatesEnabled(True)
self.blockSignals(False) | python | def smartResizeColumnsToContents( self ):
"""
Resizes the columns to the contents based on the user preferences.
"""
self.blockSignals(True)
self.setUpdatesEnabled(False)
header = self.header()
header.blockSignals(True)
columns = range(self.columnCount())
sizes = [self.columnWidth(c) for c in columns]
header.resizeSections(header.ResizeToContents)
for col in columns:
width = self.columnWidth(col)
if ( width < sizes[col] ):
self.setColumnWidth(col, sizes[col])
header.blockSignals(False)
self.setUpdatesEnabled(True)
self.blockSignals(False) | [
"def",
"smartResizeColumnsToContents",
"(",
"self",
")",
":",
"self",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"header",
"=",
"self",
".",
"header",
"(",
")",
"header",
".",
"blockSignals",
"(",
"True",
")",
"columns",
"=",
"range",
"(",
"self",
".",
"columnCount",
"(",
")",
")",
"sizes",
"=",
"[",
"self",
".",
"columnWidth",
"(",
"c",
")",
"for",
"c",
"in",
"columns",
"]",
"header",
".",
"resizeSections",
"(",
"header",
".",
"ResizeToContents",
")",
"for",
"col",
"in",
"columns",
":",
"width",
"=",
"self",
".",
"columnWidth",
"(",
"col",
")",
"if",
"(",
"width",
"<",
"sizes",
"[",
"col",
"]",
")",
":",
"self",
".",
"setColumnWidth",
"(",
"col",
",",
"sizes",
"[",
"col",
"]",
")",
"header",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"True",
")",
"self",
".",
"blockSignals",
"(",
"False",
")"
] | Resizes the columns to the contents based on the user preferences. | [
"Resizes",
"the",
"columns",
"to",
"the",
"contents",
"based",
"on",
"the",
"user",
"preferences",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1985-L2007 | train |
viatoriche/microservices | microservices/queues/runners.py | gevent_run | def gevent_run(app, monkey_patch=True, start=True, debug=False,
**kwargs): # pragma: no cover
"""Run your app in gevent.spawn, run simple loop if start == True
:param app: queues.Microservice instance
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if True, server will be start (simple loop)
:param kwargs: other params for WSGIServer(**kwargs)
:return: server
"""
if monkey_patch:
from gevent import monkey
monkey.patch_all()
import gevent
gevent.spawn(app.run, debug=debug, **kwargs)
if start:
while not app.stopped:
gevent.sleep(0.1) | python | def gevent_run(app, monkey_patch=True, start=True, debug=False,
**kwargs): # pragma: no cover
"""Run your app in gevent.spawn, run simple loop if start == True
:param app: queues.Microservice instance
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if True, server will be start (simple loop)
:param kwargs: other params for WSGIServer(**kwargs)
:return: server
"""
if monkey_patch:
from gevent import monkey
monkey.patch_all()
import gevent
gevent.spawn(app.run, debug=debug, **kwargs)
if start:
while not app.stopped:
gevent.sleep(0.1) | [
"def",
"gevent_run",
"(",
"app",
",",
"monkey_patch",
"=",
"True",
",",
"start",
"=",
"True",
",",
"debug",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"if",
"monkey_patch",
":",
"from",
"gevent",
"import",
"monkey",
"monkey",
".",
"patch_all",
"(",
")",
"import",
"gevent",
"gevent",
".",
"spawn",
"(",
"app",
".",
"run",
",",
"debug",
"=",
"debug",
",",
"*",
"*",
"kwargs",
")",
"if",
"start",
":",
"while",
"not",
"app",
".",
"stopped",
":",
"gevent",
".",
"sleep",
"(",
"0.1",
")"
] | Run your app in gevent.spawn, run simple loop if start == True
:param app: queues.Microservice instance
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if True, server will be start (simple loop)
:param kwargs: other params for WSGIServer(**kwargs)
:return: server | [
"Run",
"your",
"app",
"in",
"gevent",
".",
"spawn",
"run",
"simple",
"loop",
"if",
"start",
"==",
"True"
] | 3510563edd15dc6131b8a948d6062856cd904ac7 | https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/queues/runners.py#L1-L22 | train |
viatoriche/microservices | microservices/utils/__init__.py | dict_update | def dict_update(d, u):
"""Recursive dict update
:param d: goal dict
:param u: updates for d
:return: new dict
"""
for k, v in six.iteritems(u):
if isinstance(v, collections.Mapping):
r = dict_update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d | python | def dict_update(d, u):
"""Recursive dict update
:param d: goal dict
:param u: updates for d
:return: new dict
"""
for k, v in six.iteritems(u):
if isinstance(v, collections.Mapping):
r = dict_update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d | [
"def",
"dict_update",
"(",
"d",
",",
"u",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"u",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"Mapping",
")",
":",
"r",
"=",
"dict_update",
"(",
"d",
".",
"get",
"(",
"k",
",",
"{",
"}",
")",
",",
"v",
")",
"d",
"[",
"k",
"]",
"=",
"r",
"else",
":",
"d",
"[",
"k",
"]",
"=",
"u",
"[",
"k",
"]",
"return",
"d"
] | Recursive dict update
:param d: goal dict
:param u: updates for d
:return: new dict | [
"Recursive",
"dict",
"update"
] | 3510563edd15dc6131b8a948d6062856cd904ac7 | https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/utils/__init__.py#L39-L52 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.get_schema | def get_schema(self, schema_id):
"""
Retrieves the schema with the given schema_id from the registry
and returns it as a `dict`.
"""
res = requests.get(self._url('/schemas/ids/{}', schema_id))
raise_if_failed(res)
return json.loads(res.json()['schema']) | python | def get_schema(self, schema_id):
"""
Retrieves the schema with the given schema_id from the registry
and returns it as a `dict`.
"""
res = requests.get(self._url('/schemas/ids/{}', schema_id))
raise_if_failed(res)
return json.loads(res.json()['schema']) | [
"def",
"get_schema",
"(",
"self",
",",
"schema_id",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/schemas/ids/{}'",
",",
"schema_id",
")",
")",
"raise_if_failed",
"(",
"res",
")",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"json",
"(",
")",
"[",
"'schema'",
"]",
")"
] | Retrieves the schema with the given schema_id from the registry
and returns it as a `dict`. | [
"Retrieves",
"the",
"schema",
"with",
"the",
"given",
"schema_id",
"from",
"the",
"registry",
"and",
"returns",
"it",
"as",
"a",
"dict",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L51-L58 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.get_subjects | def get_subjects(self):
"""
Returns the list of subject names present in the schema registry.
"""
res = requests.get(self._url('/subjects'))
raise_if_failed(res)
return res.json() | python | def get_subjects(self):
"""
Returns the list of subject names present in the schema registry.
"""
res = requests.get(self._url('/subjects'))
raise_if_failed(res)
return res.json() | [
"def",
"get_subjects",
"(",
"self",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/subjects'",
")",
")",
"raise_if_failed",
"(",
"res",
")",
"return",
"res",
".",
"json",
"(",
")"
] | Returns the list of subject names present in the schema registry. | [
"Returns",
"the",
"list",
"of",
"subject",
"names",
"present",
"in",
"the",
"schema",
"registry",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L60-L66 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.get_subject_version_ids | def get_subject_version_ids(self, subject):
"""
Return the list of schema version ids which have been registered
under the given subject.
"""
res = requests.get(self._url('/subjects/{}/versions', subject))
raise_if_failed(res)
return res.json() | python | def get_subject_version_ids(self, subject):
"""
Return the list of schema version ids which have been registered
under the given subject.
"""
res = requests.get(self._url('/subjects/{}/versions', subject))
raise_if_failed(res)
return res.json() | [
"def",
"get_subject_version_ids",
"(",
"self",
",",
"subject",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/subjects/{}/versions'",
",",
"subject",
")",
")",
"raise_if_failed",
"(",
"res",
")",
"return",
"res",
".",
"json",
"(",
")"
] | Return the list of schema version ids which have been registered
under the given subject. | [
"Return",
"the",
"list",
"of",
"schema",
"version",
"ids",
"which",
"have",
"been",
"registered",
"under",
"the",
"given",
"subject",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L68-L75 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.get_subject_version | def get_subject_version(self, subject, version_id):
"""
Retrieves the schema registered under the given subject with
the given version id. Returns the schema as a `dict`.
"""
res = requests.get(self._url('/subjects/{}/versions/{}', subject, version_id))
raise_if_failed(res)
return json.loads(res.json()['schema']) | python | def get_subject_version(self, subject, version_id):
"""
Retrieves the schema registered under the given subject with
the given version id. Returns the schema as a `dict`.
"""
res = requests.get(self._url('/subjects/{}/versions/{}', subject, version_id))
raise_if_failed(res)
return json.loads(res.json()['schema']) | [
"def",
"get_subject_version",
"(",
"self",
",",
"subject",
",",
"version_id",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/subjects/{}/versions/{}'",
",",
"subject",
",",
"version_id",
")",
")",
"raise_if_failed",
"(",
"res",
")",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"json",
"(",
")",
"[",
"'schema'",
"]",
")"
] | Retrieves the schema registered under the given subject with
the given version id. Returns the schema as a `dict`. | [
"Retrieves",
"the",
"schema",
"registered",
"under",
"the",
"given",
"subject",
"with",
"the",
"given",
"version",
"id",
".",
"Returns",
"the",
"schema",
"as",
"a",
"dict",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L77-L84 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.schema_is_registered_for_subject | def schema_is_registered_for_subject(self, subject, schema):
"""
Returns True if the given schema is already registered under the
given subject.
"""
data = json.dumps({'schema': json.dumps(schema)})
res = requests.post(self._url('/subjects/{}', subject), data=data, headers=HEADERS)
if res.status_code == 404:
return False
raise_if_failed(res)
return True | python | def schema_is_registered_for_subject(self, subject, schema):
"""
Returns True if the given schema is already registered under the
given subject.
"""
data = json.dumps({'schema': json.dumps(schema)})
res = requests.post(self._url('/subjects/{}', subject), data=data, headers=HEADERS)
if res.status_code == 404:
return False
raise_if_failed(res)
return True | [
"def",
"schema_is_registered_for_subject",
"(",
"self",
",",
"subject",
",",
"schema",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'schema'",
":",
"json",
".",
"dumps",
"(",
"schema",
")",
"}",
")",
"res",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"_url",
"(",
"'/subjects/{}'",
",",
"subject",
")",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"HEADERS",
")",
"if",
"res",
".",
"status_code",
"==",
"404",
":",
"return",
"False",
"raise_if_failed",
"(",
"res",
")",
"return",
"True"
] | Returns True if the given schema is already registered under the
given subject. | [
"Returns",
"True",
"if",
"the",
"given",
"schema",
"is",
"already",
"registered",
"under",
"the",
"given",
"subject",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L115-L125 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.get_global_compatibility_level | def get_global_compatibility_level(self):
"""
Gets the global compatibility level.
"""
res = requests.get(self._url('/config'), headers=HEADERS)
raise_if_failed(res)
return res.json()['compatibility'] | python | def get_global_compatibility_level(self):
"""
Gets the global compatibility level.
"""
res = requests.get(self._url('/config'), headers=HEADERS)
raise_if_failed(res)
return res.json()['compatibility'] | [
"def",
"get_global_compatibility_level",
"(",
"self",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/config'",
")",
",",
"headers",
"=",
"HEADERS",
")",
"raise_if_failed",
"(",
"res",
")",
"return",
"res",
".",
"json",
"(",
")",
"[",
"'compatibility'",
"]"
] | Gets the global compatibility level. | [
"Gets",
"the",
"global",
"compatibility",
"level",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L152-L158 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.set_subject_compatibility_level | def set_subject_compatibility_level(self, subject, level):
"""
Sets the compatibility level for the given subject.
"""
res = requests.put(
self._url('/config/{}', subject),
data=json.dumps({'compatibility': level}),
headers=HEADERS)
raise_if_failed(res) | python | def set_subject_compatibility_level(self, subject, level):
"""
Sets the compatibility level for the given subject.
"""
res = requests.put(
self._url('/config/{}', subject),
data=json.dumps({'compatibility': level}),
headers=HEADERS)
raise_if_failed(res) | [
"def",
"set_subject_compatibility_level",
"(",
"self",
",",
"subject",
",",
"level",
")",
":",
"res",
"=",
"requests",
".",
"put",
"(",
"self",
".",
"_url",
"(",
"'/config/{}'",
",",
"subject",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'compatibility'",
":",
"level",
"}",
")",
",",
"headers",
"=",
"HEADERS",
")",
"raise_if_failed",
"(",
"res",
")"
] | Sets the compatibility level for the given subject. | [
"Sets",
"the",
"compatibility",
"level",
"for",
"the",
"given",
"subject",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L160-L168 | train |
gamechanger/confluent_schema_registry_client | confluent_schema_registry_client/__init__.py | SchemaRegistryClient.get_subject_compatibility_level | def get_subject_compatibility_level(self, subject):
"""
Gets the compatibility level for the given subject.
"""
res = requests.get(self._url('/config/{}', subject), headers=HEADERS)
raise_if_failed(res)
return res.json()['compatibility'] | python | def get_subject_compatibility_level(self, subject):
"""
Gets the compatibility level for the given subject.
"""
res = requests.get(self._url('/config/{}', subject), headers=HEADERS)
raise_if_failed(res)
return res.json()['compatibility'] | [
"def",
"get_subject_compatibility_level",
"(",
"self",
",",
"subject",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"'/config/{}'",
",",
"subject",
")",
",",
"headers",
"=",
"HEADERS",
")",
"raise_if_failed",
"(",
"res",
")",
"return",
"res",
".",
"json",
"(",
")",
"[",
"'compatibility'",
"]"
] | Gets the compatibility level for the given subject. | [
"Gets",
"the",
"compatibility",
"level",
"for",
"the",
"given",
"subject",
"."
] | ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae | https://github.com/gamechanger/confluent_schema_registry_client/blob/ac9196e366724eeb2f19f1a169fd2f9a0c8d68ae/confluent_schema_registry_client/__init__.py#L170-L176 | train |
wrboyce/telegrambot | telegrambot/api/base.py | APIObject.from_api | def from_api(cls, api, **kwargs):
""" Parses a payload from the API, guided by `_api_attrs` """
if not cls._api_attrs:
raise NotImplementedError()
def resolve_attribute_type(attr_type):
# resolve arrays of types down to base type
while isinstance(attr_type, list):
attr_type = attr_type[0]
# attribute type 'self' resolves to current class
if attr_type == 'self':
attr_type = cls
# attribute type 'date' is a unix timestamp
if attr_type == 'date':
attr_type = datetime.datetime.fromtimestamp
# string attributes should use unicode literals
if attr_type is str:
attr_type = unicode
# if attribute type is an APIObject, use the from_api factory method and pass the `api` argument
if hasattr(attr_type, 'from_api'):
return lambda **kw: attr_type.from_api(api, **kw)
return attr_type
def instantiate_attr(attr_value, attr_type):
if isinstance(attr_value, dict):
return attr_type(**attr_value)
return attr_type(attr_value)
def instantiate_array(attr_values, attr_type):
func = instantiate_attr
if isinstance(attr_values[0], list):
func = instantiate_array
return [func(val, attr_type) for val in attr_values]
def instantiate(attr_value, attr_type):
if isinstance(attr_value, list):
return instantiate_array(attr_value, attr_type)
return instantiate_attr(attr_value, attr_type)
instance = cls(api)
for attr_name, attr_type, attr_default in cls._api_attrs:
# grab the current attribute value
attr_value = kwargs.get(attr_name, attr_default)
# default of TypeError means a required attribute, raise Exception
if attr_value is TypeError:
raise TypeError('{} requires argument {}'.format(cls.__name__, attr_name))
attr_type = resolve_attribute_type(attr_type)
# if value has been provided from API, instantiate it using `attr_type`
if attr_value != attr_default:
attr_value = instantiate(attr_value, attr_type)
# rename the 'from' variable, reserved word
if attr_name == 'from':
attr_name = 'froom'
# and finally set the attribute value on the instance
setattr(instance, attr_name, attr_value)
return instance | python | def from_api(cls, api, **kwargs):
""" Parses a payload from the API, guided by `_api_attrs` """
if not cls._api_attrs:
raise NotImplementedError()
def resolve_attribute_type(attr_type):
# resolve arrays of types down to base type
while isinstance(attr_type, list):
attr_type = attr_type[0]
# attribute type 'self' resolves to current class
if attr_type == 'self':
attr_type = cls
# attribute type 'date' is a unix timestamp
if attr_type == 'date':
attr_type = datetime.datetime.fromtimestamp
# string attributes should use unicode literals
if attr_type is str:
attr_type = unicode
# if attribute type is an APIObject, use the from_api factory method and pass the `api` argument
if hasattr(attr_type, 'from_api'):
return lambda **kw: attr_type.from_api(api, **kw)
return attr_type
def instantiate_attr(attr_value, attr_type):
if isinstance(attr_value, dict):
return attr_type(**attr_value)
return attr_type(attr_value)
def instantiate_array(attr_values, attr_type):
func = instantiate_attr
if isinstance(attr_values[0], list):
func = instantiate_array
return [func(val, attr_type) for val in attr_values]
def instantiate(attr_value, attr_type):
if isinstance(attr_value, list):
return instantiate_array(attr_value, attr_type)
return instantiate_attr(attr_value, attr_type)
instance = cls(api)
for attr_name, attr_type, attr_default in cls._api_attrs:
# grab the current attribute value
attr_value = kwargs.get(attr_name, attr_default)
# default of TypeError means a required attribute, raise Exception
if attr_value is TypeError:
raise TypeError('{} requires argument {}'.format(cls.__name__, attr_name))
attr_type = resolve_attribute_type(attr_type)
# if value has been provided from API, instantiate it using `attr_type`
if attr_value != attr_default:
attr_value = instantiate(attr_value, attr_type)
# rename the 'from' variable, reserved word
if attr_name == 'from':
attr_name = 'froom'
# and finally set the attribute value on the instance
setattr(instance, attr_name, attr_value)
return instance | [
"def",
"from_api",
"(",
"cls",
",",
"api",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"cls",
".",
"_api_attrs",
":",
"raise",
"NotImplementedError",
"(",
")",
"def",
"resolve_attribute_type",
"(",
"attr_type",
")",
":",
"# resolve arrays of types down to base type",
"while",
"isinstance",
"(",
"attr_type",
",",
"list",
")",
":",
"attr_type",
"=",
"attr_type",
"[",
"0",
"]",
"# attribute type 'self' resolves to current class",
"if",
"attr_type",
"==",
"'self'",
":",
"attr_type",
"=",
"cls",
"# attribute type 'date' is a unix timestamp",
"if",
"attr_type",
"==",
"'date'",
":",
"attr_type",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"# string attributes should use unicode literals",
"if",
"attr_type",
"is",
"str",
":",
"attr_type",
"=",
"unicode",
"# if attribute type is an APIObject, use the from_api factory method and pass the `api` argument",
"if",
"hasattr",
"(",
"attr_type",
",",
"'from_api'",
")",
":",
"return",
"lambda",
"*",
"*",
"kw",
":",
"attr_type",
".",
"from_api",
"(",
"api",
",",
"*",
"*",
"kw",
")",
"return",
"attr_type",
"def",
"instantiate_attr",
"(",
"attr_value",
",",
"attr_type",
")",
":",
"if",
"isinstance",
"(",
"attr_value",
",",
"dict",
")",
":",
"return",
"attr_type",
"(",
"*",
"*",
"attr_value",
")",
"return",
"attr_type",
"(",
"attr_value",
")",
"def",
"instantiate_array",
"(",
"attr_values",
",",
"attr_type",
")",
":",
"func",
"=",
"instantiate_attr",
"if",
"isinstance",
"(",
"attr_values",
"[",
"0",
"]",
",",
"list",
")",
":",
"func",
"=",
"instantiate_array",
"return",
"[",
"func",
"(",
"val",
",",
"attr_type",
")",
"for",
"val",
"in",
"attr_values",
"]",
"def",
"instantiate",
"(",
"attr_value",
",",
"attr_type",
")",
":",
"if",
"isinstance",
"(",
"attr_value",
",",
"list",
")",
":",
"return",
"instantiate_array",
"(",
"attr_value",
",",
"attr_type",
")",
"return",
"instantiate_attr",
"(",
"attr_value",
",",
"attr_type",
")",
"instance",
"=",
"cls",
"(",
"api",
")",
"for",
"attr_name",
",",
"attr_type",
",",
"attr_default",
"in",
"cls",
".",
"_api_attrs",
":",
"# grab the current attribute value",
"attr_value",
"=",
"kwargs",
".",
"get",
"(",
"attr_name",
",",
"attr_default",
")",
"# default of TypeError means a required attribute, raise Exception",
"if",
"attr_value",
"is",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'{} requires argument {}'",
".",
"format",
"(",
"cls",
".",
"__name__",
",",
"attr_name",
")",
")",
"attr_type",
"=",
"resolve_attribute_type",
"(",
"attr_type",
")",
"# if value has been provided from API, instantiate it using `attr_type`",
"if",
"attr_value",
"!=",
"attr_default",
":",
"attr_value",
"=",
"instantiate",
"(",
"attr_value",
",",
"attr_type",
")",
"# rename the 'from' variable, reserved word",
"if",
"attr_name",
"==",
"'from'",
":",
"attr_name",
"=",
"'froom'",
"# and finally set the attribute value on the instance",
"setattr",
"(",
"instance",
",",
"attr_name",
",",
"attr_value",
")",
"return",
"instance"
] | Parses a payload from the API, guided by `_api_attrs` | [
"Parses",
"a",
"payload",
"from",
"the",
"API",
"guided",
"by",
"_api_attrs"
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/base.py#L21-L76 | train |
wrboyce/telegrambot | telegrambot/api/base.py | APIObject.api_method | def api_method(self):
""" Returns the api method to `send` the current API Object type """
if not self._api_method:
raise NotImplementedError()
return getattr(self.api, self._api_method) | python | def api_method(self):
""" Returns the api method to `send` the current API Object type """
if not self._api_method:
raise NotImplementedError()
return getattr(self.api, self._api_method) | [
"def",
"api_method",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_api_method",
":",
"raise",
"NotImplementedError",
"(",
")",
"return",
"getattr",
"(",
"self",
".",
"api",
",",
"self",
".",
"_api_method",
")"
] | Returns the api method to `send` the current API Object type | [
"Returns",
"the",
"api",
"method",
"to",
"send",
"the",
"current",
"API",
"Object",
"type"
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/base.py#L78-L82 | train |
wrboyce/telegrambot | telegrambot/api/base.py | APIObject.api_payload | def api_payload(self):
""" Generates a payload ready for submission to the API, guided by `_api_payload` """
if not self._api_payload:
raise NotImplementedError()
payload = {}
for attr_name in self._api_payload:
value = getattr(self, attr_name, None)
if value is not None:
payload[attr_name] = value
return payload | python | def api_payload(self):
""" Generates a payload ready for submission to the API, guided by `_api_payload` """
if not self._api_payload:
raise NotImplementedError()
payload = {}
for attr_name in self._api_payload:
value = getattr(self, attr_name, None)
if value is not None:
payload[attr_name] = value
return payload | [
"def",
"api_payload",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_api_payload",
":",
"raise",
"NotImplementedError",
"(",
")",
"payload",
"=",
"{",
"}",
"for",
"attr_name",
"in",
"self",
".",
"_api_payload",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"attr_name",
",",
"None",
")",
"if",
"value",
"is",
"not",
"None",
":",
"payload",
"[",
"attr_name",
"]",
"=",
"value",
"return",
"payload"
] | Generates a payload ready for submission to the API, guided by `_api_payload` | [
"Generates",
"a",
"payload",
"ready",
"for",
"submission",
"to",
"the",
"API",
"guided",
"by",
"_api_payload"
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/base.py#L84-L93 | train |
wrboyce/telegrambot | telegrambot/api/base.py | APIObject.send | def send(self, **kwargs):
""" Combines api_payload and api_method to submit the current object to the API """
payload = self.api_payload()
payload.update(**kwargs)
return self.api_method()(**payload) | python | def send(self, **kwargs):
""" Combines api_payload and api_method to submit the current object to the API """
payload = self.api_payload()
payload.update(**kwargs)
return self.api_method()(**payload) | [
"def",
"send",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"self",
".",
"api_payload",
"(",
")",
"payload",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"api_method",
"(",
")",
"(",
"*",
"*",
"payload",
")"
] | Combines api_payload and api_method to submit the current object to the API | [
"Combines",
"api_payload",
"and",
"api_method",
"to",
"submit",
"the",
"current",
"object",
"to",
"the",
"API"
] | c35ce19886df4c306a2a19851cc1f63e3066d70d | https://github.com/wrboyce/telegrambot/blob/c35ce19886df4c306a2a19851cc1f63e3066d70d/telegrambot/api/base.py#L95-L99 | train |
johnnoone/aioconsul | aioconsul/common/addr.py | parse_addr | def parse_addr(addr, *, proto=None, host=None):
"""Parses an address
Returns:
Address: the parsed address
"""
port = None
if isinstance(addr, Address):
return addr
elif isinstance(addr, str):
if addr.startswith('http://'):
proto, addr = 'http', addr[7:]
if addr.startswith('udp://'):
proto, addr = 'udp', addr[6:]
elif addr.startswith('tcp://'):
proto, addr = 'tcp', addr[6:]
elif addr.startswith('unix://'):
proto, addr = 'unix', addr[7:]
a, _, b = addr.partition(':')
host = a or host
port = b or port
elif isinstance(addr, (tuple, list)):
# list is not good
a, b = addr
host = a or host
port = b or port
elif isinstance(addr, int):
port = addr
else:
raise ValueError('bad value')
if port is not None:
port = int(port)
return Address(proto, host, port) | python | def parse_addr(addr, *, proto=None, host=None):
"""Parses an address
Returns:
Address: the parsed address
"""
port = None
if isinstance(addr, Address):
return addr
elif isinstance(addr, str):
if addr.startswith('http://'):
proto, addr = 'http', addr[7:]
if addr.startswith('udp://'):
proto, addr = 'udp', addr[6:]
elif addr.startswith('tcp://'):
proto, addr = 'tcp', addr[6:]
elif addr.startswith('unix://'):
proto, addr = 'unix', addr[7:]
a, _, b = addr.partition(':')
host = a or host
port = b or port
elif isinstance(addr, (tuple, list)):
# list is not good
a, b = addr
host = a or host
port = b or port
elif isinstance(addr, int):
port = addr
else:
raise ValueError('bad value')
if port is not None:
port = int(port)
return Address(proto, host, port) | [
"def",
"parse_addr",
"(",
"addr",
",",
"*",
",",
"proto",
"=",
"None",
",",
"host",
"=",
"None",
")",
":",
"port",
"=",
"None",
"if",
"isinstance",
"(",
"addr",
",",
"Address",
")",
":",
"return",
"addr",
"elif",
"isinstance",
"(",
"addr",
",",
"str",
")",
":",
"if",
"addr",
".",
"startswith",
"(",
"'http://'",
")",
":",
"proto",
",",
"addr",
"=",
"'http'",
",",
"addr",
"[",
"7",
":",
"]",
"if",
"addr",
".",
"startswith",
"(",
"'udp://'",
")",
":",
"proto",
",",
"addr",
"=",
"'udp'",
",",
"addr",
"[",
"6",
":",
"]",
"elif",
"addr",
".",
"startswith",
"(",
"'tcp://'",
")",
":",
"proto",
",",
"addr",
"=",
"'tcp'",
",",
"addr",
"[",
"6",
":",
"]",
"elif",
"addr",
".",
"startswith",
"(",
"'unix://'",
")",
":",
"proto",
",",
"addr",
"=",
"'unix'",
",",
"addr",
"[",
"7",
":",
"]",
"a",
",",
"_",
",",
"b",
"=",
"addr",
".",
"partition",
"(",
"':'",
")",
"host",
"=",
"a",
"or",
"host",
"port",
"=",
"b",
"or",
"port",
"elif",
"isinstance",
"(",
"addr",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"# list is not good",
"a",
",",
"b",
"=",
"addr",
"host",
"=",
"a",
"or",
"host",
"port",
"=",
"b",
"or",
"port",
"elif",
"isinstance",
"(",
"addr",
",",
"int",
")",
":",
"port",
"=",
"addr",
"else",
":",
"raise",
"ValueError",
"(",
"'bad value'",
")",
"if",
"port",
"is",
"not",
"None",
":",
"port",
"=",
"int",
"(",
"port",
")",
"return",
"Address",
"(",
"proto",
",",
"host",
",",
"port",
")"
] | Parses an address
Returns:
Address: the parsed address | [
"Parses",
"an",
"address"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/common/addr.py#L12-L46 | train |
bitesofcode/projexui | projexui/widgets/xquerybuilderwidget/xquerylinewidget.py | XQueryLineWidget.applyRule | def applyRule( self ):
"""
Applies the rule from the builder system to this line edit.
"""
widget = self.queryBuilderWidget()
if ( not widget ):
return
rule = widget.findRule(self.uiTermDDL.currentText())
self.setCurrentRule(rule) | python | def applyRule( self ):
"""
Applies the rule from the builder system to this line edit.
"""
widget = self.queryBuilderWidget()
if ( not widget ):
return
rule = widget.findRule(self.uiTermDDL.currentText())
self.setCurrentRule(rule) | [
"def",
"applyRule",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"queryBuilderWidget",
"(",
")",
"if",
"(",
"not",
"widget",
")",
":",
"return",
"rule",
"=",
"widget",
".",
"findRule",
"(",
"self",
".",
"uiTermDDL",
".",
"currentText",
"(",
")",
")",
"self",
".",
"setCurrentRule",
"(",
"rule",
")"
] | Applies the rule from the builder system to this line edit. | [
"Applies",
"the",
"rule",
"from",
"the",
"builder",
"system",
"to",
"this",
"line",
"edit",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xquerybuilderwidget/xquerylinewidget.py#L53-L62 | train |
bitesofcode/projexui | projexui/widgets/xquerybuilderwidget/xquerylinewidget.py | XQueryLineWidget.updateEditor | def updateEditor( self ):
"""
Updates the editor based on the current selection.
"""
# assignt the rule operators to the choice list
rule = self.currentRule()
operator = self.currentOperator()
widget = self.uiWidgetAREA.widget()
editorType = None
text = ''
if ( rule ):
editorType = rule.editorType(operator)
# no change in types
if ( widget and editorType and type(widget) == editorType ):
return
elif ( widget ):
if ( type(widget) != QWidget ):
text = widget.text()
widget.setParent(None)
widget.deleteLater()
self.uiWidgetAREA.setWidget(None)
# create the new editor
if ( editorType ):
widget = editorType(self)
if ( isinstance(widget, QLineEdit) ):
terms = rule.completionTerms()
if ( not terms ):
qwidget = self.queryBuilderWidget()
if ( qwidget ):
terms = qwidget.completionTerms()
if ( terms ):
widget.setCompleter(XQueryCompleter(terms, widget))
self.uiWidgetAREA.setWidget(widget)
if ( type(widget) != QWidget ):
widget.setText(text) | python | def updateEditor( self ):
"""
Updates the editor based on the current selection.
"""
# assignt the rule operators to the choice list
rule = self.currentRule()
operator = self.currentOperator()
widget = self.uiWidgetAREA.widget()
editorType = None
text = ''
if ( rule ):
editorType = rule.editorType(operator)
# no change in types
if ( widget and editorType and type(widget) == editorType ):
return
elif ( widget ):
if ( type(widget) != QWidget ):
text = widget.text()
widget.setParent(None)
widget.deleteLater()
self.uiWidgetAREA.setWidget(None)
# create the new editor
if ( editorType ):
widget = editorType(self)
if ( isinstance(widget, QLineEdit) ):
terms = rule.completionTerms()
if ( not terms ):
qwidget = self.queryBuilderWidget()
if ( qwidget ):
terms = qwidget.completionTerms()
if ( terms ):
widget.setCompleter(XQueryCompleter(terms, widget))
self.uiWidgetAREA.setWidget(widget)
if ( type(widget) != QWidget ):
widget.setText(text) | [
"def",
"updateEditor",
"(",
"self",
")",
":",
"# assignt the rule operators to the choice list",
"rule",
"=",
"self",
".",
"currentRule",
"(",
")",
"operator",
"=",
"self",
".",
"currentOperator",
"(",
")",
"widget",
"=",
"self",
".",
"uiWidgetAREA",
".",
"widget",
"(",
")",
"editorType",
"=",
"None",
"text",
"=",
"''",
"if",
"(",
"rule",
")",
":",
"editorType",
"=",
"rule",
".",
"editorType",
"(",
"operator",
")",
"# no change in types",
"if",
"(",
"widget",
"and",
"editorType",
"and",
"type",
"(",
"widget",
")",
"==",
"editorType",
")",
":",
"return",
"elif",
"(",
"widget",
")",
":",
"if",
"(",
"type",
"(",
"widget",
")",
"!=",
"QWidget",
")",
":",
"text",
"=",
"widget",
".",
"text",
"(",
")",
"widget",
".",
"setParent",
"(",
"None",
")",
"widget",
".",
"deleteLater",
"(",
")",
"self",
".",
"uiWidgetAREA",
".",
"setWidget",
"(",
"None",
")",
"# create the new editor",
"if",
"(",
"editorType",
")",
":",
"widget",
"=",
"editorType",
"(",
"self",
")",
"if",
"(",
"isinstance",
"(",
"widget",
",",
"QLineEdit",
")",
")",
":",
"terms",
"=",
"rule",
".",
"completionTerms",
"(",
")",
"if",
"(",
"not",
"terms",
")",
":",
"qwidget",
"=",
"self",
".",
"queryBuilderWidget",
"(",
")",
"if",
"(",
"qwidget",
")",
":",
"terms",
"=",
"qwidget",
".",
"completionTerms",
"(",
")",
"if",
"(",
"terms",
")",
":",
"widget",
".",
"setCompleter",
"(",
"XQueryCompleter",
"(",
"terms",
",",
"widget",
")",
")",
"self",
".",
"uiWidgetAREA",
".",
"setWidget",
"(",
"widget",
")",
"if",
"(",
"type",
"(",
"widget",
")",
"!=",
"QWidget",
")",
":",
"widget",
".",
"setText",
"(",
"text",
")"
] | Updates the editor based on the current selection. | [
"Updates",
"the",
"editor",
"based",
"on",
"the",
"current",
"selection",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xquerybuilderwidget/xquerylinewidget.py#L278-L323 | train |
bitesofcode/projexui | projexui/widgets/xorbschemabox.py | XOrbSchemaBox.emitCurrentChanged | def emitCurrentChanged( self ):
"""
Emits the current schema changed signal for this combobox, provided \
the signals aren't blocked.
"""
if ( not self.signalsBlocked() ):
schema = self.currentSchema()
self.currentSchemaChanged.emit(schema)
if ( schema ):
self.currentTableChanged.emit(schema.model())
else:
self.currentTableChanged.emit(None) | python | def emitCurrentChanged( self ):
"""
Emits the current schema changed signal for this combobox, provided \
the signals aren't blocked.
"""
if ( not self.signalsBlocked() ):
schema = self.currentSchema()
self.currentSchemaChanged.emit(schema)
if ( schema ):
self.currentTableChanged.emit(schema.model())
else:
self.currentTableChanged.emit(None) | [
"def",
"emitCurrentChanged",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
")",
":",
"schema",
"=",
"self",
".",
"currentSchema",
"(",
")",
"self",
".",
"currentSchemaChanged",
".",
"emit",
"(",
"schema",
")",
"if",
"(",
"schema",
")",
":",
"self",
".",
"currentTableChanged",
".",
"emit",
"(",
"schema",
".",
"model",
"(",
")",
")",
"else",
":",
"self",
".",
"currentTableChanged",
".",
"emit",
"(",
"None",
")"
] | Emits the current schema changed signal for this combobox, provided \
the signals aren't blocked. | [
"Emits",
"the",
"current",
"schema",
"changed",
"signal",
"for",
"this",
"combobox",
"provided",
"\\",
"the",
"signals",
"aren",
"t",
"blocked",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbschemabox.py#L59-L70 | train |
bitesofcode/projexui | projexui/configs/xshortcutconfig/xshortcutwidget.py | XShortcutWidget.save | def save( self ):
"""
Saves the current settings for the actions in the list and exits the
widget.
"""
if ( not self.updateShortcut() ):
return False
for i in range(self.uiActionTREE.topLevelItemCount()):
item = self.uiActionTREE.topLevelItem(i)
action = item.action()
action.setShortcut( QKeySequence(item.text(1)) )
return True | python | def save( self ):
"""
Saves the current settings for the actions in the list and exits the
widget.
"""
if ( not self.updateShortcut() ):
return False
for i in range(self.uiActionTREE.topLevelItemCount()):
item = self.uiActionTREE.topLevelItem(i)
action = item.action()
action.setShortcut( QKeySequence(item.text(1)) )
return True | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"updateShortcut",
"(",
")",
")",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"uiActionTREE",
".",
"topLevelItemCount",
"(",
")",
")",
":",
"item",
"=",
"self",
".",
"uiActionTREE",
".",
"topLevelItem",
"(",
"i",
")",
"action",
"=",
"item",
".",
"action",
"(",
")",
"action",
".",
"setShortcut",
"(",
"QKeySequence",
"(",
"item",
".",
"text",
"(",
"1",
")",
")",
")",
"return",
"True"
] | Saves the current settings for the actions in the list and exits the
widget. | [
"Saves",
"the",
"current",
"settings",
"for",
"the",
"actions",
"in",
"the",
"list",
"and",
"exits",
"the",
"widget",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/configs/xshortcutconfig/xshortcutwidget.py#L119-L132 | train |
bitesofcode/projexui | projexui/widgets/xpopupbutton.py | XPopupButton.showPopup | def showPopup(self):
"""
Shows the popup for this button.
"""
as_dialog = QApplication.keyboardModifiers()
anchor = self.defaultAnchor()
if anchor:
self.popupWidget().setAnchor(anchor)
else:
anchor = self.popupWidget().anchor()
if ( anchor & (XPopupWidget.Anchor.BottomLeft |
XPopupWidget.Anchor.BottomCenter |
XPopupWidget.Anchor.BottomRight) ):
pos = QPoint(self.width() / 2, 0)
else:
pos = QPoint(self.width() / 2, self.height())
pos = self.mapToGlobal(pos)
if not self.signalsBlocked():
self.popupAboutToShow.emit()
self._popupWidget.popup(pos)
if as_dialog:
self._popupWidget.setCurrentMode(XPopupWidget.Mode.Dialog) | python | def showPopup(self):
"""
Shows the popup for this button.
"""
as_dialog = QApplication.keyboardModifiers()
anchor = self.defaultAnchor()
if anchor:
self.popupWidget().setAnchor(anchor)
else:
anchor = self.popupWidget().anchor()
if ( anchor & (XPopupWidget.Anchor.BottomLeft |
XPopupWidget.Anchor.BottomCenter |
XPopupWidget.Anchor.BottomRight) ):
pos = QPoint(self.width() / 2, 0)
else:
pos = QPoint(self.width() / 2, self.height())
pos = self.mapToGlobal(pos)
if not self.signalsBlocked():
self.popupAboutToShow.emit()
self._popupWidget.popup(pos)
if as_dialog:
self._popupWidget.setCurrentMode(XPopupWidget.Mode.Dialog) | [
"def",
"showPopup",
"(",
"self",
")",
":",
"as_dialog",
"=",
"QApplication",
".",
"keyboardModifiers",
"(",
")",
"anchor",
"=",
"self",
".",
"defaultAnchor",
"(",
")",
"if",
"anchor",
":",
"self",
".",
"popupWidget",
"(",
")",
".",
"setAnchor",
"(",
"anchor",
")",
"else",
":",
"anchor",
"=",
"self",
".",
"popupWidget",
"(",
")",
".",
"anchor",
"(",
")",
"if",
"(",
"anchor",
"&",
"(",
"XPopupWidget",
".",
"Anchor",
".",
"BottomLeft",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"BottomCenter",
"|",
"XPopupWidget",
".",
"Anchor",
".",
"BottomRight",
")",
")",
":",
"pos",
"=",
"QPoint",
"(",
"self",
".",
"width",
"(",
")",
"/",
"2",
",",
"0",
")",
"else",
":",
"pos",
"=",
"QPoint",
"(",
"self",
".",
"width",
"(",
")",
"/",
"2",
",",
"self",
".",
"height",
"(",
")",
")",
"pos",
"=",
"self",
".",
"mapToGlobal",
"(",
"pos",
")",
"if",
"not",
"self",
".",
"signalsBlocked",
"(",
")",
":",
"self",
".",
"popupAboutToShow",
".",
"emit",
"(",
")",
"self",
".",
"_popupWidget",
".",
"popup",
"(",
"pos",
")",
"if",
"as_dialog",
":",
"self",
".",
"_popupWidget",
".",
"setCurrentMode",
"(",
"XPopupWidget",
".",
"Mode",
".",
"Dialog",
")"
] | Shows the popup for this button. | [
"Shows",
"the",
"popup",
"for",
"this",
"button",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupbutton.py#L128-L154 | train |
bitesofcode/projexui | projexui/widgets/xpopupbutton.py | XPopupButton.togglePopup | def togglePopup(self):
"""
Toggles whether or not the popup is visible.
"""
if not self._popupWidget.isVisible():
self.showPopup()
elif self._popupWidget.currentMode() != self._popupWidget.Mode.Dialog:
self._popupWidget.close() | python | def togglePopup(self):
"""
Toggles whether or not the popup is visible.
"""
if not self._popupWidget.isVisible():
self.showPopup()
elif self._popupWidget.currentMode() != self._popupWidget.Mode.Dialog:
self._popupWidget.close() | [
"def",
"togglePopup",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_popupWidget",
".",
"isVisible",
"(",
")",
":",
"self",
".",
"showPopup",
"(",
")",
"elif",
"self",
".",
"_popupWidget",
".",
"currentMode",
"(",
")",
"!=",
"self",
".",
"_popupWidget",
".",
"Mode",
".",
"Dialog",
":",
"self",
".",
"_popupWidget",
".",
"close",
"(",
")"
] | Toggles whether or not the popup is visible. | [
"Toggles",
"whether",
"or",
"not",
"the",
"popup",
"is",
"visible",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupbutton.py#L156-L163 | train |
neithere/eav-django | eav/facets.py | Facet.form_field | def form_field(self):
"Returns appropriate form field."
label = unicode(self)
defaults = dict(required=False, label=label, widget=self.widget)
defaults.update(self.extra)
return self.field_class(**defaults) | python | def form_field(self):
"Returns appropriate form field."
label = unicode(self)
defaults = dict(required=False, label=label, widget=self.widget)
defaults.update(self.extra)
return self.field_class(**defaults) | [
"def",
"form_field",
"(",
"self",
")",
":",
"label",
"=",
"unicode",
"(",
"self",
")",
"defaults",
"=",
"dict",
"(",
"required",
"=",
"False",
",",
"label",
"=",
"label",
",",
"widget",
"=",
"self",
".",
"widget",
")",
"defaults",
".",
"update",
"(",
"self",
".",
"extra",
")",
"return",
"self",
".",
"field_class",
"(",
"*",
"*",
"defaults",
")"
] | Returns appropriate form field. | [
"Returns",
"appropriate",
"form",
"field",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/facets.py#L69-L74 | train |
neithere/eav-django | eav/facets.py | Facet.attr_name | def attr_name(self):
"Returns attribute name for this facet"
return self.schema.name if self.schema else self.field.name | python | def attr_name(self):
"Returns attribute name for this facet"
return self.schema.name if self.schema else self.field.name | [
"def",
"attr_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"schema",
".",
"name",
"if",
"self",
".",
"schema",
"else",
"self",
".",
"field",
".",
"name"
] | Returns attribute name for this facet | [
"Returns",
"attribute",
"name",
"for",
"this",
"facet"
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/facets.py#L77-L79 | train |
neithere/eav-django | eav/facets.py | BaseFacetSet.get_field_and_lookup | def get_field_and_lookup(self, name):
"""
Returns field instance and lookup prefix for given attribute name.
Can be overloaded in subclasses to provide filtering across multiple models.
"""
name = self.get_queryset().model._meta.get_field(name)
lookup_prefix = ''
return name, lookup_prefix | python | def get_field_and_lookup(self, name):
"""
Returns field instance and lookup prefix for given attribute name.
Can be overloaded in subclasses to provide filtering across multiple models.
"""
name = self.get_queryset().model._meta.get_field(name)
lookup_prefix = ''
return name, lookup_prefix | [
"def",
"get_field_and_lookup",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"get_queryset",
"(",
")",
".",
"model",
".",
"_meta",
".",
"get_field",
"(",
"name",
")",
"lookup_prefix",
"=",
"''",
"return",
"name",
",",
"lookup_prefix"
] | Returns field instance and lookup prefix for given attribute name.
Can be overloaded in subclasses to provide filtering across multiple models. | [
"Returns",
"field",
"instance",
"and",
"lookup",
"prefix",
"for",
"given",
"attribute",
"name",
".",
"Can",
"be",
"overloaded",
"in",
"subclasses",
"to",
"provide",
"filtering",
"across",
"multiple",
"models",
"."
] | 7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/facets.py#L304-L311 | train |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/stream_collector_proxy.py | _StreamCollectorProxy.StreamMetrics | def StreamMetrics(self, request_iterator, context):
"""Dispatches metrics streamed by collector"""
LOG.debug("StreamMetrics called")
# set up arguments
collect_args = (next(request_iterator))
max_metrics_buffer = 0
max_collect_duration = 0
cfg = Metric(pb=collect_args.Metrics_Arg.metrics[0])
try:
max_metrics_buffer = int(cfg.config["max-metrics-buffer"])
except Exception as ex:
LOG.debug("Unable to get schedule parameters: {}".format(ex))
try:
max_collect_duration = int(cfg.config["max-collect-duration"])
except Exception as ex:
LOG.debug("Unable to get schedule parameters: {}".format(ex))
if max_metrics_buffer > 0:
self.max_metrics_buffer = max_metrics_buffer
if max_collect_duration > 0:
self.max_collect_duration = max_collect_duration
# start collection thread
thread = threading.Thread(target=self._stream_wrapper, args=(collect_args,),)
thread.daemon = True
thread.start()
# stream metrics
metrics = []
metrics_to_stream = []
stream_timeout = self.max_collect_duration
while context.is_active():
try:
# wait for metrics until timeout is reached
t_start = time.time()
metrics = self.metrics_queue.get(block=True, timeout=stream_timeout)
elapsed = round(time.time() - t_start)
stream_timeout -= elapsed
except queue.Empty:
LOG.debug("Max collect duration exceeded. Streaming {} metrics".format(len(metrics_to_stream)))
metrics_col = CollectReply(Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
metrics_to_stream = []
stream_timeout = self.max_collect_duration
yield metrics_col
else:
for metric in metrics:
metrics_to_stream.append(metric)
if len(metrics_to_stream) == self.max_metrics_buffer:
LOG.debug("Max metrics buffer reached. Streaming {} metrics".format(len(metrics_to_stream)))
metrics_col = CollectReply(
Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
metrics_to_stream = []
stream_timeout = self.max_collect_duration
yield metrics_col
# stream metrics if max_metrics_buffer is 0 or enough metrics has been collected
if self.max_metrics_buffer == 0:
LOG.debug("Max metrics buffer set to 0. Streaming {} metrics".format(len(metrics_to_stream)))
metrics_col = CollectReply(Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
metrics_to_stream = []
stream_timeout = self.max_collect_duration
yield metrics_col
# sent notification if stream has been stopped
self.done_queue.put(True) | python | def StreamMetrics(self, request_iterator, context):
"""Dispatches metrics streamed by collector"""
LOG.debug("StreamMetrics called")
# set up arguments
collect_args = (next(request_iterator))
max_metrics_buffer = 0
max_collect_duration = 0
cfg = Metric(pb=collect_args.Metrics_Arg.metrics[0])
try:
max_metrics_buffer = int(cfg.config["max-metrics-buffer"])
except Exception as ex:
LOG.debug("Unable to get schedule parameters: {}".format(ex))
try:
max_collect_duration = int(cfg.config["max-collect-duration"])
except Exception as ex:
LOG.debug("Unable to get schedule parameters: {}".format(ex))
if max_metrics_buffer > 0:
self.max_metrics_buffer = max_metrics_buffer
if max_collect_duration > 0:
self.max_collect_duration = max_collect_duration
# start collection thread
thread = threading.Thread(target=self._stream_wrapper, args=(collect_args,),)
thread.daemon = True
thread.start()
# stream metrics
metrics = []
metrics_to_stream = []
stream_timeout = self.max_collect_duration
while context.is_active():
try:
# wait for metrics until timeout is reached
t_start = time.time()
metrics = self.metrics_queue.get(block=True, timeout=stream_timeout)
elapsed = round(time.time() - t_start)
stream_timeout -= elapsed
except queue.Empty:
LOG.debug("Max collect duration exceeded. Streaming {} metrics".format(len(metrics_to_stream)))
metrics_col = CollectReply(Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
metrics_to_stream = []
stream_timeout = self.max_collect_duration
yield metrics_col
else:
for metric in metrics:
metrics_to_stream.append(metric)
if len(metrics_to_stream) == self.max_metrics_buffer:
LOG.debug("Max metrics buffer reached. Streaming {} metrics".format(len(metrics_to_stream)))
metrics_col = CollectReply(
Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
metrics_to_stream = []
stream_timeout = self.max_collect_duration
yield metrics_col
# stream metrics if max_metrics_buffer is 0 or enough metrics has been collected
if self.max_metrics_buffer == 0:
LOG.debug("Max metrics buffer set to 0. Streaming {} metrics".format(len(metrics_to_stream)))
metrics_col = CollectReply(Metrics_Reply=MetricsReply(metrics=[m.pb for m in metrics_to_stream]))
metrics_to_stream = []
stream_timeout = self.max_collect_duration
yield metrics_col
# sent notification if stream has been stopped
self.done_queue.put(True) | [
"def",
"StreamMetrics",
"(",
"self",
",",
"request_iterator",
",",
"context",
")",
":",
"LOG",
".",
"debug",
"(",
"\"StreamMetrics called\"",
")",
"# set up arguments",
"collect_args",
"=",
"(",
"next",
"(",
"request_iterator",
")",
")",
"max_metrics_buffer",
"=",
"0",
"max_collect_duration",
"=",
"0",
"cfg",
"=",
"Metric",
"(",
"pb",
"=",
"collect_args",
".",
"Metrics_Arg",
".",
"metrics",
"[",
"0",
"]",
")",
"try",
":",
"max_metrics_buffer",
"=",
"int",
"(",
"cfg",
".",
"config",
"[",
"\"max-metrics-buffer\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"LOG",
".",
"debug",
"(",
"\"Unable to get schedule parameters: {}\"",
".",
"format",
"(",
"ex",
")",
")",
"try",
":",
"max_collect_duration",
"=",
"int",
"(",
"cfg",
".",
"config",
"[",
"\"max-collect-duration\"",
"]",
")",
"except",
"Exception",
"as",
"ex",
":",
"LOG",
".",
"debug",
"(",
"\"Unable to get schedule parameters: {}\"",
".",
"format",
"(",
"ex",
")",
")",
"if",
"max_metrics_buffer",
">",
"0",
":",
"self",
".",
"max_metrics_buffer",
"=",
"max_metrics_buffer",
"if",
"max_collect_duration",
">",
"0",
":",
"self",
".",
"max_collect_duration",
"=",
"max_collect_duration",
"# start collection thread",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_stream_wrapper",
",",
"args",
"=",
"(",
"collect_args",
",",
")",
",",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")",
"# stream metrics",
"metrics",
"=",
"[",
"]",
"metrics_to_stream",
"=",
"[",
"]",
"stream_timeout",
"=",
"self",
".",
"max_collect_duration",
"while",
"context",
".",
"is_active",
"(",
")",
":",
"try",
":",
"# wait for metrics until timeout is reached",
"t_start",
"=",
"time",
".",
"time",
"(",
")",
"metrics",
"=",
"self",
".",
"metrics_queue",
".",
"get",
"(",
"block",
"=",
"True",
",",
"timeout",
"=",
"stream_timeout",
")",
"elapsed",
"=",
"round",
"(",
"time",
".",
"time",
"(",
")",
"-",
"t_start",
")",
"stream_timeout",
"-=",
"elapsed",
"except",
"queue",
".",
"Empty",
":",
"LOG",
".",
"debug",
"(",
"\"Max collect duration exceeded. Streaming {} metrics\"",
".",
"format",
"(",
"len",
"(",
"metrics_to_stream",
")",
")",
")",
"metrics_col",
"=",
"CollectReply",
"(",
"Metrics_Reply",
"=",
"MetricsReply",
"(",
"metrics",
"=",
"[",
"m",
".",
"pb",
"for",
"m",
"in",
"metrics_to_stream",
"]",
")",
")",
"metrics_to_stream",
"=",
"[",
"]",
"stream_timeout",
"=",
"self",
".",
"max_collect_duration",
"yield",
"metrics_col",
"else",
":",
"for",
"metric",
"in",
"metrics",
":",
"metrics_to_stream",
".",
"append",
"(",
"metric",
")",
"if",
"len",
"(",
"metrics_to_stream",
")",
"==",
"self",
".",
"max_metrics_buffer",
":",
"LOG",
".",
"debug",
"(",
"\"Max metrics buffer reached. Streaming {} metrics\"",
".",
"format",
"(",
"len",
"(",
"metrics_to_stream",
")",
")",
")",
"metrics_col",
"=",
"CollectReply",
"(",
"Metrics_Reply",
"=",
"MetricsReply",
"(",
"metrics",
"=",
"[",
"m",
".",
"pb",
"for",
"m",
"in",
"metrics_to_stream",
"]",
")",
")",
"metrics_to_stream",
"=",
"[",
"]",
"stream_timeout",
"=",
"self",
".",
"max_collect_duration",
"yield",
"metrics_col",
"# stream metrics if max_metrics_buffer is 0 or enough metrics has been collected",
"if",
"self",
".",
"max_metrics_buffer",
"==",
"0",
":",
"LOG",
".",
"debug",
"(",
"\"Max metrics buffer set to 0. Streaming {} metrics\"",
".",
"format",
"(",
"len",
"(",
"metrics_to_stream",
")",
")",
")",
"metrics_col",
"=",
"CollectReply",
"(",
"Metrics_Reply",
"=",
"MetricsReply",
"(",
"metrics",
"=",
"[",
"m",
".",
"pb",
"for",
"m",
"in",
"metrics_to_stream",
"]",
")",
")",
"metrics_to_stream",
"=",
"[",
"]",
"stream_timeout",
"=",
"self",
".",
"max_collect_duration",
"yield",
"metrics_col",
"# sent notification if stream has been stopped",
"self",
".",
"done_queue",
".",
"put",
"(",
"True",
")"
] | Dispatches metrics streamed by collector | [
"Dispatches",
"metrics",
"streamed",
"by",
"collector"
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/stream_collector_proxy.py#L57-L120 | train |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/stream_collector_proxy.py | _StreamCollectorProxy.GetMetricTypes | def GetMetricTypes(self, request, context):
"""Dispatches the request to the plugins update_catalog method"""
LOG.debug("GetMetricTypes called")
try:
metrics = self.plugin.update_catalog(ConfigMap(pb=request.config))
return MetricsReply(metrics=[m.pb for m in metrics])
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err, traceback.format_exc())
return MetricsReply(metrics=[], error=msg) | python | def GetMetricTypes(self, request, context):
"""Dispatches the request to the plugins update_catalog method"""
LOG.debug("GetMetricTypes called")
try:
metrics = self.plugin.update_catalog(ConfigMap(pb=request.config))
return MetricsReply(metrics=[m.pb for m in metrics])
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err, traceback.format_exc())
return MetricsReply(metrics=[], error=msg) | [
"def",
"GetMetricTypes",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"LOG",
".",
"debug",
"(",
"\"GetMetricTypes called\"",
")",
"try",
":",
"metrics",
"=",
"self",
".",
"plugin",
".",
"update_catalog",
"(",
"ConfigMap",
"(",
"pb",
"=",
"request",
".",
"config",
")",
")",
"return",
"MetricsReply",
"(",
"metrics",
"=",
"[",
"m",
".",
"pb",
"for",
"m",
"in",
"metrics",
"]",
")",
"except",
"Exception",
"as",
"err",
":",
"msg",
"=",
"\"message: {}\\n\\nstack trace: {}\"",
".",
"format",
"(",
"err",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"MetricsReply",
"(",
"metrics",
"=",
"[",
"]",
",",
"error",
"=",
"msg",
")"
] | Dispatches the request to the plugins update_catalog method | [
"Dispatches",
"the",
"request",
"to",
"the",
"plugins",
"update_catalog",
"method"
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/stream_collector_proxy.py#L122-L131 | train |
davidemoro/play_mqtt | play_mqtt/providers.py | MQTTProvider.command_publish | def command_publish(self, command, **kwargs):
""" Publish a MQTT message """
mqttc = mqtt.Client()
mqttc.connect(
command['host'],
port=int(command['port']))
mqttc.loop_start()
try:
mqttc.publish(
command['endpoint'],
command['payload'])
finally:
mqttc.loop_stop(force=False) | python | def command_publish(self, command, **kwargs):
""" Publish a MQTT message """
mqttc = mqtt.Client()
mqttc.connect(
command['host'],
port=int(command['port']))
mqttc.loop_start()
try:
mqttc.publish(
command['endpoint'],
command['payload'])
finally:
mqttc.loop_stop(force=False) | [
"def",
"command_publish",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"mqttc",
"=",
"mqtt",
".",
"Client",
"(",
")",
"mqttc",
".",
"connect",
"(",
"command",
"[",
"'host'",
"]",
",",
"port",
"=",
"int",
"(",
"command",
"[",
"'port'",
"]",
")",
")",
"mqttc",
".",
"loop_start",
"(",
")",
"try",
":",
"mqttc",
".",
"publish",
"(",
"command",
"[",
"'endpoint'",
"]",
",",
"command",
"[",
"'payload'",
"]",
")",
"finally",
":",
"mqttc",
".",
"loop_stop",
"(",
"force",
"=",
"False",
")"
] | Publish a MQTT message | [
"Publish",
"a",
"MQTT",
"message"
] | 4994074c20ab8a5abd221f8b8088e5fc44ba2a5e | https://github.com/davidemoro/play_mqtt/blob/4994074c20ab8a5abd221f8b8088e5fc44ba2a5e/play_mqtt/providers.py#L8-L22 | train |
davidemoro/play_mqtt | play_mqtt/providers.py | MQTTProvider.command_subscribe | def command_subscribe(self, command, **kwargs):
""" Subscribe to a topic or list of topics """
topic = command['topic']
encoding = command.get('encoding', 'utf-8')
name = command['name']
if not hasattr(self.engine, '_mqtt'):
self.engine._mqtt = {}
self.engine.variables[name] = []
def on_message(client, userdata, msg):
userdata.append(msg.payload.decode(encoding))
self.engine._mqtt[name] = client = mqtt.Client(
userdata=self.engine.variables[name])
client.on_message = on_message
client.connect(
command['host'],
port=int(command['port'])
)
client.subscribe(topic)
client.loop_start()
self.engine.register_teardown_callback(
client.loop_stop) | python | def command_subscribe(self, command, **kwargs):
""" Subscribe to a topic or list of topics """
topic = command['topic']
encoding = command.get('encoding', 'utf-8')
name = command['name']
if not hasattr(self.engine, '_mqtt'):
self.engine._mqtt = {}
self.engine.variables[name] = []
def on_message(client, userdata, msg):
userdata.append(msg.payload.decode(encoding))
self.engine._mqtt[name] = client = mqtt.Client(
userdata=self.engine.variables[name])
client.on_message = on_message
client.connect(
command['host'],
port=int(command['port'])
)
client.subscribe(topic)
client.loop_start()
self.engine.register_teardown_callback(
client.loop_stop) | [
"def",
"command_subscribe",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"topic",
"=",
"command",
"[",
"'topic'",
"]",
"encoding",
"=",
"command",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
"name",
"=",
"command",
"[",
"'name'",
"]",
"if",
"not",
"hasattr",
"(",
"self",
".",
"engine",
",",
"'_mqtt'",
")",
":",
"self",
".",
"engine",
".",
"_mqtt",
"=",
"{",
"}",
"self",
".",
"engine",
".",
"variables",
"[",
"name",
"]",
"=",
"[",
"]",
"def",
"on_message",
"(",
"client",
",",
"userdata",
",",
"msg",
")",
":",
"userdata",
".",
"append",
"(",
"msg",
".",
"payload",
".",
"decode",
"(",
"encoding",
")",
")",
"self",
".",
"engine",
".",
"_mqtt",
"[",
"name",
"]",
"=",
"client",
"=",
"mqtt",
".",
"Client",
"(",
"userdata",
"=",
"self",
".",
"engine",
".",
"variables",
"[",
"name",
"]",
")",
"client",
".",
"on_message",
"=",
"on_message",
"client",
".",
"connect",
"(",
"command",
"[",
"'host'",
"]",
",",
"port",
"=",
"int",
"(",
"command",
"[",
"'port'",
"]",
")",
")",
"client",
".",
"subscribe",
"(",
"topic",
")",
"client",
".",
"loop_start",
"(",
")",
"self",
".",
"engine",
".",
"register_teardown_callback",
"(",
"client",
".",
"loop_stop",
")"
] | Subscribe to a topic or list of topics | [
"Subscribe",
"to",
"a",
"topic",
"or",
"list",
"of",
"topics"
] | 4994074c20ab8a5abd221f8b8088e5fc44ba2a5e | https://github.com/davidemoro/play_mqtt/blob/4994074c20ab8a5abd221f8b8088e5fc44ba2a5e/play_mqtt/providers.py#L24-L45 | train |
Danielhiversen/pyMetno | metno/__init__.py | get_data | def get_data(param, data):
"""Retrieve weather parameter."""
try:
for (_, selected_time_entry) in data:
loc_data = selected_time_entry['location']
if param not in loc_data:
continue
if param == 'precipitation':
new_state = loc_data[param]['@value']
elif param == 'symbol':
new_state = int(float(loc_data[param]['@number']))
elif param in ('temperature', 'pressure', 'humidity',
'dewpointTemperature'):
new_state = round(float(loc_data[param]['@value']), 1)
elif param in ('windSpeed', 'windGust'):
new_state = round(float(loc_data[param]['@mps']) * 3.6, 1)
elif param == 'windDirection':
new_state = round(float(loc_data[param]['@deg']), 1)
elif param in ('fog', 'cloudiness', 'lowClouds',
'mediumClouds', 'highClouds'):
new_state = round(float(loc_data[param]['@percent']), 1)
return new_state
except (ValueError, IndexError, KeyError):
return None | python | def get_data(param, data):
"""Retrieve weather parameter."""
try:
for (_, selected_time_entry) in data:
loc_data = selected_time_entry['location']
if param not in loc_data:
continue
if param == 'precipitation':
new_state = loc_data[param]['@value']
elif param == 'symbol':
new_state = int(float(loc_data[param]['@number']))
elif param in ('temperature', 'pressure', 'humidity',
'dewpointTemperature'):
new_state = round(float(loc_data[param]['@value']), 1)
elif param in ('windSpeed', 'windGust'):
new_state = round(float(loc_data[param]['@mps']) * 3.6, 1)
elif param == 'windDirection':
new_state = round(float(loc_data[param]['@deg']), 1)
elif param in ('fog', 'cloudiness', 'lowClouds',
'mediumClouds', 'highClouds'):
new_state = round(float(loc_data[param]['@percent']), 1)
return new_state
except (ValueError, IndexError, KeyError):
return None | [
"def",
"get_data",
"(",
"param",
",",
"data",
")",
":",
"try",
":",
"for",
"(",
"_",
",",
"selected_time_entry",
")",
"in",
"data",
":",
"loc_data",
"=",
"selected_time_entry",
"[",
"'location'",
"]",
"if",
"param",
"not",
"in",
"loc_data",
":",
"continue",
"if",
"param",
"==",
"'precipitation'",
":",
"new_state",
"=",
"loc_data",
"[",
"param",
"]",
"[",
"'@value'",
"]",
"elif",
"param",
"==",
"'symbol'",
":",
"new_state",
"=",
"int",
"(",
"float",
"(",
"loc_data",
"[",
"param",
"]",
"[",
"'@number'",
"]",
")",
")",
"elif",
"param",
"in",
"(",
"'temperature'",
",",
"'pressure'",
",",
"'humidity'",
",",
"'dewpointTemperature'",
")",
":",
"new_state",
"=",
"round",
"(",
"float",
"(",
"loc_data",
"[",
"param",
"]",
"[",
"'@value'",
"]",
")",
",",
"1",
")",
"elif",
"param",
"in",
"(",
"'windSpeed'",
",",
"'windGust'",
")",
":",
"new_state",
"=",
"round",
"(",
"float",
"(",
"loc_data",
"[",
"param",
"]",
"[",
"'@mps'",
"]",
")",
"*",
"3.6",
",",
"1",
")",
"elif",
"param",
"==",
"'windDirection'",
":",
"new_state",
"=",
"round",
"(",
"float",
"(",
"loc_data",
"[",
"param",
"]",
"[",
"'@deg'",
"]",
")",
",",
"1",
")",
"elif",
"param",
"in",
"(",
"'fog'",
",",
"'cloudiness'",
",",
"'lowClouds'",
",",
"'mediumClouds'",
",",
"'highClouds'",
")",
":",
"new_state",
"=",
"round",
"(",
"float",
"(",
"loc_data",
"[",
"param",
"]",
"[",
"'@percent'",
"]",
")",
",",
"1",
")",
"return",
"new_state",
"except",
"(",
"ValueError",
",",
"IndexError",
",",
"KeyError",
")",
":",
"return",
"None"
] | Retrieve weather parameter. | [
"Retrieve",
"weather",
"parameter",
"."
] | 7d200a495fdea0e1a9310069fdcd65f205d6e6f5 | https://github.com/Danielhiversen/pyMetno/blob/7d200a495fdea0e1a9310069fdcd65f205d6e6f5/metno/__init__.py#L144-L168 | train |
Danielhiversen/pyMetno | metno/__init__.py | parse_datetime | def parse_datetime(dt_str):
"""Parse datetime."""
date_format = "%Y-%m-%dT%H:%M:%S %z"
dt_str = dt_str.replace("Z", " +0000")
return datetime.datetime.strptime(dt_str, date_format) | python | def parse_datetime(dt_str):
"""Parse datetime."""
date_format = "%Y-%m-%dT%H:%M:%S %z"
dt_str = dt_str.replace("Z", " +0000")
return datetime.datetime.strptime(dt_str, date_format) | [
"def",
"parse_datetime",
"(",
"dt_str",
")",
":",
"date_format",
"=",
"\"%Y-%m-%dT%H:%M:%S %z\"",
"dt_str",
"=",
"dt_str",
".",
"replace",
"(",
"\"Z\"",
",",
"\" +0000\"",
")",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"dt_str",
",",
"date_format",
")"
] | Parse datetime. | [
"Parse",
"datetime",
"."
] | 7d200a495fdea0e1a9310069fdcd65f205d6e6f5 | https://github.com/Danielhiversen/pyMetno/blob/7d200a495fdea0e1a9310069fdcd65f205d6e6f5/metno/__init__.py#L257-L261 | train |
Danielhiversen/pyMetno | metno/__init__.py | MetWeatherData.fetching_data | async def fetching_data(self, *_):
"""Get the latest data from met.no."""
try:
with async_timeout.timeout(10):
resp = await self._websession.get(self._api_url, params=self._urlparams)
if resp.status != 200:
_LOGGER.error('%s returned %s', self._api_url, resp.status)
return False
text = await resp.text()
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error('%s returned %s', self._api_url, err)
return False
try:
self.data = xmltodict.parse(text)['weatherdata']
except (ExpatError, IndexError) as err:
_LOGGER.error('%s returned %s', resp.url, err)
return False
return True | python | async def fetching_data(self, *_):
"""Get the latest data from met.no."""
try:
with async_timeout.timeout(10):
resp = await self._websession.get(self._api_url, params=self._urlparams)
if resp.status != 200:
_LOGGER.error('%s returned %s', self._api_url, resp.status)
return False
text = await resp.text()
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error('%s returned %s', self._api_url, err)
return False
try:
self.data = xmltodict.parse(text)['weatherdata']
except (ExpatError, IndexError) as err:
_LOGGER.error('%s returned %s', resp.url, err)
return False
return True | [
"async",
"def",
"fetching_data",
"(",
"self",
",",
"*",
"_",
")",
":",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"10",
")",
":",
"resp",
"=",
"await",
"self",
".",
"_websession",
".",
"get",
"(",
"self",
".",
"_api_url",
",",
"params",
"=",
"self",
".",
"_urlparams",
")",
"if",
"resp",
".",
"status",
"!=",
"200",
":",
"_LOGGER",
".",
"error",
"(",
"'%s returned %s'",
",",
"self",
".",
"_api_url",
",",
"resp",
".",
"status",
")",
"return",
"False",
"text",
"=",
"await",
"resp",
".",
"text",
"(",
")",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"ClientError",
")",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"'%s returned %s'",
",",
"self",
".",
"_api_url",
",",
"err",
")",
"return",
"False",
"try",
":",
"self",
".",
"data",
"=",
"xmltodict",
".",
"parse",
"(",
"text",
")",
"[",
"'weatherdata'",
"]",
"except",
"(",
"ExpatError",
",",
"IndexError",
")",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"'%s returned %s'",
",",
"resp",
".",
"url",
",",
"err",
")",
"return",
"False",
"return",
"True"
] | Get the latest data from met.no. | [
"Get",
"the",
"latest",
"data",
"from",
"met",
".",
"no",
"."
] | 7d200a495fdea0e1a9310069fdcd65f205d6e6f5 | https://github.com/Danielhiversen/pyMetno/blob/7d200a495fdea0e1a9310069fdcd65f205d6e6f5/metno/__init__.py#L75-L93 | train |
Danielhiversen/pyMetno | metno/__init__.py | MetWeatherData.get_forecast | def get_forecast(self, time_zone):
"""Get the forecast weather data from met.no."""
if self.data is None:
return []
now = datetime.datetime.now(time_zone).replace(hour=12, minute=0,
second=0, microsecond=0)
times = [now + datetime.timedelta(days=k) for k in range(1, 6)]
return [self.get_weather(_time) for _time in times] | python | def get_forecast(self, time_zone):
"""Get the forecast weather data from met.no."""
if self.data is None:
return []
now = datetime.datetime.now(time_zone).replace(hour=12, minute=0,
second=0, microsecond=0)
times = [now + datetime.timedelta(days=k) for k in range(1, 6)]
return [self.get_weather(_time) for _time in times] | [
"def",
"get_forecast",
"(",
"self",
",",
"time_zone",
")",
":",
"if",
"self",
".",
"data",
"is",
"None",
":",
"return",
"[",
"]",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"time_zone",
")",
".",
"replace",
"(",
"hour",
"=",
"12",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"times",
"=",
"[",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"k",
")",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"6",
")",
"]",
"return",
"[",
"self",
".",
"get_weather",
"(",
"_time",
")",
"for",
"_time",
"in",
"times",
"]"
] | Get the forecast weather data from met.no. | [
"Get",
"the",
"forecast",
"weather",
"data",
"from",
"met",
".",
"no",
"."
] | 7d200a495fdea0e1a9310069fdcd65f205d6e6f5 | https://github.com/Danielhiversen/pyMetno/blob/7d200a495fdea0e1a9310069fdcd65f205d6e6f5/metno/__init__.py#L99-L107 | train |
Danielhiversen/pyMetno | metno/__init__.py | MetWeatherData.get_weather | def get_weather(self, time, max_hour=6):
"""Get the current weather data from met.no."""
if self.data is None:
return {}
ordered_entries = []
for time_entry in self.data['product']['time']:
valid_from = parse_datetime(time_entry['@from'])
valid_to = parse_datetime(time_entry['@to'])
if time > valid_to:
# Has already passed. Never select this.
continue
average_dist = (abs((valid_to - time).total_seconds()) +
abs((valid_from - time).total_seconds()))
if average_dist > max_hour * 3600:
continue
ordered_entries.append((average_dist, time_entry))
if not ordered_entries:
return {}
ordered_entries.sort(key=lambda item: item[0])
res = dict()
res['datetime'] = time
res['temperature'] = get_data('temperature', ordered_entries)
res['condition'] = CONDITIONS.get(get_data('symbol', ordered_entries))
res['pressure'] = get_data('pressure', ordered_entries)
res['humidity'] = get_data('humidity', ordered_entries)
res['wind_speed'] = get_data('windSpeed', ordered_entries)
res['wind_bearing'] = get_data('windDirection', ordered_entries)
return res | python | def get_weather(self, time, max_hour=6):
"""Get the current weather data from met.no."""
if self.data is None:
return {}
ordered_entries = []
for time_entry in self.data['product']['time']:
valid_from = parse_datetime(time_entry['@from'])
valid_to = parse_datetime(time_entry['@to'])
if time > valid_to:
# Has already passed. Never select this.
continue
average_dist = (abs((valid_to - time).total_seconds()) +
abs((valid_from - time).total_seconds()))
if average_dist > max_hour * 3600:
continue
ordered_entries.append((average_dist, time_entry))
if not ordered_entries:
return {}
ordered_entries.sort(key=lambda item: item[0])
res = dict()
res['datetime'] = time
res['temperature'] = get_data('temperature', ordered_entries)
res['condition'] = CONDITIONS.get(get_data('symbol', ordered_entries))
res['pressure'] = get_data('pressure', ordered_entries)
res['humidity'] = get_data('humidity', ordered_entries)
res['wind_speed'] = get_data('windSpeed', ordered_entries)
res['wind_bearing'] = get_data('windDirection', ordered_entries)
return res | [
"def",
"get_weather",
"(",
"self",
",",
"time",
",",
"max_hour",
"=",
"6",
")",
":",
"if",
"self",
".",
"data",
"is",
"None",
":",
"return",
"{",
"}",
"ordered_entries",
"=",
"[",
"]",
"for",
"time_entry",
"in",
"self",
".",
"data",
"[",
"'product'",
"]",
"[",
"'time'",
"]",
":",
"valid_from",
"=",
"parse_datetime",
"(",
"time_entry",
"[",
"'@from'",
"]",
")",
"valid_to",
"=",
"parse_datetime",
"(",
"time_entry",
"[",
"'@to'",
"]",
")",
"if",
"time",
">",
"valid_to",
":",
"# Has already passed. Never select this.",
"continue",
"average_dist",
"=",
"(",
"abs",
"(",
"(",
"valid_to",
"-",
"time",
")",
".",
"total_seconds",
"(",
")",
")",
"+",
"abs",
"(",
"(",
"valid_from",
"-",
"time",
")",
".",
"total_seconds",
"(",
")",
")",
")",
"if",
"average_dist",
">",
"max_hour",
"*",
"3600",
":",
"continue",
"ordered_entries",
".",
"append",
"(",
"(",
"average_dist",
",",
"time_entry",
")",
")",
"if",
"not",
"ordered_entries",
":",
"return",
"{",
"}",
"ordered_entries",
".",
"sort",
"(",
"key",
"=",
"lambda",
"item",
":",
"item",
"[",
"0",
"]",
")",
"res",
"=",
"dict",
"(",
")",
"res",
"[",
"'datetime'",
"]",
"=",
"time",
"res",
"[",
"'temperature'",
"]",
"=",
"get_data",
"(",
"'temperature'",
",",
"ordered_entries",
")",
"res",
"[",
"'condition'",
"]",
"=",
"CONDITIONS",
".",
"get",
"(",
"get_data",
"(",
"'symbol'",
",",
"ordered_entries",
")",
")",
"res",
"[",
"'pressure'",
"]",
"=",
"get_data",
"(",
"'pressure'",
",",
"ordered_entries",
")",
"res",
"[",
"'humidity'",
"]",
"=",
"get_data",
"(",
"'humidity'",
",",
"ordered_entries",
")",
"res",
"[",
"'wind_speed'",
"]",
"=",
"get_data",
"(",
"'windSpeed'",
",",
"ordered_entries",
")",
"res",
"[",
"'wind_bearing'",
"]",
"=",
"get_data",
"(",
"'windDirection'",
",",
"ordered_entries",
")",
"return",
"res"
] | Get the current weather data from met.no. | [
"Get",
"the",
"current",
"weather",
"data",
"from",
"met",
".",
"no",
"."
] | 7d200a495fdea0e1a9310069fdcd65f205d6e6f5 | https://github.com/Danielhiversen/pyMetno/blob/7d200a495fdea0e1a9310069fdcd65f205d6e6f5/metno/__init__.py#L109-L141 | train |
johnnoone/aioconsul | aioconsul/client/util.py | prepare_node | def prepare_node(data):
"""Prepare node for catalog endpoint
Parameters:
data (Union[str, dict]): Node ID or node definition
Returns:
Tuple[str, dict]: where first is ID and second is node definition
Extract from /v1/health/service/<service>::
{
"Node": {
"Node": "foobar",
"Address": "10.1.10.12",
"TaggedAddresses": {
"lan": "10.1.10.12",
"wan": "10.1.10.12"
}
},
"Service": {...},
"Checks": [...]
}
"""
if not data:
return None, {}
if isinstance(data, str):
return data, {}
# from /v1/health/service/<service>
if all(field in data for field in ("Node", "Service", "Checks")):
return data["Node"]["Node"], data["Node"]
result = {}
if "ID" in data:
result["Node"] = data["ID"]
for k in ("Datacenter", "Node", "Address",
"TaggedAddresses", "Service",
"Check", "Checks"):
if k in data:
result[k] = data[k]
if list(result) == ["Node"]:
return result["Node"], {}
return result.get("Node"), result | python | def prepare_node(data):
"""Prepare node for catalog endpoint
Parameters:
data (Union[str, dict]): Node ID or node definition
Returns:
Tuple[str, dict]: where first is ID and second is node definition
Extract from /v1/health/service/<service>::
{
"Node": {
"Node": "foobar",
"Address": "10.1.10.12",
"TaggedAddresses": {
"lan": "10.1.10.12",
"wan": "10.1.10.12"
}
},
"Service": {...},
"Checks": [...]
}
"""
if not data:
return None, {}
if isinstance(data, str):
return data, {}
# from /v1/health/service/<service>
if all(field in data for field in ("Node", "Service", "Checks")):
return data["Node"]["Node"], data["Node"]
result = {}
if "ID" in data:
result["Node"] = data["ID"]
for k in ("Datacenter", "Node", "Address",
"TaggedAddresses", "Service",
"Check", "Checks"):
if k in data:
result[k] = data[k]
if list(result) == ["Node"]:
return result["Node"], {}
return result.get("Node"), result | [
"def",
"prepare_node",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
",",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"data",
",",
"{",
"}",
"# from /v1/health/service/<service>",
"if",
"all",
"(",
"field",
"in",
"data",
"for",
"field",
"in",
"(",
"\"Node\"",
",",
"\"Service\"",
",",
"\"Checks\"",
")",
")",
":",
"return",
"data",
"[",
"\"Node\"",
"]",
"[",
"\"Node\"",
"]",
",",
"data",
"[",
"\"Node\"",
"]",
"result",
"=",
"{",
"}",
"if",
"\"ID\"",
"in",
"data",
":",
"result",
"[",
"\"Node\"",
"]",
"=",
"data",
"[",
"\"ID\"",
"]",
"for",
"k",
"in",
"(",
"\"Datacenter\"",
",",
"\"Node\"",
",",
"\"Address\"",
",",
"\"TaggedAddresses\"",
",",
"\"Service\"",
",",
"\"Check\"",
",",
"\"Checks\"",
")",
":",
"if",
"k",
"in",
"data",
":",
"result",
"[",
"k",
"]",
"=",
"data",
"[",
"k",
"]",
"if",
"list",
"(",
"result",
")",
"==",
"[",
"\"Node\"",
"]",
":",
"return",
"result",
"[",
"\"Node\"",
"]",
",",
"{",
"}",
"return",
"result",
".",
"get",
"(",
"\"Node\"",
")",
",",
"result"
] | Prepare node for catalog endpoint
Parameters:
data (Union[str, dict]): Node ID or node definition
Returns:
Tuple[str, dict]: where first is ID and second is node definition
Extract from /v1/health/service/<service>::
{
"Node": {
"Node": "foobar",
"Address": "10.1.10.12",
"TaggedAddresses": {
"lan": "10.1.10.12",
"wan": "10.1.10.12"
}
},
"Service": {...},
"Checks": [...]
} | [
"Prepare",
"node",
"for",
"catalog",
"endpoint"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/util.py#L3-L46 | train |
johnnoone/aioconsul | aioconsul/client/util.py | prepare_service | def prepare_service(data):
"""Prepare service for catalog endpoint
Parameters:
data (Union[str, dict]): Service ID or service definition
Returns:
Tuple[str, dict]: str is ID and dict is service
Transform ``/v1/health/state/<state>``::
{
"Node": "foobar",
"CheckID": "service:redis",
"Name": "Service 'redis' check",
"Status": "passing",
"Notes": "",
"Output": "",
"ServiceID": "redis1",
"ServiceName": "redis"
}
to::
{
"ID": "redis1",
"Service": "redis"
}
Extract from /v1/health/service/<service>::
{
"Node": {...},
"Service": {
"ID": "redis1",
"Service": "redis",
"Tags": None,
"Address": "10.1.10.12",
"Port": 8000
},
"Checks": [...]
}
"""
if not data:
return None, {}
if isinstance(data, str):
return data, {}
# from /v1/health/service/<service>
if all(field in data for field in ("Node", "Service", "Checks")):
return data["Service"]["ID"], data["Service"]
# from /v1/health/checks/<service>
# from /v1/health/node/<node>
# from /v1/health/state/<state>
# from /v1/catalog/service/<service>
if all(field in data for field in ("ServiceName", "ServiceID")):
return data["ServiceID"], {
"ID": data["ServiceID"],
"Service": data["ServiceName"],
"Tags": data.get("ServiceTags"),
"Address": data.get("ServiceAddress"),
"Port": data.get("ServicePort"),
}
if list(data) == ["ID"]:
return data["ID"], {}
result = {}
if "Name" in data:
result["Service"] = data["Name"]
for k in ("Service", "ID", "Tags", "Address", "Port"):
if k in data:
result[k] = data[k]
return result.get("ID"), result | python | def prepare_service(data):
"""Prepare service for catalog endpoint
Parameters:
data (Union[str, dict]): Service ID or service definition
Returns:
Tuple[str, dict]: str is ID and dict is service
Transform ``/v1/health/state/<state>``::
{
"Node": "foobar",
"CheckID": "service:redis",
"Name": "Service 'redis' check",
"Status": "passing",
"Notes": "",
"Output": "",
"ServiceID": "redis1",
"ServiceName": "redis"
}
to::
{
"ID": "redis1",
"Service": "redis"
}
Extract from /v1/health/service/<service>::
{
"Node": {...},
"Service": {
"ID": "redis1",
"Service": "redis",
"Tags": None,
"Address": "10.1.10.12",
"Port": 8000
},
"Checks": [...]
}
"""
if not data:
return None, {}
if isinstance(data, str):
return data, {}
# from /v1/health/service/<service>
if all(field in data for field in ("Node", "Service", "Checks")):
return data["Service"]["ID"], data["Service"]
# from /v1/health/checks/<service>
# from /v1/health/node/<node>
# from /v1/health/state/<state>
# from /v1/catalog/service/<service>
if all(field in data for field in ("ServiceName", "ServiceID")):
return data["ServiceID"], {
"ID": data["ServiceID"],
"Service": data["ServiceName"],
"Tags": data.get("ServiceTags"),
"Address": data.get("ServiceAddress"),
"Port": data.get("ServicePort"),
}
if list(data) == ["ID"]:
return data["ID"], {}
result = {}
if "Name" in data:
result["Service"] = data["Name"]
for k in ("Service", "ID", "Tags", "Address", "Port"):
if k in data:
result[k] = data[k]
return result.get("ID"), result | [
"def",
"prepare_service",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
",",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"data",
",",
"{",
"}",
"# from /v1/health/service/<service>",
"if",
"all",
"(",
"field",
"in",
"data",
"for",
"field",
"in",
"(",
"\"Node\"",
",",
"\"Service\"",
",",
"\"Checks\"",
")",
")",
":",
"return",
"data",
"[",
"\"Service\"",
"]",
"[",
"\"ID\"",
"]",
",",
"data",
"[",
"\"Service\"",
"]",
"# from /v1/health/checks/<service>",
"# from /v1/health/node/<node>",
"# from /v1/health/state/<state>",
"# from /v1/catalog/service/<service>",
"if",
"all",
"(",
"field",
"in",
"data",
"for",
"field",
"in",
"(",
"\"ServiceName\"",
",",
"\"ServiceID\"",
")",
")",
":",
"return",
"data",
"[",
"\"ServiceID\"",
"]",
",",
"{",
"\"ID\"",
":",
"data",
"[",
"\"ServiceID\"",
"]",
",",
"\"Service\"",
":",
"data",
"[",
"\"ServiceName\"",
"]",
",",
"\"Tags\"",
":",
"data",
".",
"get",
"(",
"\"ServiceTags\"",
")",
",",
"\"Address\"",
":",
"data",
".",
"get",
"(",
"\"ServiceAddress\"",
")",
",",
"\"Port\"",
":",
"data",
".",
"get",
"(",
"\"ServicePort\"",
")",
",",
"}",
"if",
"list",
"(",
"data",
")",
"==",
"[",
"\"ID\"",
"]",
":",
"return",
"data",
"[",
"\"ID\"",
"]",
",",
"{",
"}",
"result",
"=",
"{",
"}",
"if",
"\"Name\"",
"in",
"data",
":",
"result",
"[",
"\"Service\"",
"]",
"=",
"data",
"[",
"\"Name\"",
"]",
"for",
"k",
"in",
"(",
"\"Service\"",
",",
"\"ID\"",
",",
"\"Tags\"",
",",
"\"Address\"",
",",
"\"Port\"",
")",
":",
"if",
"k",
"in",
"data",
":",
"result",
"[",
"k",
"]",
"=",
"data",
"[",
"k",
"]",
"return",
"result",
".",
"get",
"(",
"\"ID\"",
")",
",",
"result"
] | Prepare service for catalog endpoint
Parameters:
data (Union[str, dict]): Service ID or service definition
Returns:
Tuple[str, dict]: str is ID and dict is service
Transform ``/v1/health/state/<state>``::
{
"Node": "foobar",
"CheckID": "service:redis",
"Name": "Service 'redis' check",
"Status": "passing",
"Notes": "",
"Output": "",
"ServiceID": "redis1",
"ServiceName": "redis"
}
to::
{
"ID": "redis1",
"Service": "redis"
}
Extract from /v1/health/service/<service>::
{
"Node": {...},
"Service": {
"ID": "redis1",
"Service": "redis",
"Tags": None,
"Address": "10.1.10.12",
"Port": 8000
},
"Checks": [...]
} | [
"Prepare",
"service",
"for",
"catalog",
"endpoint"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/util.py#L49-L125 | train |
johnnoone/aioconsul | aioconsul/client/util.py | prepare_check | def prepare_check(data):
"""Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition
"""
if not data:
return None, {}
if isinstance(data, str):
return data, {}
result = {}
if "ID" in data:
result["CheckID"] = data["ID"]
for k in ("Node", "CheckID", "Name", "Notes", "Status", "ServiceID"):
if k in data:
result[k] = data[k]
if list(result) == ["CheckID"]:
return result["CheckID"], {}
return result.get("CheckID"), result | python | def prepare_check(data):
"""Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition
"""
if not data:
return None, {}
if isinstance(data, str):
return data, {}
result = {}
if "ID" in data:
result["CheckID"] = data["ID"]
for k in ("Node", "CheckID", "Name", "Notes", "Status", "ServiceID"):
if k in data:
result[k] = data[k]
if list(result) == ["CheckID"]:
return result["CheckID"], {}
return result.get("CheckID"), result | [
"def",
"prepare_check",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
",",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"data",
",",
"{",
"}",
"result",
"=",
"{",
"}",
"if",
"\"ID\"",
"in",
"data",
":",
"result",
"[",
"\"CheckID\"",
"]",
"=",
"data",
"[",
"\"ID\"",
"]",
"for",
"k",
"in",
"(",
"\"Node\"",
",",
"\"CheckID\"",
",",
"\"Name\"",
",",
"\"Notes\"",
",",
"\"Status\"",
",",
"\"ServiceID\"",
")",
":",
"if",
"k",
"in",
"data",
":",
"result",
"[",
"k",
"]",
"=",
"data",
"[",
"k",
"]",
"if",
"list",
"(",
"result",
")",
"==",
"[",
"\"CheckID\"",
"]",
":",
"return",
"result",
"[",
"\"CheckID\"",
"]",
",",
"{",
"}",
"return",
"result",
".",
"get",
"(",
"\"CheckID\"",
")",
",",
"result"
] | Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition | [
"Prepare",
"check",
"for",
"catalog",
"endpoint"
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/util.py#L128-L150 | train |
ponty/pyavrutils | pyavrutils/avrgcc.py | AvrGcc.optimize_no | def optimize_no(self):
''' all options set to default
'''
self.optimization = 0
self.relax = False
self.gc_sections = False
self.ffunction_sections = False
self.fdata_sections = False
self.fno_inline_small_functions = False | python | def optimize_no(self):
''' all options set to default
'''
self.optimization = 0
self.relax = False
self.gc_sections = False
self.ffunction_sections = False
self.fdata_sections = False
self.fno_inline_small_functions = False | [
"def",
"optimize_no",
"(",
"self",
")",
":",
"self",
".",
"optimization",
"=",
"0",
"self",
".",
"relax",
"=",
"False",
"self",
".",
"gc_sections",
"=",
"False",
"self",
".",
"ffunction_sections",
"=",
"False",
"self",
".",
"fdata_sections",
"=",
"False",
"self",
".",
"fno_inline_small_functions",
"=",
"False"
] | all options set to default | [
"all",
"options",
"set",
"to",
"default"
] | 7a396a25b3ac076ede07b5cd5cbd416ebb578a28 | https://github.com/ponty/pyavrutils/blob/7a396a25b3ac076ede07b5cd5cbd416ebb578a28/pyavrutils/avrgcc.py#L76-L84 | train |
bitesofcode/projexui | projexui/xresourcemanager.py | XResourceManager.init | def init(self):
"""
Initializes the plugins for this resource manager.
"""
# import any compiled resource modules
if not self._initialized:
self._initialized = True
wrap = projexui.qt.QT_WRAPPER.lower()
ignore = lambda x: not x.split('.')[-1].startswith(wrap)
projex.importmodules(self.plugins(), ignore=ignore) | python | def init(self):
"""
Initializes the plugins for this resource manager.
"""
# import any compiled resource modules
if not self._initialized:
self._initialized = True
wrap = projexui.qt.QT_WRAPPER.lower()
ignore = lambda x: not x.split('.')[-1].startswith(wrap)
projex.importmodules(self.plugins(), ignore=ignore) | [
"def",
"init",
"(",
"self",
")",
":",
"# import any compiled resource modules\r",
"if",
"not",
"self",
".",
"_initialized",
":",
"self",
".",
"_initialized",
"=",
"True",
"wrap",
"=",
"projexui",
".",
"qt",
".",
"QT_WRAPPER",
".",
"lower",
"(",
")",
"ignore",
"=",
"lambda",
"x",
":",
"not",
"x",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
".",
"startswith",
"(",
"wrap",
")",
"projex",
".",
"importmodules",
"(",
"self",
".",
"plugins",
"(",
")",
",",
"ignore",
"=",
"ignore",
")"
] | Initializes the plugins for this resource manager. | [
"Initializes",
"the",
"plugins",
"for",
"this",
"resource",
"manager",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xresourcemanager.py#L244-L253 | train |
intelsdi-x/snap-plugin-lib-py | snap_plugin/v1/config_policy.py | ConfigPolicy.policies | def policies(self):
"""Return list of policies zipped with their respective data type"""
policies = [self._pb.integer_policy, self._pb.float_policy,
self._pb.string_policy, self._pb.bool_policy]
key_types = ["integer", "float", "string", "bool"]
return zip(key_types, policies) | python | def policies(self):
"""Return list of policies zipped with their respective data type"""
policies = [self._pb.integer_policy, self._pb.float_policy,
self._pb.string_policy, self._pb.bool_policy]
key_types = ["integer", "float", "string", "bool"]
return zip(key_types, policies) | [
"def",
"policies",
"(",
"self",
")",
":",
"policies",
"=",
"[",
"self",
".",
"_pb",
".",
"integer_policy",
",",
"self",
".",
"_pb",
".",
"float_policy",
",",
"self",
".",
"_pb",
".",
"string_policy",
",",
"self",
".",
"_pb",
".",
"bool_policy",
"]",
"key_types",
"=",
"[",
"\"integer\"",
",",
"\"float\"",
",",
"\"string\"",
",",
"\"bool\"",
"]",
"return",
"zip",
"(",
"key_types",
",",
"policies",
")"
] | Return list of policies zipped with their respective data type | [
"Return",
"list",
"of",
"policies",
"zipped",
"with",
"their",
"respective",
"data",
"type"
] | 8da5d00ac5f9d2b48a7239563ac7788209891ca4 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_policy.py#L140-L145 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | add_measurement | def add_measurement(measurement):
"""Add measurement data to the submission buffer for eventual writing to
InfluxDB.
Example:
.. code:: python
import sprockets_influxdb as influxdb
measurement = influxdb.Measurement('example', 'measurement-name')
measurement.set_tag('foo', 'bar')
measurement.set_field('baz', 1.05)
influxdb.add_measurement(measurement)
:param :class:`~sprockets_influxdb.Measurement` measurement: The
measurement to add to the buffer for submission to InfluxDB.
"""
global _buffer_size
if not _enabled:
LOGGER.debug('Discarding measurement for %s while not enabled',
measurement.database)
return
if _stopping:
LOGGER.warning('Discarding measurement for %s while stopping',
measurement.database)
return
if _buffer_size > _max_buffer_size:
LOGGER.warning('Discarding measurement due to buffer size limit')
return
if not measurement.fields:
raise ValueError('Measurement does not contain a field')
if measurement.database not in _measurements:
_measurements[measurement.database] = []
value = measurement.marshall()
_measurements[measurement.database].append(value)
# Ensure that len(measurements) < _trigger_size are written
if not _timeout:
if (_batch_future and _batch_future.done()) or not _batch_future:
_start_timeout()
# Check to see if the batch should be triggered
_buffer_size = _pending_measurements()
if _buffer_size >= _trigger_size:
_trigger_batch_write() | python | def add_measurement(measurement):
"""Add measurement data to the submission buffer for eventual writing to
InfluxDB.
Example:
.. code:: python
import sprockets_influxdb as influxdb
measurement = influxdb.Measurement('example', 'measurement-name')
measurement.set_tag('foo', 'bar')
measurement.set_field('baz', 1.05)
influxdb.add_measurement(measurement)
:param :class:`~sprockets_influxdb.Measurement` measurement: The
measurement to add to the buffer for submission to InfluxDB.
"""
global _buffer_size
if not _enabled:
LOGGER.debug('Discarding measurement for %s while not enabled',
measurement.database)
return
if _stopping:
LOGGER.warning('Discarding measurement for %s while stopping',
measurement.database)
return
if _buffer_size > _max_buffer_size:
LOGGER.warning('Discarding measurement due to buffer size limit')
return
if not measurement.fields:
raise ValueError('Measurement does not contain a field')
if measurement.database not in _measurements:
_measurements[measurement.database] = []
value = measurement.marshall()
_measurements[measurement.database].append(value)
# Ensure that len(measurements) < _trigger_size are written
if not _timeout:
if (_batch_future and _batch_future.done()) or not _batch_future:
_start_timeout()
# Check to see if the batch should be triggered
_buffer_size = _pending_measurements()
if _buffer_size >= _trigger_size:
_trigger_batch_write() | [
"def",
"add_measurement",
"(",
"measurement",
")",
":",
"global",
"_buffer_size",
"if",
"not",
"_enabled",
":",
"LOGGER",
".",
"debug",
"(",
"'Discarding measurement for %s while not enabled'",
",",
"measurement",
".",
"database",
")",
"return",
"if",
"_stopping",
":",
"LOGGER",
".",
"warning",
"(",
"'Discarding measurement for %s while stopping'",
",",
"measurement",
".",
"database",
")",
"return",
"if",
"_buffer_size",
">",
"_max_buffer_size",
":",
"LOGGER",
".",
"warning",
"(",
"'Discarding measurement due to buffer size limit'",
")",
"return",
"if",
"not",
"measurement",
".",
"fields",
":",
"raise",
"ValueError",
"(",
"'Measurement does not contain a field'",
")",
"if",
"measurement",
".",
"database",
"not",
"in",
"_measurements",
":",
"_measurements",
"[",
"measurement",
".",
"database",
"]",
"=",
"[",
"]",
"value",
"=",
"measurement",
".",
"marshall",
"(",
")",
"_measurements",
"[",
"measurement",
".",
"database",
"]",
".",
"append",
"(",
"value",
")",
"# Ensure that len(measurements) < _trigger_size are written",
"if",
"not",
"_timeout",
":",
"if",
"(",
"_batch_future",
"and",
"_batch_future",
".",
"done",
"(",
")",
")",
"or",
"not",
"_batch_future",
":",
"_start_timeout",
"(",
")",
"# Check to see if the batch should be triggered",
"_buffer_size",
"=",
"_pending_measurements",
"(",
")",
"if",
"_buffer_size",
">=",
"_trigger_size",
":",
"_trigger_batch_write",
"(",
")"
] | Add measurement data to the submission buffer for eventual writing to
InfluxDB.
Example:
.. code:: python
import sprockets_influxdb as influxdb
measurement = influxdb.Measurement('example', 'measurement-name')
measurement.set_tag('foo', 'bar')
measurement.set_field('baz', 1.05)
influxdb.add_measurement(measurement)
:param :class:`~sprockets_influxdb.Measurement` measurement: The
measurement to add to the buffer for submission to InfluxDB. | [
"Add",
"measurement",
"data",
"to",
"the",
"submission",
"buffer",
"for",
"eventual",
"writing",
"to",
"InfluxDB",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L159-L212 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | flush | def flush():
"""Flush all pending measurements to InfluxDB. This will ensure that all
measurements that are in the buffer for any database are written. If the
requests fail, it will continue to try and submit the metrics until they
are successfully written.
:rtype: :class:`~tornado.concurrent.Future`
"""
flush_future = concurrent.Future()
if _batch_future and not _batch_future.done():
LOGGER.debug('Flush waiting on incomplete _batch_future')
_flush_wait(flush_future, _batch_future)
else:
LOGGER.info('Flushing buffer with %i measurements to InfluxDB',
_pending_measurements())
_flush_wait(flush_future, _write_measurements())
return flush_future | python | def flush():
"""Flush all pending measurements to InfluxDB. This will ensure that all
measurements that are in the buffer for any database are written. If the
requests fail, it will continue to try and submit the metrics until they
are successfully written.
:rtype: :class:`~tornado.concurrent.Future`
"""
flush_future = concurrent.Future()
if _batch_future and not _batch_future.done():
LOGGER.debug('Flush waiting on incomplete _batch_future')
_flush_wait(flush_future, _batch_future)
else:
LOGGER.info('Flushing buffer with %i measurements to InfluxDB',
_pending_measurements())
_flush_wait(flush_future, _write_measurements())
return flush_future | [
"def",
"flush",
"(",
")",
":",
"flush_future",
"=",
"concurrent",
".",
"Future",
"(",
")",
"if",
"_batch_future",
"and",
"not",
"_batch_future",
".",
"done",
"(",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Flush waiting on incomplete _batch_future'",
")",
"_flush_wait",
"(",
"flush_future",
",",
"_batch_future",
")",
"else",
":",
"LOGGER",
".",
"info",
"(",
"'Flushing buffer with %i measurements to InfluxDB'",
",",
"_pending_measurements",
"(",
")",
")",
"_flush_wait",
"(",
"flush_future",
",",
"_write_measurements",
"(",
")",
")",
"return",
"flush_future"
] | Flush all pending measurements to InfluxDB. This will ensure that all
measurements that are in the buffer for any database are written. If the
requests fail, it will continue to try and submit the metrics until they
are successfully written.
:rtype: :class:`~tornado.concurrent.Future` | [
"Flush",
"all",
"pending",
"measurements",
"to",
"InfluxDB",
".",
"This",
"will",
"ensure",
"that",
"all",
"measurements",
"that",
"are",
"in",
"the",
"buffer",
"for",
"any",
"database",
"are",
"written",
".",
"If",
"the",
"requests",
"fail",
"it",
"will",
"continue",
"to",
"try",
"and",
"submit",
"the",
"metrics",
"until",
"they",
"are",
"successfully",
"written",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L215-L232 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | set_auth_credentials | def set_auth_credentials(username, password):
"""Override the default authentication credentials obtained from the
environment variable configuration.
:param str username: The username to use
:param str password: The password to use
"""
global _credentials, _dirty
LOGGER.debug('Setting authentication credentials')
_credentials = username, password
_dirty = True | python | def set_auth_credentials(username, password):
"""Override the default authentication credentials obtained from the
environment variable configuration.
:param str username: The username to use
:param str password: The password to use
"""
global _credentials, _dirty
LOGGER.debug('Setting authentication credentials')
_credentials = username, password
_dirty = True | [
"def",
"set_auth_credentials",
"(",
"username",
",",
"password",
")",
":",
"global",
"_credentials",
",",
"_dirty",
"LOGGER",
".",
"debug",
"(",
"'Setting authentication credentials'",
")",
"_credentials",
"=",
"username",
",",
"password",
"_dirty",
"=",
"True"
] | Override the default authentication credentials obtained from the
environment variable configuration.
:param str username: The username to use
:param str password: The password to use | [
"Override",
"the",
"default",
"authentication",
"credentials",
"obtained",
"from",
"the",
"environment",
"variable",
"configuration",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L334-L346 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | set_base_url | def set_base_url(url):
"""Override the default base URL value created from the environment
variable configuration.
:param str url: The base URL to use when submitting measurements
"""
global _base_url, _dirty
LOGGER.debug('Setting base URL to %s', url)
_base_url = url
_dirty = True | python | def set_base_url(url):
"""Override the default base URL value created from the environment
variable configuration.
:param str url: The base URL to use when submitting measurements
"""
global _base_url, _dirty
LOGGER.debug('Setting base URL to %s', url)
_base_url = url
_dirty = True | [
"def",
"set_base_url",
"(",
"url",
")",
":",
"global",
"_base_url",
",",
"_dirty",
"LOGGER",
".",
"debug",
"(",
"'Setting base URL to %s'",
",",
"url",
")",
"_base_url",
"=",
"url",
"_dirty",
"=",
"True"
] | Override the default base URL value created from the environment
variable configuration.
:param str url: The base URL to use when submitting measurements | [
"Override",
"the",
"default",
"base",
"URL",
"value",
"created",
"from",
"the",
"environment",
"variable",
"configuration",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L349-L360 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | set_max_clients | def set_max_clients(limit):
"""Set the maximum number of simultaneous batch submission that can execute
in parallel.
:param int limit: The maximum number of simultaneous batch submissions
"""
global _dirty, _max_clients
LOGGER.debug('Setting maximum client limit to %i', limit)
_dirty = True
_max_clients = limit | python | def set_max_clients(limit):
"""Set the maximum number of simultaneous batch submission that can execute
in parallel.
:param int limit: The maximum number of simultaneous batch submissions
"""
global _dirty, _max_clients
LOGGER.debug('Setting maximum client limit to %i', limit)
_dirty = True
_max_clients = limit | [
"def",
"set_max_clients",
"(",
"limit",
")",
":",
"global",
"_dirty",
",",
"_max_clients",
"LOGGER",
".",
"debug",
"(",
"'Setting maximum client limit to %i'",
",",
"limit",
")",
"_dirty",
"=",
"True",
"_max_clients",
"=",
"limit"
] | Set the maximum number of simultaneous batch submission that can execute
in parallel.
:param int limit: The maximum number of simultaneous batch submissions | [
"Set",
"the",
"maximum",
"number",
"of",
"simultaneous",
"batch",
"submission",
"that",
"can",
"execute",
"in",
"parallel",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L390-L401 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | set_sample_probability | def set_sample_probability(probability):
"""Set the probability that a batch will be submitted to the InfluxDB
server. This should be a value that is greater than or equal to ``0`` and
less than or equal to ``1.0``. A value of ``0.25`` would represent a
probability of 25% that a batch would be written to InfluxDB.
:param float probability: The value between 0 and 1.0 that represents the
probability that a batch will be submitted to the InfluxDB server.
"""
global _sample_probability
if not 0.0 <= probability <= 1.0:
raise ValueError('Invalid probability value')
LOGGER.debug('Setting sample probability to %.2f', probability)
_sample_probability = float(probability) | python | def set_sample_probability(probability):
"""Set the probability that a batch will be submitted to the InfluxDB
server. This should be a value that is greater than or equal to ``0`` and
less than or equal to ``1.0``. A value of ``0.25`` would represent a
probability of 25% that a batch would be written to InfluxDB.
:param float probability: The value between 0 and 1.0 that represents the
probability that a batch will be submitted to the InfluxDB server.
"""
global _sample_probability
if not 0.0 <= probability <= 1.0:
raise ValueError('Invalid probability value')
LOGGER.debug('Setting sample probability to %.2f', probability)
_sample_probability = float(probability) | [
"def",
"set_sample_probability",
"(",
"probability",
")",
":",
"global",
"_sample_probability",
"if",
"not",
"0.0",
"<=",
"probability",
"<=",
"1.0",
":",
"raise",
"ValueError",
"(",
"'Invalid probability value'",
")",
"LOGGER",
".",
"debug",
"(",
"'Setting sample probability to %.2f'",
",",
"probability",
")",
"_sample_probability",
"=",
"float",
"(",
"probability",
")"
] | Set the probability that a batch will be submitted to the InfluxDB
server. This should be a value that is greater than or equal to ``0`` and
less than or equal to ``1.0``. A value of ``0.25`` would represent a
probability of 25% that a batch would be written to InfluxDB.
:param float probability: The value between 0 and 1.0 that represents the
probability that a batch will be submitted to the InfluxDB server. | [
"Set",
"the",
"probability",
"that",
"a",
"batch",
"will",
"be",
"submitted",
"to",
"the",
"InfluxDB",
"server",
".",
"This",
"should",
"be",
"a",
"value",
"that",
"is",
"greater",
"than",
"or",
"equal",
"to",
"0",
"and",
"less",
"than",
"or",
"equal",
"to",
"1",
".",
"0",
".",
"A",
"value",
"of",
"0",
".",
"25",
"would",
"represent",
"a",
"probability",
"of",
"25%",
"that",
"a",
"batch",
"would",
"be",
"written",
"to",
"InfluxDB",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L404-L420 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | set_timeout | def set_timeout(milliseconds):
"""Override the maximum duration to wait for submitting measurements to
InfluxDB.
:param int milliseconds: Maximum wait in milliseconds
"""
global _timeout, _timeout_interval
LOGGER.debug('Setting batch wait timeout to %i ms', milliseconds)
_timeout_interval = milliseconds
_maybe_stop_timeout()
_timeout = ioloop.IOLoop.current().add_timeout(milliseconds, _on_timeout) | python | def set_timeout(milliseconds):
"""Override the maximum duration to wait for submitting measurements to
InfluxDB.
:param int milliseconds: Maximum wait in milliseconds
"""
global _timeout, _timeout_interval
LOGGER.debug('Setting batch wait timeout to %i ms', milliseconds)
_timeout_interval = milliseconds
_maybe_stop_timeout()
_timeout = ioloop.IOLoop.current().add_timeout(milliseconds, _on_timeout) | [
"def",
"set_timeout",
"(",
"milliseconds",
")",
":",
"global",
"_timeout",
",",
"_timeout_interval",
"LOGGER",
".",
"debug",
"(",
"'Setting batch wait timeout to %i ms'",
",",
"milliseconds",
")",
"_timeout_interval",
"=",
"milliseconds",
"_maybe_stop_timeout",
"(",
")",
"_timeout",
"=",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"add_timeout",
"(",
"milliseconds",
",",
"_on_timeout",
")"
] | Override the maximum duration to wait for submitting measurements to
InfluxDB.
:param int milliseconds: Maximum wait in milliseconds | [
"Override",
"the",
"maximum",
"duration",
"to",
"wait",
"for",
"submitting",
"measurements",
"to",
"InfluxDB",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L423-L435 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _create_http_client | def _create_http_client():
"""Create the HTTP client with authentication credentials if required."""
global _http_client
defaults = {'user_agent': USER_AGENT}
auth_username, auth_password = _credentials
if auth_username and auth_password:
defaults['auth_username'] = auth_username
defaults['auth_password'] = auth_password
_http_client = httpclient.AsyncHTTPClient(
force_instance=True, defaults=defaults,
max_clients=_max_clients) | python | def _create_http_client():
"""Create the HTTP client with authentication credentials if required."""
global _http_client
defaults = {'user_agent': USER_AGENT}
auth_username, auth_password = _credentials
if auth_username and auth_password:
defaults['auth_username'] = auth_username
defaults['auth_password'] = auth_password
_http_client = httpclient.AsyncHTTPClient(
force_instance=True, defaults=defaults,
max_clients=_max_clients) | [
"def",
"_create_http_client",
"(",
")",
":",
"global",
"_http_client",
"defaults",
"=",
"{",
"'user_agent'",
":",
"USER_AGENT",
"}",
"auth_username",
",",
"auth_password",
"=",
"_credentials",
"if",
"auth_username",
"and",
"auth_password",
":",
"defaults",
"[",
"'auth_username'",
"]",
"=",
"auth_username",
"defaults",
"[",
"'auth_password'",
"]",
"=",
"auth_password",
"_http_client",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
"force_instance",
"=",
"True",
",",
"defaults",
"=",
"defaults",
",",
"max_clients",
"=",
"_max_clients",
")"
] | Create the HTTP client with authentication credentials if required. | [
"Create",
"the",
"HTTP",
"client",
"with",
"authentication",
"credentials",
"if",
"required",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L472-L484 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _flush_wait | def _flush_wait(flush_future, write_future):
"""Pause briefly allowing any pending metric writes to complete before
shutting down.
:param tornado.concurrent.Future flush_future: The future to resolve
when the shutdown is complete.
:param tornado.concurrent.Future write_future: The future that is for the
current batch write operation.
"""
if write_future.done():
if not _pending_measurements():
flush_future.set_result(True)
return
else:
write_future = _write_measurements()
ioloop.IOLoop.current().add_timeout(
ioloop.IOLoop.current().time() + 0.25,
_flush_wait, flush_future, write_future) | python | def _flush_wait(flush_future, write_future):
"""Pause briefly allowing any pending metric writes to complete before
shutting down.
:param tornado.concurrent.Future flush_future: The future to resolve
when the shutdown is complete.
:param tornado.concurrent.Future write_future: The future that is for the
current batch write operation.
"""
if write_future.done():
if not _pending_measurements():
flush_future.set_result(True)
return
else:
write_future = _write_measurements()
ioloop.IOLoop.current().add_timeout(
ioloop.IOLoop.current().time() + 0.25,
_flush_wait, flush_future, write_future) | [
"def",
"_flush_wait",
"(",
"flush_future",
",",
"write_future",
")",
":",
"if",
"write_future",
".",
"done",
"(",
")",
":",
"if",
"not",
"_pending_measurements",
"(",
")",
":",
"flush_future",
".",
"set_result",
"(",
"True",
")",
"return",
"else",
":",
"write_future",
"=",
"_write_measurements",
"(",
")",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"add_timeout",
"(",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"time",
"(",
")",
"+",
"0.25",
",",
"_flush_wait",
",",
"flush_future",
",",
"write_future",
")"
] | Pause briefly allowing any pending metric writes to complete before
shutting down.
:param tornado.concurrent.Future flush_future: The future to resolve
when the shutdown is complete.
:param tornado.concurrent.Future write_future: The future that is for the
current batch write operation. | [
"Pause",
"briefly",
"allowing",
"any",
"pending",
"metric",
"writes",
"to",
"complete",
"before",
"shutting",
"down",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L487-L505 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _futures_wait | def _futures_wait(wait_future, futures):
"""Waits for all futures to be completed. If the futures are not done,
wait 100ms and then invoke itself via the ioloop and check again. If
they are done, set a result on `wait_future` indicating the list of
futures are done.
:param wait_future: The future to complete when all `futures` are done
:type wait_future: tornado.concurrent.Future
:param list futures: The list of futures to watch for completion
"""
global _buffer_size, _writing
remaining = []
for (future, batch, database, measurements) in futures:
# If the future hasn't completed, add it to the remaining stack
if not future.done():
remaining.append((future, batch, database, measurements))
continue
# Get the result of the HTTP request, processing any errors
error = future.exception()
if isinstance(error, httpclient.HTTPError):
if error.code == 400:
_write_error_batch(batch, database, measurements)
elif error.code >= 500:
_on_5xx_error(batch, error, database, measurements)
else:
LOGGER.error('Error submitting %s batch %s to InfluxDB (%s): '
'%s', database, batch, error.code,
error.response.body)
elif isinstance(error, (TimeoutError, OSError, socket.error,
select.error, ssl.socket_error)):
_on_5xx_error(batch, error, database, measurements)
# If there are futures that remain, try again in 100ms.
if remaining:
return ioloop.IOLoop.current().add_timeout(
ioloop.IOLoop.current().time() + 0.1,
_futures_wait, wait_future, remaining)
else: # Start the next timeout or trigger the next batch
_buffer_size = _pending_measurements()
LOGGER.debug('Batch submitted, %i measurements remain', _buffer_size)
if _buffer_size >= _trigger_size:
ioloop.IOLoop.current().add_callback(_trigger_batch_write)
elif _buffer_size:
_start_timeout()
_writing = False
wait_future.set_result(True) | python | def _futures_wait(wait_future, futures):
"""Waits for all futures to be completed. If the futures are not done,
wait 100ms and then invoke itself via the ioloop and check again. If
they are done, set a result on `wait_future` indicating the list of
futures are done.
:param wait_future: The future to complete when all `futures` are done
:type wait_future: tornado.concurrent.Future
:param list futures: The list of futures to watch for completion
"""
global _buffer_size, _writing
remaining = []
for (future, batch, database, measurements) in futures:
# If the future hasn't completed, add it to the remaining stack
if not future.done():
remaining.append((future, batch, database, measurements))
continue
# Get the result of the HTTP request, processing any errors
error = future.exception()
if isinstance(error, httpclient.HTTPError):
if error.code == 400:
_write_error_batch(batch, database, measurements)
elif error.code >= 500:
_on_5xx_error(batch, error, database, measurements)
else:
LOGGER.error('Error submitting %s batch %s to InfluxDB (%s): '
'%s', database, batch, error.code,
error.response.body)
elif isinstance(error, (TimeoutError, OSError, socket.error,
select.error, ssl.socket_error)):
_on_5xx_error(batch, error, database, measurements)
# If there are futures that remain, try again in 100ms.
if remaining:
return ioloop.IOLoop.current().add_timeout(
ioloop.IOLoop.current().time() + 0.1,
_futures_wait, wait_future, remaining)
else: # Start the next timeout or trigger the next batch
_buffer_size = _pending_measurements()
LOGGER.debug('Batch submitted, %i measurements remain', _buffer_size)
if _buffer_size >= _trigger_size:
ioloop.IOLoop.current().add_callback(_trigger_batch_write)
elif _buffer_size:
_start_timeout()
_writing = False
wait_future.set_result(True) | [
"def",
"_futures_wait",
"(",
"wait_future",
",",
"futures",
")",
":",
"global",
"_buffer_size",
",",
"_writing",
"remaining",
"=",
"[",
"]",
"for",
"(",
"future",
",",
"batch",
",",
"database",
",",
"measurements",
")",
"in",
"futures",
":",
"# If the future hasn't completed, add it to the remaining stack",
"if",
"not",
"future",
".",
"done",
"(",
")",
":",
"remaining",
".",
"append",
"(",
"(",
"future",
",",
"batch",
",",
"database",
",",
"measurements",
")",
")",
"continue",
"# Get the result of the HTTP request, processing any errors",
"error",
"=",
"future",
".",
"exception",
"(",
")",
"if",
"isinstance",
"(",
"error",
",",
"httpclient",
".",
"HTTPError",
")",
":",
"if",
"error",
".",
"code",
"==",
"400",
":",
"_write_error_batch",
"(",
"batch",
",",
"database",
",",
"measurements",
")",
"elif",
"error",
".",
"code",
">=",
"500",
":",
"_on_5xx_error",
"(",
"batch",
",",
"error",
",",
"database",
",",
"measurements",
")",
"else",
":",
"LOGGER",
".",
"error",
"(",
"'Error submitting %s batch %s to InfluxDB (%s): '",
"'%s'",
",",
"database",
",",
"batch",
",",
"error",
".",
"code",
",",
"error",
".",
"response",
".",
"body",
")",
"elif",
"isinstance",
"(",
"error",
",",
"(",
"TimeoutError",
",",
"OSError",
",",
"socket",
".",
"error",
",",
"select",
".",
"error",
",",
"ssl",
".",
"socket_error",
")",
")",
":",
"_on_5xx_error",
"(",
"batch",
",",
"error",
",",
"database",
",",
"measurements",
")",
"# If there are futures that remain, try again in 100ms.",
"if",
"remaining",
":",
"return",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"add_timeout",
"(",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"time",
"(",
")",
"+",
"0.1",
",",
"_futures_wait",
",",
"wait_future",
",",
"remaining",
")",
"else",
":",
"# Start the next timeout or trigger the next batch",
"_buffer_size",
"=",
"_pending_measurements",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"'Batch submitted, %i measurements remain'",
",",
"_buffer_size",
")",
"if",
"_buffer_size",
">=",
"_trigger_size",
":",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"add_callback",
"(",
"_trigger_batch_write",
")",
"elif",
"_buffer_size",
":",
"_start_timeout",
"(",
")",
"_writing",
"=",
"False",
"wait_future",
".",
"set_result",
"(",
"True",
")"
] | Waits for all futures to be completed. If the futures are not done,
wait 100ms and then invoke itself via the ioloop and check again. If
they are done, set a result on `wait_future` indicating the list of
futures are done.
:param wait_future: The future to complete when all `futures` are done
:type wait_future: tornado.concurrent.Future
:param list futures: The list of futures to watch for completion | [
"Waits",
"for",
"all",
"futures",
"to",
"be",
"completed",
".",
"If",
"the",
"futures",
"are",
"not",
"done",
"wait",
"100ms",
"and",
"then",
"invoke",
"itself",
"via",
"the",
"ioloop",
"and",
"check",
"again",
".",
"If",
"they",
"are",
"done",
"set",
"a",
"result",
"on",
"wait_future",
"indicating",
"the",
"list",
"of",
"futures",
"are",
"done",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L508-L558 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _maybe_stop_timeout | def _maybe_stop_timeout():
"""If there is a pending timeout, remove it from the IOLoop and set the
``_timeout`` global to None.
"""
global _timeout
if _timeout is not None:
LOGGER.debug('Removing the pending timeout (%r)', _timeout)
ioloop.IOLoop.current().remove_timeout(_timeout)
_timeout = None | python | def _maybe_stop_timeout():
"""If there is a pending timeout, remove it from the IOLoop and set the
``_timeout`` global to None.
"""
global _timeout
if _timeout is not None:
LOGGER.debug('Removing the pending timeout (%r)', _timeout)
ioloop.IOLoop.current().remove_timeout(_timeout)
_timeout = None | [
"def",
"_maybe_stop_timeout",
"(",
")",
":",
"global",
"_timeout",
"if",
"_timeout",
"is",
"not",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'Removing the pending timeout (%r)'",
",",
"_timeout",
")",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"remove_timeout",
"(",
"_timeout",
")",
"_timeout",
"=",
"None"
] | If there is a pending timeout, remove it from the IOLoop and set the
``_timeout`` global to None. | [
"If",
"there",
"is",
"a",
"pending",
"timeout",
"remove",
"it",
"from",
"the",
"IOLoop",
"and",
"set",
"the",
"_timeout",
"global",
"to",
"None",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L561-L571 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _maybe_warn_about_buffer_size | def _maybe_warn_about_buffer_size():
"""Check the buffer size and issue a warning if it's too large and
a warning has not been issued for more than 60 seconds.
"""
global _last_warning
if not _last_warning:
_last_warning = time.time()
if _buffer_size > _warn_threshold and (time.time() - _last_warning) > 120:
LOGGER.warning('InfluxDB measurement buffer has %i entries',
_buffer_size) | python | def _maybe_warn_about_buffer_size():
"""Check the buffer size and issue a warning if it's too large and
a warning has not been issued for more than 60 seconds.
"""
global _last_warning
if not _last_warning:
_last_warning = time.time()
if _buffer_size > _warn_threshold and (time.time() - _last_warning) > 120:
LOGGER.warning('InfluxDB measurement buffer has %i entries',
_buffer_size) | [
"def",
"_maybe_warn_about_buffer_size",
"(",
")",
":",
"global",
"_last_warning",
"if",
"not",
"_last_warning",
":",
"_last_warning",
"=",
"time",
".",
"time",
"(",
")",
"if",
"_buffer_size",
">",
"_warn_threshold",
"and",
"(",
"time",
".",
"time",
"(",
")",
"-",
"_last_warning",
")",
">",
"120",
":",
"LOGGER",
".",
"warning",
"(",
"'InfluxDB measurement buffer has %i entries'",
",",
"_buffer_size",
")"
] | Check the buffer size and issue a warning if it's too large and
a warning has not been issued for more than 60 seconds. | [
"Check",
"the",
"buffer",
"size",
"and",
"issue",
"a",
"warning",
"if",
"it",
"s",
"too",
"large",
"and",
"a",
"warning",
"has",
"not",
"been",
"issued",
"for",
"more",
"than",
"60",
"seconds",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L574-L586 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _on_5xx_error | def _on_5xx_error(batch, error, database, measurements):
"""Handle a batch submission error, logging the problem and adding the
measurements back to the stack.
:param str batch: The batch ID
:param mixed error: The error that was returned
:param str database: The database the submission failed for
:param list measurements: The measurements to add back to the stack
"""
LOGGER.info('Appending %s measurements to stack due to batch %s %r',
database, batch, error)
_measurements[database] = _measurements[database] + measurements | python | def _on_5xx_error(batch, error, database, measurements):
"""Handle a batch submission error, logging the problem and adding the
measurements back to the stack.
:param str batch: The batch ID
:param mixed error: The error that was returned
:param str database: The database the submission failed for
:param list measurements: The measurements to add back to the stack
"""
LOGGER.info('Appending %s measurements to stack due to batch %s %r',
database, batch, error)
_measurements[database] = _measurements[database] + measurements | [
"def",
"_on_5xx_error",
"(",
"batch",
",",
"error",
",",
"database",
",",
"measurements",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Appending %s measurements to stack due to batch %s %r'",
",",
"database",
",",
"batch",
",",
"error",
")",
"_measurements",
"[",
"database",
"]",
"=",
"_measurements",
"[",
"database",
"]",
"+",
"measurements"
] | Handle a batch submission error, logging the problem and adding the
measurements back to the stack.
:param str batch: The batch ID
:param mixed error: The error that was returned
:param str database: The database the submission failed for
:param list measurements: The measurements to add back to the stack | [
"Handle",
"a",
"batch",
"submission",
"error",
"logging",
"the",
"problem",
"and",
"adding",
"the",
"measurements",
"back",
"to",
"the",
"stack",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L589-L601 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _on_timeout | def _on_timeout():
"""Invoked periodically to ensure that metrics that have been collected
are submitted to InfluxDB.
:rtype: tornado.concurrent.Future or None
"""
global _buffer_size
LOGGER.debug('No metrics submitted in the last %.2f seconds',
_timeout_interval / 1000.0)
_buffer_size = _pending_measurements()
if _buffer_size:
return _trigger_batch_write()
_start_timeout() | python | def _on_timeout():
"""Invoked periodically to ensure that metrics that have been collected
are submitted to InfluxDB.
:rtype: tornado.concurrent.Future or None
"""
global _buffer_size
LOGGER.debug('No metrics submitted in the last %.2f seconds',
_timeout_interval / 1000.0)
_buffer_size = _pending_measurements()
if _buffer_size:
return _trigger_batch_write()
_start_timeout() | [
"def",
"_on_timeout",
"(",
")",
":",
"global",
"_buffer_size",
"LOGGER",
".",
"debug",
"(",
"'No metrics submitted in the last %.2f seconds'",
",",
"_timeout_interval",
"/",
"1000.0",
")",
"_buffer_size",
"=",
"_pending_measurements",
"(",
")",
"if",
"_buffer_size",
":",
"return",
"_trigger_batch_write",
"(",
")",
"_start_timeout",
"(",
")"
] | Invoked periodically to ensure that metrics that have been collected
are submitted to InfluxDB.
:rtype: tornado.concurrent.Future or None | [
"Invoked",
"periodically",
"to",
"ensure",
"that",
"metrics",
"that",
"have",
"been",
"collected",
"are",
"submitted",
"to",
"InfluxDB",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L604-L618 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _sample_batch | def _sample_batch():
"""Determine if a batch should be processed and if not, pop off all of
the pending metrics for that batch.
:rtype: bool
"""
if _sample_probability == 1.0 or random.random() < _sample_probability:
return True
# Pop off all the metrics for the batch
for database in _measurements:
_measurements[database] = _measurements[database][_max_batch_size:]
return False | python | def _sample_batch():
"""Determine if a batch should be processed and if not, pop off all of
the pending metrics for that batch.
:rtype: bool
"""
if _sample_probability == 1.0 or random.random() < _sample_probability:
return True
# Pop off all the metrics for the batch
for database in _measurements:
_measurements[database] = _measurements[database][_max_batch_size:]
return False | [
"def",
"_sample_batch",
"(",
")",
":",
"if",
"_sample_probability",
"==",
"1.0",
"or",
"random",
".",
"random",
"(",
")",
"<",
"_sample_probability",
":",
"return",
"True",
"# Pop off all the metrics for the batch",
"for",
"database",
"in",
"_measurements",
":",
"_measurements",
"[",
"database",
"]",
"=",
"_measurements",
"[",
"database",
"]",
"[",
"_max_batch_size",
":",
"]",
"return",
"False"
] | Determine if a batch should be processed and if not, pop off all of
the pending metrics for that batch.
:rtype: bool | [
"Determine",
"if",
"a",
"batch",
"should",
"be",
"processed",
"and",
"if",
"not",
"pop",
"off",
"all",
"of",
"the",
"pending",
"metrics",
"for",
"that",
"batch",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L631-L644 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _start_timeout | def _start_timeout():
"""Stop a running timeout if it's there, then create a new one."""
global _timeout
LOGGER.debug('Adding a new timeout in %i ms', _timeout_interval)
_maybe_stop_timeout()
_timeout = ioloop.IOLoop.current().add_timeout(
ioloop.IOLoop.current().time() + _timeout_interval / 1000.0,
_on_timeout) | python | def _start_timeout():
"""Stop a running timeout if it's there, then create a new one."""
global _timeout
LOGGER.debug('Adding a new timeout in %i ms', _timeout_interval)
_maybe_stop_timeout()
_timeout = ioloop.IOLoop.current().add_timeout(
ioloop.IOLoop.current().time() + _timeout_interval / 1000.0,
_on_timeout) | [
"def",
"_start_timeout",
"(",
")",
":",
"global",
"_timeout",
"LOGGER",
".",
"debug",
"(",
"'Adding a new timeout in %i ms'",
",",
"_timeout_interval",
")",
"_maybe_stop_timeout",
"(",
")",
"_timeout",
"=",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"add_timeout",
"(",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"time",
"(",
")",
"+",
"_timeout_interval",
"/",
"1000.0",
",",
"_on_timeout",
")"
] | Stop a running timeout if it's there, then create a new one. | [
"Stop",
"a",
"running",
"timeout",
"if",
"it",
"s",
"there",
"then",
"create",
"a",
"new",
"one",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L647-L655 | train |
sprockets/sprockets-influxdb | sprockets_influxdb.py | _trigger_batch_write | def _trigger_batch_write():
"""Stop a timeout if it's running, and then write the measurements."""
global _batch_future
LOGGER.debug('Batch write triggered (%r/%r)',
_buffer_size, _trigger_size)
_maybe_stop_timeout()
_maybe_warn_about_buffer_size()
_batch_future = _write_measurements()
return _batch_future | python | def _trigger_batch_write():
"""Stop a timeout if it's running, and then write the measurements."""
global _batch_future
LOGGER.debug('Batch write triggered (%r/%r)',
_buffer_size, _trigger_size)
_maybe_stop_timeout()
_maybe_warn_about_buffer_size()
_batch_future = _write_measurements()
return _batch_future | [
"def",
"_trigger_batch_write",
"(",
")",
":",
"global",
"_batch_future",
"LOGGER",
".",
"debug",
"(",
"'Batch write triggered (%r/%r)'",
",",
"_buffer_size",
",",
"_trigger_size",
")",
"_maybe_stop_timeout",
"(",
")",
"_maybe_warn_about_buffer_size",
"(",
")",
"_batch_future",
"=",
"_write_measurements",
"(",
")",
"return",
"_batch_future"
] | Stop a timeout if it's running, and then write the measurements. | [
"Stop",
"a",
"timeout",
"if",
"it",
"s",
"running",
"and",
"then",
"write",
"the",
"measurements",
"."
] | cce73481b8f26b02e65e3f9914a9a22eceff3063 | https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L658-L667 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.