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
sequencelengths 20
707
| docstring
stringlengths 3
17.3k
| docstring_tokens
sequencelengths 3
222
| sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value | idx
int64 0
252k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
paragbaxi/qualysapi | qualysapi/config.py | QualysConnectConfig.get_auth | def get_auth(self):
''' Returns username from the configfile. '''
return (self._cfgparse.get(self._section, 'username'), self._cfgparse.get(self._section, 'password')) | python | def get_auth(self):
''' Returns username from the configfile. '''
return (self._cfgparse.get(self._section, 'username'), self._cfgparse.get(self._section, 'password')) | [
"def",
"get_auth",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_cfgparse",
".",
"get",
"(",
"self",
".",
"_section",
",",
"'username'",
")",
",",
"self",
".",
"_cfgparse",
".",
"get",
"(",
"self",
".",
"_section",
",",
"'password'",
")",
")"
] | Returns username from the configfile. | [
"Returns",
"username",
"from",
"the",
"configfile",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/config.py#L211-L213 | train | 251,000 |
paragbaxi/qualysapi | qualysapi/util.py | connect | def connect(config_file=qcs.default_filename, section='info', remember_me=False, remember_me_always=False):
""" Return a QGAPIConnect object for v1 API pulling settings from config
file.
"""
# Retrieve login credentials.
conf = qcconf.QualysConnectConfig(filename=config_file, section=section, remember_me=remember_me,
remember_me_always=remember_me_always)
connect = qcconn.QGConnector(conf.get_auth(),
conf.get_hostname(),
conf.proxies,
conf.max_retries)
logger.info("Finished building connector.")
return connect | python | def connect(config_file=qcs.default_filename, section='info', remember_me=False, remember_me_always=False):
""" Return a QGAPIConnect object for v1 API pulling settings from config
file.
"""
# Retrieve login credentials.
conf = qcconf.QualysConnectConfig(filename=config_file, section=section, remember_me=remember_me,
remember_me_always=remember_me_always)
connect = qcconn.QGConnector(conf.get_auth(),
conf.get_hostname(),
conf.proxies,
conf.max_retries)
logger.info("Finished building connector.")
return connect | [
"def",
"connect",
"(",
"config_file",
"=",
"qcs",
".",
"default_filename",
",",
"section",
"=",
"'info'",
",",
"remember_me",
"=",
"False",
",",
"remember_me_always",
"=",
"False",
")",
":",
"# Retrieve login credentials.",
"conf",
"=",
"qcconf",
".",
"QualysConnectConfig",
"(",
"filename",
"=",
"config_file",
",",
"section",
"=",
"section",
",",
"remember_me",
"=",
"remember_me",
",",
"remember_me_always",
"=",
"remember_me_always",
")",
"connect",
"=",
"qcconn",
".",
"QGConnector",
"(",
"conf",
".",
"get_auth",
"(",
")",
",",
"conf",
".",
"get_hostname",
"(",
")",
",",
"conf",
".",
"proxies",
",",
"conf",
".",
"max_retries",
")",
"logger",
".",
"info",
"(",
"\"Finished building connector.\"",
")",
"return",
"connect"
] | Return a QGAPIConnect object for v1 API pulling settings from config
file. | [
"Return",
"a",
"QGAPIConnect",
"object",
"for",
"v1",
"API",
"pulling",
"settings",
"from",
"config",
"file",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/util.py#L18-L30 | train | 251,001 |
paragbaxi/qualysapi | qualysapi/connector.py | QGConnector.format_api_version | def format_api_version(self, api_version):
""" Return QualysGuard API version for api_version specified.
"""
# Convert to int.
if type(api_version) == str:
api_version = api_version.lower()
if api_version[0] == 'v' and api_version[1].isdigit():
# Remove first 'v' in case the user typed 'v1' or 'v2', etc.
api_version = api_version[1:]
# Check for input matching Qualys modules.
if api_version in ('asset management', 'assets', 'tag', 'tagging', 'tags'):
# Convert to Asset Management API.
api_version = 'am'
elif api_version in ('am2'):
# Convert to Asset Management API v2
api_version = 'am2'
elif api_version in ('webapp', 'web application scanning', 'webapp scanning'):
# Convert to WAS API.
api_version = 'was'
elif api_version in ('pol', 'pc'):
# Convert PC module to API number 2.
api_version = 2
else:
api_version = int(api_version)
return api_version | python | def format_api_version(self, api_version):
""" Return QualysGuard API version for api_version specified.
"""
# Convert to int.
if type(api_version) == str:
api_version = api_version.lower()
if api_version[0] == 'v' and api_version[1].isdigit():
# Remove first 'v' in case the user typed 'v1' or 'v2', etc.
api_version = api_version[1:]
# Check for input matching Qualys modules.
if api_version in ('asset management', 'assets', 'tag', 'tagging', 'tags'):
# Convert to Asset Management API.
api_version = 'am'
elif api_version in ('am2'):
# Convert to Asset Management API v2
api_version = 'am2'
elif api_version in ('webapp', 'web application scanning', 'webapp scanning'):
# Convert to WAS API.
api_version = 'was'
elif api_version in ('pol', 'pc'):
# Convert PC module to API number 2.
api_version = 2
else:
api_version = int(api_version)
return api_version | [
"def",
"format_api_version",
"(",
"self",
",",
"api_version",
")",
":",
"# Convert to int.",
"if",
"type",
"(",
"api_version",
")",
"==",
"str",
":",
"api_version",
"=",
"api_version",
".",
"lower",
"(",
")",
"if",
"api_version",
"[",
"0",
"]",
"==",
"'v'",
"and",
"api_version",
"[",
"1",
"]",
".",
"isdigit",
"(",
")",
":",
"# Remove first 'v' in case the user typed 'v1' or 'v2', etc.",
"api_version",
"=",
"api_version",
"[",
"1",
":",
"]",
"# Check for input matching Qualys modules.",
"if",
"api_version",
"in",
"(",
"'asset management'",
",",
"'assets'",
",",
"'tag'",
",",
"'tagging'",
",",
"'tags'",
")",
":",
"# Convert to Asset Management API.",
"api_version",
"=",
"'am'",
"elif",
"api_version",
"in",
"(",
"'am2'",
")",
":",
"# Convert to Asset Management API v2",
"api_version",
"=",
"'am2'",
"elif",
"api_version",
"in",
"(",
"'webapp'",
",",
"'web application scanning'",
",",
"'webapp scanning'",
")",
":",
"# Convert to WAS API.",
"api_version",
"=",
"'was'",
"elif",
"api_version",
"in",
"(",
"'pol'",
",",
"'pc'",
")",
":",
"# Convert PC module to API number 2.",
"api_version",
"=",
"2",
"else",
":",
"api_version",
"=",
"int",
"(",
"api_version",
")",
"return",
"api_version"
] | Return QualysGuard API version for api_version specified. | [
"Return",
"QualysGuard",
"API",
"version",
"for",
"api_version",
"specified",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L72-L97 | train | 251,002 |
paragbaxi/qualysapi | qualysapi/connector.py | QGConnector.which_api_version | def which_api_version(self, api_call):
""" Return QualysGuard API version for api_call specified.
"""
# Leverage patterns of calls to API methods.
if api_call.endswith('.php'):
# API v1.
return 1
elif api_call.startswith('api/2.0/'):
# API v2.
return 2
elif '/am/' in api_call:
# Asset Management API.
return 'am'
elif '/was/' in api_call:
# WAS API.
return 'was'
return False | python | def which_api_version(self, api_call):
""" Return QualysGuard API version for api_call specified.
"""
# Leverage patterns of calls to API methods.
if api_call.endswith('.php'):
# API v1.
return 1
elif api_call.startswith('api/2.0/'):
# API v2.
return 2
elif '/am/' in api_call:
# Asset Management API.
return 'am'
elif '/was/' in api_call:
# WAS API.
return 'was'
return False | [
"def",
"which_api_version",
"(",
"self",
",",
"api_call",
")",
":",
"# Leverage patterns of calls to API methods.",
"if",
"api_call",
".",
"endswith",
"(",
"'.php'",
")",
":",
"# API v1.",
"return",
"1",
"elif",
"api_call",
".",
"startswith",
"(",
"'api/2.0/'",
")",
":",
"# API v2.",
"return",
"2",
"elif",
"'/am/'",
"in",
"api_call",
":",
"# Asset Management API.",
"return",
"'am'",
"elif",
"'/was/'",
"in",
"api_call",
":",
"# WAS API.",
"return",
"'was'",
"return",
"False"
] | Return QualysGuard API version for api_call specified. | [
"Return",
"QualysGuard",
"API",
"version",
"for",
"api_call",
"specified",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L99-L116 | train | 251,003 |
paragbaxi/qualysapi | qualysapi/connector.py | QGConnector.url_api_version | def url_api_version(self, api_version):
""" Return base API url string for the QualysGuard api_version and server.
"""
# Set base url depending on API version.
if api_version == 1:
# QualysGuard API v1 url.
url = "https://%s/msp/" % (self.server,)
elif api_version == 2:
# QualysGuard API v2 url.
url = "https://%s/" % (self.server,)
elif api_version == 'was':
# QualysGuard REST v3 API url (Portal API).
url = "https://%s/qps/rest/3.0/" % (self.server,)
elif api_version == 'am':
# QualysGuard REST v1 API url (Portal API).
url = "https://%s/qps/rest/1.0/" % (self.server,)
elif api_version == 'am2':
# QualysGuard REST v1 API url (Portal API).
url = "https://%s/qps/rest/2.0/" % (self.server,)
else:
raise Exception("Unknown QualysGuard API Version Number (%s)" % (api_version,))
logger.debug("Base url =\n%s" % (url))
return url | python | def url_api_version(self, api_version):
""" Return base API url string for the QualysGuard api_version and server.
"""
# Set base url depending on API version.
if api_version == 1:
# QualysGuard API v1 url.
url = "https://%s/msp/" % (self.server,)
elif api_version == 2:
# QualysGuard API v2 url.
url = "https://%s/" % (self.server,)
elif api_version == 'was':
# QualysGuard REST v3 API url (Portal API).
url = "https://%s/qps/rest/3.0/" % (self.server,)
elif api_version == 'am':
# QualysGuard REST v1 API url (Portal API).
url = "https://%s/qps/rest/1.0/" % (self.server,)
elif api_version == 'am2':
# QualysGuard REST v1 API url (Portal API).
url = "https://%s/qps/rest/2.0/" % (self.server,)
else:
raise Exception("Unknown QualysGuard API Version Number (%s)" % (api_version,))
logger.debug("Base url =\n%s" % (url))
return url | [
"def",
"url_api_version",
"(",
"self",
",",
"api_version",
")",
":",
"# Set base url depending on API version.",
"if",
"api_version",
"==",
"1",
":",
"# QualysGuard API v1 url.",
"url",
"=",
"\"https://%s/msp/\"",
"%",
"(",
"self",
".",
"server",
",",
")",
"elif",
"api_version",
"==",
"2",
":",
"# QualysGuard API v2 url.",
"url",
"=",
"\"https://%s/\"",
"%",
"(",
"self",
".",
"server",
",",
")",
"elif",
"api_version",
"==",
"'was'",
":",
"# QualysGuard REST v3 API url (Portal API).",
"url",
"=",
"\"https://%s/qps/rest/3.0/\"",
"%",
"(",
"self",
".",
"server",
",",
")",
"elif",
"api_version",
"==",
"'am'",
":",
"# QualysGuard REST v1 API url (Portal API).",
"url",
"=",
"\"https://%s/qps/rest/1.0/\"",
"%",
"(",
"self",
".",
"server",
",",
")",
"elif",
"api_version",
"==",
"'am2'",
":",
"# QualysGuard REST v1 API url (Portal API).",
"url",
"=",
"\"https://%s/qps/rest/2.0/\"",
"%",
"(",
"self",
".",
"server",
",",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unknown QualysGuard API Version Number (%s)\"",
"%",
"(",
"api_version",
",",
")",
")",
"logger",
".",
"debug",
"(",
"\"Base url =\\n%s\"",
"%",
"(",
"url",
")",
")",
"return",
"url"
] | Return base API url string for the QualysGuard api_version and server. | [
"Return",
"base",
"API",
"url",
"string",
"for",
"the",
"QualysGuard",
"api_version",
"and",
"server",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L118-L141 | train | 251,004 |
paragbaxi/qualysapi | qualysapi/connector.py | QGConnector.format_http_method | def format_http_method(self, api_version, api_call, data):
""" Return QualysGuard API http method, with POST preferred..
"""
# Define get methods for automatic http request methodology.
#
# All API v2 requests are POST methods.
if api_version == 2:
return 'post'
elif api_version == 1:
if api_call in self.api_methods['1 post']:
return 'post'
else:
return 'get'
elif api_version == 'was':
# WAS API call.
# Because WAS API enables user to GET API resources in URI, let's chop off the resource.
# '/download/was/report/18823' --> '/download/was/report/'
api_call_endpoint = api_call[:api_call.rfind('/') + 1]
if api_call_endpoint in self.api_methods['was get']:
return 'get'
# Post calls with no payload will result in HTTPError: 415 Client Error: Unsupported Media Type.
if data is None:
# No post data. Some calls change to GET with no post data.
if api_call_endpoint in self.api_methods['was no data get']:
return 'get'
else:
return 'post'
else:
# Call with post data.
return 'post'
else:
# Asset Management API call.
if api_call in self.api_methods['am get']:
return 'get'
else:
return 'post' | python | def format_http_method(self, api_version, api_call, data):
""" Return QualysGuard API http method, with POST preferred..
"""
# Define get methods for automatic http request methodology.
#
# All API v2 requests are POST methods.
if api_version == 2:
return 'post'
elif api_version == 1:
if api_call in self.api_methods['1 post']:
return 'post'
else:
return 'get'
elif api_version == 'was':
# WAS API call.
# Because WAS API enables user to GET API resources in URI, let's chop off the resource.
# '/download/was/report/18823' --> '/download/was/report/'
api_call_endpoint = api_call[:api_call.rfind('/') + 1]
if api_call_endpoint in self.api_methods['was get']:
return 'get'
# Post calls with no payload will result in HTTPError: 415 Client Error: Unsupported Media Type.
if data is None:
# No post data. Some calls change to GET with no post data.
if api_call_endpoint in self.api_methods['was no data get']:
return 'get'
else:
return 'post'
else:
# Call with post data.
return 'post'
else:
# Asset Management API call.
if api_call in self.api_methods['am get']:
return 'get'
else:
return 'post' | [
"def",
"format_http_method",
"(",
"self",
",",
"api_version",
",",
"api_call",
",",
"data",
")",
":",
"# Define get methods for automatic http request methodology.",
"#",
"# All API v2 requests are POST methods.",
"if",
"api_version",
"==",
"2",
":",
"return",
"'post'",
"elif",
"api_version",
"==",
"1",
":",
"if",
"api_call",
"in",
"self",
".",
"api_methods",
"[",
"'1 post'",
"]",
":",
"return",
"'post'",
"else",
":",
"return",
"'get'",
"elif",
"api_version",
"==",
"'was'",
":",
"# WAS API call.",
"# Because WAS API enables user to GET API resources in URI, let's chop off the resource.",
"# '/download/was/report/18823' --> '/download/was/report/'",
"api_call_endpoint",
"=",
"api_call",
"[",
":",
"api_call",
".",
"rfind",
"(",
"'/'",
")",
"+",
"1",
"]",
"if",
"api_call_endpoint",
"in",
"self",
".",
"api_methods",
"[",
"'was get'",
"]",
":",
"return",
"'get'",
"# Post calls with no payload will result in HTTPError: 415 Client Error: Unsupported Media Type.",
"if",
"data",
"is",
"None",
":",
"# No post data. Some calls change to GET with no post data.",
"if",
"api_call_endpoint",
"in",
"self",
".",
"api_methods",
"[",
"'was no data get'",
"]",
":",
"return",
"'get'",
"else",
":",
"return",
"'post'",
"else",
":",
"# Call with post data.",
"return",
"'post'",
"else",
":",
"# Asset Management API call.",
"if",
"api_call",
"in",
"self",
".",
"api_methods",
"[",
"'am get'",
"]",
":",
"return",
"'get'",
"else",
":",
"return",
"'post'"
] | Return QualysGuard API http method, with POST preferred.. | [
"Return",
"QualysGuard",
"API",
"http",
"method",
"with",
"POST",
"preferred",
".."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L143-L179 | train | 251,005 |
paragbaxi/qualysapi | qualysapi/connector.py | QGConnector.preformat_call | def preformat_call(self, api_call):
""" Return properly formatted QualysGuard API call.
"""
# Remove possible starting slashes or trailing question marks in call.
api_call_formatted = api_call.lstrip('/')
api_call_formatted = api_call_formatted.rstrip('?')
if api_call != api_call_formatted:
# Show difference
logger.debug('api_call post strip =\n%s' % api_call_formatted)
return api_call_formatted | python | def preformat_call(self, api_call):
""" Return properly formatted QualysGuard API call.
"""
# Remove possible starting slashes or trailing question marks in call.
api_call_formatted = api_call.lstrip('/')
api_call_formatted = api_call_formatted.rstrip('?')
if api_call != api_call_formatted:
# Show difference
logger.debug('api_call post strip =\n%s' % api_call_formatted)
return api_call_formatted | [
"def",
"preformat_call",
"(",
"self",
",",
"api_call",
")",
":",
"# Remove possible starting slashes or trailing question marks in call.",
"api_call_formatted",
"=",
"api_call",
".",
"lstrip",
"(",
"'/'",
")",
"api_call_formatted",
"=",
"api_call_formatted",
".",
"rstrip",
"(",
"'?'",
")",
"if",
"api_call",
"!=",
"api_call_formatted",
":",
"# Show difference",
"logger",
".",
"debug",
"(",
"'api_call post strip =\\n%s'",
"%",
"api_call_formatted",
")",
"return",
"api_call_formatted"
] | Return properly formatted QualysGuard API call. | [
"Return",
"properly",
"formatted",
"QualysGuard",
"API",
"call",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L181-L191 | train | 251,006 |
paragbaxi/qualysapi | qualysapi/connector.py | QGConnector.format_call | def format_call(self, api_version, api_call):
""" Return properly formatted QualysGuard API call according to api_version etiquette.
"""
# Remove possible starting slashes or trailing question marks in call.
api_call = api_call.lstrip('/')
api_call = api_call.rstrip('?')
logger.debug('api_call post strip =\n%s' % api_call)
# Make sure call always ends in slash for API v2 calls.
if (api_version == 2 and api_call[-1] != '/'):
# Add slash.
logger.debug('Adding "/" to api_call.')
api_call += '/'
if api_call in self.api_methods_with_trailing_slash[api_version]:
# Add slash.
logger.debug('Adding "/" to api_call.')
api_call += '/'
return api_call | python | def format_call(self, api_version, api_call):
""" Return properly formatted QualysGuard API call according to api_version etiquette.
"""
# Remove possible starting slashes or trailing question marks in call.
api_call = api_call.lstrip('/')
api_call = api_call.rstrip('?')
logger.debug('api_call post strip =\n%s' % api_call)
# Make sure call always ends in slash for API v2 calls.
if (api_version == 2 and api_call[-1] != '/'):
# Add slash.
logger.debug('Adding "/" to api_call.')
api_call += '/'
if api_call in self.api_methods_with_trailing_slash[api_version]:
# Add slash.
logger.debug('Adding "/" to api_call.')
api_call += '/'
return api_call | [
"def",
"format_call",
"(",
"self",
",",
"api_version",
",",
"api_call",
")",
":",
"# Remove possible starting slashes or trailing question marks in call.",
"api_call",
"=",
"api_call",
".",
"lstrip",
"(",
"'/'",
")",
"api_call",
"=",
"api_call",
".",
"rstrip",
"(",
"'?'",
")",
"logger",
".",
"debug",
"(",
"'api_call post strip =\\n%s'",
"%",
"api_call",
")",
"# Make sure call always ends in slash for API v2 calls.",
"if",
"(",
"api_version",
"==",
"2",
"and",
"api_call",
"[",
"-",
"1",
"]",
"!=",
"'/'",
")",
":",
"# Add slash.",
"logger",
".",
"debug",
"(",
"'Adding \"/\" to api_call.'",
")",
"api_call",
"+=",
"'/'",
"if",
"api_call",
"in",
"self",
".",
"api_methods_with_trailing_slash",
"[",
"api_version",
"]",
":",
"# Add slash.",
"logger",
".",
"debug",
"(",
"'Adding \"/\" to api_call.'",
")",
"api_call",
"+=",
"'/'",
"return",
"api_call"
] | Return properly formatted QualysGuard API call according to api_version etiquette. | [
"Return",
"properly",
"formatted",
"QualysGuard",
"API",
"call",
"according",
"to",
"api_version",
"etiquette",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L193-L210 | train | 251,007 |
paragbaxi/qualysapi | qualysapi/connector.py | QGConnector.format_payload | def format_payload(self, api_version, data):
""" Return appropriate QualysGuard API call.
"""
# Check if payload is for API v1 or API v2.
if (api_version in (1, 2)):
# Check if string type.
if type(data) == str:
# Convert to dictionary.
logger.debug('Converting string to dict:\n%s' % data)
# Remove possible starting question mark & ending ampersands.
data = data.lstrip('?')
data = data.rstrip('&')
# Convert to dictionary.
data = parse_qs(data)
logger.debug('Converted:\n%s' % str(data))
elif api_version in ('am', 'was', 'am2'):
if type(data) == etree._Element:
logger.debug('Converting lxml.builder.E to string')
data = etree.tostring(data)
logger.debug('Converted:\n%s' % data)
return data | python | def format_payload(self, api_version, data):
""" Return appropriate QualysGuard API call.
"""
# Check if payload is for API v1 or API v2.
if (api_version in (1, 2)):
# Check if string type.
if type(data) == str:
# Convert to dictionary.
logger.debug('Converting string to dict:\n%s' % data)
# Remove possible starting question mark & ending ampersands.
data = data.lstrip('?')
data = data.rstrip('&')
# Convert to dictionary.
data = parse_qs(data)
logger.debug('Converted:\n%s' % str(data))
elif api_version in ('am', 'was', 'am2'):
if type(data) == etree._Element:
logger.debug('Converting lxml.builder.E to string')
data = etree.tostring(data)
logger.debug('Converted:\n%s' % data)
return data | [
"def",
"format_payload",
"(",
"self",
",",
"api_version",
",",
"data",
")",
":",
"# Check if payload is for API v1 or API v2.",
"if",
"(",
"api_version",
"in",
"(",
"1",
",",
"2",
")",
")",
":",
"# Check if string type.",
"if",
"type",
"(",
"data",
")",
"==",
"str",
":",
"# Convert to dictionary.",
"logger",
".",
"debug",
"(",
"'Converting string to dict:\\n%s'",
"%",
"data",
")",
"# Remove possible starting question mark & ending ampersands.",
"data",
"=",
"data",
".",
"lstrip",
"(",
"'?'",
")",
"data",
"=",
"data",
".",
"rstrip",
"(",
"'&'",
")",
"# Convert to dictionary.",
"data",
"=",
"parse_qs",
"(",
"data",
")",
"logger",
".",
"debug",
"(",
"'Converted:\\n%s'",
"%",
"str",
"(",
"data",
")",
")",
"elif",
"api_version",
"in",
"(",
"'am'",
",",
"'was'",
",",
"'am2'",
")",
":",
"if",
"type",
"(",
"data",
")",
"==",
"etree",
".",
"_Element",
":",
"logger",
".",
"debug",
"(",
"'Converting lxml.builder.E to string'",
")",
"data",
"=",
"etree",
".",
"tostring",
"(",
"data",
")",
"logger",
".",
"debug",
"(",
"'Converted:\\n%s'",
"%",
"data",
")",
"return",
"data"
] | Return appropriate QualysGuard API call. | [
"Return",
"appropriate",
"QualysGuard",
"API",
"call",
"."
] | 2c8bf1d5d300117403062885c8e10b5665eb4615 | https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L212-L233 | train | 251,008 |
tox-dev/tox-travis | src/tox_travis/after.py | travis_after | def travis_after(ini, envlist):
"""Wait for all jobs to finish, then exit successfully."""
# after-all disabled for pull requests
if os.environ.get('TRAVIS_PULL_REQUEST', 'false') != 'false':
return
if not after_config_matches(ini, envlist):
return # This is not the one that needs to wait
github_token = os.environ.get('GITHUB_TOKEN')
if not github_token:
print('No GitHub token given.', file=sys.stderr)
sys.exit(NO_GITHUB_TOKEN)
api_url = os.environ.get('TRAVIS_API_URL', 'https://api.travis-ci.org')
build_id = os.environ.get('TRAVIS_BUILD_ID')
job_number = os.environ.get('TRAVIS_JOB_NUMBER')
try:
polling_interval = int(os.environ.get('TRAVIS_POLLING_INTERVAL', 5))
except ValueError:
print('Invalid polling interval given: {0}'.format(
repr(os.environ.get('TRAVIS_POLLING_INTERVAL'))), file=sys.stderr)
sys.exit(INVALID_POLLING_INTERVAL)
if not all([api_url, build_id, job_number]):
print('Required Travis environment not given.', file=sys.stderr)
sys.exit(INCOMPLETE_TRAVIS_ENVIRONMENT)
# This may raise an Exception, and it should be printed
job_statuses = get_job_statuses(
github_token, api_url, build_id, polling_interval, job_number)
if not all(job_statuses):
print('Some jobs were not successful.')
sys.exit(JOBS_FAILED)
print('All required jobs were successful.') | python | def travis_after(ini, envlist):
"""Wait for all jobs to finish, then exit successfully."""
# after-all disabled for pull requests
if os.environ.get('TRAVIS_PULL_REQUEST', 'false') != 'false':
return
if not after_config_matches(ini, envlist):
return # This is not the one that needs to wait
github_token = os.environ.get('GITHUB_TOKEN')
if not github_token:
print('No GitHub token given.', file=sys.stderr)
sys.exit(NO_GITHUB_TOKEN)
api_url = os.environ.get('TRAVIS_API_URL', 'https://api.travis-ci.org')
build_id = os.environ.get('TRAVIS_BUILD_ID')
job_number = os.environ.get('TRAVIS_JOB_NUMBER')
try:
polling_interval = int(os.environ.get('TRAVIS_POLLING_INTERVAL', 5))
except ValueError:
print('Invalid polling interval given: {0}'.format(
repr(os.environ.get('TRAVIS_POLLING_INTERVAL'))), file=sys.stderr)
sys.exit(INVALID_POLLING_INTERVAL)
if not all([api_url, build_id, job_number]):
print('Required Travis environment not given.', file=sys.stderr)
sys.exit(INCOMPLETE_TRAVIS_ENVIRONMENT)
# This may raise an Exception, and it should be printed
job_statuses = get_job_statuses(
github_token, api_url, build_id, polling_interval, job_number)
if not all(job_statuses):
print('Some jobs were not successful.')
sys.exit(JOBS_FAILED)
print('All required jobs were successful.') | [
"def",
"travis_after",
"(",
"ini",
",",
"envlist",
")",
":",
"# after-all disabled for pull requests",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_PULL_REQUEST'",
",",
"'false'",
")",
"!=",
"'false'",
":",
"return",
"if",
"not",
"after_config_matches",
"(",
"ini",
",",
"envlist",
")",
":",
"return",
"# This is not the one that needs to wait",
"github_token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'GITHUB_TOKEN'",
")",
"if",
"not",
"github_token",
":",
"print",
"(",
"'No GitHub token given.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"NO_GITHUB_TOKEN",
")",
"api_url",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_API_URL'",
",",
"'https://api.travis-ci.org'",
")",
"build_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_BUILD_ID'",
")",
"job_number",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_JOB_NUMBER'",
")",
"try",
":",
"polling_interval",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_POLLING_INTERVAL'",
",",
"5",
")",
")",
"except",
"ValueError",
":",
"print",
"(",
"'Invalid polling interval given: {0}'",
".",
"format",
"(",
"repr",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_POLLING_INTERVAL'",
")",
")",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"INVALID_POLLING_INTERVAL",
")",
"if",
"not",
"all",
"(",
"[",
"api_url",
",",
"build_id",
",",
"job_number",
"]",
")",
":",
"print",
"(",
"'Required Travis environment not given.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"INCOMPLETE_TRAVIS_ENVIRONMENT",
")",
"# This may raise an Exception, and it should be printed",
"job_statuses",
"=",
"get_job_statuses",
"(",
"github_token",
",",
"api_url",
",",
"build_id",
",",
"polling_interval",
",",
"job_number",
")",
"if",
"not",
"all",
"(",
"job_statuses",
")",
":",
"print",
"(",
"'Some jobs were not successful.'",
")",
"sys",
".",
"exit",
"(",
"JOBS_FAILED",
")",
"print",
"(",
"'All required jobs were successful.'",
")"
] | Wait for all jobs to finish, then exit successfully. | [
"Wait",
"for",
"all",
"jobs",
"to",
"finish",
"then",
"exit",
"successfully",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L25-L62 | train | 251,009 |
tox-dev/tox-travis | src/tox_travis/after.py | after_config_matches | def after_config_matches(ini, envlist):
"""Determine if this job should wait for the others."""
section = ini.sections.get('travis:after', {})
if not section:
return False # Never wait if it's not configured
if 'envlist' in section or 'toxenv' in section:
if 'toxenv' in section:
print('The "toxenv" key of the [travis:after] section is '
'deprecated in favor of the "envlist" key.', file=sys.stderr)
toxenv = section.get('toxenv')
required = set(split_env(section.get('envlist', toxenv) or ''))
actual = set(envlist)
if required - actual:
return False
# Translate travis requirements to env requirements
env_requirements = [
(TRAVIS_FACTORS[factor], value) for factor, value
in parse_dict(section.get('travis', '')).items()
if factor in TRAVIS_FACTORS
] + [
(name, value) for name, value
in parse_dict(section.get('env', '')).items()
]
return all([
os.environ.get(name) == value
for name, value in env_requirements
]) | python | def after_config_matches(ini, envlist):
"""Determine if this job should wait for the others."""
section = ini.sections.get('travis:after', {})
if not section:
return False # Never wait if it's not configured
if 'envlist' in section or 'toxenv' in section:
if 'toxenv' in section:
print('The "toxenv" key of the [travis:after] section is '
'deprecated in favor of the "envlist" key.', file=sys.stderr)
toxenv = section.get('toxenv')
required = set(split_env(section.get('envlist', toxenv) or ''))
actual = set(envlist)
if required - actual:
return False
# Translate travis requirements to env requirements
env_requirements = [
(TRAVIS_FACTORS[factor], value) for factor, value
in parse_dict(section.get('travis', '')).items()
if factor in TRAVIS_FACTORS
] + [
(name, value) for name, value
in parse_dict(section.get('env', '')).items()
]
return all([
os.environ.get(name) == value
for name, value in env_requirements
]) | [
"def",
"after_config_matches",
"(",
"ini",
",",
"envlist",
")",
":",
"section",
"=",
"ini",
".",
"sections",
".",
"get",
"(",
"'travis:after'",
",",
"{",
"}",
")",
"if",
"not",
"section",
":",
"return",
"False",
"# Never wait if it's not configured",
"if",
"'envlist'",
"in",
"section",
"or",
"'toxenv'",
"in",
"section",
":",
"if",
"'toxenv'",
"in",
"section",
":",
"print",
"(",
"'The \"toxenv\" key of the [travis:after] section is '",
"'deprecated in favor of the \"envlist\" key.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"toxenv",
"=",
"section",
".",
"get",
"(",
"'toxenv'",
")",
"required",
"=",
"set",
"(",
"split_env",
"(",
"section",
".",
"get",
"(",
"'envlist'",
",",
"toxenv",
")",
"or",
"''",
")",
")",
"actual",
"=",
"set",
"(",
"envlist",
")",
"if",
"required",
"-",
"actual",
":",
"return",
"False",
"# Translate travis requirements to env requirements",
"env_requirements",
"=",
"[",
"(",
"TRAVIS_FACTORS",
"[",
"factor",
"]",
",",
"value",
")",
"for",
"factor",
",",
"value",
"in",
"parse_dict",
"(",
"section",
".",
"get",
"(",
"'travis'",
",",
"''",
")",
")",
".",
"items",
"(",
")",
"if",
"factor",
"in",
"TRAVIS_FACTORS",
"]",
"+",
"[",
"(",
"name",
",",
"value",
")",
"for",
"name",
",",
"value",
"in",
"parse_dict",
"(",
"section",
".",
"get",
"(",
"'env'",
",",
"''",
")",
")",
".",
"items",
"(",
")",
"]",
"return",
"all",
"(",
"[",
"os",
".",
"environ",
".",
"get",
"(",
"name",
")",
"==",
"value",
"for",
"name",
",",
"value",
"in",
"env_requirements",
"]",
")"
] | Determine if this job should wait for the others. | [
"Determine",
"if",
"this",
"job",
"should",
"wait",
"for",
"the",
"others",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L65-L96 | train | 251,010 |
tox-dev/tox-travis | src/tox_travis/after.py | get_job_statuses | def get_job_statuses(github_token, api_url, build_id,
polling_interval, job_number):
"""Wait for all the travis jobs to complete.
Once the other jobs are complete, return a list of booleans,
indicating whether or not the job was successful. Ignore jobs
marked "allow_failure".
"""
auth = get_json('{api_url}/auth/github'.format(api_url=api_url),
data={'github_token': github_token})['access_token']
while True:
build = get_json('{api_url}/builds/{build_id}'.format(
api_url=api_url, build_id=build_id), auth=auth)
jobs = [job for job in build['jobs']
if job['number'] != job_number and
not job['allow_failure']] # Ignore allowed failures
if all(job['finished_at'] for job in jobs):
break # All the jobs have completed
elif any(job['state'] != 'passed'
for job in jobs if job['finished_at']):
break # Some required job that finished did not pass
print('Waiting for jobs to complete: {job_numbers}'.format(
job_numbers=[job['number'] for job in jobs
if not job['finished_at']]))
time.sleep(polling_interval)
return [job['state'] == 'passed' for job in jobs] | python | def get_job_statuses(github_token, api_url, build_id,
polling_interval, job_number):
"""Wait for all the travis jobs to complete.
Once the other jobs are complete, return a list of booleans,
indicating whether or not the job was successful. Ignore jobs
marked "allow_failure".
"""
auth = get_json('{api_url}/auth/github'.format(api_url=api_url),
data={'github_token': github_token})['access_token']
while True:
build = get_json('{api_url}/builds/{build_id}'.format(
api_url=api_url, build_id=build_id), auth=auth)
jobs = [job for job in build['jobs']
if job['number'] != job_number and
not job['allow_failure']] # Ignore allowed failures
if all(job['finished_at'] for job in jobs):
break # All the jobs have completed
elif any(job['state'] != 'passed'
for job in jobs if job['finished_at']):
break # Some required job that finished did not pass
print('Waiting for jobs to complete: {job_numbers}'.format(
job_numbers=[job['number'] for job in jobs
if not job['finished_at']]))
time.sleep(polling_interval)
return [job['state'] == 'passed' for job in jobs] | [
"def",
"get_job_statuses",
"(",
"github_token",
",",
"api_url",
",",
"build_id",
",",
"polling_interval",
",",
"job_number",
")",
":",
"auth",
"=",
"get_json",
"(",
"'{api_url}/auth/github'",
".",
"format",
"(",
"api_url",
"=",
"api_url",
")",
",",
"data",
"=",
"{",
"'github_token'",
":",
"github_token",
"}",
")",
"[",
"'access_token'",
"]",
"while",
"True",
":",
"build",
"=",
"get_json",
"(",
"'{api_url}/builds/{build_id}'",
".",
"format",
"(",
"api_url",
"=",
"api_url",
",",
"build_id",
"=",
"build_id",
")",
",",
"auth",
"=",
"auth",
")",
"jobs",
"=",
"[",
"job",
"for",
"job",
"in",
"build",
"[",
"'jobs'",
"]",
"if",
"job",
"[",
"'number'",
"]",
"!=",
"job_number",
"and",
"not",
"job",
"[",
"'allow_failure'",
"]",
"]",
"# Ignore allowed failures",
"if",
"all",
"(",
"job",
"[",
"'finished_at'",
"]",
"for",
"job",
"in",
"jobs",
")",
":",
"break",
"# All the jobs have completed",
"elif",
"any",
"(",
"job",
"[",
"'state'",
"]",
"!=",
"'passed'",
"for",
"job",
"in",
"jobs",
"if",
"job",
"[",
"'finished_at'",
"]",
")",
":",
"break",
"# Some required job that finished did not pass",
"print",
"(",
"'Waiting for jobs to complete: {job_numbers}'",
".",
"format",
"(",
"job_numbers",
"=",
"[",
"job",
"[",
"'number'",
"]",
"for",
"job",
"in",
"jobs",
"if",
"not",
"job",
"[",
"'finished_at'",
"]",
"]",
")",
")",
"time",
".",
"sleep",
"(",
"polling_interval",
")",
"return",
"[",
"job",
"[",
"'state'",
"]",
"==",
"'passed'",
"for",
"job",
"in",
"jobs",
"]"
] | Wait for all the travis jobs to complete.
Once the other jobs are complete, return a list of booleans,
indicating whether or not the job was successful. Ignore jobs
marked "allow_failure". | [
"Wait",
"for",
"all",
"the",
"travis",
"jobs",
"to",
"complete",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L99-L127 | train | 251,011 |
tox-dev/tox-travis | src/tox_travis/after.py | get_json | def get_json(url, auth=None, data=None):
"""Make a GET request, and return the response as parsed JSON."""
headers = {
'Accept': 'application/vnd.travis-ci.2+json',
'User-Agent': 'Travis/Tox-Travis-1.0a',
# User-Agent must start with "Travis/" in order to work
}
if auth:
headers['Authorization'] = 'token {auth}'.format(auth=auth)
params = {}
if data:
headers['Content-Type'] = 'application/json'
params['data'] = json.dumps(data).encode('utf-8')
request = urllib2.Request(url, headers=headers, **params)
response = urllib2.urlopen(request).read()
return json.loads(response.decode('utf-8')) | python | def get_json(url, auth=None, data=None):
"""Make a GET request, and return the response as parsed JSON."""
headers = {
'Accept': 'application/vnd.travis-ci.2+json',
'User-Agent': 'Travis/Tox-Travis-1.0a',
# User-Agent must start with "Travis/" in order to work
}
if auth:
headers['Authorization'] = 'token {auth}'.format(auth=auth)
params = {}
if data:
headers['Content-Type'] = 'application/json'
params['data'] = json.dumps(data).encode('utf-8')
request = urllib2.Request(url, headers=headers, **params)
response = urllib2.urlopen(request).read()
return json.loads(response.decode('utf-8')) | [
"def",
"get_json",
"(",
"url",
",",
"auth",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/vnd.travis-ci.2+json'",
",",
"'User-Agent'",
":",
"'Travis/Tox-Travis-1.0a'",
",",
"# User-Agent must start with \"Travis/\" in order to work",
"}",
"if",
"auth",
":",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'token {auth}'",
".",
"format",
"(",
"auth",
"=",
"auth",
")",
"params",
"=",
"{",
"}",
"if",
"data",
":",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"params",
"[",
"'data'",
"]",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"params",
")",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"request",
")",
".",
"read",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] | Make a GET request, and return the response as parsed JSON. | [
"Make",
"a",
"GET",
"request",
"and",
"return",
"the",
"response",
"as",
"parsed",
"JSON",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L130-L147 | train | 251,012 |
tox-dev/tox-travis | src/tox_travis/envlist.py | detect_envlist | def detect_envlist(ini):
"""Default envlist automatically based on the Travis environment."""
# Find the envs that tox knows about
declared_envs = get_declared_envs(ini)
# Find all the envs for all the desired factors given
desired_factors = get_desired_factors(ini)
# Reduce desired factors
desired_envs = ['-'.join(env) for env in product(*desired_factors)]
# Find matching envs
return match_envs(declared_envs, desired_envs,
passthru=len(desired_factors) == 1) | python | def detect_envlist(ini):
"""Default envlist automatically based on the Travis environment."""
# Find the envs that tox knows about
declared_envs = get_declared_envs(ini)
# Find all the envs for all the desired factors given
desired_factors = get_desired_factors(ini)
# Reduce desired factors
desired_envs = ['-'.join(env) for env in product(*desired_factors)]
# Find matching envs
return match_envs(declared_envs, desired_envs,
passthru=len(desired_factors) == 1) | [
"def",
"detect_envlist",
"(",
"ini",
")",
":",
"# Find the envs that tox knows about",
"declared_envs",
"=",
"get_declared_envs",
"(",
"ini",
")",
"# Find all the envs for all the desired factors given",
"desired_factors",
"=",
"get_desired_factors",
"(",
"ini",
")",
"# Reduce desired factors",
"desired_envs",
"=",
"[",
"'-'",
".",
"join",
"(",
"env",
")",
"for",
"env",
"in",
"product",
"(",
"*",
"desired_factors",
")",
"]",
"# Find matching envs",
"return",
"match_envs",
"(",
"declared_envs",
",",
"desired_envs",
",",
"passthru",
"=",
"len",
"(",
"desired_factors",
")",
"==",
"1",
")"
] | Default envlist automatically based on the Travis environment. | [
"Default",
"envlist",
"automatically",
"based",
"on",
"the",
"Travis",
"environment",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L14-L27 | train | 251,013 |
tox-dev/tox-travis | src/tox_travis/envlist.py | autogen_envconfigs | def autogen_envconfigs(config, envs):
"""Make the envconfigs for undeclared envs.
This is a stripped-down version of parseini.__init__ made for making
an envconfig.
"""
prefix = 'tox' if config.toxinipath.basename == 'setup.cfg' else None
reader = tox.config.SectionReader("tox", config._cfg, prefix=prefix)
distshare_default = "{homedir}/.tox/distshare"
reader.addsubstitutions(toxinidir=config.toxinidir,
homedir=config.homedir)
reader.addsubstitutions(toxworkdir=config.toxworkdir)
config.distdir = reader.getpath("distdir", "{toxworkdir}/dist")
reader.addsubstitutions(distdir=config.distdir)
config.distshare = reader.getpath("distshare", distshare_default)
reader.addsubstitutions(distshare=config.distshare)
try:
make_envconfig = tox.config.ParseIni.make_envconfig # tox 3.4.0+
except AttributeError:
make_envconfig = tox.config.parseini.make_envconfig
# Dig past the unbound method in Python 2
make_envconfig = getattr(make_envconfig, '__func__', make_envconfig)
# Create the undeclared envs
for env in envs:
section = tox.config.testenvprefix + env
config.envconfigs[env] = make_envconfig(
config, env, section, reader._subs, config) | python | def autogen_envconfigs(config, envs):
"""Make the envconfigs for undeclared envs.
This is a stripped-down version of parseini.__init__ made for making
an envconfig.
"""
prefix = 'tox' if config.toxinipath.basename == 'setup.cfg' else None
reader = tox.config.SectionReader("tox", config._cfg, prefix=prefix)
distshare_default = "{homedir}/.tox/distshare"
reader.addsubstitutions(toxinidir=config.toxinidir,
homedir=config.homedir)
reader.addsubstitutions(toxworkdir=config.toxworkdir)
config.distdir = reader.getpath("distdir", "{toxworkdir}/dist")
reader.addsubstitutions(distdir=config.distdir)
config.distshare = reader.getpath("distshare", distshare_default)
reader.addsubstitutions(distshare=config.distshare)
try:
make_envconfig = tox.config.ParseIni.make_envconfig # tox 3.4.0+
except AttributeError:
make_envconfig = tox.config.parseini.make_envconfig
# Dig past the unbound method in Python 2
make_envconfig = getattr(make_envconfig, '__func__', make_envconfig)
# Create the undeclared envs
for env in envs:
section = tox.config.testenvprefix + env
config.envconfigs[env] = make_envconfig(
config, env, section, reader._subs, config) | [
"def",
"autogen_envconfigs",
"(",
"config",
",",
"envs",
")",
":",
"prefix",
"=",
"'tox'",
"if",
"config",
".",
"toxinipath",
".",
"basename",
"==",
"'setup.cfg'",
"else",
"None",
"reader",
"=",
"tox",
".",
"config",
".",
"SectionReader",
"(",
"\"tox\"",
",",
"config",
".",
"_cfg",
",",
"prefix",
"=",
"prefix",
")",
"distshare_default",
"=",
"\"{homedir}/.tox/distshare\"",
"reader",
".",
"addsubstitutions",
"(",
"toxinidir",
"=",
"config",
".",
"toxinidir",
",",
"homedir",
"=",
"config",
".",
"homedir",
")",
"reader",
".",
"addsubstitutions",
"(",
"toxworkdir",
"=",
"config",
".",
"toxworkdir",
")",
"config",
".",
"distdir",
"=",
"reader",
".",
"getpath",
"(",
"\"distdir\"",
",",
"\"{toxworkdir}/dist\"",
")",
"reader",
".",
"addsubstitutions",
"(",
"distdir",
"=",
"config",
".",
"distdir",
")",
"config",
".",
"distshare",
"=",
"reader",
".",
"getpath",
"(",
"\"distshare\"",
",",
"distshare_default",
")",
"reader",
".",
"addsubstitutions",
"(",
"distshare",
"=",
"config",
".",
"distshare",
")",
"try",
":",
"make_envconfig",
"=",
"tox",
".",
"config",
".",
"ParseIni",
".",
"make_envconfig",
"# tox 3.4.0+",
"except",
"AttributeError",
":",
"make_envconfig",
"=",
"tox",
".",
"config",
".",
"parseini",
".",
"make_envconfig",
"# Dig past the unbound method in Python 2",
"make_envconfig",
"=",
"getattr",
"(",
"make_envconfig",
",",
"'__func__'",
",",
"make_envconfig",
")",
"# Create the undeclared envs",
"for",
"env",
"in",
"envs",
":",
"section",
"=",
"tox",
".",
"config",
".",
"testenvprefix",
"+",
"env",
"config",
".",
"envconfigs",
"[",
"env",
"]",
"=",
"make_envconfig",
"(",
"config",
",",
"env",
",",
"section",
",",
"reader",
".",
"_subs",
",",
"config",
")"
] | Make the envconfigs for undeclared envs.
This is a stripped-down version of parseini.__init__ made for making
an envconfig. | [
"Make",
"the",
"envconfigs",
"for",
"undeclared",
"envs",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L30-L59 | train | 251,014 |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_declared_envs | def get_declared_envs(ini):
"""Get the full list of envs from the tox ini.
This notably also includes envs that aren't in the envlist,
but are declared by having their own testenv:envname section.
The envs are expected in a particular order. First the ones
declared in the envlist, then the other testenvs in order.
"""
tox_section_name = 'tox:tox' if ini.path.endswith('setup.cfg') else 'tox'
tox_section = ini.sections.get(tox_section_name, {})
envlist = split_env(tox_section.get('envlist', []))
# Add additional envs that are declared as sections in the ini
section_envs = [
section[8:] for section in sorted(ini.sections, key=ini.lineof)
if section.startswith('testenv:')
]
return envlist + [env for env in section_envs if env not in envlist] | python | def get_declared_envs(ini):
"""Get the full list of envs from the tox ini.
This notably also includes envs that aren't in the envlist,
but are declared by having their own testenv:envname section.
The envs are expected in a particular order. First the ones
declared in the envlist, then the other testenvs in order.
"""
tox_section_name = 'tox:tox' if ini.path.endswith('setup.cfg') else 'tox'
tox_section = ini.sections.get(tox_section_name, {})
envlist = split_env(tox_section.get('envlist', []))
# Add additional envs that are declared as sections in the ini
section_envs = [
section[8:] for section in sorted(ini.sections, key=ini.lineof)
if section.startswith('testenv:')
]
return envlist + [env for env in section_envs if env not in envlist] | [
"def",
"get_declared_envs",
"(",
"ini",
")",
":",
"tox_section_name",
"=",
"'tox:tox'",
"if",
"ini",
".",
"path",
".",
"endswith",
"(",
"'setup.cfg'",
")",
"else",
"'tox'",
"tox_section",
"=",
"ini",
".",
"sections",
".",
"get",
"(",
"tox_section_name",
",",
"{",
"}",
")",
"envlist",
"=",
"split_env",
"(",
"tox_section",
".",
"get",
"(",
"'envlist'",
",",
"[",
"]",
")",
")",
"# Add additional envs that are declared as sections in the ini",
"section_envs",
"=",
"[",
"section",
"[",
"8",
":",
"]",
"for",
"section",
"in",
"sorted",
"(",
"ini",
".",
"sections",
",",
"key",
"=",
"ini",
".",
"lineof",
")",
"if",
"section",
".",
"startswith",
"(",
"'testenv:'",
")",
"]",
"return",
"envlist",
"+",
"[",
"env",
"for",
"env",
"in",
"section_envs",
"if",
"env",
"not",
"in",
"envlist",
"]"
] | Get the full list of envs from the tox ini.
This notably also includes envs that aren't in the envlist,
but are declared by having their own testenv:envname section.
The envs are expected in a particular order. First the ones
declared in the envlist, then the other testenvs in order. | [
"Get",
"the",
"full",
"list",
"of",
"envs",
"from",
"the",
"tox",
"ini",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L62-L81 | train | 251,015 |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_version_info | def get_version_info():
"""Get version info from the sys module.
Override from environment for testing.
"""
overrides = os.environ.get('__TOX_TRAVIS_SYS_VERSION')
if overrides:
version, major, minor = overrides.split(',')[:3]
major, minor = int(major), int(minor)
else:
version, (major, minor) = sys.version, sys.version_info[:2]
return version, major, minor | python | def get_version_info():
"""Get version info from the sys module.
Override from environment for testing.
"""
overrides = os.environ.get('__TOX_TRAVIS_SYS_VERSION')
if overrides:
version, major, minor = overrides.split(',')[:3]
major, minor = int(major), int(minor)
else:
version, (major, minor) = sys.version, sys.version_info[:2]
return version, major, minor | [
"def",
"get_version_info",
"(",
")",
":",
"overrides",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'__TOX_TRAVIS_SYS_VERSION'",
")",
"if",
"overrides",
":",
"version",
",",
"major",
",",
"minor",
"=",
"overrides",
".",
"split",
"(",
"','",
")",
"[",
":",
"3",
"]",
"major",
",",
"minor",
"=",
"int",
"(",
"major",
")",
",",
"int",
"(",
"minor",
")",
"else",
":",
"version",
",",
"(",
"major",
",",
"minor",
")",
"=",
"sys",
".",
"version",
",",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
"return",
"version",
",",
"major",
",",
"minor"
] | Get version info from the sys module.
Override from environment for testing. | [
"Get",
"version",
"info",
"from",
"the",
"sys",
"module",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L84-L95 | train | 251,016 |
tox-dev/tox-travis | src/tox_travis/envlist.py | guess_python_env | def guess_python_env():
"""Guess the default python env to use."""
version, major, minor = get_version_info()
if 'PyPy' in version:
return 'pypy3' if major == 3 else 'pypy'
return 'py{major}{minor}'.format(major=major, minor=minor) | python | def guess_python_env():
"""Guess the default python env to use."""
version, major, minor = get_version_info()
if 'PyPy' in version:
return 'pypy3' if major == 3 else 'pypy'
return 'py{major}{minor}'.format(major=major, minor=minor) | [
"def",
"guess_python_env",
"(",
")",
":",
"version",
",",
"major",
",",
"minor",
"=",
"get_version_info",
"(",
")",
"if",
"'PyPy'",
"in",
"version",
":",
"return",
"'pypy3'",
"if",
"major",
"==",
"3",
"else",
"'pypy'",
"return",
"'py{major}{minor}'",
".",
"format",
"(",
"major",
"=",
"major",
",",
"minor",
"=",
"minor",
")"
] | Guess the default python env to use. | [
"Guess",
"the",
"default",
"python",
"env",
"to",
"use",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L98-L103 | train | 251,017 |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_default_envlist | def get_default_envlist(version):
"""Parse a default tox env based on the version.
The version comes from the ``TRAVIS_PYTHON_VERSION`` environment
variable. If that isn't set or is invalid, then use
sys.version_info to come up with a reasonable default.
"""
if version in ['pypy', 'pypy3']:
return version
# Assume single digit major and minor versions
match = re.match(r'^(\d)\.(\d)(?:\.\d+)?$', version or '')
if match:
major, minor = match.groups()
return 'py{major}{minor}'.format(major=major, minor=minor)
return guess_python_env() | python | def get_default_envlist(version):
"""Parse a default tox env based on the version.
The version comes from the ``TRAVIS_PYTHON_VERSION`` environment
variable. If that isn't set or is invalid, then use
sys.version_info to come up with a reasonable default.
"""
if version in ['pypy', 'pypy3']:
return version
# Assume single digit major and minor versions
match = re.match(r'^(\d)\.(\d)(?:\.\d+)?$', version or '')
if match:
major, minor = match.groups()
return 'py{major}{minor}'.format(major=major, minor=minor)
return guess_python_env() | [
"def",
"get_default_envlist",
"(",
"version",
")",
":",
"if",
"version",
"in",
"[",
"'pypy'",
",",
"'pypy3'",
"]",
":",
"return",
"version",
"# Assume single digit major and minor versions",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(\\d)\\.(\\d)(?:\\.\\d+)?$'",
",",
"version",
"or",
"''",
")",
"if",
"match",
":",
"major",
",",
"minor",
"=",
"match",
".",
"groups",
"(",
")",
"return",
"'py{major}{minor}'",
".",
"format",
"(",
"major",
"=",
"major",
",",
"minor",
"=",
"minor",
")",
"return",
"guess_python_env",
"(",
")"
] | Parse a default tox env based on the version.
The version comes from the ``TRAVIS_PYTHON_VERSION`` environment
variable. If that isn't set or is invalid, then use
sys.version_info to come up with a reasonable default. | [
"Parse",
"a",
"default",
"tox",
"env",
"based",
"on",
"the",
"version",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L106-L122 | train | 251,018 |
tox-dev/tox-travis | src/tox_travis/envlist.py | get_desired_factors | def get_desired_factors(ini):
"""Get the list of desired envs per declared factor.
Look at all the accepted configuration locations, and give a list
of envlists, one for each Travis factor found.
Look in the ``[travis]`` section for the known Travis factors,
which are backed by environment variable checking behind the
scenes, but provide a cleaner interface.
Also look for the ``[tox:travis]`` section, which is deprecated,
and treat it as an additional ``python`` key from the ``[travis]``
section.
Finally, look for factors based directly on environment variables,
listed in the ``[travis:env]`` section. Configuration found in the
``[travis]`` and ``[tox:travis]`` sections are converted to this
form under the hood, and are considered in the same way.
Special consideration is given to the ``python`` factor. If this
factor is set in the environment, then an appropriate configuration
will be provided automatically if no manual configuration is
provided.
To allow for the most flexible processing, the envlists provided
by each factor are not combined after they are selected, but
instead returned as a list of envlists, and expected to be
combined as and when appropriate by the caller. This allows for
special handling based on the number of factors that were found
to apply to this environment.
"""
# Find configuration based on known travis factors
travis_section = ini.sections.get('travis', {})
found_factors = [
(factor, parse_dict(travis_section[factor]))
for factor in TRAVIS_FACTORS
if factor in travis_section
]
# Backward compatibility with the old tox:travis section
if 'tox:travis' in ini.sections:
print('The [tox:travis] section is deprecated in favor of'
' the "python" key of the [travis] section.', file=sys.stderr)
found_factors.append(('python', ini.sections['tox:travis']))
# Inject any needed autoenv
version = os.environ.get('TRAVIS_PYTHON_VERSION')
if version:
default_envlist = get_default_envlist(version)
if not any(factor == 'python' for factor, _ in found_factors):
found_factors.insert(0, ('python', {version: default_envlist}))
python_factors = [(factor, mapping)
for factor, mapping in found_factors
if version and factor == 'python']
for _, mapping in python_factors:
mapping.setdefault(version, default_envlist)
# Convert known travis factors to env factors,
# and combine with declared env factors.
env_factors = [
(TRAVIS_FACTORS[factor], mapping)
for factor, mapping in found_factors
] + [
(name, parse_dict(value))
for name, value in ini.sections.get('travis:env', {}).items()
]
# Choose the correct envlists based on the factor values
return [
split_env(mapping[os.environ[name]])
for name, mapping in env_factors
if name in os.environ and os.environ[name] in mapping
] | python | def get_desired_factors(ini):
"""Get the list of desired envs per declared factor.
Look at all the accepted configuration locations, and give a list
of envlists, one for each Travis factor found.
Look in the ``[travis]`` section for the known Travis factors,
which are backed by environment variable checking behind the
scenes, but provide a cleaner interface.
Also look for the ``[tox:travis]`` section, which is deprecated,
and treat it as an additional ``python`` key from the ``[travis]``
section.
Finally, look for factors based directly on environment variables,
listed in the ``[travis:env]`` section. Configuration found in the
``[travis]`` and ``[tox:travis]`` sections are converted to this
form under the hood, and are considered in the same way.
Special consideration is given to the ``python`` factor. If this
factor is set in the environment, then an appropriate configuration
will be provided automatically if no manual configuration is
provided.
To allow for the most flexible processing, the envlists provided
by each factor are not combined after they are selected, but
instead returned as a list of envlists, and expected to be
combined as and when appropriate by the caller. This allows for
special handling based on the number of factors that were found
to apply to this environment.
"""
# Find configuration based on known travis factors
travis_section = ini.sections.get('travis', {})
found_factors = [
(factor, parse_dict(travis_section[factor]))
for factor in TRAVIS_FACTORS
if factor in travis_section
]
# Backward compatibility with the old tox:travis section
if 'tox:travis' in ini.sections:
print('The [tox:travis] section is deprecated in favor of'
' the "python" key of the [travis] section.', file=sys.stderr)
found_factors.append(('python', ini.sections['tox:travis']))
# Inject any needed autoenv
version = os.environ.get('TRAVIS_PYTHON_VERSION')
if version:
default_envlist = get_default_envlist(version)
if not any(factor == 'python' for factor, _ in found_factors):
found_factors.insert(0, ('python', {version: default_envlist}))
python_factors = [(factor, mapping)
for factor, mapping in found_factors
if version and factor == 'python']
for _, mapping in python_factors:
mapping.setdefault(version, default_envlist)
# Convert known travis factors to env factors,
# and combine with declared env factors.
env_factors = [
(TRAVIS_FACTORS[factor], mapping)
for factor, mapping in found_factors
] + [
(name, parse_dict(value))
for name, value in ini.sections.get('travis:env', {}).items()
]
# Choose the correct envlists based on the factor values
return [
split_env(mapping[os.environ[name]])
for name, mapping in env_factors
if name in os.environ and os.environ[name] in mapping
] | [
"def",
"get_desired_factors",
"(",
"ini",
")",
":",
"# Find configuration based on known travis factors",
"travis_section",
"=",
"ini",
".",
"sections",
".",
"get",
"(",
"'travis'",
",",
"{",
"}",
")",
"found_factors",
"=",
"[",
"(",
"factor",
",",
"parse_dict",
"(",
"travis_section",
"[",
"factor",
"]",
")",
")",
"for",
"factor",
"in",
"TRAVIS_FACTORS",
"if",
"factor",
"in",
"travis_section",
"]",
"# Backward compatibility with the old tox:travis section",
"if",
"'tox:travis'",
"in",
"ini",
".",
"sections",
":",
"print",
"(",
"'The [tox:travis] section is deprecated in favor of'",
"' the \"python\" key of the [travis] section.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"found_factors",
".",
"append",
"(",
"(",
"'python'",
",",
"ini",
".",
"sections",
"[",
"'tox:travis'",
"]",
")",
")",
"# Inject any needed autoenv",
"version",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_PYTHON_VERSION'",
")",
"if",
"version",
":",
"default_envlist",
"=",
"get_default_envlist",
"(",
"version",
")",
"if",
"not",
"any",
"(",
"factor",
"==",
"'python'",
"for",
"factor",
",",
"_",
"in",
"found_factors",
")",
":",
"found_factors",
".",
"insert",
"(",
"0",
",",
"(",
"'python'",
",",
"{",
"version",
":",
"default_envlist",
"}",
")",
")",
"python_factors",
"=",
"[",
"(",
"factor",
",",
"mapping",
")",
"for",
"factor",
",",
"mapping",
"in",
"found_factors",
"if",
"version",
"and",
"factor",
"==",
"'python'",
"]",
"for",
"_",
",",
"mapping",
"in",
"python_factors",
":",
"mapping",
".",
"setdefault",
"(",
"version",
",",
"default_envlist",
")",
"# Convert known travis factors to env factors,",
"# and combine with declared env factors.",
"env_factors",
"=",
"[",
"(",
"TRAVIS_FACTORS",
"[",
"factor",
"]",
",",
"mapping",
")",
"for",
"factor",
",",
"mapping",
"in",
"found_factors",
"]",
"+",
"[",
"(",
"name",
",",
"parse_dict",
"(",
"value",
")",
")",
"for",
"name",
",",
"value",
"in",
"ini",
".",
"sections",
".",
"get",
"(",
"'travis:env'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
"]",
"# Choose the correct envlists based on the factor values",
"return",
"[",
"split_env",
"(",
"mapping",
"[",
"os",
".",
"environ",
"[",
"name",
"]",
"]",
")",
"for",
"name",
",",
"mapping",
"in",
"env_factors",
"if",
"name",
"in",
"os",
".",
"environ",
"and",
"os",
".",
"environ",
"[",
"name",
"]",
"in",
"mapping",
"]"
] | Get the list of desired envs per declared factor.
Look at all the accepted configuration locations, and give a list
of envlists, one for each Travis factor found.
Look in the ``[travis]`` section for the known Travis factors,
which are backed by environment variable checking behind the
scenes, but provide a cleaner interface.
Also look for the ``[tox:travis]`` section, which is deprecated,
and treat it as an additional ``python`` key from the ``[travis]``
section.
Finally, look for factors based directly on environment variables,
listed in the ``[travis:env]`` section. Configuration found in the
``[travis]`` and ``[tox:travis]`` sections are converted to this
form under the hood, and are considered in the same way.
Special consideration is given to the ``python`` factor. If this
factor is set in the environment, then an appropriate configuration
will be provided automatically if no manual configuration is
provided.
To allow for the most flexible processing, the envlists provided
by each factor are not combined after they are selected, but
instead returned as a list of envlists, and expected to be
combined as and when appropriate by the caller. This allows for
special handling based on the number of factors that were found
to apply to this environment. | [
"Get",
"the",
"list",
"of",
"desired",
"envs",
"per",
"declared",
"factor",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L125-L197 | train | 251,019 |
tox-dev/tox-travis | src/tox_travis/envlist.py | match_envs | def match_envs(declared_envs, desired_envs, passthru):
"""Determine the envs that match the desired_envs.
If ``passthru` is True, and none of the declared envs match the
desired envs, then the desired envs will be used verbatim.
:param declared_envs: The envs that are declared in the tox config.
:param desired_envs: The envs desired from the tox-travis config.
:param bool passthru: Whether to used the ``desired_envs`` as a
fallback if no declared envs match.
"""
matched = [
declared for declared in declared_envs
if any(env_matches(declared, desired) for desired in desired_envs)
]
return desired_envs if not matched and passthru else matched | python | def match_envs(declared_envs, desired_envs, passthru):
"""Determine the envs that match the desired_envs.
If ``passthru` is True, and none of the declared envs match the
desired envs, then the desired envs will be used verbatim.
:param declared_envs: The envs that are declared in the tox config.
:param desired_envs: The envs desired from the tox-travis config.
:param bool passthru: Whether to used the ``desired_envs`` as a
fallback if no declared envs match.
"""
matched = [
declared for declared in declared_envs
if any(env_matches(declared, desired) for desired in desired_envs)
]
return desired_envs if not matched and passthru else matched | [
"def",
"match_envs",
"(",
"declared_envs",
",",
"desired_envs",
",",
"passthru",
")",
":",
"matched",
"=",
"[",
"declared",
"for",
"declared",
"in",
"declared_envs",
"if",
"any",
"(",
"env_matches",
"(",
"declared",
",",
"desired",
")",
"for",
"desired",
"in",
"desired_envs",
")",
"]",
"return",
"desired_envs",
"if",
"not",
"matched",
"and",
"passthru",
"else",
"matched"
] | Determine the envs that match the desired_envs.
If ``passthru` is True, and none of the declared envs match the
desired envs, then the desired envs will be used verbatim.
:param declared_envs: The envs that are declared in the tox config.
:param desired_envs: The envs desired from the tox-travis config.
:param bool passthru: Whether to used the ``desired_envs`` as a
fallback if no declared envs match. | [
"Determine",
"the",
"envs",
"that",
"match",
"the",
"desired_envs",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L200-L215 | train | 251,020 |
tox-dev/tox-travis | src/tox_travis/envlist.py | env_matches | def env_matches(declared, desired):
"""Determine if a declared env matches a desired env.
Rather than simply using the name of the env verbatim, take a
closer look to see if all the desired factors are fulfilled. If
the desired factors are fulfilled, but there are other factors,
it should still match the env.
"""
desired_factors = desired.split('-')
declared_factors = declared.split('-')
return all(factor in declared_factors for factor in desired_factors) | python | def env_matches(declared, desired):
"""Determine if a declared env matches a desired env.
Rather than simply using the name of the env verbatim, take a
closer look to see if all the desired factors are fulfilled. If
the desired factors are fulfilled, but there are other factors,
it should still match the env.
"""
desired_factors = desired.split('-')
declared_factors = declared.split('-')
return all(factor in declared_factors for factor in desired_factors) | [
"def",
"env_matches",
"(",
"declared",
",",
"desired",
")",
":",
"desired_factors",
"=",
"desired",
".",
"split",
"(",
"'-'",
")",
"declared_factors",
"=",
"declared",
".",
"split",
"(",
"'-'",
")",
"return",
"all",
"(",
"factor",
"in",
"declared_factors",
"for",
"factor",
"in",
"desired_factors",
")"
] | Determine if a declared env matches a desired env.
Rather than simply using the name of the env verbatim, take a
closer look to see if all the desired factors are fulfilled. If
the desired factors are fulfilled, but there are other factors,
it should still match the env. | [
"Determine",
"if",
"a",
"declared",
"env",
"matches",
"a",
"desired",
"env",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L218-L228 | train | 251,021 |
tox-dev/tox-travis | src/tox_travis/envlist.py | override_ignore_outcome | def override_ignore_outcome(ini):
"""Decide whether to override ignore_outcomes."""
travis_reader = tox.config.SectionReader("travis", ini)
return travis_reader.getbool('unignore_outcomes', False) | python | def override_ignore_outcome(ini):
"""Decide whether to override ignore_outcomes."""
travis_reader = tox.config.SectionReader("travis", ini)
return travis_reader.getbool('unignore_outcomes', False) | [
"def",
"override_ignore_outcome",
"(",
"ini",
")",
":",
"travis_reader",
"=",
"tox",
".",
"config",
".",
"SectionReader",
"(",
"\"travis\"",
",",
"ini",
")",
"return",
"travis_reader",
".",
"getbool",
"(",
"'unignore_outcomes'",
",",
"False",
")"
] | Decide whether to override ignore_outcomes. | [
"Decide",
"whether",
"to",
"override",
"ignore_outcomes",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L231-L234 | train | 251,022 |
tox-dev/tox-travis | src/tox_travis/hooks.py | tox_addoption | def tox_addoption(parser):
"""Add arguments and needed monkeypatches."""
parser.add_argument(
'--travis-after', dest='travis_after', action='store_true',
help='Exit successfully after all Travis jobs complete successfully.')
if 'TRAVIS' in os.environ:
pypy_version_monkeypatch()
subcommand_test_monkeypatch(tox_subcommand_test_post) | python | def tox_addoption(parser):
"""Add arguments and needed monkeypatches."""
parser.add_argument(
'--travis-after', dest='travis_after', action='store_true',
help='Exit successfully after all Travis jobs complete successfully.')
if 'TRAVIS' in os.environ:
pypy_version_monkeypatch()
subcommand_test_monkeypatch(tox_subcommand_test_post) | [
"def",
"tox_addoption",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--travis-after'",
",",
"dest",
"=",
"'travis_after'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Exit successfully after all Travis jobs complete successfully.'",
")",
"if",
"'TRAVIS'",
"in",
"os",
".",
"environ",
":",
"pypy_version_monkeypatch",
"(",
")",
"subcommand_test_monkeypatch",
"(",
"tox_subcommand_test_post",
")"
] | Add arguments and needed monkeypatches. | [
"Add",
"arguments",
"and",
"needed",
"monkeypatches",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hooks.py#L19-L27 | train | 251,023 |
tox-dev/tox-travis | src/tox_travis/hooks.py | tox_configure | def tox_configure(config):
"""Check for the presence of the added options."""
if 'TRAVIS' not in os.environ:
return
ini = config._cfg
# envlist
if 'TOXENV' not in os.environ and not config.option.env:
envlist = detect_envlist(ini)
undeclared = set(envlist) - set(config.envconfigs)
if undeclared:
print('Matching undeclared envs is deprecated. Be sure all the '
'envs that Tox should run are declared in the tox config.',
file=sys.stderr)
autogen_envconfigs(config, undeclared)
config.envlist = envlist
# Override ignore_outcomes
if override_ignore_outcome(ini):
for envconfig in config.envconfigs.values():
envconfig.ignore_outcome = False
# after
if config.option.travis_after:
print('The after all feature has been deprecated. Check out Travis\' '
'build stages, which are a better solution. '
'See https://tox-travis.readthedocs.io/en/stable/after.html '
'for more details.', file=sys.stderr) | python | def tox_configure(config):
"""Check for the presence of the added options."""
if 'TRAVIS' not in os.environ:
return
ini = config._cfg
# envlist
if 'TOXENV' not in os.environ and not config.option.env:
envlist = detect_envlist(ini)
undeclared = set(envlist) - set(config.envconfigs)
if undeclared:
print('Matching undeclared envs is deprecated. Be sure all the '
'envs that Tox should run are declared in the tox config.',
file=sys.stderr)
autogen_envconfigs(config, undeclared)
config.envlist = envlist
# Override ignore_outcomes
if override_ignore_outcome(ini):
for envconfig in config.envconfigs.values():
envconfig.ignore_outcome = False
# after
if config.option.travis_after:
print('The after all feature has been deprecated. Check out Travis\' '
'build stages, which are a better solution. '
'See https://tox-travis.readthedocs.io/en/stable/after.html '
'for more details.', file=sys.stderr) | [
"def",
"tox_configure",
"(",
"config",
")",
":",
"if",
"'TRAVIS'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"ini",
"=",
"config",
".",
"_cfg",
"# envlist",
"if",
"'TOXENV'",
"not",
"in",
"os",
".",
"environ",
"and",
"not",
"config",
".",
"option",
".",
"env",
":",
"envlist",
"=",
"detect_envlist",
"(",
"ini",
")",
"undeclared",
"=",
"set",
"(",
"envlist",
")",
"-",
"set",
"(",
"config",
".",
"envconfigs",
")",
"if",
"undeclared",
":",
"print",
"(",
"'Matching undeclared envs is deprecated. Be sure all the '",
"'envs that Tox should run are declared in the tox config.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"autogen_envconfigs",
"(",
"config",
",",
"undeclared",
")",
"config",
".",
"envlist",
"=",
"envlist",
"# Override ignore_outcomes",
"if",
"override_ignore_outcome",
"(",
"ini",
")",
":",
"for",
"envconfig",
"in",
"config",
".",
"envconfigs",
".",
"values",
"(",
")",
":",
"envconfig",
".",
"ignore_outcome",
"=",
"False",
"# after",
"if",
"config",
".",
"option",
".",
"travis_after",
":",
"print",
"(",
"'The after all feature has been deprecated. Check out Travis\\' '",
"'build stages, which are a better solution. '",
"'See https://tox-travis.readthedocs.io/en/stable/after.html '",
"'for more details.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | Check for the presence of the added options. | [
"Check",
"for",
"the",
"presence",
"of",
"the",
"added",
"options",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hooks.py#L31-L59 | train | 251,024 |
tox-dev/tox-travis | src/tox_travis/utils.py | parse_dict | def parse_dict(value):
"""Parse a dict value from the tox config.
.. code-block: ini
[travis]
python =
2.7: py27, docs
3.5: py{35,36}
With this config, the value of ``python`` would be parsed
by this function, and would return::
{
'2.7': 'py27, docs',
'3.5': 'py{35,36}',
}
"""
lines = [line.strip() for line in value.strip().splitlines()]
pairs = [line.split(':', 1) for line in lines if line]
return dict((k.strip(), v.strip()) for k, v in pairs) | python | def parse_dict(value):
"""Parse a dict value from the tox config.
.. code-block: ini
[travis]
python =
2.7: py27, docs
3.5: py{35,36}
With this config, the value of ``python`` would be parsed
by this function, and would return::
{
'2.7': 'py27, docs',
'3.5': 'py{35,36}',
}
"""
lines = [line.strip() for line in value.strip().splitlines()]
pairs = [line.split(':', 1) for line in lines if line]
return dict((k.strip(), v.strip()) for k, v in pairs) | [
"def",
"parse_dict",
"(",
"value",
")",
":",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"value",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
"]",
"pairs",
"=",
"[",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"for",
"line",
"in",
"lines",
"if",
"line",
"]",
"return",
"dict",
"(",
"(",
"k",
".",
"strip",
"(",
")",
",",
"v",
".",
"strip",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"pairs",
")"
] | Parse a dict value from the tox config.
.. code-block: ini
[travis]
python =
2.7: py27, docs
3.5: py{35,36}
With this config, the value of ``python`` would be parsed
by this function, and would return::
{
'2.7': 'py27, docs',
'3.5': 'py{35,36}',
} | [
"Parse",
"a",
"dict",
"value",
"from",
"the",
"tox",
"config",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/utils.py#L11-L32 | train | 251,025 |
tox-dev/tox-travis | src/tox_travis/hacks.py | pypy_version_monkeypatch | def pypy_version_monkeypatch():
"""Patch Tox to work with non-default PyPy 3 versions."""
# Travis virtualenv do not provide `pypy3`, which tox tries to execute.
# This doesnt affect Travis python version `pypy3`, as the pyenv pypy3
# is in the PATH.
# https://github.com/travis-ci/travis-ci/issues/6304
# Force use of the virtualenv `python`.
version = os.environ.get('TRAVIS_PYTHON_VERSION')
if version and default_factors and version.startswith('pypy3.3-'):
default_factors['pypy3'] = 'python' | python | def pypy_version_monkeypatch():
"""Patch Tox to work with non-default PyPy 3 versions."""
# Travis virtualenv do not provide `pypy3`, which tox tries to execute.
# This doesnt affect Travis python version `pypy3`, as the pyenv pypy3
# is in the PATH.
# https://github.com/travis-ci/travis-ci/issues/6304
# Force use of the virtualenv `python`.
version = os.environ.get('TRAVIS_PYTHON_VERSION')
if version and default_factors and version.startswith('pypy3.3-'):
default_factors['pypy3'] = 'python' | [
"def",
"pypy_version_monkeypatch",
"(",
")",
":",
"# Travis virtualenv do not provide `pypy3`, which tox tries to execute.",
"# This doesnt affect Travis python version `pypy3`, as the pyenv pypy3",
"# is in the PATH.",
"# https://github.com/travis-ci/travis-ci/issues/6304",
"# Force use of the virtualenv `python`.",
"version",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_PYTHON_VERSION'",
")",
"if",
"version",
"and",
"default_factors",
"and",
"version",
".",
"startswith",
"(",
"'pypy3.3-'",
")",
":",
"default_factors",
"[",
"'pypy3'",
"]",
"=",
"'python'"
] | Patch Tox to work with non-default PyPy 3 versions. | [
"Patch",
"Tox",
"to",
"work",
"with",
"non",
"-",
"default",
"PyPy",
"3",
"versions",
"."
] | d97a966c19abb020298a7e4b91fe83dd1d0a4517 | https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hacks.py#L9-L18 | train | 251,026 |
adafruit/Adafruit_CircuitPython_MCP230xx | adafruit_mcp230xx.py | DigitalInOut.direction | def direction(self):
"""The direction of the pin, either True for an input or
False for an output.
"""
if _get_bit(self._mcp.iodir, self._pin):
return digitalio.Direction.INPUT
return digitalio.Direction.OUTPUT | python | def direction(self):
"""The direction of the pin, either True for an input or
False for an output.
"""
if _get_bit(self._mcp.iodir, self._pin):
return digitalio.Direction.INPUT
return digitalio.Direction.OUTPUT | [
"def",
"direction",
"(",
"self",
")",
":",
"if",
"_get_bit",
"(",
"self",
".",
"_mcp",
".",
"iodir",
",",
"self",
".",
"_pin",
")",
":",
"return",
"digitalio",
".",
"Direction",
".",
"INPUT",
"return",
"digitalio",
".",
"Direction",
".",
"OUTPUT"
] | The direction of the pin, either True for an input or
False for an output. | [
"The",
"direction",
"of",
"the",
"pin",
"either",
"True",
"for",
"an",
"input",
"or",
"False",
"for",
"an",
"output",
"."
] | da9480befecef31c2428062919b9f3da6f428d15 | https://github.com/adafruit/Adafruit_CircuitPython_MCP230xx/blob/da9480befecef31c2428062919b9f3da6f428d15/adafruit_mcp230xx.py#L148-L154 | train | 251,027 |
adafruit/Adafruit_CircuitPython_MCP230xx | adafruit_mcp230xx.py | DigitalInOut.pull | def pull(self):
"""Enable or disable internal pull-up resistors for this pin. A
value of digitalio.Pull.UP will enable a pull-up resistor, and None will
disable it. Pull-down resistors are NOT supported!
"""
if _get_bit(self._mcp.gppu, self._pin):
return digitalio.Pull.UP
return None | python | def pull(self):
"""Enable or disable internal pull-up resistors for this pin. A
value of digitalio.Pull.UP will enable a pull-up resistor, and None will
disable it. Pull-down resistors are NOT supported!
"""
if _get_bit(self._mcp.gppu, self._pin):
return digitalio.Pull.UP
return None | [
"def",
"pull",
"(",
"self",
")",
":",
"if",
"_get_bit",
"(",
"self",
".",
"_mcp",
".",
"gppu",
",",
"self",
".",
"_pin",
")",
":",
"return",
"digitalio",
".",
"Pull",
".",
"UP",
"return",
"None"
] | Enable or disable internal pull-up resistors for this pin. A
value of digitalio.Pull.UP will enable a pull-up resistor, and None will
disable it. Pull-down resistors are NOT supported! | [
"Enable",
"or",
"disable",
"internal",
"pull",
"-",
"up",
"resistors",
"for",
"this",
"pin",
".",
"A",
"value",
"of",
"digitalio",
".",
"Pull",
".",
"UP",
"will",
"enable",
"a",
"pull",
"-",
"up",
"resistor",
"and",
"None",
"will",
"disable",
"it",
".",
"Pull",
"-",
"down",
"resistors",
"are",
"NOT",
"supported!"
] | da9480befecef31c2428062919b9f3da6f428d15 | https://github.com/adafruit/Adafruit_CircuitPython_MCP230xx/blob/da9480befecef31c2428062919b9f3da6f428d15/adafruit_mcp230xx.py#L166-L173 | train | 251,028 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/statistics/table.py | get_throttled_read_event_count | def get_throttled_read_event_count(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled read events during a given time frame
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: int -- Number of throttled read events during the time period
"""
try:
metrics = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ReadThrottleEvents')
except BotoServerError:
raise
if metrics:
throttled_read_events = int(metrics[0]['Sum'])
else:
throttled_read_events = 0
logger.info('{0} - Read throttle count: {1:d}'.format(
table_name, throttled_read_events))
return throttled_read_events | python | def get_throttled_read_event_count(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled read events during a given time frame
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: int -- Number of throttled read events during the time period
"""
try:
metrics = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ReadThrottleEvents')
except BotoServerError:
raise
if metrics:
throttled_read_events = int(metrics[0]['Sum'])
else:
throttled_read_events = 0
logger.info('{0} - Read throttle count: {1:d}'.format(
table_name, throttled_read_events))
return throttled_read_events | [
"def",
"get_throttled_read_event_count",
"(",
"table_name",
",",
"lookback_window_start",
"=",
"15",
",",
"lookback_period",
"=",
"5",
")",
":",
"try",
":",
"metrics",
"=",
"__get_aws_metric",
"(",
"table_name",
",",
"lookback_window_start",
",",
"lookback_period",
",",
"'ReadThrottleEvents'",
")",
"except",
"BotoServerError",
":",
"raise",
"if",
"metrics",
":",
"throttled_read_events",
"=",
"int",
"(",
"metrics",
"[",
"0",
"]",
"[",
"'Sum'",
"]",
")",
"else",
":",
"throttled_read_events",
"=",
"0",
"logger",
".",
"info",
"(",
"'{0} - Read throttle count: {1:d}'",
".",
"format",
"(",
"table_name",
",",
"throttled_read_events",
")",
")",
"return",
"throttled_read_events"
] | Returns the number of throttled read events during a given time frame
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: int -- Number of throttled read events during the time period | [
"Returns",
"the",
"number",
"of",
"throttled",
"read",
"events",
"during",
"a",
"given",
"time",
"frame"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L58-L86 | train | 251,029 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/statistics/table.py | get_throttled_by_consumed_read_percent | def get_throttled_by_consumed_read_percent(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled read events in percent of consumption
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: float -- Percent of throttled read events by consumption
"""
try:
metrics1 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ConsumedReadCapacityUnits')
metrics2 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ReadThrottleEvents')
except BotoServerError:
raise
if metrics1 and metrics2:
lookback_seconds = lookback_period * 60
throttled_by_consumed_read_percent = (
(
(float(metrics2[0]['Sum']) / float(lookback_seconds)) /
(float(metrics1[0]['Sum']) / float(lookback_seconds))
) * 100)
else:
throttled_by_consumed_read_percent = 0
logger.info('{0} - Throttled read percent by consumption: {1:.2f}%'.format(
table_name, throttled_by_consumed_read_percent))
return throttled_by_consumed_read_percent | python | def get_throttled_by_consumed_read_percent(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled read events in percent of consumption
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: float -- Percent of throttled read events by consumption
"""
try:
metrics1 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ConsumedReadCapacityUnits')
metrics2 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ReadThrottleEvents')
except BotoServerError:
raise
if metrics1 and metrics2:
lookback_seconds = lookback_period * 60
throttled_by_consumed_read_percent = (
(
(float(metrics2[0]['Sum']) / float(lookback_seconds)) /
(float(metrics1[0]['Sum']) / float(lookback_seconds))
) * 100)
else:
throttled_by_consumed_read_percent = 0
logger.info('{0} - Throttled read percent by consumption: {1:.2f}%'.format(
table_name, throttled_by_consumed_read_percent))
return throttled_by_consumed_read_percent | [
"def",
"get_throttled_by_consumed_read_percent",
"(",
"table_name",
",",
"lookback_window_start",
"=",
"15",
",",
"lookback_period",
"=",
"5",
")",
":",
"try",
":",
"metrics1",
"=",
"__get_aws_metric",
"(",
"table_name",
",",
"lookback_window_start",
",",
"lookback_period",
",",
"'ConsumedReadCapacityUnits'",
")",
"metrics2",
"=",
"__get_aws_metric",
"(",
"table_name",
",",
"lookback_window_start",
",",
"lookback_period",
",",
"'ReadThrottleEvents'",
")",
"except",
"BotoServerError",
":",
"raise",
"if",
"metrics1",
"and",
"metrics2",
":",
"lookback_seconds",
"=",
"lookback_period",
"*",
"60",
"throttled_by_consumed_read_percent",
"=",
"(",
"(",
"(",
"float",
"(",
"metrics2",
"[",
"0",
"]",
"[",
"'Sum'",
"]",
")",
"/",
"float",
"(",
"lookback_seconds",
")",
")",
"/",
"(",
"float",
"(",
"metrics1",
"[",
"0",
"]",
"[",
"'Sum'",
"]",
")",
"/",
"float",
"(",
"lookback_seconds",
")",
")",
")",
"*",
"100",
")",
"else",
":",
"throttled_by_consumed_read_percent",
"=",
"0",
"logger",
".",
"info",
"(",
"'{0} - Throttled read percent by consumption: {1:.2f}%'",
".",
"format",
"(",
"table_name",
",",
"throttled_by_consumed_read_percent",
")",
")",
"return",
"throttled_by_consumed_read_percent"
] | Returns the number of throttled read events in percent of consumption
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: float -- Percent of throttled read events by consumption | [
"Returns",
"the",
"number",
"of",
"throttled",
"read",
"events",
"in",
"percent",
"of",
"consumption"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L132-L171 | train | 251,030 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/statistics/table.py | get_throttled_by_consumed_write_percent | def get_throttled_by_consumed_write_percent(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled write events in percent of consumption
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: float -- Percent of throttled write events by consumption
"""
try:
metrics1 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ConsumedWriteCapacityUnits')
metrics2 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'WriteThrottleEvents')
except BotoServerError:
raise
if metrics1 and metrics2:
lookback_seconds = lookback_period * 60
throttled_by_consumed_write_percent = (
(
(float(metrics2[0]['Sum']) / float(lookback_seconds)) /
(float(metrics1[0]['Sum']) / float(lookback_seconds))
) * 100)
else:
throttled_by_consumed_write_percent = 0
logger.info(
'{0} - Throttled write percent by consumption: {1:.2f}%'.format(
table_name, throttled_by_consumed_write_percent))
return throttled_by_consumed_write_percent | python | def get_throttled_by_consumed_write_percent(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled write events in percent of consumption
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: float -- Percent of throttled write events by consumption
"""
try:
metrics1 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'ConsumedWriteCapacityUnits')
metrics2 = __get_aws_metric(
table_name,
lookback_window_start,
lookback_period,
'WriteThrottleEvents')
except BotoServerError:
raise
if metrics1 and metrics2:
lookback_seconds = lookback_period * 60
throttled_by_consumed_write_percent = (
(
(float(metrics2[0]['Sum']) / float(lookback_seconds)) /
(float(metrics1[0]['Sum']) / float(lookback_seconds))
) * 100)
else:
throttled_by_consumed_write_percent = 0
logger.info(
'{0} - Throttled write percent by consumption: {1:.2f}%'.format(
table_name, throttled_by_consumed_write_percent))
return throttled_by_consumed_write_percent | [
"def",
"get_throttled_by_consumed_write_percent",
"(",
"table_name",
",",
"lookback_window_start",
"=",
"15",
",",
"lookback_period",
"=",
"5",
")",
":",
"try",
":",
"metrics1",
"=",
"__get_aws_metric",
"(",
"table_name",
",",
"lookback_window_start",
",",
"lookback_period",
",",
"'ConsumedWriteCapacityUnits'",
")",
"metrics2",
"=",
"__get_aws_metric",
"(",
"table_name",
",",
"lookback_window_start",
",",
"lookback_period",
",",
"'WriteThrottleEvents'",
")",
"except",
"BotoServerError",
":",
"raise",
"if",
"metrics1",
"and",
"metrics2",
":",
"lookback_seconds",
"=",
"lookback_period",
"*",
"60",
"throttled_by_consumed_write_percent",
"=",
"(",
"(",
"(",
"float",
"(",
"metrics2",
"[",
"0",
"]",
"[",
"'Sum'",
"]",
")",
"/",
"float",
"(",
"lookback_seconds",
")",
")",
"/",
"(",
"float",
"(",
"metrics1",
"[",
"0",
"]",
"[",
"'Sum'",
"]",
")",
"/",
"float",
"(",
"lookback_seconds",
")",
")",
")",
"*",
"100",
")",
"else",
":",
"throttled_by_consumed_write_percent",
"=",
"0",
"logger",
".",
"info",
"(",
"'{0} - Throttled write percent by consumption: {1:.2f}%'",
".",
"format",
"(",
"table_name",
",",
"throttled_by_consumed_write_percent",
")",
")",
"return",
"throttled_by_consumed_write_percent"
] | Returns the number of throttled write events in percent of consumption
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: Relative start time for the CloudWatch metric
:type lookback_period: int
:param lookback_period: Number of minutes to look at
:returns: float -- Percent of throttled write events by consumption | [
"Returns",
"the",
"number",
"of",
"throttled",
"write",
"events",
"in",
"percent",
"of",
"consumption"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L291-L332 | train | 251,031 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/statistics/table.py | __get_aws_metric | def __get_aws_metric(table_name, lookback_window_start, lookback_period,
metric_name):
""" Returns a metric list from the AWS CloudWatch service, may return
None if no metric exists
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: How many minutes to look at
:type lookback_period: int
:type lookback_period: Length of the lookback period in minutes
:type metric_name: str
:param metric_name: Name of the metric to retrieve from CloudWatch
:returns: list -- A list of time series data for the given metric, may
be None if there was no data
"""
try:
now = datetime.utcnow()
start_time = now - timedelta(minutes=lookback_window_start)
end_time = now - timedelta(
minutes=lookback_window_start - lookback_period)
return cloudwatch_connection.get_metric_statistics(
period=lookback_period * 60,
start_time=start_time,
end_time=end_time,
metric_name=metric_name,
namespace='AWS/DynamoDB',
statistics=['Sum'],
dimensions={'TableName': table_name},
unit='Count')
except BotoServerError as error:
logger.error(
'Unknown boto error. Status: "{0}". '
'Reason: "{1}". Message: {2}'.format(
error.status,
error.reason,
error.message))
raise | python | def __get_aws_metric(table_name, lookback_window_start, lookback_period,
metric_name):
""" Returns a metric list from the AWS CloudWatch service, may return
None if no metric exists
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: How many minutes to look at
:type lookback_period: int
:type lookback_period: Length of the lookback period in minutes
:type metric_name: str
:param metric_name: Name of the metric to retrieve from CloudWatch
:returns: list -- A list of time series data for the given metric, may
be None if there was no data
"""
try:
now = datetime.utcnow()
start_time = now - timedelta(minutes=lookback_window_start)
end_time = now - timedelta(
minutes=lookback_window_start - lookback_period)
return cloudwatch_connection.get_metric_statistics(
period=lookback_period * 60,
start_time=start_time,
end_time=end_time,
metric_name=metric_name,
namespace='AWS/DynamoDB',
statistics=['Sum'],
dimensions={'TableName': table_name},
unit='Count')
except BotoServerError as error:
logger.error(
'Unknown boto error. Status: "{0}". '
'Reason: "{1}". Message: {2}'.format(
error.status,
error.reason,
error.message))
raise | [
"def",
"__get_aws_metric",
"(",
"table_name",
",",
"lookback_window_start",
",",
"lookback_period",
",",
"metric_name",
")",
":",
"try",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"start_time",
"=",
"now",
"-",
"timedelta",
"(",
"minutes",
"=",
"lookback_window_start",
")",
"end_time",
"=",
"now",
"-",
"timedelta",
"(",
"minutes",
"=",
"lookback_window_start",
"-",
"lookback_period",
")",
"return",
"cloudwatch_connection",
".",
"get_metric_statistics",
"(",
"period",
"=",
"lookback_period",
"*",
"60",
",",
"start_time",
"=",
"start_time",
",",
"end_time",
"=",
"end_time",
",",
"metric_name",
"=",
"metric_name",
",",
"namespace",
"=",
"'AWS/DynamoDB'",
",",
"statistics",
"=",
"[",
"'Sum'",
"]",
",",
"dimensions",
"=",
"{",
"'TableName'",
":",
"table_name",
"}",
",",
"unit",
"=",
"'Count'",
")",
"except",
"BotoServerError",
"as",
"error",
":",
"logger",
".",
"error",
"(",
"'Unknown boto error. Status: \"{0}\". '",
"'Reason: \"{1}\". Message: {2}'",
".",
"format",
"(",
"error",
".",
"status",
",",
"error",
".",
"reason",
",",
"error",
".",
"message",
")",
")",
"raise"
] | Returns a metric list from the AWS CloudWatch service, may return
None if no metric exists
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window_start: How many minutes to look at
:type lookback_period: int
:type lookback_period: Length of the lookback period in minutes
:type metric_name: str
:param metric_name: Name of the metric to retrieve from CloudWatch
:returns: list -- A list of time series data for the given metric, may
be None if there was no data | [
"Returns",
"a",
"metric",
"list",
"from",
"the",
"AWS",
"CloudWatch",
"service",
"may",
"return",
"None",
"if",
"no",
"metric",
"exists"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L340-L378 | train | 251,032 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/core/gsi.py | ensure_provisioning | def ensure_provisioning(
table_name, table_key, gsi_name, gsi_key,
num_consec_read_checks, num_consec_write_checks):
""" Ensure that provisioning is correct for Global Secondary Indexes
:type table_name: str
:param table_name: Name of the DynamoDB table
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_name: str
:param gsi_name: Name of the GSI
:type gsi_key: str
:param gsi_key: GSI configuration option key name
:type num_consec_read_checks: int
:param num_consec_read_checks: How many consecutive checks have we had
:type num_consec_write_checks: int
:param num_consec_write_checks: How many consecutive checks have we had
:returns: (int, int) -- num_consec_read_checks, num_consec_write_checks
"""
if get_global_option('circuit_breaker_url') or get_gsi_option(
table_key, gsi_key, 'circuit_breaker_url'):
if circuit_breaker.is_open(table_name, table_key, gsi_name, gsi_key):
logger.warning('Circuit breaker is OPEN!')
return (0, 0)
logger.info(
'{0} - Will ensure provisioning for global secondary index {1}'.format(
table_name, gsi_name))
# Handle throughput alarm checks
__ensure_provisioning_alarm(table_name, table_key, gsi_name, gsi_key)
try:
read_update_needed, updated_read_units, num_consec_read_checks = \
__ensure_provisioning_reads(
table_name,
table_key,
gsi_name,
gsi_key,
num_consec_read_checks)
write_update_needed, updated_write_units, num_consec_write_checks = \
__ensure_provisioning_writes(
table_name,
table_key,
gsi_name,
gsi_key,
num_consec_write_checks)
if read_update_needed:
num_consec_read_checks = 0
if write_update_needed:
num_consec_write_checks = 0
# Handle throughput updates
if read_update_needed or write_update_needed:
logger.info(
'{0} - GSI: {1} - Changing provisioning to {2:d} '
'read units and {3:d} write units'.format(
table_name,
gsi_name,
int(updated_read_units),
int(updated_write_units)))
__update_throughput(
table_name,
table_key,
gsi_name,
gsi_key,
updated_read_units,
updated_write_units)
else:
logger.info(
'{0} - GSI: {1} - No need to change provisioning'.format(
table_name,
gsi_name))
except JSONResponseError:
raise
except BotoServerError:
raise
return num_consec_read_checks, num_consec_write_checks | python | def ensure_provisioning(
table_name, table_key, gsi_name, gsi_key,
num_consec_read_checks, num_consec_write_checks):
""" Ensure that provisioning is correct for Global Secondary Indexes
:type table_name: str
:param table_name: Name of the DynamoDB table
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_name: str
:param gsi_name: Name of the GSI
:type gsi_key: str
:param gsi_key: GSI configuration option key name
:type num_consec_read_checks: int
:param num_consec_read_checks: How many consecutive checks have we had
:type num_consec_write_checks: int
:param num_consec_write_checks: How many consecutive checks have we had
:returns: (int, int) -- num_consec_read_checks, num_consec_write_checks
"""
if get_global_option('circuit_breaker_url') or get_gsi_option(
table_key, gsi_key, 'circuit_breaker_url'):
if circuit_breaker.is_open(table_name, table_key, gsi_name, gsi_key):
logger.warning('Circuit breaker is OPEN!')
return (0, 0)
logger.info(
'{0} - Will ensure provisioning for global secondary index {1}'.format(
table_name, gsi_name))
# Handle throughput alarm checks
__ensure_provisioning_alarm(table_name, table_key, gsi_name, gsi_key)
try:
read_update_needed, updated_read_units, num_consec_read_checks = \
__ensure_provisioning_reads(
table_name,
table_key,
gsi_name,
gsi_key,
num_consec_read_checks)
write_update_needed, updated_write_units, num_consec_write_checks = \
__ensure_provisioning_writes(
table_name,
table_key,
gsi_name,
gsi_key,
num_consec_write_checks)
if read_update_needed:
num_consec_read_checks = 0
if write_update_needed:
num_consec_write_checks = 0
# Handle throughput updates
if read_update_needed or write_update_needed:
logger.info(
'{0} - GSI: {1} - Changing provisioning to {2:d} '
'read units and {3:d} write units'.format(
table_name,
gsi_name,
int(updated_read_units),
int(updated_write_units)))
__update_throughput(
table_name,
table_key,
gsi_name,
gsi_key,
updated_read_units,
updated_write_units)
else:
logger.info(
'{0} - GSI: {1} - No need to change provisioning'.format(
table_name,
gsi_name))
except JSONResponseError:
raise
except BotoServerError:
raise
return num_consec_read_checks, num_consec_write_checks | [
"def",
"ensure_provisioning",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
",",
"num_consec_read_checks",
",",
"num_consec_write_checks",
")",
":",
"if",
"get_global_option",
"(",
"'circuit_breaker_url'",
")",
"or",
"get_gsi_option",
"(",
"table_key",
",",
"gsi_key",
",",
"'circuit_breaker_url'",
")",
":",
"if",
"circuit_breaker",
".",
"is_open",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
")",
":",
"logger",
".",
"warning",
"(",
"'Circuit breaker is OPEN!'",
")",
"return",
"(",
"0",
",",
"0",
")",
"logger",
".",
"info",
"(",
"'{0} - Will ensure provisioning for global secondary index {1}'",
".",
"format",
"(",
"table_name",
",",
"gsi_name",
")",
")",
"# Handle throughput alarm checks",
"__ensure_provisioning_alarm",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
")",
"try",
":",
"read_update_needed",
",",
"updated_read_units",
",",
"num_consec_read_checks",
"=",
"__ensure_provisioning_reads",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
",",
"num_consec_read_checks",
")",
"write_update_needed",
",",
"updated_write_units",
",",
"num_consec_write_checks",
"=",
"__ensure_provisioning_writes",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
",",
"num_consec_write_checks",
")",
"if",
"read_update_needed",
":",
"num_consec_read_checks",
"=",
"0",
"if",
"write_update_needed",
":",
"num_consec_write_checks",
"=",
"0",
"# Handle throughput updates",
"if",
"read_update_needed",
"or",
"write_update_needed",
":",
"logger",
".",
"info",
"(",
"'{0} - GSI: {1} - Changing provisioning to {2:d} '",
"'read units and {3:d} write units'",
".",
"format",
"(",
"table_name",
",",
"gsi_name",
",",
"int",
"(",
"updated_read_units",
")",
",",
"int",
"(",
"updated_write_units",
")",
")",
")",
"__update_throughput",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
",",
"updated_read_units",
",",
"updated_write_units",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'{0} - GSI: {1} - No need to change provisioning'",
".",
"format",
"(",
"table_name",
",",
"gsi_name",
")",
")",
"except",
"JSONResponseError",
":",
"raise",
"except",
"BotoServerError",
":",
"raise",
"return",
"num_consec_read_checks",
",",
"num_consec_write_checks"
] | Ensure that provisioning is correct for Global Secondary Indexes
:type table_name: str
:param table_name: Name of the DynamoDB table
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_name: str
:param gsi_name: Name of the GSI
:type gsi_key: str
:param gsi_key: GSI configuration option key name
:type num_consec_read_checks: int
:param num_consec_read_checks: How many consecutive checks have we had
:type num_consec_write_checks: int
:param num_consec_write_checks: How many consecutive checks have we had
:returns: (int, int) -- num_consec_read_checks, num_consec_write_checks | [
"Ensure",
"that",
"provisioning",
"is",
"correct",
"for",
"Global",
"Secondary",
"Indexes"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/gsi.py#L13-L93 | train | 251,033 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/core/gsi.py | __update_throughput | def __update_throughput(
table_name, table_key, gsi_name, gsi_key, read_units, write_units):
""" Update throughput on the GSI
:type table_name: str
:param table_name: Name of the DynamoDB table
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_name: str
:param gsi_name: Name of the GSI
:type gsi_key: str
:param gsi_key: Configuration option key name
:type read_units: int
:param read_units: New read unit provisioning
:type write_units: int
:param write_units: New write unit provisioning
"""
try:
current_ru = dynamodb.get_provisioned_gsi_read_units(
table_name, gsi_name)
current_wu = dynamodb.get_provisioned_gsi_write_units(
table_name, gsi_name)
except JSONResponseError:
raise
# Check table status
try:
gsi_status = dynamodb.get_gsi_status(table_name, gsi_name)
except JSONResponseError:
raise
logger.debug('{0} - GSI: {1} - GSI status is {2}'.format(
table_name, gsi_name, gsi_status))
if gsi_status != 'ACTIVE':
logger.warning(
'{0} - GSI: {1} - Not performing throughput changes when GSI '
'status is {2}'.format(table_name, gsi_name, gsi_status))
return
# If this setting is True, we will only scale down when
# BOTH reads AND writes are low
if get_gsi_option(table_key, gsi_key, 'always_decrease_rw_together'):
read_units, write_units = __calculate_always_decrease_rw_values(
table_name,
gsi_name,
read_units,
current_ru,
write_units,
current_wu)
if read_units == current_ru and write_units == current_wu:
logger.info('{0} - GSI: {1} - No changes to perform'.format(
table_name, gsi_name))
return
dynamodb.update_gsi_provisioning(
table_name,
table_key,
gsi_name,
gsi_key,
int(read_units),
int(write_units)) | python | def __update_throughput(
table_name, table_key, gsi_name, gsi_key, read_units, write_units):
""" Update throughput on the GSI
:type table_name: str
:param table_name: Name of the DynamoDB table
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_name: str
:param gsi_name: Name of the GSI
:type gsi_key: str
:param gsi_key: Configuration option key name
:type read_units: int
:param read_units: New read unit provisioning
:type write_units: int
:param write_units: New write unit provisioning
"""
try:
current_ru = dynamodb.get_provisioned_gsi_read_units(
table_name, gsi_name)
current_wu = dynamodb.get_provisioned_gsi_write_units(
table_name, gsi_name)
except JSONResponseError:
raise
# Check table status
try:
gsi_status = dynamodb.get_gsi_status(table_name, gsi_name)
except JSONResponseError:
raise
logger.debug('{0} - GSI: {1} - GSI status is {2}'.format(
table_name, gsi_name, gsi_status))
if gsi_status != 'ACTIVE':
logger.warning(
'{0} - GSI: {1} - Not performing throughput changes when GSI '
'status is {2}'.format(table_name, gsi_name, gsi_status))
return
# If this setting is True, we will only scale down when
# BOTH reads AND writes are low
if get_gsi_option(table_key, gsi_key, 'always_decrease_rw_together'):
read_units, write_units = __calculate_always_decrease_rw_values(
table_name,
gsi_name,
read_units,
current_ru,
write_units,
current_wu)
if read_units == current_ru and write_units == current_wu:
logger.info('{0} - GSI: {1} - No changes to perform'.format(
table_name, gsi_name))
return
dynamodb.update_gsi_provisioning(
table_name,
table_key,
gsi_name,
gsi_key,
int(read_units),
int(write_units)) | [
"def",
"__update_throughput",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
",",
"read_units",
",",
"write_units",
")",
":",
"try",
":",
"current_ru",
"=",
"dynamodb",
".",
"get_provisioned_gsi_read_units",
"(",
"table_name",
",",
"gsi_name",
")",
"current_wu",
"=",
"dynamodb",
".",
"get_provisioned_gsi_write_units",
"(",
"table_name",
",",
"gsi_name",
")",
"except",
"JSONResponseError",
":",
"raise",
"# Check table status",
"try",
":",
"gsi_status",
"=",
"dynamodb",
".",
"get_gsi_status",
"(",
"table_name",
",",
"gsi_name",
")",
"except",
"JSONResponseError",
":",
"raise",
"logger",
".",
"debug",
"(",
"'{0} - GSI: {1} - GSI status is {2}'",
".",
"format",
"(",
"table_name",
",",
"gsi_name",
",",
"gsi_status",
")",
")",
"if",
"gsi_status",
"!=",
"'ACTIVE'",
":",
"logger",
".",
"warning",
"(",
"'{0} - GSI: {1} - Not performing throughput changes when GSI '",
"'status is {2}'",
".",
"format",
"(",
"table_name",
",",
"gsi_name",
",",
"gsi_status",
")",
")",
"return",
"# If this setting is True, we will only scale down when",
"# BOTH reads AND writes are low",
"if",
"get_gsi_option",
"(",
"table_key",
",",
"gsi_key",
",",
"'always_decrease_rw_together'",
")",
":",
"read_units",
",",
"write_units",
"=",
"__calculate_always_decrease_rw_values",
"(",
"table_name",
",",
"gsi_name",
",",
"read_units",
",",
"current_ru",
",",
"write_units",
",",
"current_wu",
")",
"if",
"read_units",
"==",
"current_ru",
"and",
"write_units",
"==",
"current_wu",
":",
"logger",
".",
"info",
"(",
"'{0} - GSI: {1} - No changes to perform'",
".",
"format",
"(",
"table_name",
",",
"gsi_name",
")",
")",
"return",
"dynamodb",
".",
"update_gsi_provisioning",
"(",
"table_name",
",",
"table_key",
",",
"gsi_name",
",",
"gsi_key",
",",
"int",
"(",
"read_units",
")",
",",
"int",
"(",
"write_units",
")",
")"
] | Update throughput on the GSI
:type table_name: str
:param table_name: Name of the DynamoDB table
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_name: str
:param gsi_name: Name of the GSI
:type gsi_key: str
:param gsi_key: Configuration option key name
:type read_units: int
:param read_units: New read unit provisioning
:type write_units: int
:param write_units: New write unit provisioning | [
"Update",
"throughput",
"on",
"the",
"GSI"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/gsi.py#L1027-L1088 | train | 251,034 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/core/circuit_breaker.py | is_open | def is_open(table_name=None, table_key=None, gsi_name=None, gsi_key=None):
""" Checks whether the circuit breaker is open
:param table_name: Name of the table being checked
:param table_key: Configuration key for table
:param gsi_name: Name of the GSI being checked
:param gsi_key: Configuration key for the GSI
:returns: bool -- True if the circuit is open
"""
logger.debug('Checking circuit breaker status')
# Parse the URL to make sure it is OK
pattern = re.compile(
r'^(?P<scheme>http(s)?://)'
r'((?P<username>.+):(?P<password>.+)@){0,1}'
r'(?P<url>.*)$'
)
url = timeout = None
if gsi_name:
url = get_gsi_option(table_key, gsi_key, 'circuit_breaker_url')
timeout = get_gsi_option(table_key, gsi_key, 'circuit_breaker_timeout')
elif table_name:
url = get_table_option(table_key, 'circuit_breaker_url')
timeout = get_table_option(table_key, 'circuit_breaker_timeout')
if not url:
url = get_global_option('circuit_breaker_url')
timeout = get_global_option('circuit_breaker_timeout')
match = pattern.match(url)
if not match:
logger.error('Malformatted URL: {0}'.format(url))
sys.exit(1)
use_basic_auth = False
if match.group('username') and match.group('password'):
use_basic_auth = True
# Make the actual URL to call
auth = ()
if use_basic_auth:
url = '{scheme}{url}'.format(
scheme=match.group('scheme'),
url=match.group('url'))
auth = (match.group('username'), match.group('password'))
headers = {}
if table_name:
headers["x-table-name"] = table_name
if gsi_name:
headers["x-gsi-name"] = gsi_name
# Make the actual request
try:
response = requests.get(
url,
auth=auth,
timeout=timeout / 1000.00,
headers=headers)
if int(response.status_code) >= 200 and int(response.status_code) < 300:
logger.info('Circuit breaker is closed')
return False
else:
logger.warning(
'Circuit breaker returned with status code {0:d}'.format(
response.status_code))
except requests.exceptions.SSLError as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.Timeout as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.ConnectionError as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.HTTPError as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.TooManyRedirects as error:
logger.warning('Circuit breaker: {0}'.format(error))
except Exception as error:
logger.error('Unhandled exception: {0}'.format(error))
logger.error(
'Please file a bug at '
'https://github.com/sebdah/dynamic-dynamodb/issues')
return True | python | def is_open(table_name=None, table_key=None, gsi_name=None, gsi_key=None):
""" Checks whether the circuit breaker is open
:param table_name: Name of the table being checked
:param table_key: Configuration key for table
:param gsi_name: Name of the GSI being checked
:param gsi_key: Configuration key for the GSI
:returns: bool -- True if the circuit is open
"""
logger.debug('Checking circuit breaker status')
# Parse the URL to make sure it is OK
pattern = re.compile(
r'^(?P<scheme>http(s)?://)'
r'((?P<username>.+):(?P<password>.+)@){0,1}'
r'(?P<url>.*)$'
)
url = timeout = None
if gsi_name:
url = get_gsi_option(table_key, gsi_key, 'circuit_breaker_url')
timeout = get_gsi_option(table_key, gsi_key, 'circuit_breaker_timeout')
elif table_name:
url = get_table_option(table_key, 'circuit_breaker_url')
timeout = get_table_option(table_key, 'circuit_breaker_timeout')
if not url:
url = get_global_option('circuit_breaker_url')
timeout = get_global_option('circuit_breaker_timeout')
match = pattern.match(url)
if not match:
logger.error('Malformatted URL: {0}'.format(url))
sys.exit(1)
use_basic_auth = False
if match.group('username') and match.group('password'):
use_basic_auth = True
# Make the actual URL to call
auth = ()
if use_basic_auth:
url = '{scheme}{url}'.format(
scheme=match.group('scheme'),
url=match.group('url'))
auth = (match.group('username'), match.group('password'))
headers = {}
if table_name:
headers["x-table-name"] = table_name
if gsi_name:
headers["x-gsi-name"] = gsi_name
# Make the actual request
try:
response = requests.get(
url,
auth=auth,
timeout=timeout / 1000.00,
headers=headers)
if int(response.status_code) >= 200 and int(response.status_code) < 300:
logger.info('Circuit breaker is closed')
return False
else:
logger.warning(
'Circuit breaker returned with status code {0:d}'.format(
response.status_code))
except requests.exceptions.SSLError as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.Timeout as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.ConnectionError as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.HTTPError as error:
logger.warning('Circuit breaker: {0}'.format(error))
except requests.exceptions.TooManyRedirects as error:
logger.warning('Circuit breaker: {0}'.format(error))
except Exception as error:
logger.error('Unhandled exception: {0}'.format(error))
logger.error(
'Please file a bug at '
'https://github.com/sebdah/dynamic-dynamodb/issues')
return True | [
"def",
"is_open",
"(",
"table_name",
"=",
"None",
",",
"table_key",
"=",
"None",
",",
"gsi_name",
"=",
"None",
",",
"gsi_key",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Checking circuit breaker status'",
")",
"# Parse the URL to make sure it is OK",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'^(?P<scheme>http(s)?://)'",
"r'((?P<username>.+):(?P<password>.+)@){0,1}'",
"r'(?P<url>.*)$'",
")",
"url",
"=",
"timeout",
"=",
"None",
"if",
"gsi_name",
":",
"url",
"=",
"get_gsi_option",
"(",
"table_key",
",",
"gsi_key",
",",
"'circuit_breaker_url'",
")",
"timeout",
"=",
"get_gsi_option",
"(",
"table_key",
",",
"gsi_key",
",",
"'circuit_breaker_timeout'",
")",
"elif",
"table_name",
":",
"url",
"=",
"get_table_option",
"(",
"table_key",
",",
"'circuit_breaker_url'",
")",
"timeout",
"=",
"get_table_option",
"(",
"table_key",
",",
"'circuit_breaker_timeout'",
")",
"if",
"not",
"url",
":",
"url",
"=",
"get_global_option",
"(",
"'circuit_breaker_url'",
")",
"timeout",
"=",
"get_global_option",
"(",
"'circuit_breaker_timeout'",
")",
"match",
"=",
"pattern",
".",
"match",
"(",
"url",
")",
"if",
"not",
"match",
":",
"logger",
".",
"error",
"(",
"'Malformatted URL: {0}'",
".",
"format",
"(",
"url",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"use_basic_auth",
"=",
"False",
"if",
"match",
".",
"group",
"(",
"'username'",
")",
"and",
"match",
".",
"group",
"(",
"'password'",
")",
":",
"use_basic_auth",
"=",
"True",
"# Make the actual URL to call",
"auth",
"=",
"(",
")",
"if",
"use_basic_auth",
":",
"url",
"=",
"'{scheme}{url}'",
".",
"format",
"(",
"scheme",
"=",
"match",
".",
"group",
"(",
"'scheme'",
")",
",",
"url",
"=",
"match",
".",
"group",
"(",
"'url'",
")",
")",
"auth",
"=",
"(",
"match",
".",
"group",
"(",
"'username'",
")",
",",
"match",
".",
"group",
"(",
"'password'",
")",
")",
"headers",
"=",
"{",
"}",
"if",
"table_name",
":",
"headers",
"[",
"\"x-table-name\"",
"]",
"=",
"table_name",
"if",
"gsi_name",
":",
"headers",
"[",
"\"x-gsi-name\"",
"]",
"=",
"gsi_name",
"# Make the actual request",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"auth",
",",
"timeout",
"=",
"timeout",
"/",
"1000.00",
",",
"headers",
"=",
"headers",
")",
"if",
"int",
"(",
"response",
".",
"status_code",
")",
">=",
"200",
"and",
"int",
"(",
"response",
".",
"status_code",
")",
"<",
"300",
":",
"logger",
".",
"info",
"(",
"'Circuit breaker is closed'",
")",
"return",
"False",
"else",
":",
"logger",
".",
"warning",
"(",
"'Circuit breaker returned with status code {0:d}'",
".",
"format",
"(",
"response",
".",
"status_code",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"SSLError",
"as",
"error",
":",
"logger",
".",
"warning",
"(",
"'Circuit breaker: {0}'",
".",
"format",
"(",
"error",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
"as",
"error",
":",
"logger",
".",
"warning",
"(",
"'Circuit breaker: {0}'",
".",
"format",
"(",
"error",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"error",
":",
"logger",
".",
"warning",
"(",
"'Circuit breaker: {0}'",
".",
"format",
"(",
"error",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"error",
":",
"logger",
".",
"warning",
"(",
"'Circuit breaker: {0}'",
".",
"format",
"(",
"error",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"TooManyRedirects",
"as",
"error",
":",
"logger",
".",
"warning",
"(",
"'Circuit breaker: {0}'",
".",
"format",
"(",
"error",
")",
")",
"except",
"Exception",
"as",
"error",
":",
"logger",
".",
"error",
"(",
"'Unhandled exception: {0}'",
".",
"format",
"(",
"error",
")",
")",
"logger",
".",
"error",
"(",
"'Please file a bug at '",
"'https://github.com/sebdah/dynamic-dynamodb/issues'",
")",
"return",
"True"
] | Checks whether the circuit breaker is open
:param table_name: Name of the table being checked
:param table_key: Configuration key for table
:param gsi_name: Name of the GSI being checked
:param gsi_key: Configuration key for the GSI
:returns: bool -- True if the circuit is open | [
"Checks",
"whether",
"the",
"circuit",
"breaker",
"is",
"open"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/circuit_breaker.py#L13-L97 | train | 251,035 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/cloudwatch.py | __get_connection_cloudwatch | def __get_connection_cloudwatch():
""" Ensure connection to CloudWatch """
region = get_global_option('region')
try:
if (get_global_option('aws_access_key_id') and
get_global_option('aws_secret_access_key')):
logger.debug(
'Authenticating to CloudWatch using '
'credentials in configuration file')
connection = cloudwatch.connect_to_region(
region,
aws_access_key_id=get_global_option('aws_access_key_id'),
aws_secret_access_key=get_global_option(
'aws_secret_access_key'))
else:
logger.debug(
'Authenticating using boto\'s authentication handler')
connection = cloudwatch.connect_to_region(region)
except Exception as err:
logger.error('Failed connecting to CloudWatch: {0}'.format(err))
logger.error(
'Please report an issue at: '
'https://github.com/sebdah/dynamic-dynamodb/issues')
raise
logger.debug('Connected to CloudWatch in {0}'.format(region))
return connection | python | def __get_connection_cloudwatch():
""" Ensure connection to CloudWatch """
region = get_global_option('region')
try:
if (get_global_option('aws_access_key_id') and
get_global_option('aws_secret_access_key')):
logger.debug(
'Authenticating to CloudWatch using '
'credentials in configuration file')
connection = cloudwatch.connect_to_region(
region,
aws_access_key_id=get_global_option('aws_access_key_id'),
aws_secret_access_key=get_global_option(
'aws_secret_access_key'))
else:
logger.debug(
'Authenticating using boto\'s authentication handler')
connection = cloudwatch.connect_to_region(region)
except Exception as err:
logger.error('Failed connecting to CloudWatch: {0}'.format(err))
logger.error(
'Please report an issue at: '
'https://github.com/sebdah/dynamic-dynamodb/issues')
raise
logger.debug('Connected to CloudWatch in {0}'.format(region))
return connection | [
"def",
"__get_connection_cloudwatch",
"(",
")",
":",
"region",
"=",
"get_global_option",
"(",
"'region'",
")",
"try",
":",
"if",
"(",
"get_global_option",
"(",
"'aws_access_key_id'",
")",
"and",
"get_global_option",
"(",
"'aws_secret_access_key'",
")",
")",
":",
"logger",
".",
"debug",
"(",
"'Authenticating to CloudWatch using '",
"'credentials in configuration file'",
")",
"connection",
"=",
"cloudwatch",
".",
"connect_to_region",
"(",
"region",
",",
"aws_access_key_id",
"=",
"get_global_option",
"(",
"'aws_access_key_id'",
")",
",",
"aws_secret_access_key",
"=",
"get_global_option",
"(",
"'aws_secret_access_key'",
")",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Authenticating using boto\\'s authentication handler'",
")",
"connection",
"=",
"cloudwatch",
".",
"connect_to_region",
"(",
"region",
")",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"'Failed connecting to CloudWatch: {0}'",
".",
"format",
"(",
"err",
")",
")",
"logger",
".",
"error",
"(",
"'Please report an issue at: '",
"'https://github.com/sebdah/dynamic-dynamodb/issues'",
")",
"raise",
"logger",
".",
"debug",
"(",
"'Connected to CloudWatch in {0}'",
".",
"format",
"(",
"region",
")",
")",
"return",
"connection"
] | Ensure connection to CloudWatch | [
"Ensure",
"connection",
"to",
"CloudWatch"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/cloudwatch.py#L9-L36 | train | 251,036 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/dynamodb.py | get_tables_and_gsis | def get_tables_and_gsis():
""" Get a set of tables and gsis and their configuration keys
:returns: set -- A set of tuples (table_name, table_conf_key)
"""
table_names = set()
configured_tables = get_configured_tables()
not_used_tables = set(configured_tables)
# Add regexp table names
for table_instance in list_tables():
for key_name in configured_tables:
try:
if re.match(key_name, table_instance.table_name):
logger.debug("Table {0} match with config key {1}".format(
table_instance.table_name, key_name))
# Notify users about regexps that match multiple tables
if table_instance.table_name in [x[0] for x in table_names]:
logger.warning(
'Table {0} matches more than one regexp in config, '
'skipping this match: "{1}"'.format(
table_instance.table_name, key_name))
else:
table_names.add(
(
table_instance.table_name,
key_name
))
not_used_tables.discard(key_name)
else:
logger.debug(
"Table {0} did not match with config key {1}".format(
table_instance.table_name, key_name))
except re.error:
logger.error('Invalid regular expression: "{0}"'.format(
key_name))
sys.exit(1)
if not_used_tables:
logger.warning(
'No tables matching the following configured '
'tables found: {0}'.format(', '.join(not_used_tables)))
return sorted(table_names) | python | def get_tables_and_gsis():
""" Get a set of tables and gsis and their configuration keys
:returns: set -- A set of tuples (table_name, table_conf_key)
"""
table_names = set()
configured_tables = get_configured_tables()
not_used_tables = set(configured_tables)
# Add regexp table names
for table_instance in list_tables():
for key_name in configured_tables:
try:
if re.match(key_name, table_instance.table_name):
logger.debug("Table {0} match with config key {1}".format(
table_instance.table_name, key_name))
# Notify users about regexps that match multiple tables
if table_instance.table_name in [x[0] for x in table_names]:
logger.warning(
'Table {0} matches more than one regexp in config, '
'skipping this match: "{1}"'.format(
table_instance.table_name, key_name))
else:
table_names.add(
(
table_instance.table_name,
key_name
))
not_used_tables.discard(key_name)
else:
logger.debug(
"Table {0} did not match with config key {1}".format(
table_instance.table_name, key_name))
except re.error:
logger.error('Invalid regular expression: "{0}"'.format(
key_name))
sys.exit(1)
if not_used_tables:
logger.warning(
'No tables matching the following configured '
'tables found: {0}'.format(', '.join(not_used_tables)))
return sorted(table_names) | [
"def",
"get_tables_and_gsis",
"(",
")",
":",
"table_names",
"=",
"set",
"(",
")",
"configured_tables",
"=",
"get_configured_tables",
"(",
")",
"not_used_tables",
"=",
"set",
"(",
"configured_tables",
")",
"# Add regexp table names",
"for",
"table_instance",
"in",
"list_tables",
"(",
")",
":",
"for",
"key_name",
"in",
"configured_tables",
":",
"try",
":",
"if",
"re",
".",
"match",
"(",
"key_name",
",",
"table_instance",
".",
"table_name",
")",
":",
"logger",
".",
"debug",
"(",
"\"Table {0} match with config key {1}\"",
".",
"format",
"(",
"table_instance",
".",
"table_name",
",",
"key_name",
")",
")",
"# Notify users about regexps that match multiple tables",
"if",
"table_instance",
".",
"table_name",
"in",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"table_names",
"]",
":",
"logger",
".",
"warning",
"(",
"'Table {0} matches more than one regexp in config, '",
"'skipping this match: \"{1}\"'",
".",
"format",
"(",
"table_instance",
".",
"table_name",
",",
"key_name",
")",
")",
"else",
":",
"table_names",
".",
"add",
"(",
"(",
"table_instance",
".",
"table_name",
",",
"key_name",
")",
")",
"not_used_tables",
".",
"discard",
"(",
"key_name",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Table {0} did not match with config key {1}\"",
".",
"format",
"(",
"table_instance",
".",
"table_name",
",",
"key_name",
")",
")",
"except",
"re",
".",
"error",
":",
"logger",
".",
"error",
"(",
"'Invalid regular expression: \"{0}\"'",
".",
"format",
"(",
"key_name",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not_used_tables",
":",
"logger",
".",
"warning",
"(",
"'No tables matching the following configured '",
"'tables found: {0}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"not_used_tables",
")",
")",
")",
"return",
"sorted",
"(",
"table_names",
")"
] | Get a set of tables and gsis and their configuration keys
:returns: set -- A set of tuples (table_name, table_conf_key) | [
"Get",
"a",
"set",
"of",
"tables",
"and",
"gsis",
"and",
"their",
"configuration",
"keys"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L21-L65 | train | 251,037 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/dynamodb.py | list_tables | def list_tables():
""" Return list of DynamoDB tables available from AWS
:returns: list -- List of DynamoDB tables
"""
tables = []
try:
table_list = DYNAMODB_CONNECTION.list_tables()
while True:
for table_name in table_list[u'TableNames']:
tables.append(get_table(table_name))
if u'LastEvaluatedTableName' in table_list:
table_list = DYNAMODB_CONNECTION.list_tables(
table_list[u'LastEvaluatedTableName'])
else:
break
except DynamoDBResponseError as error:
dynamodb_error = error.body['__type'].rsplit('#', 1)[1]
if dynamodb_error == 'ResourceNotFoundException':
logger.error('No tables found')
elif dynamodb_error == 'AccessDeniedException':
logger.debug(
'Your AWS API keys lack access to listing tables. '
'That is an issue if you are trying to use regular '
'expressions in your table configuration.')
elif dynamodb_error == 'UnrecognizedClientException':
logger.error(
'Invalid security token. Are your AWS API keys correct?')
else:
logger.error(
(
'Unhandled exception: {0}: {1}. '
'Please file a bug report at '
'https://github.com/sebdah/dynamic-dynamodb/issues'
).format(
dynamodb_error,
error.body['message']))
except JSONResponseError as error:
logger.error('Communication error: {0}'.format(error))
sys.exit(1)
return tables | python | def list_tables():
""" Return list of DynamoDB tables available from AWS
:returns: list -- List of DynamoDB tables
"""
tables = []
try:
table_list = DYNAMODB_CONNECTION.list_tables()
while True:
for table_name in table_list[u'TableNames']:
tables.append(get_table(table_name))
if u'LastEvaluatedTableName' in table_list:
table_list = DYNAMODB_CONNECTION.list_tables(
table_list[u'LastEvaluatedTableName'])
else:
break
except DynamoDBResponseError as error:
dynamodb_error = error.body['__type'].rsplit('#', 1)[1]
if dynamodb_error == 'ResourceNotFoundException':
logger.error('No tables found')
elif dynamodb_error == 'AccessDeniedException':
logger.debug(
'Your AWS API keys lack access to listing tables. '
'That is an issue if you are trying to use regular '
'expressions in your table configuration.')
elif dynamodb_error == 'UnrecognizedClientException':
logger.error(
'Invalid security token. Are your AWS API keys correct?')
else:
logger.error(
(
'Unhandled exception: {0}: {1}. '
'Please file a bug report at '
'https://github.com/sebdah/dynamic-dynamodb/issues'
).format(
dynamodb_error,
error.body['message']))
except JSONResponseError as error:
logger.error('Communication error: {0}'.format(error))
sys.exit(1)
return tables | [
"def",
"list_tables",
"(",
")",
":",
"tables",
"=",
"[",
"]",
"try",
":",
"table_list",
"=",
"DYNAMODB_CONNECTION",
".",
"list_tables",
"(",
")",
"while",
"True",
":",
"for",
"table_name",
"in",
"table_list",
"[",
"u'TableNames'",
"]",
":",
"tables",
".",
"append",
"(",
"get_table",
"(",
"table_name",
")",
")",
"if",
"u'LastEvaluatedTableName'",
"in",
"table_list",
":",
"table_list",
"=",
"DYNAMODB_CONNECTION",
".",
"list_tables",
"(",
"table_list",
"[",
"u'LastEvaluatedTableName'",
"]",
")",
"else",
":",
"break",
"except",
"DynamoDBResponseError",
"as",
"error",
":",
"dynamodb_error",
"=",
"error",
".",
"body",
"[",
"'__type'",
"]",
".",
"rsplit",
"(",
"'#'",
",",
"1",
")",
"[",
"1",
"]",
"if",
"dynamodb_error",
"==",
"'ResourceNotFoundException'",
":",
"logger",
".",
"error",
"(",
"'No tables found'",
")",
"elif",
"dynamodb_error",
"==",
"'AccessDeniedException'",
":",
"logger",
".",
"debug",
"(",
"'Your AWS API keys lack access to listing tables. '",
"'That is an issue if you are trying to use regular '",
"'expressions in your table configuration.'",
")",
"elif",
"dynamodb_error",
"==",
"'UnrecognizedClientException'",
":",
"logger",
".",
"error",
"(",
"'Invalid security token. Are your AWS API keys correct?'",
")",
"else",
":",
"logger",
".",
"error",
"(",
"(",
"'Unhandled exception: {0}: {1}. '",
"'Please file a bug report at '",
"'https://github.com/sebdah/dynamic-dynamodb/issues'",
")",
".",
"format",
"(",
"dynamodb_error",
",",
"error",
".",
"body",
"[",
"'message'",
"]",
")",
")",
"except",
"JSONResponseError",
"as",
"error",
":",
"logger",
".",
"error",
"(",
"'Communication error: {0}'",
".",
"format",
"(",
"error",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"tables"
] | Return list of DynamoDB tables available from AWS
:returns: list -- List of DynamoDB tables | [
"Return",
"list",
"of",
"DynamoDB",
"tables",
"available",
"from",
"AWS"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L214-L260 | train | 251,038 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/dynamodb.py | table_gsis | def table_gsis(table_name):
""" Returns a list of GSIs for the given table
:type table_name: str
:param table_name: Name of the DynamoDB table
:returns: list -- List of GSI names
"""
try:
desc = DYNAMODB_CONNECTION.describe_table(table_name)[u'Table']
except JSONResponseError:
raise
if u'GlobalSecondaryIndexes' in desc:
return desc[u'GlobalSecondaryIndexes']
return [] | python | def table_gsis(table_name):
""" Returns a list of GSIs for the given table
:type table_name: str
:param table_name: Name of the DynamoDB table
:returns: list -- List of GSI names
"""
try:
desc = DYNAMODB_CONNECTION.describe_table(table_name)[u'Table']
except JSONResponseError:
raise
if u'GlobalSecondaryIndexes' in desc:
return desc[u'GlobalSecondaryIndexes']
return [] | [
"def",
"table_gsis",
"(",
"table_name",
")",
":",
"try",
":",
"desc",
"=",
"DYNAMODB_CONNECTION",
".",
"describe_table",
"(",
"table_name",
")",
"[",
"u'Table'",
"]",
"except",
"JSONResponseError",
":",
"raise",
"if",
"u'GlobalSecondaryIndexes'",
"in",
"desc",
":",
"return",
"desc",
"[",
"u'GlobalSecondaryIndexes'",
"]",
"return",
"[",
"]"
] | Returns a list of GSIs for the given table
:type table_name: str
:param table_name: Name of the DynamoDB table
:returns: list -- List of GSI names | [
"Returns",
"a",
"list",
"of",
"GSIs",
"for",
"the",
"given",
"table"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L602-L617 | train | 251,039 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/dynamodb.py | __get_connection_dynamodb | def __get_connection_dynamodb(retries=3):
""" Ensure connection to DynamoDB
:type retries: int
:param retries: Number of times to retry to connect to DynamoDB
"""
connected = False
region = get_global_option('region')
while not connected:
if (get_global_option('aws_access_key_id') and
get_global_option('aws_secret_access_key')):
logger.debug(
'Authenticating to DynamoDB using '
'credentials in configuration file')
connection = dynamodb2.connect_to_region(
region,
aws_access_key_id=get_global_option('aws_access_key_id'),
aws_secret_access_key=get_global_option(
'aws_secret_access_key'))
else:
logger.debug(
'Authenticating using boto\'s authentication handler')
connection = dynamodb2.connect_to_region(region)
if not connection:
if retries == 0:
logger.error('Failed to connect to DynamoDB. Giving up.')
raise
else:
logger.error(
'Failed to connect to DynamoDB. Retrying in 5 seconds')
retries -= 1
time.sleep(5)
else:
connected = True
logger.debug('Connected to DynamoDB in {0}'.format(region))
return connection | python | def __get_connection_dynamodb(retries=3):
""" Ensure connection to DynamoDB
:type retries: int
:param retries: Number of times to retry to connect to DynamoDB
"""
connected = False
region = get_global_option('region')
while not connected:
if (get_global_option('aws_access_key_id') and
get_global_option('aws_secret_access_key')):
logger.debug(
'Authenticating to DynamoDB using '
'credentials in configuration file')
connection = dynamodb2.connect_to_region(
region,
aws_access_key_id=get_global_option('aws_access_key_id'),
aws_secret_access_key=get_global_option(
'aws_secret_access_key'))
else:
logger.debug(
'Authenticating using boto\'s authentication handler')
connection = dynamodb2.connect_to_region(region)
if not connection:
if retries == 0:
logger.error('Failed to connect to DynamoDB. Giving up.')
raise
else:
logger.error(
'Failed to connect to DynamoDB. Retrying in 5 seconds')
retries -= 1
time.sleep(5)
else:
connected = True
logger.debug('Connected to DynamoDB in {0}'.format(region))
return connection | [
"def",
"__get_connection_dynamodb",
"(",
"retries",
"=",
"3",
")",
":",
"connected",
"=",
"False",
"region",
"=",
"get_global_option",
"(",
"'region'",
")",
"while",
"not",
"connected",
":",
"if",
"(",
"get_global_option",
"(",
"'aws_access_key_id'",
")",
"and",
"get_global_option",
"(",
"'aws_secret_access_key'",
")",
")",
":",
"logger",
".",
"debug",
"(",
"'Authenticating to DynamoDB using '",
"'credentials in configuration file'",
")",
"connection",
"=",
"dynamodb2",
".",
"connect_to_region",
"(",
"region",
",",
"aws_access_key_id",
"=",
"get_global_option",
"(",
"'aws_access_key_id'",
")",
",",
"aws_secret_access_key",
"=",
"get_global_option",
"(",
"'aws_secret_access_key'",
")",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Authenticating using boto\\'s authentication handler'",
")",
"connection",
"=",
"dynamodb2",
".",
"connect_to_region",
"(",
"region",
")",
"if",
"not",
"connection",
":",
"if",
"retries",
"==",
"0",
":",
"logger",
".",
"error",
"(",
"'Failed to connect to DynamoDB. Giving up.'",
")",
"raise",
"else",
":",
"logger",
".",
"error",
"(",
"'Failed to connect to DynamoDB. Retrying in 5 seconds'",
")",
"retries",
"-=",
"1",
"time",
".",
"sleep",
"(",
"5",
")",
"else",
":",
"connected",
"=",
"True",
"logger",
".",
"debug",
"(",
"'Connected to DynamoDB in {0}'",
".",
"format",
"(",
"region",
")",
")",
"return",
"connection"
] | Ensure connection to DynamoDB
:type retries: int
:param retries: Number of times to retry to connect to DynamoDB | [
"Ensure",
"connection",
"to",
"DynamoDB"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L620-L658 | train | 251,040 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/dynamodb.py | __is_gsi_maintenance_window | def __is_gsi_maintenance_window(table_name, gsi_name, maintenance_windows):
""" Checks that the current time is within the maintenance window
:type table_name: str
:param table_name: Name of the DynamoDB table
:type gsi_name: str
:param gsi_name: Name of the GSI
:type maintenance_windows: str
:param maintenance_windows: Example: '00:00-01:00,10:00-11:00'
:returns: bool -- True if within maintenance window
"""
# Example string '00:00-01:00,10:00-11:00'
maintenance_window_list = []
for window in maintenance_windows.split(','):
try:
start, end = window.split('-', 1)
except ValueError:
logger.error(
'{0} - GSI: {1} - '
'Malformatted maintenance window'.format(table_name, gsi_name))
return False
maintenance_window_list.append((start, end))
now = datetime.datetime.utcnow().strftime('%H%M')
for maintenance_window in maintenance_window_list:
start = ''.join(maintenance_window[0].split(':'))
end = ''.join(maintenance_window[1].split(':'))
if now >= start and now <= end:
return True
return False | python | def __is_gsi_maintenance_window(table_name, gsi_name, maintenance_windows):
""" Checks that the current time is within the maintenance window
:type table_name: str
:param table_name: Name of the DynamoDB table
:type gsi_name: str
:param gsi_name: Name of the GSI
:type maintenance_windows: str
:param maintenance_windows: Example: '00:00-01:00,10:00-11:00'
:returns: bool -- True if within maintenance window
"""
# Example string '00:00-01:00,10:00-11:00'
maintenance_window_list = []
for window in maintenance_windows.split(','):
try:
start, end = window.split('-', 1)
except ValueError:
logger.error(
'{0} - GSI: {1} - '
'Malformatted maintenance window'.format(table_name, gsi_name))
return False
maintenance_window_list.append((start, end))
now = datetime.datetime.utcnow().strftime('%H%M')
for maintenance_window in maintenance_window_list:
start = ''.join(maintenance_window[0].split(':'))
end = ''.join(maintenance_window[1].split(':'))
if now >= start and now <= end:
return True
return False | [
"def",
"__is_gsi_maintenance_window",
"(",
"table_name",
",",
"gsi_name",
",",
"maintenance_windows",
")",
":",
"# Example string '00:00-01:00,10:00-11:00'",
"maintenance_window_list",
"=",
"[",
"]",
"for",
"window",
"in",
"maintenance_windows",
".",
"split",
"(",
"','",
")",
":",
"try",
":",
"start",
",",
"end",
"=",
"window",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"except",
"ValueError",
":",
"logger",
".",
"error",
"(",
"'{0} - GSI: {1} - '",
"'Malformatted maintenance window'",
".",
"format",
"(",
"table_name",
",",
"gsi_name",
")",
")",
"return",
"False",
"maintenance_window_list",
".",
"append",
"(",
"(",
"start",
",",
"end",
")",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"'%H%M'",
")",
"for",
"maintenance_window",
"in",
"maintenance_window_list",
":",
"start",
"=",
"''",
".",
"join",
"(",
"maintenance_window",
"[",
"0",
"]",
".",
"split",
"(",
"':'",
")",
")",
"end",
"=",
"''",
".",
"join",
"(",
"maintenance_window",
"[",
"1",
"]",
".",
"split",
"(",
"':'",
")",
")",
"if",
"now",
">=",
"start",
"and",
"now",
"<=",
"end",
":",
"return",
"True",
"return",
"False"
] | Checks that the current time is within the maintenance window
:type table_name: str
:param table_name: Name of the DynamoDB table
:type gsi_name: str
:param gsi_name: Name of the GSI
:type maintenance_windows: str
:param maintenance_windows: Example: '00:00-01:00,10:00-11:00'
:returns: bool -- True if within maintenance window | [
"Checks",
"that",
"the",
"current",
"time",
"is",
"within",
"the",
"maintenance",
"window"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L661-L692 | train | 251,041 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/sns.py | publish_gsi_notification | def publish_gsi_notification(
table_key, gsi_key, message, message_types, subject=None):
""" Publish a notification for a specific GSI
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_key: str
:param gsi_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:param message_types:
List with types:
- scale-up
- scale-down
- high-throughput-alarm
- low-throughput-alarm
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None
"""
topic = get_gsi_option(table_key, gsi_key, 'sns_topic_arn')
if not topic:
return
for message_type in message_types:
if (message_type in
get_gsi_option(table_key, gsi_key, 'sns_message_types')):
__publish(topic, message, subject)
return | python | def publish_gsi_notification(
table_key, gsi_key, message, message_types, subject=None):
""" Publish a notification for a specific GSI
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_key: str
:param gsi_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:param message_types:
List with types:
- scale-up
- scale-down
- high-throughput-alarm
- low-throughput-alarm
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None
"""
topic = get_gsi_option(table_key, gsi_key, 'sns_topic_arn')
if not topic:
return
for message_type in message_types:
if (message_type in
get_gsi_option(table_key, gsi_key, 'sns_message_types')):
__publish(topic, message, subject)
return | [
"def",
"publish_gsi_notification",
"(",
"table_key",
",",
"gsi_key",
",",
"message",
",",
"message_types",
",",
"subject",
"=",
"None",
")",
":",
"topic",
"=",
"get_gsi_option",
"(",
"table_key",
",",
"gsi_key",
",",
"'sns_topic_arn'",
")",
"if",
"not",
"topic",
":",
"return",
"for",
"message_type",
"in",
"message_types",
":",
"if",
"(",
"message_type",
"in",
"get_gsi_option",
"(",
"table_key",
",",
"gsi_key",
",",
"'sns_message_types'",
")",
")",
":",
"__publish",
"(",
"topic",
",",
"message",
",",
"subject",
")",
"return"
] | Publish a notification for a specific GSI
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_key: str
:param gsi_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:param message_types:
List with types:
- scale-up
- scale-down
- high-throughput-alarm
- low-throughput-alarm
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None | [
"Publish",
"a",
"notification",
"for",
"a",
"specific",
"GSI"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L11-L40 | train | 251,042 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/sns.py | publish_table_notification | def publish_table_notification(table_key, message, message_types, subject=None):
""" Publish a notification for a specific table
:type table_key: str
:param table_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:param message_types:
List with types:
- scale-up
- scale-down
- high-throughput-alarm
- low-throughput-alarm
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None
"""
topic = get_table_option(table_key, 'sns_topic_arn')
if not topic:
return
for message_type in message_types:
if message_type in get_table_option(table_key, 'sns_message_types'):
__publish(topic, message, subject)
return | python | def publish_table_notification(table_key, message, message_types, subject=None):
""" Publish a notification for a specific table
:type table_key: str
:param table_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:param message_types:
List with types:
- scale-up
- scale-down
- high-throughput-alarm
- low-throughput-alarm
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None
"""
topic = get_table_option(table_key, 'sns_topic_arn')
if not topic:
return
for message_type in message_types:
if message_type in get_table_option(table_key, 'sns_message_types'):
__publish(topic, message, subject)
return | [
"def",
"publish_table_notification",
"(",
"table_key",
",",
"message",
",",
"message_types",
",",
"subject",
"=",
"None",
")",
":",
"topic",
"=",
"get_table_option",
"(",
"table_key",
",",
"'sns_topic_arn'",
")",
"if",
"not",
"topic",
":",
"return",
"for",
"message_type",
"in",
"message_types",
":",
"if",
"message_type",
"in",
"get_table_option",
"(",
"table_key",
",",
"'sns_message_types'",
")",
":",
"__publish",
"(",
"topic",
",",
"message",
",",
"subject",
")",
"return"
] | Publish a notification for a specific table
:type table_key: str
:param table_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:param message_types:
List with types:
- scale-up
- scale-down
- high-throughput-alarm
- low-throughput-alarm
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None | [
"Publish",
"a",
"notification",
"for",
"a",
"specific",
"table"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L43-L68 | train | 251,043 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/sns.py | __publish | def __publish(topic, message, subject=None):
""" Publish a message to a SNS topic
:type topic: str
:param topic: SNS topic to publish the message to
:type message: str
:param message: Message to send via SNS
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None
"""
try:
SNS_CONNECTION.publish(topic=topic, message=message, subject=subject)
logger.info('Sent SNS notification to {0}'.format(topic))
except BotoServerError as error:
logger.error('Problem sending SNS notification: {0}'.format(
error.message))
return | python | def __publish(topic, message, subject=None):
""" Publish a message to a SNS topic
:type topic: str
:param topic: SNS topic to publish the message to
:type message: str
:param message: Message to send via SNS
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None
"""
try:
SNS_CONNECTION.publish(topic=topic, message=message, subject=subject)
logger.info('Sent SNS notification to {0}'.format(topic))
except BotoServerError as error:
logger.error('Problem sending SNS notification: {0}'.format(
error.message))
return | [
"def",
"__publish",
"(",
"topic",
",",
"message",
",",
"subject",
"=",
"None",
")",
":",
"try",
":",
"SNS_CONNECTION",
".",
"publish",
"(",
"topic",
"=",
"topic",
",",
"message",
"=",
"message",
",",
"subject",
"=",
"subject",
")",
"logger",
".",
"info",
"(",
"'Sent SNS notification to {0}'",
".",
"format",
"(",
"topic",
")",
")",
"except",
"BotoServerError",
"as",
"error",
":",
"logger",
".",
"error",
"(",
"'Problem sending SNS notification: {0}'",
".",
"format",
"(",
"error",
".",
"message",
")",
")",
"return"
] | Publish a message to a SNS topic
:type topic: str
:param topic: SNS topic to publish the message to
:type message: str
:param message: Message to send via SNS
:type subject: str
:param subject: Subject to use for e-mail notifications
:returns: None | [
"Publish",
"a",
"message",
"to",
"a",
"SNS",
"topic"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L71-L89 | train | 251,044 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/sns.py | __get_connection_SNS | def __get_connection_SNS():
""" Ensure connection to SNS """
region = get_global_option('region')
try:
if (get_global_option('aws_access_key_id') and
get_global_option('aws_secret_access_key')):
logger.debug(
'Authenticating to SNS using '
'credentials in configuration file')
connection = sns.connect_to_region(
region,
aws_access_key_id=get_global_option(
'aws_access_key_id'),
aws_secret_access_key=get_global_option(
'aws_secret_access_key'))
else:
logger.debug(
'Authenticating using boto\'s authentication handler')
connection = sns.connect_to_region(region)
except Exception as err:
logger.error('Failed connecting to SNS: {0}'.format(err))
logger.error(
'Please report an issue at: '
'https://github.com/sebdah/dynamic-dynamodb/issues')
raise
logger.debug('Connected to SNS in {0}'.format(region))
return connection | python | def __get_connection_SNS():
""" Ensure connection to SNS """
region = get_global_option('region')
try:
if (get_global_option('aws_access_key_id') and
get_global_option('aws_secret_access_key')):
logger.debug(
'Authenticating to SNS using '
'credentials in configuration file')
connection = sns.connect_to_region(
region,
aws_access_key_id=get_global_option(
'aws_access_key_id'),
aws_secret_access_key=get_global_option(
'aws_secret_access_key'))
else:
logger.debug(
'Authenticating using boto\'s authentication handler')
connection = sns.connect_to_region(region)
except Exception as err:
logger.error('Failed connecting to SNS: {0}'.format(err))
logger.error(
'Please report an issue at: '
'https://github.com/sebdah/dynamic-dynamodb/issues')
raise
logger.debug('Connected to SNS in {0}'.format(region))
return connection | [
"def",
"__get_connection_SNS",
"(",
")",
":",
"region",
"=",
"get_global_option",
"(",
"'region'",
")",
"try",
":",
"if",
"(",
"get_global_option",
"(",
"'aws_access_key_id'",
")",
"and",
"get_global_option",
"(",
"'aws_secret_access_key'",
")",
")",
":",
"logger",
".",
"debug",
"(",
"'Authenticating to SNS using '",
"'credentials in configuration file'",
")",
"connection",
"=",
"sns",
".",
"connect_to_region",
"(",
"region",
",",
"aws_access_key_id",
"=",
"get_global_option",
"(",
"'aws_access_key_id'",
")",
",",
"aws_secret_access_key",
"=",
"get_global_option",
"(",
"'aws_secret_access_key'",
")",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Authenticating using boto\\'s authentication handler'",
")",
"connection",
"=",
"sns",
".",
"connect_to_region",
"(",
"region",
")",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"'Failed connecting to SNS: {0}'",
".",
"format",
"(",
"err",
")",
")",
"logger",
".",
"error",
"(",
"'Please report an issue at: '",
"'https://github.com/sebdah/dynamic-dynamodb/issues'",
")",
"raise",
"logger",
".",
"debug",
"(",
"'Connected to SNS in {0}'",
".",
"format",
"(",
"region",
")",
")",
"return",
"connection"
] | Ensure connection to SNS | [
"Ensure",
"connection",
"to",
"SNS"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L92-L121 | train | 251,045 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/core/table.py | __calculate_always_decrease_rw_values | def __calculate_always_decrease_rw_values(
table_name, read_units, provisioned_reads,
write_units, provisioned_writes):
""" Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
:type table_name: str
:param table_name: Name of the DynamoDB table
:type read_units: int
:param read_units: New read unit provisioning
:type provisioned_reads: int
:param provisioned_reads: Currently provisioned reads
:type write_units: int
:param write_units: New write unit provisioning
:type provisioned_writes: int
:param provisioned_writes: Currently provisioned writes
:returns: (int, int) -- (reads, writes)
"""
if read_units <= provisioned_reads and write_units <= provisioned_writes:
return (read_units, write_units)
if read_units < provisioned_reads:
logger.info(
'{0} - Reads could be decreased, but we are waiting for '
'writes to get lower than the threshold before '
'scaling down'.format(table_name))
read_units = provisioned_reads
elif write_units < provisioned_writes:
logger.info(
'{0} - Writes could be decreased, but we are waiting for '
'reads to get lower than the threshold before '
'scaling down'.format(table_name))
write_units = provisioned_writes
return (read_units, write_units) | python | def __calculate_always_decrease_rw_values(
table_name, read_units, provisioned_reads,
write_units, provisioned_writes):
""" Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
:type table_name: str
:param table_name: Name of the DynamoDB table
:type read_units: int
:param read_units: New read unit provisioning
:type provisioned_reads: int
:param provisioned_reads: Currently provisioned reads
:type write_units: int
:param write_units: New write unit provisioning
:type provisioned_writes: int
:param provisioned_writes: Currently provisioned writes
:returns: (int, int) -- (reads, writes)
"""
if read_units <= provisioned_reads and write_units <= provisioned_writes:
return (read_units, write_units)
if read_units < provisioned_reads:
logger.info(
'{0} - Reads could be decreased, but we are waiting for '
'writes to get lower than the threshold before '
'scaling down'.format(table_name))
read_units = provisioned_reads
elif write_units < provisioned_writes:
logger.info(
'{0} - Writes could be decreased, but we are waiting for '
'reads to get lower than the threshold before '
'scaling down'.format(table_name))
write_units = provisioned_writes
return (read_units, write_units) | [
"def",
"__calculate_always_decrease_rw_values",
"(",
"table_name",
",",
"read_units",
",",
"provisioned_reads",
",",
"write_units",
",",
"provisioned_writes",
")",
":",
"if",
"read_units",
"<=",
"provisioned_reads",
"and",
"write_units",
"<=",
"provisioned_writes",
":",
"return",
"(",
"read_units",
",",
"write_units",
")",
"if",
"read_units",
"<",
"provisioned_reads",
":",
"logger",
".",
"info",
"(",
"'{0} - Reads could be decreased, but we are waiting for '",
"'writes to get lower than the threshold before '",
"'scaling down'",
".",
"format",
"(",
"table_name",
")",
")",
"read_units",
"=",
"provisioned_reads",
"elif",
"write_units",
"<",
"provisioned_writes",
":",
"logger",
".",
"info",
"(",
"'{0} - Writes could be decreased, but we are waiting for '",
"'reads to get lower than the threshold before '",
"'scaling down'",
".",
"format",
"(",
"table_name",
")",
")",
"write_units",
"=",
"provisioned_writes",
"return",
"(",
"read_units",
",",
"write_units",
")"
] | Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
:type table_name: str
:param table_name: Name of the DynamoDB table
:type read_units: int
:param read_units: New read unit provisioning
:type provisioned_reads: int
:param provisioned_reads: Currently provisioned reads
:type write_units: int
:param write_units: New write unit provisioning
:type provisioned_writes: int
:param provisioned_writes: Currently provisioned writes
:returns: (int, int) -- (reads, writes) | [
"Calculate",
"values",
"for",
"always",
"-",
"decrease",
"-",
"rw",
"-",
"together"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/table.py#L81-L121 | train | 251,046 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/core/table.py | __update_throughput | def __update_throughput(table_name, key_name, read_units, write_units):
""" Update throughput on the DynamoDB table
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type read_units: int
:param read_units: New read unit provisioning
:type write_units: int
:param write_units: New write unit provisioning
"""
try:
current_ru = dynamodb.get_provisioned_table_read_units(table_name)
current_wu = dynamodb.get_provisioned_table_write_units(table_name)
except JSONResponseError:
raise
# Check table status
try:
table_status = dynamodb.get_table_status(table_name)
except JSONResponseError:
raise
logger.debug('{0} - Table status is {1}'.format(table_name, table_status))
if table_status != 'ACTIVE':
logger.warning(
'{0} - Not performing throughput changes when table '
'is {1}'.format(table_name, table_status))
return
# If this setting is True, we will only scale down when
# BOTH reads AND writes are low
if get_table_option(key_name, 'always_decrease_rw_together'):
read_units, write_units = __calculate_always_decrease_rw_values(
table_name,
read_units,
current_ru,
write_units,
current_wu)
if read_units == current_ru and write_units == current_wu:
logger.info('{0} - No changes to perform'.format(table_name))
return
dynamodb.update_table_provisioning(
table_name,
key_name,
int(read_units),
int(write_units)) | python | def __update_throughput(table_name, key_name, read_units, write_units):
""" Update throughput on the DynamoDB table
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type read_units: int
:param read_units: New read unit provisioning
:type write_units: int
:param write_units: New write unit provisioning
"""
try:
current_ru = dynamodb.get_provisioned_table_read_units(table_name)
current_wu = dynamodb.get_provisioned_table_write_units(table_name)
except JSONResponseError:
raise
# Check table status
try:
table_status = dynamodb.get_table_status(table_name)
except JSONResponseError:
raise
logger.debug('{0} - Table status is {1}'.format(table_name, table_status))
if table_status != 'ACTIVE':
logger.warning(
'{0} - Not performing throughput changes when table '
'is {1}'.format(table_name, table_status))
return
# If this setting is True, we will only scale down when
# BOTH reads AND writes are low
if get_table_option(key_name, 'always_decrease_rw_together'):
read_units, write_units = __calculate_always_decrease_rw_values(
table_name,
read_units,
current_ru,
write_units,
current_wu)
if read_units == current_ru and write_units == current_wu:
logger.info('{0} - No changes to perform'.format(table_name))
return
dynamodb.update_table_provisioning(
table_name,
key_name,
int(read_units),
int(write_units)) | [
"def",
"__update_throughput",
"(",
"table_name",
",",
"key_name",
",",
"read_units",
",",
"write_units",
")",
":",
"try",
":",
"current_ru",
"=",
"dynamodb",
".",
"get_provisioned_table_read_units",
"(",
"table_name",
")",
"current_wu",
"=",
"dynamodb",
".",
"get_provisioned_table_write_units",
"(",
"table_name",
")",
"except",
"JSONResponseError",
":",
"raise",
"# Check table status",
"try",
":",
"table_status",
"=",
"dynamodb",
".",
"get_table_status",
"(",
"table_name",
")",
"except",
"JSONResponseError",
":",
"raise",
"logger",
".",
"debug",
"(",
"'{0} - Table status is {1}'",
".",
"format",
"(",
"table_name",
",",
"table_status",
")",
")",
"if",
"table_status",
"!=",
"'ACTIVE'",
":",
"logger",
".",
"warning",
"(",
"'{0} - Not performing throughput changes when table '",
"'is {1}'",
".",
"format",
"(",
"table_name",
",",
"table_status",
")",
")",
"return",
"# If this setting is True, we will only scale down when",
"# BOTH reads AND writes are low",
"if",
"get_table_option",
"(",
"key_name",
",",
"'always_decrease_rw_together'",
")",
":",
"read_units",
",",
"write_units",
"=",
"__calculate_always_decrease_rw_values",
"(",
"table_name",
",",
"read_units",
",",
"current_ru",
",",
"write_units",
",",
"current_wu",
")",
"if",
"read_units",
"==",
"current_ru",
"and",
"write_units",
"==",
"current_wu",
":",
"logger",
".",
"info",
"(",
"'{0} - No changes to perform'",
".",
"format",
"(",
"table_name",
")",
")",
"return",
"dynamodb",
".",
"update_table_provisioning",
"(",
"table_name",
",",
"key_name",
",",
"int",
"(",
"read_units",
")",
",",
"int",
"(",
"write_units",
")",
")"
] | Update throughput on the DynamoDB table
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type read_units: int
:param read_units: New read unit provisioning
:type write_units: int
:param write_units: New write unit provisioning | [
"Update",
"throughput",
"on",
"the",
"DynamoDB",
"table"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/table.py#L897-L945 | train | 251,047 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/config/__init__.py | get_configuration | def get_configuration():
""" Get the configuration from command line and config files """
# This is the dict we will return
configuration = {
'global': {},
'logging': {},
'tables': ordereddict()
}
# Read the command line options
cmd_line_options = command_line_parser.parse()
# If a configuration file is specified, read that as well
conf_file_options = None
if 'config' in cmd_line_options:
conf_file_options = config_file_parser.parse(
cmd_line_options['config'])
# Extract global config
configuration['global'] = __get_global_options(
cmd_line_options,
conf_file_options)
# Extract logging config
configuration['logging'] = __get_logging_options(
cmd_line_options,
conf_file_options)
# Extract table configuration
# If the --table cmd line option is set, it indicates that only table
# options from the command line should be used
if 'table_name' in cmd_line_options:
configuration['tables'] = __get_cmd_table_options(cmd_line_options)
else:
configuration['tables'] = __get_config_table_options(conf_file_options)
# Ensure some basic rules
__check_gsi_rules(configuration)
__check_logging_rules(configuration)
__check_table_rules(configuration)
return configuration | python | def get_configuration():
""" Get the configuration from command line and config files """
# This is the dict we will return
configuration = {
'global': {},
'logging': {},
'tables': ordereddict()
}
# Read the command line options
cmd_line_options = command_line_parser.parse()
# If a configuration file is specified, read that as well
conf_file_options = None
if 'config' in cmd_line_options:
conf_file_options = config_file_parser.parse(
cmd_line_options['config'])
# Extract global config
configuration['global'] = __get_global_options(
cmd_line_options,
conf_file_options)
# Extract logging config
configuration['logging'] = __get_logging_options(
cmd_line_options,
conf_file_options)
# Extract table configuration
# If the --table cmd line option is set, it indicates that only table
# options from the command line should be used
if 'table_name' in cmd_line_options:
configuration['tables'] = __get_cmd_table_options(cmd_line_options)
else:
configuration['tables'] = __get_config_table_options(conf_file_options)
# Ensure some basic rules
__check_gsi_rules(configuration)
__check_logging_rules(configuration)
__check_table_rules(configuration)
return configuration | [
"def",
"get_configuration",
"(",
")",
":",
"# This is the dict we will return",
"configuration",
"=",
"{",
"'global'",
":",
"{",
"}",
",",
"'logging'",
":",
"{",
"}",
",",
"'tables'",
":",
"ordereddict",
"(",
")",
"}",
"# Read the command line options",
"cmd_line_options",
"=",
"command_line_parser",
".",
"parse",
"(",
")",
"# If a configuration file is specified, read that as well",
"conf_file_options",
"=",
"None",
"if",
"'config'",
"in",
"cmd_line_options",
":",
"conf_file_options",
"=",
"config_file_parser",
".",
"parse",
"(",
"cmd_line_options",
"[",
"'config'",
"]",
")",
"# Extract global config",
"configuration",
"[",
"'global'",
"]",
"=",
"__get_global_options",
"(",
"cmd_line_options",
",",
"conf_file_options",
")",
"# Extract logging config",
"configuration",
"[",
"'logging'",
"]",
"=",
"__get_logging_options",
"(",
"cmd_line_options",
",",
"conf_file_options",
")",
"# Extract table configuration",
"# If the --table cmd line option is set, it indicates that only table",
"# options from the command line should be used",
"if",
"'table_name'",
"in",
"cmd_line_options",
":",
"configuration",
"[",
"'tables'",
"]",
"=",
"__get_cmd_table_options",
"(",
"cmd_line_options",
")",
"else",
":",
"configuration",
"[",
"'tables'",
"]",
"=",
"__get_config_table_options",
"(",
"conf_file_options",
")",
"# Ensure some basic rules",
"__check_gsi_rules",
"(",
"configuration",
")",
"__check_logging_rules",
"(",
"configuration",
")",
"__check_table_rules",
"(",
"configuration",
")",
"return",
"configuration"
] | Get the configuration from command line and config files | [
"Get",
"the",
"configuration",
"from",
"command",
"line",
"and",
"config",
"files"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L162-L203 | train | 251,048 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/config/__init__.py | __get_cmd_table_options | def __get_cmd_table_options(cmd_line_options):
""" Get all table options from the command line
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:returns: dict -- E.g. {'table_name': {}}
"""
table_name = cmd_line_options['table_name']
options = {table_name: {}}
for option in DEFAULT_OPTIONS['table'].keys():
options[table_name][option] = DEFAULT_OPTIONS['table'][option]
if option in cmd_line_options:
options[table_name][option] = cmd_line_options[option]
return options | python | def __get_cmd_table_options(cmd_line_options):
""" Get all table options from the command line
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:returns: dict -- E.g. {'table_name': {}}
"""
table_name = cmd_line_options['table_name']
options = {table_name: {}}
for option in DEFAULT_OPTIONS['table'].keys():
options[table_name][option] = DEFAULT_OPTIONS['table'][option]
if option in cmd_line_options:
options[table_name][option] = cmd_line_options[option]
return options | [
"def",
"__get_cmd_table_options",
"(",
"cmd_line_options",
")",
":",
"table_name",
"=",
"cmd_line_options",
"[",
"'table_name'",
"]",
"options",
"=",
"{",
"table_name",
":",
"{",
"}",
"}",
"for",
"option",
"in",
"DEFAULT_OPTIONS",
"[",
"'table'",
"]",
".",
"keys",
"(",
")",
":",
"options",
"[",
"table_name",
"]",
"[",
"option",
"]",
"=",
"DEFAULT_OPTIONS",
"[",
"'table'",
"]",
"[",
"option",
"]",
"if",
"option",
"in",
"cmd_line_options",
":",
"options",
"[",
"table_name",
"]",
"[",
"option",
"]",
"=",
"cmd_line_options",
"[",
"option",
"]",
"return",
"options"
] | Get all table options from the command line
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:returns: dict -- E.g. {'table_name': {}} | [
"Get",
"all",
"table",
"options",
"from",
"the",
"command",
"line"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L206-L222 | train | 251,049 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/config/__init__.py | __get_config_table_options | def __get_config_table_options(conf_file_options):
""" Get all table options from the config file
:type conf_file_options: ordereddict
:param conf_file_options: Dictionary with all config file options
:returns: ordereddict -- E.g. {'table_name': {}}
"""
options = ordereddict()
if not conf_file_options:
return options
for table_name in conf_file_options['tables']:
options[table_name] = {}
# Regular table options
for option in DEFAULT_OPTIONS['table'].keys():
options[table_name][option] = DEFAULT_OPTIONS['table'][option]
if option not in conf_file_options['tables'][table_name]:
continue
if option == 'sns_message_types':
try:
raw_list = conf_file_options['tables'][table_name][option]
options[table_name][option] = \
[i.strip() for i in raw_list.split(',')]
except:
print(
'Error parsing the "sns-message-types" '
'option: {0}'.format(
conf_file_options['tables'][table_name][option]))
else:
options[table_name][option] = \
conf_file_options['tables'][table_name][option]
# GSI specific options
if 'gsis' in conf_file_options['tables'][table_name]:
for gsi_name in conf_file_options['tables'][table_name]['gsis']:
for option in DEFAULT_OPTIONS['gsi'].keys():
opt = DEFAULT_OPTIONS['gsi'][option]
if 'gsis' not in options[table_name]:
options[table_name]['gsis'] = {}
if gsi_name not in options[table_name]['gsis']:
options[table_name]['gsis'][gsi_name] = {}
if (option not in conf_file_options[
'tables'][table_name]['gsis'][gsi_name]):
options[table_name]['gsis'][gsi_name][option] = opt
continue
if option == 'sns_message_types':
try:
raw_list = conf_file_options[
'tables'][table_name]['gsis'][gsi_name][option]
opt = [i.strip() for i in raw_list.split(',')]
except:
print(
'Error parsing the "sns-message-types" '
'option: {0}'.format(
conf_file_options[
'tables'][table_name][
'gsis'][gsi_name][option]))
else:
opt = conf_file_options[
'tables'][table_name]['gsis'][gsi_name][option]
options[table_name]['gsis'][gsi_name][option] = opt
return options | python | def __get_config_table_options(conf_file_options):
""" Get all table options from the config file
:type conf_file_options: ordereddict
:param conf_file_options: Dictionary with all config file options
:returns: ordereddict -- E.g. {'table_name': {}}
"""
options = ordereddict()
if not conf_file_options:
return options
for table_name in conf_file_options['tables']:
options[table_name] = {}
# Regular table options
for option in DEFAULT_OPTIONS['table'].keys():
options[table_name][option] = DEFAULT_OPTIONS['table'][option]
if option not in conf_file_options['tables'][table_name]:
continue
if option == 'sns_message_types':
try:
raw_list = conf_file_options['tables'][table_name][option]
options[table_name][option] = \
[i.strip() for i in raw_list.split(',')]
except:
print(
'Error parsing the "sns-message-types" '
'option: {0}'.format(
conf_file_options['tables'][table_name][option]))
else:
options[table_name][option] = \
conf_file_options['tables'][table_name][option]
# GSI specific options
if 'gsis' in conf_file_options['tables'][table_name]:
for gsi_name in conf_file_options['tables'][table_name]['gsis']:
for option in DEFAULT_OPTIONS['gsi'].keys():
opt = DEFAULT_OPTIONS['gsi'][option]
if 'gsis' not in options[table_name]:
options[table_name]['gsis'] = {}
if gsi_name not in options[table_name]['gsis']:
options[table_name]['gsis'][gsi_name] = {}
if (option not in conf_file_options[
'tables'][table_name]['gsis'][gsi_name]):
options[table_name]['gsis'][gsi_name][option] = opt
continue
if option == 'sns_message_types':
try:
raw_list = conf_file_options[
'tables'][table_name]['gsis'][gsi_name][option]
opt = [i.strip() for i in raw_list.split(',')]
except:
print(
'Error parsing the "sns-message-types" '
'option: {0}'.format(
conf_file_options[
'tables'][table_name][
'gsis'][gsi_name][option]))
else:
opt = conf_file_options[
'tables'][table_name]['gsis'][gsi_name][option]
options[table_name]['gsis'][gsi_name][option] = opt
return options | [
"def",
"__get_config_table_options",
"(",
"conf_file_options",
")",
":",
"options",
"=",
"ordereddict",
"(",
")",
"if",
"not",
"conf_file_options",
":",
"return",
"options",
"for",
"table_name",
"in",
"conf_file_options",
"[",
"'tables'",
"]",
":",
"options",
"[",
"table_name",
"]",
"=",
"{",
"}",
"# Regular table options",
"for",
"option",
"in",
"DEFAULT_OPTIONS",
"[",
"'table'",
"]",
".",
"keys",
"(",
")",
":",
"options",
"[",
"table_name",
"]",
"[",
"option",
"]",
"=",
"DEFAULT_OPTIONS",
"[",
"'table'",
"]",
"[",
"option",
"]",
"if",
"option",
"not",
"in",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
":",
"continue",
"if",
"option",
"==",
"'sns_message_types'",
":",
"try",
":",
"raw_list",
"=",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"option",
"]",
"options",
"[",
"table_name",
"]",
"[",
"option",
"]",
"=",
"[",
"i",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"raw_list",
".",
"split",
"(",
"','",
")",
"]",
"except",
":",
"print",
"(",
"'Error parsing the \"sns-message-types\" '",
"'option: {0}'",
".",
"format",
"(",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"option",
"]",
")",
")",
"else",
":",
"options",
"[",
"table_name",
"]",
"[",
"option",
"]",
"=",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"option",
"]",
"# GSI specific options",
"if",
"'gsis'",
"in",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
":",
"for",
"gsi_name",
"in",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
":",
"for",
"option",
"in",
"DEFAULT_OPTIONS",
"[",
"'gsi'",
"]",
".",
"keys",
"(",
")",
":",
"opt",
"=",
"DEFAULT_OPTIONS",
"[",
"'gsi'",
"]",
"[",
"option",
"]",
"if",
"'gsis'",
"not",
"in",
"options",
"[",
"table_name",
"]",
":",
"options",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"=",
"{",
"}",
"if",
"gsi_name",
"not",
"in",
"options",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
":",
"options",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"[",
"gsi_name",
"]",
"=",
"{",
"}",
"if",
"(",
"option",
"not",
"in",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"[",
"gsi_name",
"]",
")",
":",
"options",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"[",
"gsi_name",
"]",
"[",
"option",
"]",
"=",
"opt",
"continue",
"if",
"option",
"==",
"'sns_message_types'",
":",
"try",
":",
"raw_list",
"=",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"[",
"gsi_name",
"]",
"[",
"option",
"]",
"opt",
"=",
"[",
"i",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"raw_list",
".",
"split",
"(",
"','",
")",
"]",
"except",
":",
"print",
"(",
"'Error parsing the \"sns-message-types\" '",
"'option: {0}'",
".",
"format",
"(",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"[",
"gsi_name",
"]",
"[",
"option",
"]",
")",
")",
"else",
":",
"opt",
"=",
"conf_file_options",
"[",
"'tables'",
"]",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"[",
"gsi_name",
"]",
"[",
"option",
"]",
"options",
"[",
"table_name",
"]",
"[",
"'gsis'",
"]",
"[",
"gsi_name",
"]",
"[",
"option",
"]",
"=",
"opt",
"return",
"options"
] | Get all table options from the config file
:type conf_file_options: ordereddict
:param conf_file_options: Dictionary with all config file options
:returns: ordereddict -- E.g. {'table_name': {}} | [
"Get",
"all",
"table",
"options",
"from",
"the",
"config",
"file"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L225-L296 | train | 251,050 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/config/__init__.py | __get_global_options | def __get_global_options(cmd_line_options, conf_file_options=None):
""" Get all global options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: dict
"""
options = {}
for option in DEFAULT_OPTIONS['global'].keys():
options[option] = DEFAULT_OPTIONS['global'][option]
if conf_file_options and option in conf_file_options:
options[option] = conf_file_options[option]
if cmd_line_options and option in cmd_line_options:
options[option] = cmd_line_options[option]
return options | python | def __get_global_options(cmd_line_options, conf_file_options=None):
""" Get all global options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: dict
"""
options = {}
for option in DEFAULT_OPTIONS['global'].keys():
options[option] = DEFAULT_OPTIONS['global'][option]
if conf_file_options and option in conf_file_options:
options[option] = conf_file_options[option]
if cmd_line_options and option in cmd_line_options:
options[option] = cmd_line_options[option]
return options | [
"def",
"__get_global_options",
"(",
"cmd_line_options",
",",
"conf_file_options",
"=",
"None",
")",
":",
"options",
"=",
"{",
"}",
"for",
"option",
"in",
"DEFAULT_OPTIONS",
"[",
"'global'",
"]",
".",
"keys",
"(",
")",
":",
"options",
"[",
"option",
"]",
"=",
"DEFAULT_OPTIONS",
"[",
"'global'",
"]",
"[",
"option",
"]",
"if",
"conf_file_options",
"and",
"option",
"in",
"conf_file_options",
":",
"options",
"[",
"option",
"]",
"=",
"conf_file_options",
"[",
"option",
"]",
"if",
"cmd_line_options",
"and",
"option",
"in",
"cmd_line_options",
":",
"options",
"[",
"option",
"]",
"=",
"cmd_line_options",
"[",
"option",
"]",
"return",
"options"
] | Get all global options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: dict | [
"Get",
"all",
"global",
"options"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L299-L319 | train | 251,051 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/config/__init__.py | __get_logging_options | def __get_logging_options(cmd_line_options, conf_file_options=None):
""" Get all logging options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: dict
"""
options = {}
for option in DEFAULT_OPTIONS['logging'].keys():
options[option] = DEFAULT_OPTIONS['logging'][option]
if conf_file_options and option in conf_file_options:
options[option] = conf_file_options[option]
if cmd_line_options and option in cmd_line_options:
options[option] = cmd_line_options[option]
return options | python | def __get_logging_options(cmd_line_options, conf_file_options=None):
""" Get all logging options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: dict
"""
options = {}
for option in DEFAULT_OPTIONS['logging'].keys():
options[option] = DEFAULT_OPTIONS['logging'][option]
if conf_file_options and option in conf_file_options:
options[option] = conf_file_options[option]
if cmd_line_options and option in cmd_line_options:
options[option] = cmd_line_options[option]
return options | [
"def",
"__get_logging_options",
"(",
"cmd_line_options",
",",
"conf_file_options",
"=",
"None",
")",
":",
"options",
"=",
"{",
"}",
"for",
"option",
"in",
"DEFAULT_OPTIONS",
"[",
"'logging'",
"]",
".",
"keys",
"(",
")",
":",
"options",
"[",
"option",
"]",
"=",
"DEFAULT_OPTIONS",
"[",
"'logging'",
"]",
"[",
"option",
"]",
"if",
"conf_file_options",
"and",
"option",
"in",
"conf_file_options",
":",
"options",
"[",
"option",
"]",
"=",
"conf_file_options",
"[",
"option",
"]",
"if",
"cmd_line_options",
"and",
"option",
"in",
"cmd_line_options",
":",
"options",
"[",
"option",
"]",
"=",
"cmd_line_options",
"[",
"option",
"]",
"return",
"options"
] | Get all logging options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: dict | [
"Get",
"all",
"logging",
"options"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L322-L342 | train | 251,052 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/config/__init__.py | __check_logging_rules | def __check_logging_rules(configuration):
""" Check that the logging values are proper """
valid_log_levels = [
'debug',
'info',
'warning',
'error'
]
if configuration['logging']['log_level'].lower() not in valid_log_levels:
print('Log level must be one of {0}'.format(
', '.join(valid_log_levels)))
sys.exit(1) | python | def __check_logging_rules(configuration):
""" Check that the logging values are proper """
valid_log_levels = [
'debug',
'info',
'warning',
'error'
]
if configuration['logging']['log_level'].lower() not in valid_log_levels:
print('Log level must be one of {0}'.format(
', '.join(valid_log_levels)))
sys.exit(1) | [
"def",
"__check_logging_rules",
"(",
"configuration",
")",
":",
"valid_log_levels",
"=",
"[",
"'debug'",
",",
"'info'",
",",
"'warning'",
",",
"'error'",
"]",
"if",
"configuration",
"[",
"'logging'",
"]",
"[",
"'log_level'",
"]",
".",
"lower",
"(",
")",
"not",
"in",
"valid_log_levels",
":",
"print",
"(",
"'Log level must be one of {0}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"valid_log_levels",
")",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Check that the logging values are proper | [
"Check",
"that",
"the",
"logging",
"values",
"are",
"proper"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L505-L516 | train | 251,053 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/calculators.py | is_consumed_over_proposed | def is_consumed_over_proposed(
current_provisioning, proposed_provisioning, consumed_units_percent):
"""
Determines if the currently consumed capacity is over the proposed capacity
for this table
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type proposed_provisioning: int
:param proposed_provisioning: New provisioning
:type consumed_units_percent: float
:param consumed_units_percent: Percent of consumed units
:returns: bool - if consumed is over max
"""
consumption_based_current_provisioning = \
int(math.ceil(current_provisioning*(consumed_units_percent/100)))
return consumption_based_current_provisioning > proposed_provisioning | python | def is_consumed_over_proposed(
current_provisioning, proposed_provisioning, consumed_units_percent):
"""
Determines if the currently consumed capacity is over the proposed capacity
for this table
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type proposed_provisioning: int
:param proposed_provisioning: New provisioning
:type consumed_units_percent: float
:param consumed_units_percent: Percent of consumed units
:returns: bool - if consumed is over max
"""
consumption_based_current_provisioning = \
int(math.ceil(current_provisioning*(consumed_units_percent/100)))
return consumption_based_current_provisioning > proposed_provisioning | [
"def",
"is_consumed_over_proposed",
"(",
"current_provisioning",
",",
"proposed_provisioning",
",",
"consumed_units_percent",
")",
":",
"consumption_based_current_provisioning",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"current_provisioning",
"*",
"(",
"consumed_units_percent",
"/",
"100",
")",
")",
")",
"return",
"consumption_based_current_provisioning",
">",
"proposed_provisioning"
] | Determines if the currently consumed capacity is over the proposed capacity
for this table
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type proposed_provisioning: int
:param proposed_provisioning: New provisioning
:type consumed_units_percent: float
:param consumed_units_percent: Percent of consumed units
:returns: bool - if consumed is over max | [
"Determines",
"if",
"the",
"currently",
"consumed",
"capacity",
"is",
"over",
"the",
"proposed",
"capacity",
"for",
"this",
"table"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/calculators.py#L342-L358 | train | 251,054 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/calculators.py | __get_min_reads | def __get_min_reads(current_provisioning, min_provisioned_reads, log_tag):
""" Get the minimum number of reads to current_provisioning
:type current_provisioning: int
:param current_provisioning: Current provisioned reads
:type min_provisioned_reads: int
:param min_provisioned_reads: Configured min provisioned reads
:type log_tag: str
:param log_tag: Prefix for the log
:returns: int -- Minimum number of reads
"""
# Fallback value to ensure that we always have at least 1 read
reads = 1
if min_provisioned_reads:
reads = int(min_provisioned_reads)
if reads > int(current_provisioning * 2):
reads = int(current_provisioning * 2)
logger.debug(
'{0} - '
'Cannot reach min-provisioned-reads as max scale up '
'is 100% of current provisioning'.format(log_tag))
logger.debug(
'{0} - Setting min provisioned reads to {1}'.format(
log_tag, min_provisioned_reads))
return reads | python | def __get_min_reads(current_provisioning, min_provisioned_reads, log_tag):
""" Get the minimum number of reads to current_provisioning
:type current_provisioning: int
:param current_provisioning: Current provisioned reads
:type min_provisioned_reads: int
:param min_provisioned_reads: Configured min provisioned reads
:type log_tag: str
:param log_tag: Prefix for the log
:returns: int -- Minimum number of reads
"""
# Fallback value to ensure that we always have at least 1 read
reads = 1
if min_provisioned_reads:
reads = int(min_provisioned_reads)
if reads > int(current_provisioning * 2):
reads = int(current_provisioning * 2)
logger.debug(
'{0} - '
'Cannot reach min-provisioned-reads as max scale up '
'is 100% of current provisioning'.format(log_tag))
logger.debug(
'{0} - Setting min provisioned reads to {1}'.format(
log_tag, min_provisioned_reads))
return reads | [
"def",
"__get_min_reads",
"(",
"current_provisioning",
",",
"min_provisioned_reads",
",",
"log_tag",
")",
":",
"# Fallback value to ensure that we always have at least 1 read",
"reads",
"=",
"1",
"if",
"min_provisioned_reads",
":",
"reads",
"=",
"int",
"(",
"min_provisioned_reads",
")",
"if",
"reads",
">",
"int",
"(",
"current_provisioning",
"*",
"2",
")",
":",
"reads",
"=",
"int",
"(",
"current_provisioning",
"*",
"2",
")",
"logger",
".",
"debug",
"(",
"'{0} - '",
"'Cannot reach min-provisioned-reads as max scale up '",
"'is 100% of current provisioning'",
".",
"format",
"(",
"log_tag",
")",
")",
"logger",
".",
"debug",
"(",
"'{0} - Setting min provisioned reads to {1}'",
".",
"format",
"(",
"log_tag",
",",
"min_provisioned_reads",
")",
")",
"return",
"reads"
] | Get the minimum number of reads to current_provisioning
:type current_provisioning: int
:param current_provisioning: Current provisioned reads
:type min_provisioned_reads: int
:param min_provisioned_reads: Configured min provisioned reads
:type log_tag: str
:param log_tag: Prefix for the log
:returns: int -- Minimum number of reads | [
"Get",
"the",
"minimum",
"number",
"of",
"reads",
"to",
"current_provisioning"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/calculators.py#L361-L389 | train | 251,055 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/calculators.py | __get_min_writes | def __get_min_writes(current_provisioning, min_provisioned_writes, log_tag):
""" Get the minimum number of writes to current_provisioning
:type current_provisioning: int
:param current_provisioning: Current provisioned writes
:type min_provisioned_writes: int
:param min_provisioned_writes: Configured min provisioned writes
:type log_tag: str
:param log_tag: Prefix for the log
:returns: int -- Minimum number of writes
"""
# Fallback value to ensure that we always have at least 1 read
writes = 1
if min_provisioned_writes:
writes = int(min_provisioned_writes)
if writes > int(current_provisioning * 2):
writes = int(current_provisioning * 2)
logger.debug(
'{0} - '
'Cannot reach min-provisioned-writes as max scale up '
'is 100% of current provisioning'.format(log_tag))
logger.debug(
'{0} - Setting min provisioned writes to {1}'.format(
log_tag, min_provisioned_writes))
return writes | python | def __get_min_writes(current_provisioning, min_provisioned_writes, log_tag):
""" Get the minimum number of writes to current_provisioning
:type current_provisioning: int
:param current_provisioning: Current provisioned writes
:type min_provisioned_writes: int
:param min_provisioned_writes: Configured min provisioned writes
:type log_tag: str
:param log_tag: Prefix for the log
:returns: int -- Minimum number of writes
"""
# Fallback value to ensure that we always have at least 1 read
writes = 1
if min_provisioned_writes:
writes = int(min_provisioned_writes)
if writes > int(current_provisioning * 2):
writes = int(current_provisioning * 2)
logger.debug(
'{0} - '
'Cannot reach min-provisioned-writes as max scale up '
'is 100% of current provisioning'.format(log_tag))
logger.debug(
'{0} - Setting min provisioned writes to {1}'.format(
log_tag, min_provisioned_writes))
return writes | [
"def",
"__get_min_writes",
"(",
"current_provisioning",
",",
"min_provisioned_writes",
",",
"log_tag",
")",
":",
"# Fallback value to ensure that we always have at least 1 read",
"writes",
"=",
"1",
"if",
"min_provisioned_writes",
":",
"writes",
"=",
"int",
"(",
"min_provisioned_writes",
")",
"if",
"writes",
">",
"int",
"(",
"current_provisioning",
"*",
"2",
")",
":",
"writes",
"=",
"int",
"(",
"current_provisioning",
"*",
"2",
")",
"logger",
".",
"debug",
"(",
"'{0} - '",
"'Cannot reach min-provisioned-writes as max scale up '",
"'is 100% of current provisioning'",
".",
"format",
"(",
"log_tag",
")",
")",
"logger",
".",
"debug",
"(",
"'{0} - Setting min provisioned writes to {1}'",
".",
"format",
"(",
"log_tag",
",",
"min_provisioned_writes",
")",
")",
"return",
"writes"
] | Get the minimum number of writes to current_provisioning
:type current_provisioning: int
:param current_provisioning: Current provisioned writes
:type min_provisioned_writes: int
:param min_provisioned_writes: Configured min provisioned writes
:type log_tag: str
:param log_tag: Prefix for the log
:returns: int -- Minimum number of writes | [
"Get",
"the",
"minimum",
"number",
"of",
"writes",
"to",
"current_provisioning"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/calculators.py#L392-L420 | train | 251,056 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/daemon.py | Daemon.restart | def restart(self, *args, **kwargs):
""" Restart the daemon """
self.stop()
try:
self.start(*args, **kwargs)
except IOError:
raise | python | def restart(self, *args, **kwargs):
""" Restart the daemon """
self.stop()
try:
self.start(*args, **kwargs)
except IOError:
raise | [
"def",
"restart",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"stop",
"(",
")",
"try",
":",
"self",
".",
"start",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"IOError",
":",
"raise"
] | Restart the daemon | [
"Restart",
"the",
"daemon"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/daemon.py#L132-L138 | train | 251,057 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/config/config_file_parser.py | __parse_options | def __parse_options(config_file, section, options):
""" Parse the section options
:type config_file: ConfigParser object
:param config_file: The config file object to use
:type section: str
:param section: Which section to read in the configuration file
:type options: list of dicts
:param options:
A list of options to parse. Example list::
[{
'key': 'aws_access_key_id',
'option': 'aws-access-key-id',
'required': False,
'type': str
}]
:returns: dict
"""
configuration = {}
for option in options:
try:
if option.get('type') == 'str':
configuration[option.get('key')] = \
config_file.get(section, option.get('option'))
elif option.get('type') == 'int':
try:
configuration[option.get('key')] = \
config_file.getint(section, option.get('option'))
except ValueError:
print('Error: Expected an integer value for {0}'.format(
option.get('option')))
sys.exit(1)
elif option.get('type') == 'float':
try:
configuration[option.get('key')] = \
config_file.getfloat(section, option.get('option'))
except ValueError:
print('Error: Expected an float value for {0}'.format(
option.get('option')))
sys.exit(1)
elif option.get('type') == 'bool':
try:
configuration[option.get('key')] = \
config_file.getboolean(section, option.get('option'))
except ValueError:
print('Error: Expected an boolean value for {0}'.format(
option.get('option')))
sys.exit(1)
elif option.get('type') == 'dict':
configuration[option.get('key')] = \
ast.literal_eval(
config_file.get(section, option.get('option')))
else:
configuration[option.get('key')] = \
config_file.get(section, option.get('option'))
except ConfigParser.NoOptionError:
if option.get('required'):
print('Missing [{0}] option "{1}" in configuration'.format(
section, option.get('option')))
sys.exit(1)
return configuration | python | def __parse_options(config_file, section, options):
""" Parse the section options
:type config_file: ConfigParser object
:param config_file: The config file object to use
:type section: str
:param section: Which section to read in the configuration file
:type options: list of dicts
:param options:
A list of options to parse. Example list::
[{
'key': 'aws_access_key_id',
'option': 'aws-access-key-id',
'required': False,
'type': str
}]
:returns: dict
"""
configuration = {}
for option in options:
try:
if option.get('type') == 'str':
configuration[option.get('key')] = \
config_file.get(section, option.get('option'))
elif option.get('type') == 'int':
try:
configuration[option.get('key')] = \
config_file.getint(section, option.get('option'))
except ValueError:
print('Error: Expected an integer value for {0}'.format(
option.get('option')))
sys.exit(1)
elif option.get('type') == 'float':
try:
configuration[option.get('key')] = \
config_file.getfloat(section, option.get('option'))
except ValueError:
print('Error: Expected an float value for {0}'.format(
option.get('option')))
sys.exit(1)
elif option.get('type') == 'bool':
try:
configuration[option.get('key')] = \
config_file.getboolean(section, option.get('option'))
except ValueError:
print('Error: Expected an boolean value for {0}'.format(
option.get('option')))
sys.exit(1)
elif option.get('type') == 'dict':
configuration[option.get('key')] = \
ast.literal_eval(
config_file.get(section, option.get('option')))
else:
configuration[option.get('key')] = \
config_file.get(section, option.get('option'))
except ConfigParser.NoOptionError:
if option.get('required'):
print('Missing [{0}] option "{1}" in configuration'.format(
section, option.get('option')))
sys.exit(1)
return configuration | [
"def",
"__parse_options",
"(",
"config_file",
",",
"section",
",",
"options",
")",
":",
"configuration",
"=",
"{",
"}",
"for",
"option",
"in",
"options",
":",
"try",
":",
"if",
"option",
".",
"get",
"(",
"'type'",
")",
"==",
"'str'",
":",
"configuration",
"[",
"option",
".",
"get",
"(",
"'key'",
")",
"]",
"=",
"config_file",
".",
"get",
"(",
"section",
",",
"option",
".",
"get",
"(",
"'option'",
")",
")",
"elif",
"option",
".",
"get",
"(",
"'type'",
")",
"==",
"'int'",
":",
"try",
":",
"configuration",
"[",
"option",
".",
"get",
"(",
"'key'",
")",
"]",
"=",
"config_file",
".",
"getint",
"(",
"section",
",",
"option",
".",
"get",
"(",
"'option'",
")",
")",
"except",
"ValueError",
":",
"print",
"(",
"'Error: Expected an integer value for {0}'",
".",
"format",
"(",
"option",
".",
"get",
"(",
"'option'",
")",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"elif",
"option",
".",
"get",
"(",
"'type'",
")",
"==",
"'float'",
":",
"try",
":",
"configuration",
"[",
"option",
".",
"get",
"(",
"'key'",
")",
"]",
"=",
"config_file",
".",
"getfloat",
"(",
"section",
",",
"option",
".",
"get",
"(",
"'option'",
")",
")",
"except",
"ValueError",
":",
"print",
"(",
"'Error: Expected an float value for {0}'",
".",
"format",
"(",
"option",
".",
"get",
"(",
"'option'",
")",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"elif",
"option",
".",
"get",
"(",
"'type'",
")",
"==",
"'bool'",
":",
"try",
":",
"configuration",
"[",
"option",
".",
"get",
"(",
"'key'",
")",
"]",
"=",
"config_file",
".",
"getboolean",
"(",
"section",
",",
"option",
".",
"get",
"(",
"'option'",
")",
")",
"except",
"ValueError",
":",
"print",
"(",
"'Error: Expected an boolean value for {0}'",
".",
"format",
"(",
"option",
".",
"get",
"(",
"'option'",
")",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"elif",
"option",
".",
"get",
"(",
"'type'",
")",
"==",
"'dict'",
":",
"configuration",
"[",
"option",
".",
"get",
"(",
"'key'",
")",
"]",
"=",
"ast",
".",
"literal_eval",
"(",
"config_file",
".",
"get",
"(",
"section",
",",
"option",
".",
"get",
"(",
"'option'",
")",
")",
")",
"else",
":",
"configuration",
"[",
"option",
".",
"get",
"(",
"'key'",
")",
"]",
"=",
"config_file",
".",
"get",
"(",
"section",
",",
"option",
".",
"get",
"(",
"'option'",
")",
")",
"except",
"ConfigParser",
".",
"NoOptionError",
":",
"if",
"option",
".",
"get",
"(",
"'required'",
")",
":",
"print",
"(",
"'Missing [{0}] option \"{1}\" in configuration'",
".",
"format",
"(",
"section",
",",
"option",
".",
"get",
"(",
"'option'",
")",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"configuration"
] | Parse the section options
:type config_file: ConfigParser object
:param config_file: The config file object to use
:type section: str
:param section: Which section to read in the configuration file
:type options: list of dicts
:param options:
A list of options to parse. Example list::
[{
'key': 'aws_access_key_id',
'option': 'aws-access-key-id',
'required': False,
'type': str
}]
:returns: dict | [
"Parse",
"the",
"section",
"options"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/config_file_parser.py#L392-L453 | train | 251,058 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/__init__.py | main | def main():
""" Main function called from dynamic-dynamodb """
try:
if get_global_option('show_config'):
print json.dumps(config.get_configuration(), indent=2)
elif get_global_option('daemon'):
daemon = DynamicDynamoDBDaemon(
'{0}/dynamic-dynamodb.{1}.pid'.format(
get_global_option('pid_file_dir'),
get_global_option('instance')))
if get_global_option('daemon') == 'start':
logger.debug('Starting daemon')
try:
daemon.start()
logger.info('Daemon started')
except IOError as error:
logger.error('Could not create pid file: {0}'.format(error))
logger.error('Daemon not started')
elif get_global_option('daemon') == 'stop':
logger.debug('Stopping daemon')
daemon.stop()
logger.info('Daemon stopped')
sys.exit(0)
elif get_global_option('daemon') == 'restart':
logger.debug('Restarting daemon')
daemon.restart()
logger.info('Daemon restarted')
elif get_global_option('daemon') in ['foreground', 'fg']:
logger.debug('Starting daemon in foreground')
daemon.run()
logger.info('Daemon started in foreground')
else:
print(
'Valid options for --daemon are start, '
'stop, restart, and foreground')
sys.exit(1)
else:
if get_global_option('run_once'):
execute()
else:
while True:
execute()
except Exception as error:
logger.exception(error) | python | def main():
""" Main function called from dynamic-dynamodb """
try:
if get_global_option('show_config'):
print json.dumps(config.get_configuration(), indent=2)
elif get_global_option('daemon'):
daemon = DynamicDynamoDBDaemon(
'{0}/dynamic-dynamodb.{1}.pid'.format(
get_global_option('pid_file_dir'),
get_global_option('instance')))
if get_global_option('daemon') == 'start':
logger.debug('Starting daemon')
try:
daemon.start()
logger.info('Daemon started')
except IOError as error:
logger.error('Could not create pid file: {0}'.format(error))
logger.error('Daemon not started')
elif get_global_option('daemon') == 'stop':
logger.debug('Stopping daemon')
daemon.stop()
logger.info('Daemon stopped')
sys.exit(0)
elif get_global_option('daemon') == 'restart':
logger.debug('Restarting daemon')
daemon.restart()
logger.info('Daemon restarted')
elif get_global_option('daemon') in ['foreground', 'fg']:
logger.debug('Starting daemon in foreground')
daemon.run()
logger.info('Daemon started in foreground')
else:
print(
'Valid options for --daemon are start, '
'stop, restart, and foreground')
sys.exit(1)
else:
if get_global_option('run_once'):
execute()
else:
while True:
execute()
except Exception as error:
logger.exception(error) | [
"def",
"main",
"(",
")",
":",
"try",
":",
"if",
"get_global_option",
"(",
"'show_config'",
")",
":",
"print",
"json",
".",
"dumps",
"(",
"config",
".",
"get_configuration",
"(",
")",
",",
"indent",
"=",
"2",
")",
"elif",
"get_global_option",
"(",
"'daemon'",
")",
":",
"daemon",
"=",
"DynamicDynamoDBDaemon",
"(",
"'{0}/dynamic-dynamodb.{1}.pid'",
".",
"format",
"(",
"get_global_option",
"(",
"'pid_file_dir'",
")",
",",
"get_global_option",
"(",
"'instance'",
")",
")",
")",
"if",
"get_global_option",
"(",
"'daemon'",
")",
"==",
"'start'",
":",
"logger",
".",
"debug",
"(",
"'Starting daemon'",
")",
"try",
":",
"daemon",
".",
"start",
"(",
")",
"logger",
".",
"info",
"(",
"'Daemon started'",
")",
"except",
"IOError",
"as",
"error",
":",
"logger",
".",
"error",
"(",
"'Could not create pid file: {0}'",
".",
"format",
"(",
"error",
")",
")",
"logger",
".",
"error",
"(",
"'Daemon not started'",
")",
"elif",
"get_global_option",
"(",
"'daemon'",
")",
"==",
"'stop'",
":",
"logger",
".",
"debug",
"(",
"'Stopping daemon'",
")",
"daemon",
".",
"stop",
"(",
")",
"logger",
".",
"info",
"(",
"'Daemon stopped'",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"elif",
"get_global_option",
"(",
"'daemon'",
")",
"==",
"'restart'",
":",
"logger",
".",
"debug",
"(",
"'Restarting daemon'",
")",
"daemon",
".",
"restart",
"(",
")",
"logger",
".",
"info",
"(",
"'Daemon restarted'",
")",
"elif",
"get_global_option",
"(",
"'daemon'",
")",
"in",
"[",
"'foreground'",
",",
"'fg'",
"]",
":",
"logger",
".",
"debug",
"(",
"'Starting daemon in foreground'",
")",
"daemon",
".",
"run",
"(",
")",
"logger",
".",
"info",
"(",
"'Daemon started in foreground'",
")",
"else",
":",
"print",
"(",
"'Valid options for --daemon are start, '",
"'stop, restart, and foreground'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"else",
":",
"if",
"get_global_option",
"(",
"'run_once'",
")",
":",
"execute",
"(",
")",
"else",
":",
"while",
"True",
":",
"execute",
"(",
")",
"except",
"Exception",
"as",
"error",
":",
"logger",
".",
"exception",
"(",
"error",
")"
] | Main function called from dynamic-dynamodb | [
"Main",
"function",
"called",
"from",
"dynamic",
"-",
"dynamodb"
] | bfd0ca806b1c3301e724696de90ef0f973410493 | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/__init__.py#L56-L104 | train | 251,059 |
ransford/sllurp | sllurp/llrp_decoder.py | decode_tve_parameter | def decode_tve_parameter(data):
"""Generic byte decoding function for TVE parameters.
Given an array of bytes, tries to interpret a TVE parameter from the
beginning of the array. Returns the decoded data and the number of bytes
it read."""
(nontve,) = struct.unpack(nontve_header, data[:nontve_header_len])
if nontve == 1023: # customparameter
(size,) = struct.unpack('!H',
data[nontve_header_len:nontve_header_len+2])
(subtype,) = struct.unpack('!H', data[size-4:size-2])
param_name, param_fmt = ext_param_formats[subtype]
(unpacked,) = struct.unpack(param_fmt, data[size-2:size])
return {param_name: unpacked}, size
# decode the TVE field's header (1 bit "reserved" + 7-bit type)
(msgtype,) = struct.unpack(tve_header, data[:tve_header_len])
if not msgtype & 0b10000000:
# not a TV-encoded param
return None, 0
msgtype = msgtype & 0x7f
try:
param_name, param_fmt = tve_param_formats[msgtype]
logger.debug('found %s (type=%s)', param_name, msgtype)
except KeyError:
return None, 0
# decode the body
nbytes = struct.calcsize(param_fmt)
end = tve_header_len + nbytes
try:
unpacked = struct.unpack(param_fmt, data[tve_header_len:end])
return {param_name: unpacked}, end
except struct.error:
return None, 0 | python | def decode_tve_parameter(data):
"""Generic byte decoding function for TVE parameters.
Given an array of bytes, tries to interpret a TVE parameter from the
beginning of the array. Returns the decoded data and the number of bytes
it read."""
(nontve,) = struct.unpack(nontve_header, data[:nontve_header_len])
if nontve == 1023: # customparameter
(size,) = struct.unpack('!H',
data[nontve_header_len:nontve_header_len+2])
(subtype,) = struct.unpack('!H', data[size-4:size-2])
param_name, param_fmt = ext_param_formats[subtype]
(unpacked,) = struct.unpack(param_fmt, data[size-2:size])
return {param_name: unpacked}, size
# decode the TVE field's header (1 bit "reserved" + 7-bit type)
(msgtype,) = struct.unpack(tve_header, data[:tve_header_len])
if not msgtype & 0b10000000:
# not a TV-encoded param
return None, 0
msgtype = msgtype & 0x7f
try:
param_name, param_fmt = tve_param_formats[msgtype]
logger.debug('found %s (type=%s)', param_name, msgtype)
except KeyError:
return None, 0
# decode the body
nbytes = struct.calcsize(param_fmt)
end = tve_header_len + nbytes
try:
unpacked = struct.unpack(param_fmt, data[tve_header_len:end])
return {param_name: unpacked}, end
except struct.error:
return None, 0 | [
"def",
"decode_tve_parameter",
"(",
"data",
")",
":",
"(",
"nontve",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"nontve_header",
",",
"data",
"[",
":",
"nontve_header_len",
"]",
")",
"if",
"nontve",
"==",
"1023",
":",
"# customparameter",
"(",
"size",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"'!H'",
",",
"data",
"[",
"nontve_header_len",
":",
"nontve_header_len",
"+",
"2",
"]",
")",
"(",
"subtype",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"'!H'",
",",
"data",
"[",
"size",
"-",
"4",
":",
"size",
"-",
"2",
"]",
")",
"param_name",
",",
"param_fmt",
"=",
"ext_param_formats",
"[",
"subtype",
"]",
"(",
"unpacked",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"param_fmt",
",",
"data",
"[",
"size",
"-",
"2",
":",
"size",
"]",
")",
"return",
"{",
"param_name",
":",
"unpacked",
"}",
",",
"size",
"# decode the TVE field's header (1 bit \"reserved\" + 7-bit type)",
"(",
"msgtype",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"tve_header",
",",
"data",
"[",
":",
"tve_header_len",
"]",
")",
"if",
"not",
"msgtype",
"&",
"0b10000000",
":",
"# not a TV-encoded param",
"return",
"None",
",",
"0",
"msgtype",
"=",
"msgtype",
"&",
"0x7f",
"try",
":",
"param_name",
",",
"param_fmt",
"=",
"tve_param_formats",
"[",
"msgtype",
"]",
"logger",
".",
"debug",
"(",
"'found %s (type=%s)'",
",",
"param_name",
",",
"msgtype",
")",
"except",
"KeyError",
":",
"return",
"None",
",",
"0",
"# decode the body",
"nbytes",
"=",
"struct",
".",
"calcsize",
"(",
"param_fmt",
")",
"end",
"=",
"tve_header_len",
"+",
"nbytes",
"try",
":",
"unpacked",
"=",
"struct",
".",
"unpack",
"(",
"param_fmt",
",",
"data",
"[",
"tve_header_len",
":",
"end",
"]",
")",
"return",
"{",
"param_name",
":",
"unpacked",
"}",
",",
"end",
"except",
"struct",
".",
"error",
":",
"return",
"None",
",",
"0"
] | Generic byte decoding function for TVE parameters.
Given an array of bytes, tries to interpret a TVE parameter from the
beginning of the array. Returns the decoded data and the number of bytes
it read. | [
"Generic",
"byte",
"decoding",
"function",
"for",
"TVE",
"parameters",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp_decoder.py#L39-L74 | train | 251,060 |
ransford/sllurp | setup.py | read | def read(filename):
"""
Get the long description from a file.
"""
fname = os.path.join(here, filename)
with codecs.open(fname, encoding='utf-8') as f:
return f.read() | python | def read(filename):
"""
Get the long description from a file.
"""
fname = os.path.join(here, filename)
with codecs.open(fname, encoding='utf-8') as f:
return f.read() | [
"def",
"read",
"(",
"filename",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"here",
",",
"filename",
")",
"with",
"codecs",
".",
"open",
"(",
"fname",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | Get the long description from a file. | [
"Get",
"the",
"long",
"description",
"from",
"a",
"file",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/setup.py#L10-L16 | train | 251,061 |
ransford/sllurp | sllurp/llrp.py | LLRPMessage.deserialize | def deserialize(self):
"""Turns a sequence of bytes into a message dictionary."""
if self.msgbytes is None:
raise LLRPError('No message bytes to deserialize.')
data = self.msgbytes
msgtype, length, msgid = struct.unpack(self.full_hdr_fmt,
data[:self.full_hdr_len])
ver = (msgtype >> 10) & BITMASK(3)
msgtype = msgtype & BITMASK(10)
try:
name = Message_Type2Name[msgtype]
logger.debug('deserializing %s command', name)
decoder = Message_struct[name]['decode']
except KeyError:
raise LLRPError('Cannot find decoder for message type '
'{}'.format(msgtype))
body = data[self.full_hdr_len:length]
try:
self.msgdict = {
name: dict(decoder(body))
}
self.msgdict[name]['Ver'] = ver
self.msgdict[name]['Type'] = msgtype
self.msgdict[name]['ID'] = msgid
logger.debug('done deserializing %s command', name)
except ValueError:
logger.exception('Unable to decode body %s, %s', body,
decoder(body))
except LLRPError:
logger.exception('Problem with %s message format', name)
return ''
return '' | python | def deserialize(self):
"""Turns a sequence of bytes into a message dictionary."""
if self.msgbytes is None:
raise LLRPError('No message bytes to deserialize.')
data = self.msgbytes
msgtype, length, msgid = struct.unpack(self.full_hdr_fmt,
data[:self.full_hdr_len])
ver = (msgtype >> 10) & BITMASK(3)
msgtype = msgtype & BITMASK(10)
try:
name = Message_Type2Name[msgtype]
logger.debug('deserializing %s command', name)
decoder = Message_struct[name]['decode']
except KeyError:
raise LLRPError('Cannot find decoder for message type '
'{}'.format(msgtype))
body = data[self.full_hdr_len:length]
try:
self.msgdict = {
name: dict(decoder(body))
}
self.msgdict[name]['Ver'] = ver
self.msgdict[name]['Type'] = msgtype
self.msgdict[name]['ID'] = msgid
logger.debug('done deserializing %s command', name)
except ValueError:
logger.exception('Unable to decode body %s, %s', body,
decoder(body))
except LLRPError:
logger.exception('Problem with %s message format', name)
return ''
return '' | [
"def",
"deserialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"msgbytes",
"is",
"None",
":",
"raise",
"LLRPError",
"(",
"'No message bytes to deserialize.'",
")",
"data",
"=",
"self",
".",
"msgbytes",
"msgtype",
",",
"length",
",",
"msgid",
"=",
"struct",
".",
"unpack",
"(",
"self",
".",
"full_hdr_fmt",
",",
"data",
"[",
":",
"self",
".",
"full_hdr_len",
"]",
")",
"ver",
"=",
"(",
"msgtype",
">>",
"10",
")",
"&",
"BITMASK",
"(",
"3",
")",
"msgtype",
"=",
"msgtype",
"&",
"BITMASK",
"(",
"10",
")",
"try",
":",
"name",
"=",
"Message_Type2Name",
"[",
"msgtype",
"]",
"logger",
".",
"debug",
"(",
"'deserializing %s command'",
",",
"name",
")",
"decoder",
"=",
"Message_struct",
"[",
"name",
"]",
"[",
"'decode'",
"]",
"except",
"KeyError",
":",
"raise",
"LLRPError",
"(",
"'Cannot find decoder for message type '",
"'{}'",
".",
"format",
"(",
"msgtype",
")",
")",
"body",
"=",
"data",
"[",
"self",
".",
"full_hdr_len",
":",
"length",
"]",
"try",
":",
"self",
".",
"msgdict",
"=",
"{",
"name",
":",
"dict",
"(",
"decoder",
"(",
"body",
")",
")",
"}",
"self",
".",
"msgdict",
"[",
"name",
"]",
"[",
"'Ver'",
"]",
"=",
"ver",
"self",
".",
"msgdict",
"[",
"name",
"]",
"[",
"'Type'",
"]",
"=",
"msgtype",
"self",
".",
"msgdict",
"[",
"name",
"]",
"[",
"'ID'",
"]",
"=",
"msgid",
"logger",
".",
"debug",
"(",
"'done deserializing %s command'",
",",
"name",
")",
"except",
"ValueError",
":",
"logger",
".",
"exception",
"(",
"'Unable to decode body %s, %s'",
",",
"body",
",",
"decoder",
"(",
"body",
")",
")",
"except",
"LLRPError",
":",
"logger",
".",
"exception",
"(",
"'Problem with %s message format'",
",",
"name",
")",
"return",
"''",
"return",
"''"
] | Turns a sequence of bytes into a message dictionary. | [
"Turns",
"a",
"sequence",
"of",
"bytes",
"into",
"a",
"message",
"dictionary",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L66-L97 | train | 251,062 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.parseReaderConfig | def parseReaderConfig(self, confdict):
"""Parse a reader configuration dictionary.
Examples:
{
Type: 23,
Data: b'\x00'
}
{
Type: 1023,
Vendor: 25882,
Subtype: 21,
Data: b'\x00'
}
"""
logger.debug('parseReaderConfig input: %s', confdict)
conf = {}
for k, v in confdict.items():
if not k.startswith('Parameter'):
continue
ty = v['Type']
data = v['Data']
vendor = None
subtype = None
try:
vendor, subtype = v['Vendor'], v['Subtype']
except KeyError:
pass
if ty == 1023:
if vendor == 25882 and subtype == 37:
tempc = struct.unpack('!H', data)[0]
conf.update(temperature=tempc)
else:
conf[ty] = data
return conf | python | def parseReaderConfig(self, confdict):
"""Parse a reader configuration dictionary.
Examples:
{
Type: 23,
Data: b'\x00'
}
{
Type: 1023,
Vendor: 25882,
Subtype: 21,
Data: b'\x00'
}
"""
logger.debug('parseReaderConfig input: %s', confdict)
conf = {}
for k, v in confdict.items():
if not k.startswith('Parameter'):
continue
ty = v['Type']
data = v['Data']
vendor = None
subtype = None
try:
vendor, subtype = v['Vendor'], v['Subtype']
except KeyError:
pass
if ty == 1023:
if vendor == 25882 and subtype == 37:
tempc = struct.unpack('!H', data)[0]
conf.update(temperature=tempc)
else:
conf[ty] = data
return conf | [
"def",
"parseReaderConfig",
"(",
"self",
",",
"confdict",
")",
":",
"logger",
".",
"debug",
"(",
"'parseReaderConfig input: %s'",
",",
"confdict",
")",
"conf",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"confdict",
".",
"items",
"(",
")",
":",
"if",
"not",
"k",
".",
"startswith",
"(",
"'Parameter'",
")",
":",
"continue",
"ty",
"=",
"v",
"[",
"'Type'",
"]",
"data",
"=",
"v",
"[",
"'Data'",
"]",
"vendor",
"=",
"None",
"subtype",
"=",
"None",
"try",
":",
"vendor",
",",
"subtype",
"=",
"v",
"[",
"'Vendor'",
"]",
",",
"v",
"[",
"'Subtype'",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"ty",
"==",
"1023",
":",
"if",
"vendor",
"==",
"25882",
"and",
"subtype",
"==",
"37",
":",
"tempc",
"=",
"struct",
".",
"unpack",
"(",
"'!H'",
",",
"data",
")",
"[",
"0",
"]",
"conf",
".",
"update",
"(",
"temperature",
"=",
"tempc",
")",
"else",
":",
"conf",
"[",
"ty",
"]",
"=",
"data",
"return",
"conf"
] | Parse a reader configuration dictionary.
Examples:
{
Type: 23,
Data: b'\x00'
}
{
Type: 1023,
Vendor: 25882,
Subtype: 21,
Data: b'\x00'
} | [
"Parse",
"a",
"reader",
"configuration",
"dictionary",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L291-L326 | train | 251,063 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.parseCapabilities | def parseCapabilities(self, capdict):
"""Parse a capabilities dictionary and adjust instance settings.
At the time this function is called, the user has requested some
settings (e.g., mode identifier), but we haven't yet asked the reader
whether those requested settings are within its capabilities. This
function's job is to parse the reader's capabilities, compare them
against any requested settings, and raise an error if there are any
incompatibilities.
Sets the following instance variables:
- self.antennas (list of antenna numbers, e.g., [1] or [1, 2])
- self.tx_power_table (list of dBm values)
- self.reader_mode (dictionary of mode settings, e.g., Tari)
Raises ReaderConfigurationError if the requested settings are not
within the reader's capabilities.
"""
# check requested antenna set
gdc = capdict['GeneralDeviceCapabilities']
max_ant = gdc['MaxNumberOfAntennaSupported']
if max(self.antennas) > max_ant:
reqd = ','.join(map(str, self.antennas))
avail = ','.join(map(str, range(1, max_ant + 1)))
errmsg = ('Invalid antenna set specified: requested={},'
' available={}; ignoring invalid antennas'.format(
reqd, avail))
raise ReaderConfigurationError(errmsg)
logger.debug('set antennas: %s', self.antennas)
# parse available transmit power entries, set self.tx_power
bandcap = capdict['RegulatoryCapabilities']['UHFBandCapabilities']
self.tx_power_table = self.parsePowerTable(bandcap)
logger.debug('tx_power_table: %s', self.tx_power_table)
self.setTxPower(self.tx_power)
# parse list of reader's supported mode identifiers
regcap = capdict['RegulatoryCapabilities']
modes = regcap['UHFBandCapabilities']['UHFRFModeTable']
mode_list = [modes[k] for k in sorted(modes.keys(), key=natural_keys)]
# select a mode by matching available modes to requested parameters
if self.mode_identifier is not None:
logger.debug('Setting mode from mode_identifier=%s',
self.mode_identifier)
try:
mode = [mo for mo in mode_list
if mo['ModeIdentifier'] == self.mode_identifier][0]
self.reader_mode = mode
except IndexError:
valid_modes = sorted(mo['ModeIdentifier'] for mo in mode_list)
errstr = ('Invalid mode_identifier; valid mode_identifiers'
' are {}'.format(valid_modes))
raise ReaderConfigurationError(errstr)
# if we're trying to set Tari explicitly, but the selected mode doesn't
# support the requested Tari, that's a configuration error.
if self.reader_mode and self.tari:
if self.reader_mode['MinTari'] < self.tari < self.reader_mode['MaxTari']:
logger.debug('Overriding mode Tari %s with requested Tari %s',
self.reader_mode['MaxTari'], self.tari)
else:
errstr = ('Requested Tari {} is incompatible with selected '
'mode {}'.format(self.tari, self.reader_mode))
logger.info('using reader mode: %s', self.reader_mode) | python | def parseCapabilities(self, capdict):
"""Parse a capabilities dictionary and adjust instance settings.
At the time this function is called, the user has requested some
settings (e.g., mode identifier), but we haven't yet asked the reader
whether those requested settings are within its capabilities. This
function's job is to parse the reader's capabilities, compare them
against any requested settings, and raise an error if there are any
incompatibilities.
Sets the following instance variables:
- self.antennas (list of antenna numbers, e.g., [1] or [1, 2])
- self.tx_power_table (list of dBm values)
- self.reader_mode (dictionary of mode settings, e.g., Tari)
Raises ReaderConfigurationError if the requested settings are not
within the reader's capabilities.
"""
# check requested antenna set
gdc = capdict['GeneralDeviceCapabilities']
max_ant = gdc['MaxNumberOfAntennaSupported']
if max(self.antennas) > max_ant:
reqd = ','.join(map(str, self.antennas))
avail = ','.join(map(str, range(1, max_ant + 1)))
errmsg = ('Invalid antenna set specified: requested={},'
' available={}; ignoring invalid antennas'.format(
reqd, avail))
raise ReaderConfigurationError(errmsg)
logger.debug('set antennas: %s', self.antennas)
# parse available transmit power entries, set self.tx_power
bandcap = capdict['RegulatoryCapabilities']['UHFBandCapabilities']
self.tx_power_table = self.parsePowerTable(bandcap)
logger.debug('tx_power_table: %s', self.tx_power_table)
self.setTxPower(self.tx_power)
# parse list of reader's supported mode identifiers
regcap = capdict['RegulatoryCapabilities']
modes = regcap['UHFBandCapabilities']['UHFRFModeTable']
mode_list = [modes[k] for k in sorted(modes.keys(), key=natural_keys)]
# select a mode by matching available modes to requested parameters
if self.mode_identifier is not None:
logger.debug('Setting mode from mode_identifier=%s',
self.mode_identifier)
try:
mode = [mo for mo in mode_list
if mo['ModeIdentifier'] == self.mode_identifier][0]
self.reader_mode = mode
except IndexError:
valid_modes = sorted(mo['ModeIdentifier'] for mo in mode_list)
errstr = ('Invalid mode_identifier; valid mode_identifiers'
' are {}'.format(valid_modes))
raise ReaderConfigurationError(errstr)
# if we're trying to set Tari explicitly, but the selected mode doesn't
# support the requested Tari, that's a configuration error.
if self.reader_mode and self.tari:
if self.reader_mode['MinTari'] < self.tari < self.reader_mode['MaxTari']:
logger.debug('Overriding mode Tari %s with requested Tari %s',
self.reader_mode['MaxTari'], self.tari)
else:
errstr = ('Requested Tari {} is incompatible with selected '
'mode {}'.format(self.tari, self.reader_mode))
logger.info('using reader mode: %s', self.reader_mode) | [
"def",
"parseCapabilities",
"(",
"self",
",",
"capdict",
")",
":",
"# check requested antenna set",
"gdc",
"=",
"capdict",
"[",
"'GeneralDeviceCapabilities'",
"]",
"max_ant",
"=",
"gdc",
"[",
"'MaxNumberOfAntennaSupported'",
"]",
"if",
"max",
"(",
"self",
".",
"antennas",
")",
">",
"max_ant",
":",
"reqd",
"=",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"self",
".",
"antennas",
")",
")",
"avail",
"=",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"range",
"(",
"1",
",",
"max_ant",
"+",
"1",
")",
")",
")",
"errmsg",
"=",
"(",
"'Invalid antenna set specified: requested={},'",
"' available={}; ignoring invalid antennas'",
".",
"format",
"(",
"reqd",
",",
"avail",
")",
")",
"raise",
"ReaderConfigurationError",
"(",
"errmsg",
")",
"logger",
".",
"debug",
"(",
"'set antennas: %s'",
",",
"self",
".",
"antennas",
")",
"# parse available transmit power entries, set self.tx_power",
"bandcap",
"=",
"capdict",
"[",
"'RegulatoryCapabilities'",
"]",
"[",
"'UHFBandCapabilities'",
"]",
"self",
".",
"tx_power_table",
"=",
"self",
".",
"parsePowerTable",
"(",
"bandcap",
")",
"logger",
".",
"debug",
"(",
"'tx_power_table: %s'",
",",
"self",
".",
"tx_power_table",
")",
"self",
".",
"setTxPower",
"(",
"self",
".",
"tx_power",
")",
"# parse list of reader's supported mode identifiers",
"regcap",
"=",
"capdict",
"[",
"'RegulatoryCapabilities'",
"]",
"modes",
"=",
"regcap",
"[",
"'UHFBandCapabilities'",
"]",
"[",
"'UHFRFModeTable'",
"]",
"mode_list",
"=",
"[",
"modes",
"[",
"k",
"]",
"for",
"k",
"in",
"sorted",
"(",
"modes",
".",
"keys",
"(",
")",
",",
"key",
"=",
"natural_keys",
")",
"]",
"# select a mode by matching available modes to requested parameters",
"if",
"self",
".",
"mode_identifier",
"is",
"not",
"None",
":",
"logger",
".",
"debug",
"(",
"'Setting mode from mode_identifier=%s'",
",",
"self",
".",
"mode_identifier",
")",
"try",
":",
"mode",
"=",
"[",
"mo",
"for",
"mo",
"in",
"mode_list",
"if",
"mo",
"[",
"'ModeIdentifier'",
"]",
"==",
"self",
".",
"mode_identifier",
"]",
"[",
"0",
"]",
"self",
".",
"reader_mode",
"=",
"mode",
"except",
"IndexError",
":",
"valid_modes",
"=",
"sorted",
"(",
"mo",
"[",
"'ModeIdentifier'",
"]",
"for",
"mo",
"in",
"mode_list",
")",
"errstr",
"=",
"(",
"'Invalid mode_identifier; valid mode_identifiers'",
"' are {}'",
".",
"format",
"(",
"valid_modes",
")",
")",
"raise",
"ReaderConfigurationError",
"(",
"errstr",
")",
"# if we're trying to set Tari explicitly, but the selected mode doesn't",
"# support the requested Tari, that's a configuration error.",
"if",
"self",
".",
"reader_mode",
"and",
"self",
".",
"tari",
":",
"if",
"self",
".",
"reader_mode",
"[",
"'MinTari'",
"]",
"<",
"self",
".",
"tari",
"<",
"self",
".",
"reader_mode",
"[",
"'MaxTari'",
"]",
":",
"logger",
".",
"debug",
"(",
"'Overriding mode Tari %s with requested Tari %s'",
",",
"self",
".",
"reader_mode",
"[",
"'MaxTari'",
"]",
",",
"self",
".",
"tari",
")",
"else",
":",
"errstr",
"=",
"(",
"'Requested Tari {} is incompatible with selected '",
"'mode {}'",
".",
"format",
"(",
"self",
".",
"tari",
",",
"self",
".",
"reader_mode",
")",
")",
"logger",
".",
"info",
"(",
"'using reader mode: %s'",
",",
"self",
".",
"reader_mode",
")"
] | Parse a capabilities dictionary and adjust instance settings.
At the time this function is called, the user has requested some
settings (e.g., mode identifier), but we haven't yet asked the reader
whether those requested settings are within its capabilities. This
function's job is to parse the reader's capabilities, compare them
against any requested settings, and raise an error if there are any
incompatibilities.
Sets the following instance variables:
- self.antennas (list of antenna numbers, e.g., [1] or [1, 2])
- self.tx_power_table (list of dBm values)
- self.reader_mode (dictionary of mode settings, e.g., Tari)
Raises ReaderConfigurationError if the requested settings are not
within the reader's capabilities. | [
"Parse",
"a",
"capabilities",
"dictionary",
"and",
"adjust",
"instance",
"settings",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L328-L393 | train | 251,064 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.startInventory | def startInventory(self, proto=None, force_regen_rospec=False):
"""Add a ROSpec to the reader and enable it."""
if self.state == LLRPClient.STATE_INVENTORYING:
logger.warn('ignoring startInventory() while already inventorying')
return None
rospec = self.getROSpec(force_new=force_regen_rospec)['ROSpec']
logger.info('starting inventory')
# upside-down chain of callbacks: add, enable, start ROSpec
# started_rospec = defer.Deferred()
# started_rospec.addCallback(self._setState_wrapper,
# LLRPClient.STATE_INVENTORYING)
# started_rospec.addErrback(self.panic, 'START_ROSPEC failed')
# logger.debug('made started_rospec')
enabled_rospec = defer.Deferred()
enabled_rospec.addCallback(self._setState_wrapper,
LLRPClient.STATE_INVENTORYING)
# enabled_rospec.addCallback(self.send_START_ROSPEC, rospec,
# onCompletion=started_rospec)
enabled_rospec.addErrback(self.panic, 'ENABLE_ROSPEC failed')
logger.debug('made enabled_rospec')
added_rospec = defer.Deferred()
added_rospec.addCallback(self.send_ENABLE_ROSPEC, rospec,
onCompletion=enabled_rospec)
added_rospec.addErrback(self.panic, 'ADD_ROSPEC failed')
logger.debug('made added_rospec')
self.send_ADD_ROSPEC(rospec, onCompletion=added_rospec) | python | def startInventory(self, proto=None, force_regen_rospec=False):
"""Add a ROSpec to the reader and enable it."""
if self.state == LLRPClient.STATE_INVENTORYING:
logger.warn('ignoring startInventory() while already inventorying')
return None
rospec = self.getROSpec(force_new=force_regen_rospec)['ROSpec']
logger.info('starting inventory')
# upside-down chain of callbacks: add, enable, start ROSpec
# started_rospec = defer.Deferred()
# started_rospec.addCallback(self._setState_wrapper,
# LLRPClient.STATE_INVENTORYING)
# started_rospec.addErrback(self.panic, 'START_ROSPEC failed')
# logger.debug('made started_rospec')
enabled_rospec = defer.Deferred()
enabled_rospec.addCallback(self._setState_wrapper,
LLRPClient.STATE_INVENTORYING)
# enabled_rospec.addCallback(self.send_START_ROSPEC, rospec,
# onCompletion=started_rospec)
enabled_rospec.addErrback(self.panic, 'ENABLE_ROSPEC failed')
logger.debug('made enabled_rospec')
added_rospec = defer.Deferred()
added_rospec.addCallback(self.send_ENABLE_ROSPEC, rospec,
onCompletion=enabled_rospec)
added_rospec.addErrback(self.panic, 'ADD_ROSPEC failed')
logger.debug('made added_rospec')
self.send_ADD_ROSPEC(rospec, onCompletion=added_rospec) | [
"def",
"startInventory",
"(",
"self",
",",
"proto",
"=",
"None",
",",
"force_regen_rospec",
"=",
"False",
")",
":",
"if",
"self",
".",
"state",
"==",
"LLRPClient",
".",
"STATE_INVENTORYING",
":",
"logger",
".",
"warn",
"(",
"'ignoring startInventory() while already inventorying'",
")",
"return",
"None",
"rospec",
"=",
"self",
".",
"getROSpec",
"(",
"force_new",
"=",
"force_regen_rospec",
")",
"[",
"'ROSpec'",
"]",
"logger",
".",
"info",
"(",
"'starting inventory'",
")",
"# upside-down chain of callbacks: add, enable, start ROSpec",
"# started_rospec = defer.Deferred()",
"# started_rospec.addCallback(self._setState_wrapper,",
"# LLRPClient.STATE_INVENTORYING)",
"# started_rospec.addErrback(self.panic, 'START_ROSPEC failed')",
"# logger.debug('made started_rospec')",
"enabled_rospec",
"=",
"defer",
".",
"Deferred",
"(",
")",
"enabled_rospec",
".",
"addCallback",
"(",
"self",
".",
"_setState_wrapper",
",",
"LLRPClient",
".",
"STATE_INVENTORYING",
")",
"# enabled_rospec.addCallback(self.send_START_ROSPEC, rospec,",
"# onCompletion=started_rospec)",
"enabled_rospec",
".",
"addErrback",
"(",
"self",
".",
"panic",
",",
"'ENABLE_ROSPEC failed'",
")",
"logger",
".",
"debug",
"(",
"'made enabled_rospec'",
")",
"added_rospec",
"=",
"defer",
".",
"Deferred",
"(",
")",
"added_rospec",
".",
"addCallback",
"(",
"self",
".",
"send_ENABLE_ROSPEC",
",",
"rospec",
",",
"onCompletion",
"=",
"enabled_rospec",
")",
"added_rospec",
".",
"addErrback",
"(",
"self",
".",
"panic",
",",
"'ADD_ROSPEC failed'",
")",
"logger",
".",
"debug",
"(",
"'made added_rospec'",
")",
"self",
".",
"send_ADD_ROSPEC",
"(",
"rospec",
",",
"onCompletion",
"=",
"added_rospec",
")"
] | Add a ROSpec to the reader and enable it. | [
"Add",
"a",
"ROSpec",
"to",
"the",
"reader",
"and",
"enable",
"it",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1038-L1069 | train | 251,065 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.stopPolitely | def stopPolitely(self, disconnect=False):
"""Delete all active ROSpecs. Return a Deferred that will be called
when the DELETE_ROSPEC_RESPONSE comes back."""
logger.info('stopping politely')
if disconnect:
logger.info('will disconnect when stopped')
self.disconnecting = True
self.sendMessage({
'DELETE_ACCESSSPEC': {
'Ver': 1,
'Type': 41,
'ID': 0,
'AccessSpecID': 0 # all AccessSpecs
}})
self.setState(LLRPClient.STATE_SENT_DELETE_ACCESSSPEC)
d = defer.Deferred()
d.addCallback(self.stopAllROSpecs)
d.addErrback(self.panic, 'DELETE_ACCESSSPEC failed')
self._deferreds['DELETE_ACCESSSPEC_RESPONSE'].append(d)
return d | python | def stopPolitely(self, disconnect=False):
"""Delete all active ROSpecs. Return a Deferred that will be called
when the DELETE_ROSPEC_RESPONSE comes back."""
logger.info('stopping politely')
if disconnect:
logger.info('will disconnect when stopped')
self.disconnecting = True
self.sendMessage({
'DELETE_ACCESSSPEC': {
'Ver': 1,
'Type': 41,
'ID': 0,
'AccessSpecID': 0 # all AccessSpecs
}})
self.setState(LLRPClient.STATE_SENT_DELETE_ACCESSSPEC)
d = defer.Deferred()
d.addCallback(self.stopAllROSpecs)
d.addErrback(self.panic, 'DELETE_ACCESSSPEC failed')
self._deferreds['DELETE_ACCESSSPEC_RESPONSE'].append(d)
return d | [
"def",
"stopPolitely",
"(",
"self",
",",
"disconnect",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"'stopping politely'",
")",
"if",
"disconnect",
":",
"logger",
".",
"info",
"(",
"'will disconnect when stopped'",
")",
"self",
".",
"disconnecting",
"=",
"True",
"self",
".",
"sendMessage",
"(",
"{",
"'DELETE_ACCESSSPEC'",
":",
"{",
"'Ver'",
":",
"1",
",",
"'Type'",
":",
"41",
",",
"'ID'",
":",
"0",
",",
"'AccessSpecID'",
":",
"0",
"# all AccessSpecs",
"}",
"}",
")",
"self",
".",
"setState",
"(",
"LLRPClient",
".",
"STATE_SENT_DELETE_ACCESSSPEC",
")",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"d",
".",
"addCallback",
"(",
"self",
".",
"stopAllROSpecs",
")",
"d",
".",
"addErrback",
"(",
"self",
".",
"panic",
",",
"'DELETE_ACCESSSPEC failed'",
")",
"self",
".",
"_deferreds",
"[",
"'DELETE_ACCESSSPEC_RESPONSE'",
"]",
".",
"append",
"(",
"d",
")",
"return",
"d"
] | Delete all active ROSpecs. Return a Deferred that will be called
when the DELETE_ROSPEC_RESPONSE comes back. | [
"Delete",
"all",
"active",
"ROSpecs",
".",
"Return",
"a",
"Deferred",
"that",
"will",
"be",
"called",
"when",
"the",
"DELETE_ROSPEC_RESPONSE",
"comes",
"back",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1103-L1124 | train | 251,066 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.parsePowerTable | def parsePowerTable(uhfbandcap):
"""Parse the transmit power table
@param uhfbandcap: Capability dictionary from
self.capabilities['RegulatoryCapabilities']['UHFBandCapabilities']
@return: a list of [0, dBm value, dBm value, ...]
>>> LLRPClient.parsePowerTable({'TransmitPowerLevelTableEntry1': \
{'Index': 1, 'TransmitPowerValue': 3225}})
[0, 32.25]
>>> LLRPClient.parsePowerTable({})
[0]
"""
bandtbl = {k: v for k, v in uhfbandcap.items()
if k.startswith('TransmitPowerLevelTableEntry')}
tx_power_table = [0] * (len(bandtbl) + 1)
for k, v in bandtbl.items():
idx = v['Index']
tx_power_table[idx] = int(v['TransmitPowerValue']) / 100.0
return tx_power_table | python | def parsePowerTable(uhfbandcap):
"""Parse the transmit power table
@param uhfbandcap: Capability dictionary from
self.capabilities['RegulatoryCapabilities']['UHFBandCapabilities']
@return: a list of [0, dBm value, dBm value, ...]
>>> LLRPClient.parsePowerTable({'TransmitPowerLevelTableEntry1': \
{'Index': 1, 'TransmitPowerValue': 3225}})
[0, 32.25]
>>> LLRPClient.parsePowerTable({})
[0]
"""
bandtbl = {k: v for k, v in uhfbandcap.items()
if k.startswith('TransmitPowerLevelTableEntry')}
tx_power_table = [0] * (len(bandtbl) + 1)
for k, v in bandtbl.items():
idx = v['Index']
tx_power_table[idx] = int(v['TransmitPowerValue']) / 100.0
return tx_power_table | [
"def",
"parsePowerTable",
"(",
"uhfbandcap",
")",
":",
"bandtbl",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"uhfbandcap",
".",
"items",
"(",
")",
"if",
"k",
".",
"startswith",
"(",
"'TransmitPowerLevelTableEntry'",
")",
"}",
"tx_power_table",
"=",
"[",
"0",
"]",
"*",
"(",
"len",
"(",
"bandtbl",
")",
"+",
"1",
")",
"for",
"k",
",",
"v",
"in",
"bandtbl",
".",
"items",
"(",
")",
":",
"idx",
"=",
"v",
"[",
"'Index'",
"]",
"tx_power_table",
"[",
"idx",
"]",
"=",
"int",
"(",
"v",
"[",
"'TransmitPowerValue'",
"]",
")",
"/",
"100.0",
"return",
"tx_power_table"
] | Parse the transmit power table
@param uhfbandcap: Capability dictionary from
self.capabilities['RegulatoryCapabilities']['UHFBandCapabilities']
@return: a list of [0, dBm value, dBm value, ...]
>>> LLRPClient.parsePowerTable({'TransmitPowerLevelTableEntry1': \
{'Index': 1, 'TransmitPowerValue': 3225}})
[0, 32.25]
>>> LLRPClient.parsePowerTable({})
[0] | [
"Parse",
"the",
"transmit",
"power",
"table"
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1143-L1163 | train | 251,067 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.get_tx_power | def get_tx_power(self, tx_power):
"""Validates tx_power against self.tx_power_table
@param tx_power: index into the self.tx_power_table list; if tx_power
is 0 then the max power from self.tx_power_table
@return: a dict {antenna: (tx_power_index, power_dbm)} from
self.tx_power_table
@raise: LLRPError if the requested index is out of range
"""
if not self.tx_power_table:
logger.warn('get_tx_power(): tx_power_table is empty!')
return {}
logger.debug('requested tx_power: %s', tx_power)
min_power = self.tx_power_table.index(min(self.tx_power_table))
max_power = self.tx_power_table.index(max(self.tx_power_table))
ret = {}
for antid, tx_power in tx_power.items():
if tx_power == 0:
# tx_power = 0 means max power
max_power_dbm = max(self.tx_power_table)
tx_power = self.tx_power_table.index(max_power_dbm)
ret[antid] = (tx_power, max_power_dbm)
try:
power_dbm = self.tx_power_table[tx_power]
ret[antid] = (tx_power, power_dbm)
except IndexError:
raise LLRPError('Invalid tx_power for antenna {}: '
'requested={}, min_available={}, '
'max_available={}'.format(
antid, self.tx_power, min_power,
max_power))
return ret | python | def get_tx_power(self, tx_power):
"""Validates tx_power against self.tx_power_table
@param tx_power: index into the self.tx_power_table list; if tx_power
is 0 then the max power from self.tx_power_table
@return: a dict {antenna: (tx_power_index, power_dbm)} from
self.tx_power_table
@raise: LLRPError if the requested index is out of range
"""
if not self.tx_power_table:
logger.warn('get_tx_power(): tx_power_table is empty!')
return {}
logger.debug('requested tx_power: %s', tx_power)
min_power = self.tx_power_table.index(min(self.tx_power_table))
max_power = self.tx_power_table.index(max(self.tx_power_table))
ret = {}
for antid, tx_power in tx_power.items():
if tx_power == 0:
# tx_power = 0 means max power
max_power_dbm = max(self.tx_power_table)
tx_power = self.tx_power_table.index(max_power_dbm)
ret[antid] = (tx_power, max_power_dbm)
try:
power_dbm = self.tx_power_table[tx_power]
ret[antid] = (tx_power, power_dbm)
except IndexError:
raise LLRPError('Invalid tx_power for antenna {}: '
'requested={}, min_available={}, '
'max_available={}'.format(
antid, self.tx_power, min_power,
max_power))
return ret | [
"def",
"get_tx_power",
"(",
"self",
",",
"tx_power",
")",
":",
"if",
"not",
"self",
".",
"tx_power_table",
":",
"logger",
".",
"warn",
"(",
"'get_tx_power(): tx_power_table is empty!'",
")",
"return",
"{",
"}",
"logger",
".",
"debug",
"(",
"'requested tx_power: %s'",
",",
"tx_power",
")",
"min_power",
"=",
"self",
".",
"tx_power_table",
".",
"index",
"(",
"min",
"(",
"self",
".",
"tx_power_table",
")",
")",
"max_power",
"=",
"self",
".",
"tx_power_table",
".",
"index",
"(",
"max",
"(",
"self",
".",
"tx_power_table",
")",
")",
"ret",
"=",
"{",
"}",
"for",
"antid",
",",
"tx_power",
"in",
"tx_power",
".",
"items",
"(",
")",
":",
"if",
"tx_power",
"==",
"0",
":",
"# tx_power = 0 means max power",
"max_power_dbm",
"=",
"max",
"(",
"self",
".",
"tx_power_table",
")",
"tx_power",
"=",
"self",
".",
"tx_power_table",
".",
"index",
"(",
"max_power_dbm",
")",
"ret",
"[",
"antid",
"]",
"=",
"(",
"tx_power",
",",
"max_power_dbm",
")",
"try",
":",
"power_dbm",
"=",
"self",
".",
"tx_power_table",
"[",
"tx_power",
"]",
"ret",
"[",
"antid",
"]",
"=",
"(",
"tx_power",
",",
"power_dbm",
")",
"except",
"IndexError",
":",
"raise",
"LLRPError",
"(",
"'Invalid tx_power for antenna {}: '",
"'requested={}, min_available={}, '",
"'max_available={}'",
".",
"format",
"(",
"antid",
",",
"self",
".",
"tx_power",
",",
"min_power",
",",
"max_power",
")",
")",
"return",
"ret"
] | Validates tx_power against self.tx_power_table
@param tx_power: index into the self.tx_power_table list; if tx_power
is 0 then the max power from self.tx_power_table
@return: a dict {antenna: (tx_power_index, power_dbm)} from
self.tx_power_table
@raise: LLRPError if the requested index is out of range | [
"Validates",
"tx_power",
"against",
"self",
".",
"tx_power_table"
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1165-L1199 | train | 251,068 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.setTxPower | def setTxPower(self, tx_power):
"""Set the transmission power for one or more antennas.
@param tx_power: index into self.tx_power_table
"""
tx_pow_validated = self.get_tx_power(tx_power)
logger.debug('tx_pow_validated: %s', tx_pow_validated)
needs_update = False
for ant, (tx_pow_idx, tx_pow_dbm) in tx_pow_validated.items():
if self.tx_power[ant] != tx_pow_idx:
self.tx_power[ant] = tx_pow_idx
needs_update = True
logger.debug('tx_power for antenna %s: %s (%s dBm)', ant,
tx_pow_idx, tx_pow_dbm)
if needs_update and self.state == LLRPClient.STATE_INVENTORYING:
logger.debug('changing tx power; will stop politely, then resume')
d = self.stopPolitely()
d.addCallback(self.startInventory, force_regen_rospec=True) | python | def setTxPower(self, tx_power):
"""Set the transmission power for one or more antennas.
@param tx_power: index into self.tx_power_table
"""
tx_pow_validated = self.get_tx_power(tx_power)
logger.debug('tx_pow_validated: %s', tx_pow_validated)
needs_update = False
for ant, (tx_pow_idx, tx_pow_dbm) in tx_pow_validated.items():
if self.tx_power[ant] != tx_pow_idx:
self.tx_power[ant] = tx_pow_idx
needs_update = True
logger.debug('tx_power for antenna %s: %s (%s dBm)', ant,
tx_pow_idx, tx_pow_dbm)
if needs_update and self.state == LLRPClient.STATE_INVENTORYING:
logger.debug('changing tx power; will stop politely, then resume')
d = self.stopPolitely()
d.addCallback(self.startInventory, force_regen_rospec=True) | [
"def",
"setTxPower",
"(",
"self",
",",
"tx_power",
")",
":",
"tx_pow_validated",
"=",
"self",
".",
"get_tx_power",
"(",
"tx_power",
")",
"logger",
".",
"debug",
"(",
"'tx_pow_validated: %s'",
",",
"tx_pow_validated",
")",
"needs_update",
"=",
"False",
"for",
"ant",
",",
"(",
"tx_pow_idx",
",",
"tx_pow_dbm",
")",
"in",
"tx_pow_validated",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"tx_power",
"[",
"ant",
"]",
"!=",
"tx_pow_idx",
":",
"self",
".",
"tx_power",
"[",
"ant",
"]",
"=",
"tx_pow_idx",
"needs_update",
"=",
"True",
"logger",
".",
"debug",
"(",
"'tx_power for antenna %s: %s (%s dBm)'",
",",
"ant",
",",
"tx_pow_idx",
",",
"tx_pow_dbm",
")",
"if",
"needs_update",
"and",
"self",
".",
"state",
"==",
"LLRPClient",
".",
"STATE_INVENTORYING",
":",
"logger",
".",
"debug",
"(",
"'changing tx power; will stop politely, then resume'",
")",
"d",
"=",
"self",
".",
"stopPolitely",
"(",
")",
"d",
".",
"addCallback",
"(",
"self",
".",
"startInventory",
",",
"force_regen_rospec",
"=",
"True",
")"
] | Set the transmission power for one or more antennas.
@param tx_power: index into self.tx_power_table | [
"Set",
"the",
"transmission",
"power",
"for",
"one",
"or",
"more",
"antennas",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1201-L1220 | train | 251,069 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.pause | def pause(self, duration_seconds=0, force=False, force_regen_rospec=False):
"""Pause an inventory operation for a set amount of time."""
logger.debug('pause(%s)', duration_seconds)
if self.state != LLRPClient.STATE_INVENTORYING:
if not force:
logger.info('ignoring pause(); not inventorying (state==%s)',
self.getStateName(self.state))
return None
else:
logger.info('forcing pause()')
if duration_seconds:
logger.info('pausing for %s seconds', duration_seconds)
rospec = self.getROSpec(force_new=force_regen_rospec)['ROSpec']
self.sendMessage({
'DISABLE_ROSPEC': {
'Ver': 1,
'Type': 25,
'ID': 0,
'ROSpecID': rospec['ROSpecID']
}})
self.setState(LLRPClient.STATE_PAUSING)
d = defer.Deferred()
d.addCallback(self._setState_wrapper, LLRPClient.STATE_PAUSED)
d.addErrback(self.complain, 'pause() failed')
self._deferreds['DISABLE_ROSPEC_RESPONSE'].append(d)
if duration_seconds > 0:
startAgain = task.deferLater(reactor, duration_seconds,
lambda: None)
startAgain.addCallback(lambda _: self.resume())
return d | python | def pause(self, duration_seconds=0, force=False, force_regen_rospec=False):
"""Pause an inventory operation for a set amount of time."""
logger.debug('pause(%s)', duration_seconds)
if self.state != LLRPClient.STATE_INVENTORYING:
if not force:
logger.info('ignoring pause(); not inventorying (state==%s)',
self.getStateName(self.state))
return None
else:
logger.info('forcing pause()')
if duration_seconds:
logger.info('pausing for %s seconds', duration_seconds)
rospec = self.getROSpec(force_new=force_regen_rospec)['ROSpec']
self.sendMessage({
'DISABLE_ROSPEC': {
'Ver': 1,
'Type': 25,
'ID': 0,
'ROSpecID': rospec['ROSpecID']
}})
self.setState(LLRPClient.STATE_PAUSING)
d = defer.Deferred()
d.addCallback(self._setState_wrapper, LLRPClient.STATE_PAUSED)
d.addErrback(self.complain, 'pause() failed')
self._deferreds['DISABLE_ROSPEC_RESPONSE'].append(d)
if duration_seconds > 0:
startAgain = task.deferLater(reactor, duration_seconds,
lambda: None)
startAgain.addCallback(lambda _: self.resume())
return d | [
"def",
"pause",
"(",
"self",
",",
"duration_seconds",
"=",
"0",
",",
"force",
"=",
"False",
",",
"force_regen_rospec",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"'pause(%s)'",
",",
"duration_seconds",
")",
"if",
"self",
".",
"state",
"!=",
"LLRPClient",
".",
"STATE_INVENTORYING",
":",
"if",
"not",
"force",
":",
"logger",
".",
"info",
"(",
"'ignoring pause(); not inventorying (state==%s)'",
",",
"self",
".",
"getStateName",
"(",
"self",
".",
"state",
")",
")",
"return",
"None",
"else",
":",
"logger",
".",
"info",
"(",
"'forcing pause()'",
")",
"if",
"duration_seconds",
":",
"logger",
".",
"info",
"(",
"'pausing for %s seconds'",
",",
"duration_seconds",
")",
"rospec",
"=",
"self",
".",
"getROSpec",
"(",
"force_new",
"=",
"force_regen_rospec",
")",
"[",
"'ROSpec'",
"]",
"self",
".",
"sendMessage",
"(",
"{",
"'DISABLE_ROSPEC'",
":",
"{",
"'Ver'",
":",
"1",
",",
"'Type'",
":",
"25",
",",
"'ID'",
":",
"0",
",",
"'ROSpecID'",
":",
"rospec",
"[",
"'ROSpecID'",
"]",
"}",
"}",
")",
"self",
".",
"setState",
"(",
"LLRPClient",
".",
"STATE_PAUSING",
")",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"d",
".",
"addCallback",
"(",
"self",
".",
"_setState_wrapper",
",",
"LLRPClient",
".",
"STATE_PAUSED",
")",
"d",
".",
"addErrback",
"(",
"self",
".",
"complain",
",",
"'pause() failed'",
")",
"self",
".",
"_deferreds",
"[",
"'DISABLE_ROSPEC_RESPONSE'",
"]",
".",
"append",
"(",
"d",
")",
"if",
"duration_seconds",
">",
"0",
":",
"startAgain",
"=",
"task",
".",
"deferLater",
"(",
"reactor",
",",
"duration_seconds",
",",
"lambda",
":",
"None",
")",
"startAgain",
".",
"addCallback",
"(",
"lambda",
"_",
":",
"self",
".",
"resume",
"(",
")",
")",
"return",
"d"
] | Pause an inventory operation for a set amount of time. | [
"Pause",
"an",
"inventory",
"operation",
"for",
"a",
"set",
"amount",
"of",
"time",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1222-L1257 | train | 251,070 |
ransford/sllurp | sllurp/llrp.py | LLRPClient.sendMessage | def sendMessage(self, msg_dict):
"""Serialize and send a dict LLRP Message
Note: IDs should be modified in original msg_dict as it is a reference.
That should be ok.
"""
sent_ids = []
for name in msg_dict:
self.last_msg_id += 1
msg_dict[name]['ID'] = self.last_msg_id
sent_ids.append((name, self.last_msg_id))
llrp_msg = LLRPMessage(msgdict=msg_dict)
assert llrp_msg.msgbytes, "LLRPMessage is empty"
self.transport.write(llrp_msg.msgbytes)
return sent_ids | python | def sendMessage(self, msg_dict):
"""Serialize and send a dict LLRP Message
Note: IDs should be modified in original msg_dict as it is a reference.
That should be ok.
"""
sent_ids = []
for name in msg_dict:
self.last_msg_id += 1
msg_dict[name]['ID'] = self.last_msg_id
sent_ids.append((name, self.last_msg_id))
llrp_msg = LLRPMessage(msgdict=msg_dict)
assert llrp_msg.msgbytes, "LLRPMessage is empty"
self.transport.write(llrp_msg.msgbytes)
return sent_ids | [
"def",
"sendMessage",
"(",
"self",
",",
"msg_dict",
")",
":",
"sent_ids",
"=",
"[",
"]",
"for",
"name",
"in",
"msg_dict",
":",
"self",
".",
"last_msg_id",
"+=",
"1",
"msg_dict",
"[",
"name",
"]",
"[",
"'ID'",
"]",
"=",
"self",
".",
"last_msg_id",
"sent_ids",
".",
"append",
"(",
"(",
"name",
",",
"self",
".",
"last_msg_id",
")",
")",
"llrp_msg",
"=",
"LLRPMessage",
"(",
"msgdict",
"=",
"msg_dict",
")",
"assert",
"llrp_msg",
".",
"msgbytes",
",",
"\"LLRPMessage is empty\"",
"self",
".",
"transport",
".",
"write",
"(",
"llrp_msg",
".",
"msgbytes",
")",
"return",
"sent_ids"
] | Serialize and send a dict LLRP Message
Note: IDs should be modified in original msg_dict as it is a reference.
That should be ok. | [
"Serialize",
"and",
"send",
"a",
"dict",
"LLRP",
"Message"
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1283-L1299 | train | 251,071 |
ransford/sllurp | sllurp/llrp.py | LLRPClientFactory.buildProtocol | def buildProtocol(self, addr):
"""Get a new LLRP client protocol object.
Consult self.antenna_dict to look up antennas to use.
"""
self.resetDelay() # reset reconnection backoff state
clargs = self.client_args.copy()
# optionally configure antennas from self.antenna_dict, which looks
# like {'10.0.0.1:5084': {'1': 'ant1', '2': 'ant2'}}
hostport = '{}:{}'.format(addr.host, addr.port)
logger.debug('Building protocol for %s', hostport)
if hostport in self.antenna_dict:
clargs['antennas'] = [
int(x) for x in self.antenna_dict[hostport].keys()]
elif addr.host in self.antenna_dict:
clargs['antennas'] = [
int(x) for x in self.antenna_dict[addr.host].keys()]
logger.debug('Antennas in buildProtocol: %s', clargs.get('antennas'))
logger.debug('%s start_inventory: %s', hostport,
clargs.get('start_inventory'))
if self.start_first and not self.protocols:
# this is the first protocol, so let's start it inventorying
clargs['start_inventory'] = True
proto = LLRPClient(factory=self, **clargs)
# register state-change callbacks with new client
for state, cbs in self._state_callbacks.items():
for cb in cbs:
proto.addStateCallback(state, cb)
# register message callbacks with new client
for msg_type, cbs in self._message_callbacks.items():
for cb in cbs:
proto.addMessageCallback(msg_type, cb)
return proto | python | def buildProtocol(self, addr):
"""Get a new LLRP client protocol object.
Consult self.antenna_dict to look up antennas to use.
"""
self.resetDelay() # reset reconnection backoff state
clargs = self.client_args.copy()
# optionally configure antennas from self.antenna_dict, which looks
# like {'10.0.0.1:5084': {'1': 'ant1', '2': 'ant2'}}
hostport = '{}:{}'.format(addr.host, addr.port)
logger.debug('Building protocol for %s', hostport)
if hostport in self.antenna_dict:
clargs['antennas'] = [
int(x) for x in self.antenna_dict[hostport].keys()]
elif addr.host in self.antenna_dict:
clargs['antennas'] = [
int(x) for x in self.antenna_dict[addr.host].keys()]
logger.debug('Antennas in buildProtocol: %s', clargs.get('antennas'))
logger.debug('%s start_inventory: %s', hostport,
clargs.get('start_inventory'))
if self.start_first and not self.protocols:
# this is the first protocol, so let's start it inventorying
clargs['start_inventory'] = True
proto = LLRPClient(factory=self, **clargs)
# register state-change callbacks with new client
for state, cbs in self._state_callbacks.items():
for cb in cbs:
proto.addStateCallback(state, cb)
# register message callbacks with new client
for msg_type, cbs in self._message_callbacks.items():
for cb in cbs:
proto.addMessageCallback(msg_type, cb)
return proto | [
"def",
"buildProtocol",
"(",
"self",
",",
"addr",
")",
":",
"self",
".",
"resetDelay",
"(",
")",
"# reset reconnection backoff state",
"clargs",
"=",
"self",
".",
"client_args",
".",
"copy",
"(",
")",
"# optionally configure antennas from self.antenna_dict, which looks",
"# like {'10.0.0.1:5084': {'1': 'ant1', '2': 'ant2'}}",
"hostport",
"=",
"'{}:{}'",
".",
"format",
"(",
"addr",
".",
"host",
",",
"addr",
".",
"port",
")",
"logger",
".",
"debug",
"(",
"'Building protocol for %s'",
",",
"hostport",
")",
"if",
"hostport",
"in",
"self",
".",
"antenna_dict",
":",
"clargs",
"[",
"'antennas'",
"]",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"antenna_dict",
"[",
"hostport",
"]",
".",
"keys",
"(",
")",
"]",
"elif",
"addr",
".",
"host",
"in",
"self",
".",
"antenna_dict",
":",
"clargs",
"[",
"'antennas'",
"]",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"antenna_dict",
"[",
"addr",
".",
"host",
"]",
".",
"keys",
"(",
")",
"]",
"logger",
".",
"debug",
"(",
"'Antennas in buildProtocol: %s'",
",",
"clargs",
".",
"get",
"(",
"'antennas'",
")",
")",
"logger",
".",
"debug",
"(",
"'%s start_inventory: %s'",
",",
"hostport",
",",
"clargs",
".",
"get",
"(",
"'start_inventory'",
")",
")",
"if",
"self",
".",
"start_first",
"and",
"not",
"self",
".",
"protocols",
":",
"# this is the first protocol, so let's start it inventorying",
"clargs",
"[",
"'start_inventory'",
"]",
"=",
"True",
"proto",
"=",
"LLRPClient",
"(",
"factory",
"=",
"self",
",",
"*",
"*",
"clargs",
")",
"# register state-change callbacks with new client",
"for",
"state",
",",
"cbs",
"in",
"self",
".",
"_state_callbacks",
".",
"items",
"(",
")",
":",
"for",
"cb",
"in",
"cbs",
":",
"proto",
".",
"addStateCallback",
"(",
"state",
",",
"cb",
")",
"# register message callbacks with new client",
"for",
"msg_type",
",",
"cbs",
"in",
"self",
".",
"_message_callbacks",
".",
"items",
"(",
")",
":",
"for",
"cb",
"in",
"cbs",
":",
"proto",
".",
"addMessageCallback",
"(",
"msg_type",
",",
"cb",
")",
"return",
"proto"
] | Get a new LLRP client protocol object.
Consult self.antenna_dict to look up antennas to use. | [
"Get",
"a",
"new",
"LLRP",
"client",
"protocol",
"object",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1339-L1376 | train | 251,072 |
ransford/sllurp | sllurp/llrp.py | LLRPClientFactory.setTxPower | def setTxPower(self, tx_power, peername=None):
"""Set the transmit power on one or all readers
If peername is None, set the transmit power for all readers.
Otherwise, set it for that specific reader.
"""
if peername:
protocols = [p for p in self.protocols
if p.peername[0] == peername]
else:
protocols = self.protocols
for proto in protocols:
proto.setTxPower(tx_power) | python | def setTxPower(self, tx_power, peername=None):
"""Set the transmit power on one or all readers
If peername is None, set the transmit power for all readers.
Otherwise, set it for that specific reader.
"""
if peername:
protocols = [p for p in self.protocols
if p.peername[0] == peername]
else:
protocols = self.protocols
for proto in protocols:
proto.setTxPower(tx_power) | [
"def",
"setTxPower",
"(",
"self",
",",
"tx_power",
",",
"peername",
"=",
"None",
")",
":",
"if",
"peername",
":",
"protocols",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"protocols",
"if",
"p",
".",
"peername",
"[",
"0",
"]",
"==",
"peername",
"]",
"else",
":",
"protocols",
"=",
"self",
".",
"protocols",
"for",
"proto",
"in",
"protocols",
":",
"proto",
".",
"setTxPower",
"(",
"tx_power",
")"
] | Set the transmit power on one or all readers
If peername is None, set the transmit power for all readers.
Otherwise, set it for that specific reader. | [
"Set",
"the",
"transmit",
"power",
"on",
"one",
"or",
"all",
"readers"
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1411-L1423 | train | 251,073 |
ransford/sllurp | sllurp/llrp.py | LLRPClientFactory.politeShutdown | def politeShutdown(self):
"""Stop inventory on all connected readers."""
protoDeferreds = []
for proto in self.protocols:
protoDeferreds.append(proto.stopPolitely(disconnect=True))
return defer.DeferredList(protoDeferreds) | python | def politeShutdown(self):
"""Stop inventory on all connected readers."""
protoDeferreds = []
for proto in self.protocols:
protoDeferreds.append(proto.stopPolitely(disconnect=True))
return defer.DeferredList(protoDeferreds) | [
"def",
"politeShutdown",
"(",
"self",
")",
":",
"protoDeferreds",
"=",
"[",
"]",
"for",
"proto",
"in",
"self",
".",
"protocols",
":",
"protoDeferreds",
".",
"append",
"(",
"proto",
".",
"stopPolitely",
"(",
"disconnect",
"=",
"True",
")",
")",
"return",
"defer",
".",
"DeferredList",
"(",
"protoDeferreds",
")"
] | Stop inventory on all connected readers. | [
"Stop",
"inventory",
"on",
"all",
"connected",
"readers",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp.py#L1425-L1430 | train | 251,074 |
ransford/sllurp | sllurp/epc/sgtin_96.py | parse_sgtin_96 | def parse_sgtin_96(sgtin_96):
'''Given a SGTIN-96 hex string, parse each segment.
Returns a dictionary of the segments.'''
if not sgtin_96:
raise Exception('Pass in a value.')
if not sgtin_96.startswith("30"):
# not a sgtin, not handled
raise Exception('Not SGTIN-96.')
binary = "{0:020b}".format(int(sgtin_96, 16)).zfill(96)
header = int(binary[:8], 2)
tag_filter = int(binary[8:11], 2)
partition = binary[11:14]
partition_value = int(partition, 2)
m, l, n, k = SGTIN_96_PARTITION_MAP[partition_value]
company_start = 8 + 3 + 3
company_end = company_start + m
company_data = int(binary[company_start:company_end], 2)
if company_data > pow(10, l):
# can't be too large
raise Exception('Company value is too large')
company_prefix = str(company_data).zfill(l)
item_start = company_end
item_end = item_start + n
item_data = binary[item_start:item_end]
item_number = int(item_data, 2)
item_reference = str(item_number).zfill(k)
serial = int(binary[-38:], 2)
return {
"header": header,
"filter": tag_filter,
"partition": partition,
"company_prefix": company_prefix,
"item_reference": item_reference,
"serial": serial
} | python | def parse_sgtin_96(sgtin_96):
'''Given a SGTIN-96 hex string, parse each segment.
Returns a dictionary of the segments.'''
if not sgtin_96:
raise Exception('Pass in a value.')
if not sgtin_96.startswith("30"):
# not a sgtin, not handled
raise Exception('Not SGTIN-96.')
binary = "{0:020b}".format(int(sgtin_96, 16)).zfill(96)
header = int(binary[:8], 2)
tag_filter = int(binary[8:11], 2)
partition = binary[11:14]
partition_value = int(partition, 2)
m, l, n, k = SGTIN_96_PARTITION_MAP[partition_value]
company_start = 8 + 3 + 3
company_end = company_start + m
company_data = int(binary[company_start:company_end], 2)
if company_data > pow(10, l):
# can't be too large
raise Exception('Company value is too large')
company_prefix = str(company_data).zfill(l)
item_start = company_end
item_end = item_start + n
item_data = binary[item_start:item_end]
item_number = int(item_data, 2)
item_reference = str(item_number).zfill(k)
serial = int(binary[-38:], 2)
return {
"header": header,
"filter": tag_filter,
"partition": partition,
"company_prefix": company_prefix,
"item_reference": item_reference,
"serial": serial
} | [
"def",
"parse_sgtin_96",
"(",
"sgtin_96",
")",
":",
"if",
"not",
"sgtin_96",
":",
"raise",
"Exception",
"(",
"'Pass in a value.'",
")",
"if",
"not",
"sgtin_96",
".",
"startswith",
"(",
"\"30\"",
")",
":",
"# not a sgtin, not handled",
"raise",
"Exception",
"(",
"'Not SGTIN-96.'",
")",
"binary",
"=",
"\"{0:020b}\"",
".",
"format",
"(",
"int",
"(",
"sgtin_96",
",",
"16",
")",
")",
".",
"zfill",
"(",
"96",
")",
"header",
"=",
"int",
"(",
"binary",
"[",
":",
"8",
"]",
",",
"2",
")",
"tag_filter",
"=",
"int",
"(",
"binary",
"[",
"8",
":",
"11",
"]",
",",
"2",
")",
"partition",
"=",
"binary",
"[",
"11",
":",
"14",
"]",
"partition_value",
"=",
"int",
"(",
"partition",
",",
"2",
")",
"m",
",",
"l",
",",
"n",
",",
"k",
"=",
"SGTIN_96_PARTITION_MAP",
"[",
"partition_value",
"]",
"company_start",
"=",
"8",
"+",
"3",
"+",
"3",
"company_end",
"=",
"company_start",
"+",
"m",
"company_data",
"=",
"int",
"(",
"binary",
"[",
"company_start",
":",
"company_end",
"]",
",",
"2",
")",
"if",
"company_data",
">",
"pow",
"(",
"10",
",",
"l",
")",
":",
"# can't be too large",
"raise",
"Exception",
"(",
"'Company value is too large'",
")",
"company_prefix",
"=",
"str",
"(",
"company_data",
")",
".",
"zfill",
"(",
"l",
")",
"item_start",
"=",
"company_end",
"item_end",
"=",
"item_start",
"+",
"n",
"item_data",
"=",
"binary",
"[",
"item_start",
":",
"item_end",
"]",
"item_number",
"=",
"int",
"(",
"item_data",
",",
"2",
")",
"item_reference",
"=",
"str",
"(",
"item_number",
")",
".",
"zfill",
"(",
"k",
")",
"serial",
"=",
"int",
"(",
"binary",
"[",
"-",
"38",
":",
"]",
",",
"2",
")",
"return",
"{",
"\"header\"",
":",
"header",
",",
"\"filter\"",
":",
"tag_filter",
",",
"\"partition\"",
":",
"partition",
",",
"\"company_prefix\"",
":",
"company_prefix",
",",
"\"item_reference\"",
":",
"item_reference",
",",
"\"serial\"",
":",
"serial",
"}"
] | Given a SGTIN-96 hex string, parse each segment.
Returns a dictionary of the segments. | [
"Given",
"a",
"SGTIN",
"-",
"96",
"hex",
"string",
"parse",
"each",
"segment",
".",
"Returns",
"a",
"dictionary",
"of",
"the",
"segments",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/epc/sgtin_96.py#L27-L71 | train | 251,075 |
ransford/sllurp | sllurp/llrp_proto.py | decode_param | def decode_param(data):
"""Decode any parameter to a byte sequence.
:param data: byte sequence representing an LLRP parameter.
:returns dict, bytes: where dict is {'Type': <decoded type>, 'Data':
<decoded data>} and bytes is the remaining bytes trailing the bytes we
could decode.
"""
logger.debug('decode_param data: %r', data)
header_len = struct.calcsize('!HH')
partype, parlen = struct.unpack('!HH', data[:header_len])
pardata = data[header_len:parlen]
logger.debug('decode_param pardata: %r', pardata)
ret = {
'Type': partype,
}
if partype == 1023:
vsfmt = '!II'
vendor, subtype = struct.unpack(vsfmt, pardata[:struct.calcsize(vsfmt)])
ret['Vendor'] = vendor
ret['Subtype'] = subtype
ret['Data'] = pardata[struct.calcsize(vsfmt):]
else:
ret['Data'] = pardata,
return ret, data[parlen:] | python | def decode_param(data):
"""Decode any parameter to a byte sequence.
:param data: byte sequence representing an LLRP parameter.
:returns dict, bytes: where dict is {'Type': <decoded type>, 'Data':
<decoded data>} and bytes is the remaining bytes trailing the bytes we
could decode.
"""
logger.debug('decode_param data: %r', data)
header_len = struct.calcsize('!HH')
partype, parlen = struct.unpack('!HH', data[:header_len])
pardata = data[header_len:parlen]
logger.debug('decode_param pardata: %r', pardata)
ret = {
'Type': partype,
}
if partype == 1023:
vsfmt = '!II'
vendor, subtype = struct.unpack(vsfmt, pardata[:struct.calcsize(vsfmt)])
ret['Vendor'] = vendor
ret['Subtype'] = subtype
ret['Data'] = pardata[struct.calcsize(vsfmt):]
else:
ret['Data'] = pardata,
return ret, data[parlen:] | [
"def",
"decode_param",
"(",
"data",
")",
":",
"logger",
".",
"debug",
"(",
"'decode_param data: %r'",
",",
"data",
")",
"header_len",
"=",
"struct",
".",
"calcsize",
"(",
"'!HH'",
")",
"partype",
",",
"parlen",
"=",
"struct",
".",
"unpack",
"(",
"'!HH'",
",",
"data",
"[",
":",
"header_len",
"]",
")",
"pardata",
"=",
"data",
"[",
"header_len",
":",
"parlen",
"]",
"logger",
".",
"debug",
"(",
"'decode_param pardata: %r'",
",",
"pardata",
")",
"ret",
"=",
"{",
"'Type'",
":",
"partype",
",",
"}",
"if",
"partype",
"==",
"1023",
":",
"vsfmt",
"=",
"'!II'",
"vendor",
",",
"subtype",
"=",
"struct",
".",
"unpack",
"(",
"vsfmt",
",",
"pardata",
"[",
":",
"struct",
".",
"calcsize",
"(",
"vsfmt",
")",
"]",
")",
"ret",
"[",
"'Vendor'",
"]",
"=",
"vendor",
"ret",
"[",
"'Subtype'",
"]",
"=",
"subtype",
"ret",
"[",
"'Data'",
"]",
"=",
"pardata",
"[",
"struct",
".",
"calcsize",
"(",
"vsfmt",
")",
":",
"]",
"else",
":",
"ret",
"[",
"'Data'",
"]",
"=",
"pardata",
",",
"return",
"ret",
",",
"data",
"[",
"parlen",
":",
"]"
] | Decode any parameter to a byte sequence.
:param data: byte sequence representing an LLRP parameter.
:returns dict, bytes: where dict is {'Type': <decoded type>, 'Data':
<decoded data>} and bytes is the remaining bytes trailing the bytes we
could decode. | [
"Decode",
"any",
"parameter",
"to",
"a",
"byte",
"sequence",
"."
] | d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1 | https://github.com/ransford/sllurp/blob/d744b7e17d7ba64a24d9a31bde6cba65d91ad9b1/sllurp/llrp_proto.py#L341-L369 | train | 251,076 |
Amsterdam/objectstore | examples/handelsregister.py | download_files | def download_files(file_list):
"""Download the latest data. """
for _, source_data_file in file_list:
sql_gz_name = source_data_file['name'].split('/')[-1]
msg = 'Downloading: %s' % (sql_gz_name)
log.debug(msg)
new_data = objectstore.get_object(
handelsregister_conn, source_data_file, 'handelsregister')
# save output to file!
with open('data/{}'.format(sql_gz_name), 'wb') as outputzip:
outputzip.write(new_data) | python | def download_files(file_list):
"""Download the latest data. """
for _, source_data_file in file_list:
sql_gz_name = source_data_file['name'].split('/')[-1]
msg = 'Downloading: %s' % (sql_gz_name)
log.debug(msg)
new_data = objectstore.get_object(
handelsregister_conn, source_data_file, 'handelsregister')
# save output to file!
with open('data/{}'.format(sql_gz_name), 'wb') as outputzip:
outputzip.write(new_data) | [
"def",
"download_files",
"(",
"file_list",
")",
":",
"for",
"_",
",",
"source_data_file",
"in",
"file_list",
":",
"sql_gz_name",
"=",
"source_data_file",
"[",
"'name'",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"msg",
"=",
"'Downloading: %s'",
"%",
"(",
"sql_gz_name",
")",
"log",
".",
"debug",
"(",
"msg",
")",
"new_data",
"=",
"objectstore",
".",
"get_object",
"(",
"handelsregister_conn",
",",
"source_data_file",
",",
"'handelsregister'",
")",
"# save output to file!",
"with",
"open",
"(",
"'data/{}'",
".",
"format",
"(",
"sql_gz_name",
")",
",",
"'wb'",
")",
"as",
"outputzip",
":",
"outputzip",
".",
"write",
"(",
"new_data",
")"
] | Download the latest data. | [
"Download",
"the",
"latest",
"data",
"."
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/examples/handelsregister.py#L48-L60 | train | 251,077 |
Amsterdam/objectstore | objectstore/objectstore.py | get_connection | def get_connection(store_settings: dict={}) -> Connection:
"""
get an objectsctore connection
"""
store = store_settings
if not store_settings:
store = make_config_from_env()
os_options = {
'tenant_id': store['TENANT_ID'],
'region_name': store['REGION_NAME'],
# 'endpoint_type': 'internalURL'
}
# when we are running in cloudvps we should use internal urls
use_internal = os.getenv('OBJECTSTORE_LOCAL', '')
if use_internal:
os_options['endpoint_type'] = 'internalURL'
connection = Connection(
authurl=store['AUTHURL'],
user=store['USER'],
key=store['PASSWORD'],
tenant_name=store['TENANT_NAME'],
auth_version=store['VERSION'],
os_options=os_options
)
return connection | python | def get_connection(store_settings: dict={}) -> Connection:
"""
get an objectsctore connection
"""
store = store_settings
if not store_settings:
store = make_config_from_env()
os_options = {
'tenant_id': store['TENANT_ID'],
'region_name': store['REGION_NAME'],
# 'endpoint_type': 'internalURL'
}
# when we are running in cloudvps we should use internal urls
use_internal = os.getenv('OBJECTSTORE_LOCAL', '')
if use_internal:
os_options['endpoint_type'] = 'internalURL'
connection = Connection(
authurl=store['AUTHURL'],
user=store['USER'],
key=store['PASSWORD'],
tenant_name=store['TENANT_NAME'],
auth_version=store['VERSION'],
os_options=os_options
)
return connection | [
"def",
"get_connection",
"(",
"store_settings",
":",
"dict",
"=",
"{",
"}",
")",
"->",
"Connection",
":",
"store",
"=",
"store_settings",
"if",
"not",
"store_settings",
":",
"store",
"=",
"make_config_from_env",
"(",
")",
"os_options",
"=",
"{",
"'tenant_id'",
":",
"store",
"[",
"'TENANT_ID'",
"]",
",",
"'region_name'",
":",
"store",
"[",
"'REGION_NAME'",
"]",
",",
"# 'endpoint_type': 'internalURL'",
"}",
"# when we are running in cloudvps we should use internal urls",
"use_internal",
"=",
"os",
".",
"getenv",
"(",
"'OBJECTSTORE_LOCAL'",
",",
"''",
")",
"if",
"use_internal",
":",
"os_options",
"[",
"'endpoint_type'",
"]",
"=",
"'internalURL'",
"connection",
"=",
"Connection",
"(",
"authurl",
"=",
"store",
"[",
"'AUTHURL'",
"]",
",",
"user",
"=",
"store",
"[",
"'USER'",
"]",
",",
"key",
"=",
"store",
"[",
"'PASSWORD'",
"]",
",",
"tenant_name",
"=",
"store",
"[",
"'TENANT_NAME'",
"]",
",",
"auth_version",
"=",
"store",
"[",
"'VERSION'",
"]",
",",
"os_options",
"=",
"os_options",
")",
"return",
"connection"
] | get an objectsctore connection | [
"get",
"an",
"objectsctore",
"connection"
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/objectstore.py#L67-L96 | train | 251,078 |
Amsterdam/objectstore | objectstore/objectstore.py | get_object | def get_object(connection, object_meta_data: dict, dirname: str):
"""
Download object from objectstore.
object_meta_data is an object retured when
using 'get_full_container_list'
"""
return connection.get_object(dirname, object_meta_data['name'])[1] | python | def get_object(connection, object_meta_data: dict, dirname: str):
"""
Download object from objectstore.
object_meta_data is an object retured when
using 'get_full_container_list'
"""
return connection.get_object(dirname, object_meta_data['name'])[1] | [
"def",
"get_object",
"(",
"connection",
",",
"object_meta_data",
":",
"dict",
",",
"dirname",
":",
"str",
")",
":",
"return",
"connection",
".",
"get_object",
"(",
"dirname",
",",
"object_meta_data",
"[",
"'name'",
"]",
")",
"[",
"1",
"]"
] | Download object from objectstore.
object_meta_data is an object retured when
using 'get_full_container_list' | [
"Download",
"object",
"from",
"objectstore",
".",
"object_meta_data",
"is",
"an",
"object",
"retured",
"when",
"using",
"get_full_container_list"
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/objectstore.py#L117-L123 | train | 251,079 |
Amsterdam/objectstore | objectstore/objectstore.py | put_object | def put_object(
connection, container: str, object_name: str,
contents, content_type: str) -> None:
"""
Put file to objectstore
container == "path/in/store"
object_name = "your_file_name.txt"
contents=thefiledata (fileobject) open('ourfile', 'rb')
content_type='csv' / 'application/json' .. etc
"""
connection.put_object(
container, object_name, contents=contents,
content_type=content_type) | python | def put_object(
connection, container: str, object_name: str,
contents, content_type: str) -> None:
"""
Put file to objectstore
container == "path/in/store"
object_name = "your_file_name.txt"
contents=thefiledata (fileobject) open('ourfile', 'rb')
content_type='csv' / 'application/json' .. etc
"""
connection.put_object(
container, object_name, contents=contents,
content_type=content_type) | [
"def",
"put_object",
"(",
"connection",
",",
"container",
":",
"str",
",",
"object_name",
":",
"str",
",",
"contents",
",",
"content_type",
":",
"str",
")",
"->",
"None",
":",
"connection",
".",
"put_object",
"(",
"container",
",",
"object_name",
",",
"contents",
"=",
"contents",
",",
"content_type",
"=",
"content_type",
")"
] | Put file to objectstore
container == "path/in/store"
object_name = "your_file_name.txt"
contents=thefiledata (fileobject) open('ourfile', 'rb')
content_type='csv' / 'application/json' .. etc | [
"Put",
"file",
"to",
"objectstore"
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/objectstore.py#L126-L140 | train | 251,080 |
Amsterdam/objectstore | objectstore/objectstore.py | delete_object | def delete_object(connection, container: str, object_meta_data: dict) -> None:
"""
Delete single object from objectstore
"""
connection.delete_object(container, object_meta_data['name']) | python | def delete_object(connection, container: str, object_meta_data: dict) -> None:
"""
Delete single object from objectstore
"""
connection.delete_object(container, object_meta_data['name']) | [
"def",
"delete_object",
"(",
"connection",
",",
"container",
":",
"str",
",",
"object_meta_data",
":",
"dict",
")",
"->",
"None",
":",
"connection",
".",
"delete_object",
"(",
"container",
",",
"object_meta_data",
"[",
"'name'",
"]",
")"
] | Delete single object from objectstore | [
"Delete",
"single",
"object",
"from",
"objectstore"
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/objectstore.py#L143-L147 | train | 251,081 |
Amsterdam/objectstore | objectstore/databasedumps.py | return_file_objects | def return_file_objects(connection, container, prefix='database'):
"""Given connecton and container find database dumps
"""
options = []
meta_data = objectstore.get_full_container_list(
connection, container, prefix='database')
env = ENV.upper()
for o_info in meta_data:
expected_file = f'database.{ENV}'
if o_info['name'].startswith(expected_file):
dt = dateparser.parse(o_info['last_modified'])
now = datetime.datetime.now()
delta = now - dt
LOG.debug('AGE: %d %s', delta.days, expected_file)
options.append((dt, o_info))
options.sort()
return options | python | def return_file_objects(connection, container, prefix='database'):
"""Given connecton and container find database dumps
"""
options = []
meta_data = objectstore.get_full_container_list(
connection, container, prefix='database')
env = ENV.upper()
for o_info in meta_data:
expected_file = f'database.{ENV}'
if o_info['name'].startswith(expected_file):
dt = dateparser.parse(o_info['last_modified'])
now = datetime.datetime.now()
delta = now - dt
LOG.debug('AGE: %d %s', delta.days, expected_file)
options.append((dt, o_info))
options.sort()
return options | [
"def",
"return_file_objects",
"(",
"connection",
",",
"container",
",",
"prefix",
"=",
"'database'",
")",
":",
"options",
"=",
"[",
"]",
"meta_data",
"=",
"objectstore",
".",
"get_full_container_list",
"(",
"connection",
",",
"container",
",",
"prefix",
"=",
"'database'",
")",
"env",
"=",
"ENV",
".",
"upper",
"(",
")",
"for",
"o_info",
"in",
"meta_data",
":",
"expected_file",
"=",
"f'database.{ENV}'",
"if",
"o_info",
"[",
"'name'",
"]",
".",
"startswith",
"(",
"expected_file",
")",
":",
"dt",
"=",
"dateparser",
".",
"parse",
"(",
"o_info",
"[",
"'last_modified'",
"]",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"delta",
"=",
"now",
"-",
"dt",
"LOG",
".",
"debug",
"(",
"'AGE: %d %s'",
",",
"delta",
".",
"days",
",",
"expected_file",
")",
"options",
".",
"append",
"(",
"(",
"dt",
",",
"o_info",
")",
")",
"options",
".",
"sort",
"(",
")",
"return",
"options"
] | Given connecton and container find database dumps | [
"Given",
"connecton",
"and",
"container",
"find",
"database",
"dumps"
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/databasedumps.py#L66-L91 | train | 251,082 |
Amsterdam/objectstore | objectstore/databasedumps.py | remove_old_dumps | def remove_old_dumps(connection, container: str, days=None):
"""Remove dumps older than x days
"""
if not days:
return
if days < 20:
LOG.error('A minimum of 20 backups is stored')
return
options = return_file_objects(connection, container)
for dt, o_info in options:
now = datetime.datetime.now()
delta = now - dt
if delta.days > days:
LOG.info('Deleting %s', o_info['name'])
objectstore.delete_object(connection, container, o_info) | python | def remove_old_dumps(connection, container: str, days=None):
"""Remove dumps older than x days
"""
if not days:
return
if days < 20:
LOG.error('A minimum of 20 backups is stored')
return
options = return_file_objects(connection, container)
for dt, o_info in options:
now = datetime.datetime.now()
delta = now - dt
if delta.days > days:
LOG.info('Deleting %s', o_info['name'])
objectstore.delete_object(connection, container, o_info) | [
"def",
"remove_old_dumps",
"(",
"connection",
",",
"container",
":",
"str",
",",
"days",
"=",
"None",
")",
":",
"if",
"not",
"days",
":",
"return",
"if",
"days",
"<",
"20",
":",
"LOG",
".",
"error",
"(",
"'A minimum of 20 backups is stored'",
")",
"return",
"options",
"=",
"return_file_objects",
"(",
"connection",
",",
"container",
")",
"for",
"dt",
",",
"o_info",
"in",
"options",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"delta",
"=",
"now",
"-",
"dt",
"if",
"delta",
".",
"days",
">",
"days",
":",
"LOG",
".",
"info",
"(",
"'Deleting %s'",
",",
"o_info",
"[",
"'name'",
"]",
")",
"objectstore",
".",
"delete_object",
"(",
"connection",
",",
"container",
",",
"o_info",
")"
] | Remove dumps older than x days | [
"Remove",
"dumps",
"older",
"than",
"x",
"days"
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/databasedumps.py#L94-L112 | train | 251,083 |
Amsterdam/objectstore | objectstore/databasedumps.py | download_database | def download_database(connection, container: str, target: str=""):
"""
Download database dump
"""
meta_data = objectstore.get_full_container_list(
connection, container, prefix='database')
options = return_file_objects(connection, container)
for o_info in meta_data:
expected_file = f'database.{ENV}'
LOG.info(o_info['name'])
if o_info['name'].startswith(expected_file):
dt = dateparser.parse(o_info['last_modified'])
# now = datetime.datetime.now()
options.append((dt, o_info))
options.sort()
if not options:
LOG.error('Dumps missing? ENVIRONMENT wrong? (acceptance / production')
LOG.error('Environtment {ENV}')
sys.exit(1)
newest = options[-1][1]
LOG.debug('Downloading: %s', (newest['name']))
target_file = os.path.join(target, expected_file)
LOG.info('TARGET: %s', target_file)
if os.path.exists(target_file):
LOG.info('Already downloaded')
return
LOG.error('TARGET does not exists downloading...')
new_data = objectstore.get_object(connection, newest, container)
# save output to file!
with open(target_file, 'wb') as outputzip:
outputzip.write(new_data) | python | def download_database(connection, container: str, target: str=""):
"""
Download database dump
"""
meta_data = objectstore.get_full_container_list(
connection, container, prefix='database')
options = return_file_objects(connection, container)
for o_info in meta_data:
expected_file = f'database.{ENV}'
LOG.info(o_info['name'])
if o_info['name'].startswith(expected_file):
dt = dateparser.parse(o_info['last_modified'])
# now = datetime.datetime.now()
options.append((dt, o_info))
options.sort()
if not options:
LOG.error('Dumps missing? ENVIRONMENT wrong? (acceptance / production')
LOG.error('Environtment {ENV}')
sys.exit(1)
newest = options[-1][1]
LOG.debug('Downloading: %s', (newest['name']))
target_file = os.path.join(target, expected_file)
LOG.info('TARGET: %s', target_file)
if os.path.exists(target_file):
LOG.info('Already downloaded')
return
LOG.error('TARGET does not exists downloading...')
new_data = objectstore.get_object(connection, newest, container)
# save output to file!
with open(target_file, 'wb') as outputzip:
outputzip.write(new_data) | [
"def",
"download_database",
"(",
"connection",
",",
"container",
":",
"str",
",",
"target",
":",
"str",
"=",
"\"\"",
")",
":",
"meta_data",
"=",
"objectstore",
".",
"get_full_container_list",
"(",
"connection",
",",
"container",
",",
"prefix",
"=",
"'database'",
")",
"options",
"=",
"return_file_objects",
"(",
"connection",
",",
"container",
")",
"for",
"o_info",
"in",
"meta_data",
":",
"expected_file",
"=",
"f'database.{ENV}'",
"LOG",
".",
"info",
"(",
"o_info",
"[",
"'name'",
"]",
")",
"if",
"o_info",
"[",
"'name'",
"]",
".",
"startswith",
"(",
"expected_file",
")",
":",
"dt",
"=",
"dateparser",
".",
"parse",
"(",
"o_info",
"[",
"'last_modified'",
"]",
")",
"# now = datetime.datetime.now()",
"options",
".",
"append",
"(",
"(",
"dt",
",",
"o_info",
")",
")",
"options",
".",
"sort",
"(",
")",
"if",
"not",
"options",
":",
"LOG",
".",
"error",
"(",
"'Dumps missing? ENVIRONMENT wrong? (acceptance / production'",
")",
"LOG",
".",
"error",
"(",
"'Environtment {ENV}'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"newest",
"=",
"options",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"LOG",
".",
"debug",
"(",
"'Downloading: %s'",
",",
"(",
"newest",
"[",
"'name'",
"]",
")",
")",
"target_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target",
",",
"expected_file",
")",
"LOG",
".",
"info",
"(",
"'TARGET: %s'",
",",
"target_file",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target_file",
")",
":",
"LOG",
".",
"info",
"(",
"'Already downloaded'",
")",
"return",
"LOG",
".",
"error",
"(",
"'TARGET does not exists downloading...'",
")",
"new_data",
"=",
"objectstore",
".",
"get_object",
"(",
"connection",
",",
"newest",
",",
"container",
")",
"# save output to file!",
"with",
"open",
"(",
"target_file",
",",
"'wb'",
")",
"as",
"outputzip",
":",
"outputzip",
".",
"write",
"(",
"new_data",
")"
] | Download database dump | [
"Download",
"database",
"dump"
] | 15852e8a3f159e4e6eb018866df0a84feb2c7f68 | https://github.com/Amsterdam/objectstore/blob/15852e8a3f159e4e6eb018866df0a84feb2c7f68/objectstore/databasedumps.py#L115-L160 | train | 251,084 |
conwetlab/ckanext-oauth2 | ckanext/oauth2/oauth2.py | OAuth2Helper.remember | def remember(self, user_name):
'''
Remember the authenticated identity.
This method simply delegates to another IIdentifier plugin if configured.
'''
log.debug('Repoze OAuth remember')
environ = toolkit.request.environ
rememberer = self._get_rememberer(environ)
identity = {'repoze.who.userid': user_name}
headers = rememberer.remember(environ, identity)
for header, value in headers:
toolkit.response.headers.add(header, value) | python | def remember(self, user_name):
'''
Remember the authenticated identity.
This method simply delegates to another IIdentifier plugin if configured.
'''
log.debug('Repoze OAuth remember')
environ = toolkit.request.environ
rememberer = self._get_rememberer(environ)
identity = {'repoze.who.userid': user_name}
headers = rememberer.remember(environ, identity)
for header, value in headers:
toolkit.response.headers.add(header, value) | [
"def",
"remember",
"(",
"self",
",",
"user_name",
")",
":",
"log",
".",
"debug",
"(",
"'Repoze OAuth remember'",
")",
"environ",
"=",
"toolkit",
".",
"request",
".",
"environ",
"rememberer",
"=",
"self",
".",
"_get_rememberer",
"(",
"environ",
")",
"identity",
"=",
"{",
"'repoze.who.userid'",
":",
"user_name",
"}",
"headers",
"=",
"rememberer",
".",
"remember",
"(",
"environ",
",",
"identity",
")",
"for",
"header",
",",
"value",
"in",
"headers",
":",
"toolkit",
".",
"response",
".",
"headers",
".",
"add",
"(",
"header",
",",
"value",
")"
] | Remember the authenticated identity.
This method simply delegates to another IIdentifier plugin if configured. | [
"Remember",
"the",
"authenticated",
"identity",
"."
] | e68dd2664229b7563d77b2c8fc869fe57b747c88 | https://github.com/conwetlab/ckanext-oauth2/blob/e68dd2664229b7563d77b2c8fc869fe57b747c88/ckanext/oauth2/oauth2.py#L206-L218 | train | 251,085 |
conwetlab/ckanext-oauth2 | ckanext/oauth2/oauth2.py | OAuth2Helper.redirect_from_callback | def redirect_from_callback(self):
'''Redirect to the callback URL after a successful authentication.'''
state = toolkit.request.params.get('state')
came_from = get_came_from(state)
toolkit.response.status = 302
toolkit.response.location = came_from | python | def redirect_from_callback(self):
'''Redirect to the callback URL after a successful authentication.'''
state = toolkit.request.params.get('state')
came_from = get_came_from(state)
toolkit.response.status = 302
toolkit.response.location = came_from | [
"def",
"redirect_from_callback",
"(",
"self",
")",
":",
"state",
"=",
"toolkit",
".",
"request",
".",
"params",
".",
"get",
"(",
"'state'",
")",
"came_from",
"=",
"get_came_from",
"(",
"state",
")",
"toolkit",
".",
"response",
".",
"status",
"=",
"302",
"toolkit",
".",
"response",
".",
"location",
"=",
"came_from"
] | Redirect to the callback URL after a successful authentication. | [
"Redirect",
"to",
"the",
"callback",
"URL",
"after",
"a",
"successful",
"authentication",
"."
] | e68dd2664229b7563d77b2c8fc869fe57b747c88 | https://github.com/conwetlab/ckanext-oauth2/blob/e68dd2664229b7563d77b2c8fc869fe57b747c88/ckanext/oauth2/oauth2.py#L220-L225 | train | 251,086 |
pinax/pinax-documents | pinax/documents/hooks.py | DocumentsDefaultHookSet.can_share_folder | def can_share_folder(self, user, folder):
"""
Return True if `user` can share `folder`.
"""
return folder.parent_id is None and folder.author_id == user.id | python | def can_share_folder(self, user, folder):
"""
Return True if `user` can share `folder`.
"""
return folder.parent_id is None and folder.author_id == user.id | [
"def",
"can_share_folder",
"(",
"self",
",",
"user",
",",
"folder",
")",
":",
"return",
"folder",
".",
"parent_id",
"is",
"None",
"and",
"folder",
".",
"author_id",
"==",
"user",
".",
"id"
] | Return True if `user` can share `folder`. | [
"Return",
"True",
"if",
"user",
"can",
"share",
"folder",
"."
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/hooks.py#L20-L24 | train | 251,087 |
pinax/pinax-documents | pinax/documents/hooks.py | DocumentsDefaultHookSet.storage_color | def storage_color(self, user_storage):
"""
Return labels indicating amount of storage used.
"""
p = user_storage.percentage
if p >= 0 and p < 60:
return "success"
if p >= 60 and p < 90:
return "warning"
if p >= 90 and p <= 100:
return "danger"
raise ValueError("percentage out of range") | python | def storage_color(self, user_storage):
"""
Return labels indicating amount of storage used.
"""
p = user_storage.percentage
if p >= 0 and p < 60:
return "success"
if p >= 60 and p < 90:
return "warning"
if p >= 90 and p <= 100:
return "danger"
raise ValueError("percentage out of range") | [
"def",
"storage_color",
"(",
"self",
",",
"user_storage",
")",
":",
"p",
"=",
"user_storage",
".",
"percentage",
"if",
"p",
">=",
"0",
"and",
"p",
"<",
"60",
":",
"return",
"\"success\"",
"if",
"p",
">=",
"60",
"and",
"p",
"<",
"90",
":",
"return",
"\"warning\"",
"if",
"p",
">=",
"90",
"and",
"p",
"<=",
"100",
":",
"return",
"\"danger\"",
"raise",
"ValueError",
"(",
"\"percentage out of range\"",
")"
] | Return labels indicating amount of storage used. | [
"Return",
"labels",
"indicating",
"amount",
"of",
"storage",
"used",
"."
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/hooks.py#L26-L37 | train | 251,088 |
pinax/pinax-documents | pinax/documents/hooks.py | DocumentsDefaultHookSet.folder_created_message | def folder_created_message(self, request, folder):
"""
Send messages.success message after successful folder creation.
"""
messages.success(request, _("Folder {} was created".format(folder))) | python | def folder_created_message(self, request, folder):
"""
Send messages.success message after successful folder creation.
"""
messages.success(request, _("Folder {} was created".format(folder))) | [
"def",
"folder_created_message",
"(",
"self",
",",
"request",
",",
"folder",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Folder {} was created\"",
".",
"format",
"(",
"folder",
")",
")",
")"
] | Send messages.success message after successful folder creation. | [
"Send",
"messages",
".",
"success",
"message",
"after",
"successful",
"folder",
"creation",
"."
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/hooks.py#L39-L43 | train | 251,089 |
pinax/pinax-documents | pinax/documents/hooks.py | DocumentsDefaultHookSet.document_created_message | def document_created_message(self, request, document):
"""
Send messages.success message after successful document creation.
"""
messages.success(request, _("Document {} was created".format(document))) | python | def document_created_message(self, request, document):
"""
Send messages.success message after successful document creation.
"""
messages.success(request, _("Document {} was created".format(document))) | [
"def",
"document_created_message",
"(",
"self",
",",
"request",
",",
"document",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Document {} was created\"",
".",
"format",
"(",
"document",
")",
")",
")"
] | Send messages.success message after successful document creation. | [
"Send",
"messages",
".",
"success",
"message",
"after",
"successful",
"document",
"creation",
"."
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/hooks.py#L45-L49 | train | 251,090 |
pinax/pinax-documents | pinax/documents/hooks.py | DocumentsDefaultHookSet.folder_shared_message | def folder_shared_message(self, request, user, folder):
"""
Send messages.success message after successful share.
"""
messages.success(request, _("Folder {} is now shared with {}".format(folder, user))) | python | def folder_shared_message(self, request, user, folder):
"""
Send messages.success message after successful share.
"""
messages.success(request, _("Folder {} is now shared with {}".format(folder, user))) | [
"def",
"folder_shared_message",
"(",
"self",
",",
"request",
",",
"user",
",",
"folder",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Folder {} is now shared with {}\"",
".",
"format",
"(",
"folder",
",",
"user",
")",
")",
")"
] | Send messages.success message after successful share. | [
"Send",
"messages",
".",
"success",
"message",
"after",
"successful",
"share",
"."
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/hooks.py#L51-L55 | train | 251,091 |
pinax/pinax-documents | pinax/documents/hooks.py | DocumentsDefaultHookSet.folder_pre_delete | def folder_pre_delete(self, request, folder):
"""
Perform folder operations prior to deletions. For example, deleting all contents.
"""
for m in folder.members():
if m.__class__ == folder.__class__:
self.folder_pre_delete(request, m)
m.delete() | python | def folder_pre_delete(self, request, folder):
"""
Perform folder operations prior to deletions. For example, deleting all contents.
"""
for m in folder.members():
if m.__class__ == folder.__class__:
self.folder_pre_delete(request, m)
m.delete() | [
"def",
"folder_pre_delete",
"(",
"self",
",",
"request",
",",
"folder",
")",
":",
"for",
"m",
"in",
"folder",
".",
"members",
"(",
")",
":",
"if",
"m",
".",
"__class__",
"==",
"folder",
".",
"__class__",
":",
"self",
".",
"folder_pre_delete",
"(",
"request",
",",
"m",
")",
"m",
".",
"delete",
"(",
")"
] | Perform folder operations prior to deletions. For example, deleting all contents. | [
"Perform",
"folder",
"operations",
"prior",
"to",
"deletions",
".",
"For",
"example",
"deleting",
"all",
"contents",
"."
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/hooks.py#L75-L82 | train | 251,092 |
pinax/pinax-documents | pinax/documents/hooks.py | DocumentsDefaultHookSet.file_upload_to | def file_upload_to(self, instance, filename):
"""
Callable passed to the FileField's upload_to kwarg on Document.file
"""
ext = filename.split(".")[-1]
filename = "{}.{}".format(uuid.uuid4(), ext)
return os.path.join("document", filename) | python | def file_upload_to(self, instance, filename):
"""
Callable passed to the FileField's upload_to kwarg on Document.file
"""
ext = filename.split(".")[-1]
filename = "{}.{}".format(uuid.uuid4(), ext)
return os.path.join("document", filename) | [
"def",
"file_upload_to",
"(",
"self",
",",
"instance",
",",
"filename",
")",
":",
"ext",
"=",
"filename",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"filename",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"uuid",
".",
"uuid4",
"(",
")",
",",
"ext",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"\"document\"",
",",
"filename",
")"
] | Callable passed to the FileField's upload_to kwarg on Document.file | [
"Callable",
"passed",
"to",
"the",
"FileField",
"s",
"upload_to",
"kwarg",
"on",
"Document",
".",
"file"
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/hooks.py#L84-L90 | train | 251,093 |
pinax/pinax-documents | pinax/documents/managers.py | FolderQuerySet.for_user | def for_user(self, user):
"""
All folders the given user can do something with.
"""
qs = SharedMemberQuerySet(model=self.model, using=self._db, user=user)
qs = qs.filter(Q(author=user) | Q(foldershareduser__user=user))
return qs.distinct() & self.distinct() | python | def for_user(self, user):
"""
All folders the given user can do something with.
"""
qs = SharedMemberQuerySet(model=self.model, using=self._db, user=user)
qs = qs.filter(Q(author=user) | Q(foldershareduser__user=user))
return qs.distinct() & self.distinct() | [
"def",
"for_user",
"(",
"self",
",",
"user",
")",
":",
"qs",
"=",
"SharedMemberQuerySet",
"(",
"model",
"=",
"self",
".",
"model",
",",
"using",
"=",
"self",
".",
"_db",
",",
"user",
"=",
"user",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"Q",
"(",
"author",
"=",
"user",
")",
"|",
"Q",
"(",
"foldershareduser__user",
"=",
"user",
")",
")",
"return",
"qs",
".",
"distinct",
"(",
")",
"&",
"self",
".",
"distinct",
"(",
")"
] | All folders the given user can do something with. | [
"All",
"folders",
"the",
"given",
"user",
"can",
"do",
"something",
"with",
"."
] | b8c6a748976ec4b22cff9b195eb426b46c7a2a1e | https://github.com/pinax/pinax-documents/blob/b8c6a748976ec4b22cff9b195eb426b46c7a2a1e/pinax/documents/managers.py#L31-L37 | train | 251,094 |
qubole/qds-sdk-py | qds_sdk/cluster.py | Cluster._parse_list | def _parse_list(cls, args):
"""
Parse command line arguments to construct a dictionary of cluster
parameters that can be used to determine which clusters to list.
Args:
`args`: sequence of arguments
Returns:
Dictionary that can be used to determine which clusters to list
"""
argparser = ArgumentParser(prog="cluster list")
group = argparser.add_mutually_exclusive_group()
group.add_argument("--id", dest="cluster_id",
help="show cluster with this id")
group.add_argument("--label", dest="label",
help="show cluster with this label")
group.add_argument("--state", dest="state", action="store",
choices=['up', 'down', 'pending', 'terminating'],
help="list only clusters in the given state")
pagination_group = group.add_argument_group()
pagination_group.add_argument("--page", dest="page", action="store", type=int,
help="page number")
pagination_group.add_argument("--per-page", dest="per_page", action="store", type=int,
help="number of clusters to be retrieved per page")
arguments = argparser.parse_args(args)
return vars(arguments) | python | def _parse_list(cls, args):
"""
Parse command line arguments to construct a dictionary of cluster
parameters that can be used to determine which clusters to list.
Args:
`args`: sequence of arguments
Returns:
Dictionary that can be used to determine which clusters to list
"""
argparser = ArgumentParser(prog="cluster list")
group = argparser.add_mutually_exclusive_group()
group.add_argument("--id", dest="cluster_id",
help="show cluster with this id")
group.add_argument("--label", dest="label",
help="show cluster with this label")
group.add_argument("--state", dest="state", action="store",
choices=['up', 'down', 'pending', 'terminating'],
help="list only clusters in the given state")
pagination_group = group.add_argument_group()
pagination_group.add_argument("--page", dest="page", action="store", type=int,
help="page number")
pagination_group.add_argument("--per-page", dest="per_page", action="store", type=int,
help="number of clusters to be retrieved per page")
arguments = argparser.parse_args(args)
return vars(arguments) | [
"def",
"_parse_list",
"(",
"cls",
",",
"args",
")",
":",
"argparser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"\"cluster list\"",
")",
"group",
"=",
"argparser",
".",
"add_mutually_exclusive_group",
"(",
")",
"group",
".",
"add_argument",
"(",
"\"--id\"",
",",
"dest",
"=",
"\"cluster_id\"",
",",
"help",
"=",
"\"show cluster with this id\"",
")",
"group",
".",
"add_argument",
"(",
"\"--label\"",
",",
"dest",
"=",
"\"label\"",
",",
"help",
"=",
"\"show cluster with this label\"",
")",
"group",
".",
"add_argument",
"(",
"\"--state\"",
",",
"dest",
"=",
"\"state\"",
",",
"action",
"=",
"\"store\"",
",",
"choices",
"=",
"[",
"'up'",
",",
"'down'",
",",
"'pending'",
",",
"'terminating'",
"]",
",",
"help",
"=",
"\"list only clusters in the given state\"",
")",
"pagination_group",
"=",
"group",
".",
"add_argument_group",
"(",
")",
"pagination_group",
".",
"add_argument",
"(",
"\"--page\"",
",",
"dest",
"=",
"\"page\"",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"int",
",",
"help",
"=",
"\"page number\"",
")",
"pagination_group",
".",
"add_argument",
"(",
"\"--per-page\"",
",",
"dest",
"=",
"\"per_page\"",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"int",
",",
"help",
"=",
"\"number of clusters to be retrieved per page\"",
")",
"arguments",
"=",
"argparser",
".",
"parse_args",
"(",
"args",
")",
"return",
"vars",
"(",
"arguments",
")"
] | Parse command line arguments to construct a dictionary of cluster
parameters that can be used to determine which clusters to list.
Args:
`args`: sequence of arguments
Returns:
Dictionary that can be used to determine which clusters to list | [
"Parse",
"command",
"line",
"arguments",
"to",
"construct",
"a",
"dictionary",
"of",
"cluster",
"parameters",
"that",
"can",
"be",
"used",
"to",
"determine",
"which",
"clusters",
"to",
"list",
"."
] | 77210fb64e5a7d567aedeea3b742a1d872fd0e5e | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L31-L62 | train | 251,095 |
qubole/qds-sdk-py | qds_sdk/cluster.py | Cluster._parse_cluster_manage_command | def _parse_cluster_manage_command(cls, args, action):
"""
Parse command line arguments for cluster manage commands.
"""
argparser = ArgumentParser(prog="cluster_manage_command")
group = argparser.add_mutually_exclusive_group(required=True)
group.add_argument("--id", dest="cluster_id",
help="execute on cluster with this id")
group.add_argument("--label", dest="label",
help="execute on cluster with this label")
if action == "remove" or action == "update":
argparser.add_argument("--private_dns",
help="the private_dns of the machine to be updated/removed", required=True)
if action == "update":
argparser.add_argument("--command",
help="the update command to be executed", required=True, choices=["replace"])
arguments = argparser.parse_args(args)
return arguments | python | def _parse_cluster_manage_command(cls, args, action):
"""
Parse command line arguments for cluster manage commands.
"""
argparser = ArgumentParser(prog="cluster_manage_command")
group = argparser.add_mutually_exclusive_group(required=True)
group.add_argument("--id", dest="cluster_id",
help="execute on cluster with this id")
group.add_argument("--label", dest="label",
help="execute on cluster with this label")
if action == "remove" or action == "update":
argparser.add_argument("--private_dns",
help="the private_dns of the machine to be updated/removed", required=True)
if action == "update":
argparser.add_argument("--command",
help="the update command to be executed", required=True, choices=["replace"])
arguments = argparser.parse_args(args)
return arguments | [
"def",
"_parse_cluster_manage_command",
"(",
"cls",
",",
"args",
",",
"action",
")",
":",
"argparser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"\"cluster_manage_command\"",
")",
"group",
"=",
"argparser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"True",
")",
"group",
".",
"add_argument",
"(",
"\"--id\"",
",",
"dest",
"=",
"\"cluster_id\"",
",",
"help",
"=",
"\"execute on cluster with this id\"",
")",
"group",
".",
"add_argument",
"(",
"\"--label\"",
",",
"dest",
"=",
"\"label\"",
",",
"help",
"=",
"\"execute on cluster with this label\"",
")",
"if",
"action",
"==",
"\"remove\"",
"or",
"action",
"==",
"\"update\"",
":",
"argparser",
".",
"add_argument",
"(",
"\"--private_dns\"",
",",
"help",
"=",
"\"the private_dns of the machine to be updated/removed\"",
",",
"required",
"=",
"True",
")",
"if",
"action",
"==",
"\"update\"",
":",
"argparser",
".",
"add_argument",
"(",
"\"--command\"",
",",
"help",
"=",
"\"the update command to be executed\"",
",",
"required",
"=",
"True",
",",
"choices",
"=",
"[",
"\"replace\"",
"]",
")",
"arguments",
"=",
"argparser",
".",
"parse_args",
"(",
"args",
")",
"return",
"arguments"
] | Parse command line arguments for cluster manage commands. | [
"Parse",
"command",
"line",
"arguments",
"for",
"cluster",
"manage",
"commands",
"."
] | 77210fb64e5a7d567aedeea3b742a1d872fd0e5e | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L530-L553 | train | 251,096 |
qubole/qds-sdk-py | qds_sdk/cluster.py | Cluster._parse_reassign_label | def _parse_reassign_label(cls, args):
"""
Parse command line arguments for reassigning label.
"""
argparser = ArgumentParser(prog="cluster reassign_label")
argparser.add_argument("destination_cluster",
metavar="destination_cluster_id_label",
help="id/label of the cluster to move the label to")
argparser.add_argument("label",
help="label to be moved from the source cluster")
arguments = argparser.parse_args(args)
return arguments | python | def _parse_reassign_label(cls, args):
"""
Parse command line arguments for reassigning label.
"""
argparser = ArgumentParser(prog="cluster reassign_label")
argparser.add_argument("destination_cluster",
metavar="destination_cluster_id_label",
help="id/label of the cluster to move the label to")
argparser.add_argument("label",
help="label to be moved from the source cluster")
arguments = argparser.parse_args(args)
return arguments | [
"def",
"_parse_reassign_label",
"(",
"cls",
",",
"args",
")",
":",
"argparser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"\"cluster reassign_label\"",
")",
"argparser",
".",
"add_argument",
"(",
"\"destination_cluster\"",
",",
"metavar",
"=",
"\"destination_cluster_id_label\"",
",",
"help",
"=",
"\"id/label of the cluster to move the label to\"",
")",
"argparser",
".",
"add_argument",
"(",
"\"label\"",
",",
"help",
"=",
"\"label to be moved from the source cluster\"",
")",
"arguments",
"=",
"argparser",
".",
"parse_args",
"(",
"args",
")",
"return",
"arguments"
] | Parse command line arguments for reassigning label. | [
"Parse",
"command",
"line",
"arguments",
"for",
"reassigning",
"label",
"."
] | 77210fb64e5a7d567aedeea3b742a1d872fd0e5e | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L556-L570 | train | 251,097 |
qubole/qds-sdk-py | qds_sdk/cluster.py | Cluster.reassign_label | def reassign_label(cls, destination_cluster, label):
"""
Reassign a label from one cluster to another.
Args:
`destination_cluster`: id/label of the cluster to move the label to
`label`: label to be moved from the source cluster
"""
conn = Qubole.agent(version=Cluster.api_version)
data = {
"destination_cluster": destination_cluster,
"label": label
}
return conn.put(cls.rest_entity_path + "/reassign-label", data) | python | def reassign_label(cls, destination_cluster, label):
"""
Reassign a label from one cluster to another.
Args:
`destination_cluster`: id/label of the cluster to move the label to
`label`: label to be moved from the source cluster
"""
conn = Qubole.agent(version=Cluster.api_version)
data = {
"destination_cluster": destination_cluster,
"label": label
}
return conn.put(cls.rest_entity_path + "/reassign-label", data) | [
"def",
"reassign_label",
"(",
"cls",
",",
"destination_cluster",
",",
"label",
")",
":",
"conn",
"=",
"Qubole",
".",
"agent",
"(",
"version",
"=",
"Cluster",
".",
"api_version",
")",
"data",
"=",
"{",
"\"destination_cluster\"",
":",
"destination_cluster",
",",
"\"label\"",
":",
"label",
"}",
"return",
"conn",
".",
"put",
"(",
"cls",
".",
"rest_entity_path",
"+",
"\"/reassign-label\"",
",",
"data",
")"
] | Reassign a label from one cluster to another.
Args:
`destination_cluster`: id/label of the cluster to move the label to
`label`: label to be moved from the source cluster | [
"Reassign",
"a",
"label",
"from",
"one",
"cluster",
"to",
"another",
"."
] | 77210fb64e5a7d567aedeea3b742a1d872fd0e5e | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L573-L587 | train | 251,098 |
qubole/qds-sdk-py | qds_sdk/cluster.py | Cluster._parse_snapshot_restore_command | def _parse_snapshot_restore_command(cls, args, action):
"""
Parse command line arguments for snapshot command.
"""
argparser = ArgumentParser(prog="cluster %s" % action)
group = argparser.add_mutually_exclusive_group(required=True)
group.add_argument("--id", dest="cluster_id",
help="execute on cluster with this id")
group.add_argument("--label", dest="label",
help="execute on cluster with this label")
argparser.add_argument("--s3_location",
help="s3_location where backup is stored", required=True)
if action == "snapshot":
argparser.add_argument("--backup_type",
help="backup_type: full/incremental, default is full")
elif action == "restore_point":
argparser.add_argument("--backup_id",
help="back_id from which restoration will be done", required=True)
argparser.add_argument("--table_names",
help="table(s) which are to be restored", required=True)
argparser.add_argument("--no-overwrite", action="store_false",
help="With this option, restore overwrites to the existing table if theres any in restore target")
argparser.add_argument("--no-automatic", action="store_false",
help="With this option, all the dependencies are automatically restored together with this backup image following the correct order")
arguments = argparser.parse_args(args)
return arguments | python | def _parse_snapshot_restore_command(cls, args, action):
"""
Parse command line arguments for snapshot command.
"""
argparser = ArgumentParser(prog="cluster %s" % action)
group = argparser.add_mutually_exclusive_group(required=True)
group.add_argument("--id", dest="cluster_id",
help="execute on cluster with this id")
group.add_argument("--label", dest="label",
help="execute on cluster with this label")
argparser.add_argument("--s3_location",
help="s3_location where backup is stored", required=True)
if action == "snapshot":
argparser.add_argument("--backup_type",
help="backup_type: full/incremental, default is full")
elif action == "restore_point":
argparser.add_argument("--backup_id",
help="back_id from which restoration will be done", required=True)
argparser.add_argument("--table_names",
help="table(s) which are to be restored", required=True)
argparser.add_argument("--no-overwrite", action="store_false",
help="With this option, restore overwrites to the existing table if theres any in restore target")
argparser.add_argument("--no-automatic", action="store_false",
help="With this option, all the dependencies are automatically restored together with this backup image following the correct order")
arguments = argparser.parse_args(args)
return arguments | [
"def",
"_parse_snapshot_restore_command",
"(",
"cls",
",",
"args",
",",
"action",
")",
":",
"argparser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"\"cluster %s\"",
"%",
"action",
")",
"group",
"=",
"argparser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"True",
")",
"group",
".",
"add_argument",
"(",
"\"--id\"",
",",
"dest",
"=",
"\"cluster_id\"",
",",
"help",
"=",
"\"execute on cluster with this id\"",
")",
"group",
".",
"add_argument",
"(",
"\"--label\"",
",",
"dest",
"=",
"\"label\"",
",",
"help",
"=",
"\"execute on cluster with this label\"",
")",
"argparser",
".",
"add_argument",
"(",
"\"--s3_location\"",
",",
"help",
"=",
"\"s3_location where backup is stored\"",
",",
"required",
"=",
"True",
")",
"if",
"action",
"==",
"\"snapshot\"",
":",
"argparser",
".",
"add_argument",
"(",
"\"--backup_type\"",
",",
"help",
"=",
"\"backup_type: full/incremental, default is full\"",
")",
"elif",
"action",
"==",
"\"restore_point\"",
":",
"argparser",
".",
"add_argument",
"(",
"\"--backup_id\"",
",",
"help",
"=",
"\"back_id from which restoration will be done\"",
",",
"required",
"=",
"True",
")",
"argparser",
".",
"add_argument",
"(",
"\"--table_names\"",
",",
"help",
"=",
"\"table(s) which are to be restored\"",
",",
"required",
"=",
"True",
")",
"argparser",
".",
"add_argument",
"(",
"\"--no-overwrite\"",
",",
"action",
"=",
"\"store_false\"",
",",
"help",
"=",
"\"With this option, restore overwrites to the existing table if theres any in restore target\"",
")",
"argparser",
".",
"add_argument",
"(",
"\"--no-automatic\"",
",",
"action",
"=",
"\"store_false\"",
",",
"help",
"=",
"\"With this option, all the dependencies are automatically restored together with this backup image following the correct order\"",
")",
"arguments",
"=",
"argparser",
".",
"parse_args",
"(",
"args",
")",
"return",
"arguments"
] | Parse command line arguments for snapshot command. | [
"Parse",
"command",
"line",
"arguments",
"for",
"snapshot",
"command",
"."
] | 77210fb64e5a7d567aedeea3b742a1d872fd0e5e | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L598-L625 | train | 251,099 |