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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
alertot/detectem | detectem/utils.py | get_most_complete_pm | def get_most_complete_pm(pms):
""" Return plugin match with longer version, if not available
will return plugin match with ``presence=True``
"""
if not pms:
return None
selected_version = None
selected_presence = None
for pm in pms:
if pm.version:
if not selected_version:
selected_version = pm
else:
if len(pm.version) > len(selected_version.version):
selected_version = pm
elif pm.presence:
selected_presence = pm
return selected_version or selected_presence | python | def get_most_complete_pm(pms):
""" Return plugin match with longer version, if not available
will return plugin match with ``presence=True``
"""
if not pms:
return None
selected_version = None
selected_presence = None
for pm in pms:
if pm.version:
if not selected_version:
selected_version = pm
else:
if len(pm.version) > len(selected_version.version):
selected_version = pm
elif pm.presence:
selected_presence = pm
return selected_version or selected_presence | [
"def",
"get_most_complete_pm",
"(",
"pms",
")",
":",
"if",
"not",
"pms",
":",
"return",
"None",
"selected_version",
"=",
"None",
"selected_presence",
"=",
"None",
"for",
"pm",
"in",
"pms",
":",
"if",
"pm",
".",
"version",
":",
"if",
"not",
"selected_version",
":",
"selected_version",
"=",
"pm",
"else",
":",
"if",
"len",
"(",
"pm",
".",
"version",
")",
">",
"len",
"(",
"selected_version",
".",
"version",
")",
":",
"selected_version",
"=",
"pm",
"elif",
"pm",
".",
"presence",
":",
"selected_presence",
"=",
"pm",
"return",
"selected_version",
"or",
"selected_presence"
] | Return plugin match with longer version, if not available
will return plugin match with ``presence=True`` | [
"Return",
"plugin",
"match",
"with",
"longer",
"version",
"if",
"not",
"available",
"will",
"return",
"plugin",
"match",
"with",
"presence",
"=",
"True"
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/utils.py#L25-L45 | train | 236,700 |
alertot/detectem | detectem/utils.py | docker_container | def docker_container():
""" Start the Splash server on a Docker container.
If the container doesn't exist, it is created and named 'splash-detectem'.
"""
if SETUP_SPLASH:
dm = DockerManager()
dm.start_container()
try:
requests.post(f'{SPLASH_URL}/_gc')
except requests.exceptions.RequestException:
pass
yield | python | def docker_container():
""" Start the Splash server on a Docker container.
If the container doesn't exist, it is created and named 'splash-detectem'.
"""
if SETUP_SPLASH:
dm = DockerManager()
dm.start_container()
try:
requests.post(f'{SPLASH_URL}/_gc')
except requests.exceptions.RequestException:
pass
yield | [
"def",
"docker_container",
"(",
")",
":",
"if",
"SETUP_SPLASH",
":",
"dm",
"=",
"DockerManager",
"(",
")",
"dm",
".",
"start_container",
"(",
")",
"try",
":",
"requests",
".",
"post",
"(",
"f'{SPLASH_URL}/_gc'",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
":",
"pass",
"yield"
] | Start the Splash server on a Docker container.
If the container doesn't exist, it is created and named 'splash-detectem'. | [
"Start",
"the",
"Splash",
"server",
"on",
"a",
"Docker",
"container",
".",
"If",
"the",
"container",
"doesn",
"t",
"exist",
"it",
"is",
"created",
"and",
"named",
"splash",
"-",
"detectem",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/utils.py#L126-L140 | train | 236,701 |
alertot/detectem | detectem/response.py | is_url_allowed | def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True | python | def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True | [
"def",
"is_url_allowed",
"(",
"url",
")",
":",
"blacklist",
"=",
"[",
"r'\\.ttf'",
",",
"r'\\.woff'",
",",
"r'fonts\\.googleapis\\.com'",
",",
"r'\\.png'",
",",
"r'\\.jpe?g'",
",",
"r'\\.gif'",
",",
"r'\\.svg'",
"]",
"for",
"ft",
"in",
"blacklist",
":",
"if",
"re",
".",
"search",
"(",
"ft",
",",
"url",
")",
":",
"return",
"False",
"return",
"True"
] | Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool | [
"Return",
"True",
"if",
"url",
"is",
"not",
"in",
"blacklist",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L21-L36 | train | 236,702 |
alertot/detectem | detectem/response.py | is_valid_mimetype | def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True | python | def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True | [
"def",
"is_valid_mimetype",
"(",
"response",
")",
":",
"blacklist",
"=",
"[",
"'image/'",
",",
"]",
"mimetype",
"=",
"response",
".",
"get",
"(",
"'mimeType'",
")",
"if",
"not",
"mimetype",
":",
"return",
"True",
"for",
"bw",
"in",
"blacklist",
":",
"if",
"bw",
"in",
"mimetype",
":",
"return",
"False",
"return",
"True"
] | Return ``True`` if the mimetype is not blacklisted.
:rtype: bool | [
"Return",
"True",
"if",
"the",
"mimetype",
"is",
"not",
"blacklisted",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L39-L57 | train | 236,703 |
alertot/detectem | detectem/response.py | get_charset | def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset | python | def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset | [
"def",
"get_charset",
"(",
"response",
")",
":",
"# Set default charset",
"charset",
"=",
"DEFAULT_CHARSET",
"m",
"=",
"re",
".",
"findall",
"(",
"r';charset=(.*)'",
",",
"response",
".",
"get",
"(",
"'mimeType'",
",",
"''",
")",
")",
"if",
"m",
":",
"charset",
"=",
"m",
"[",
"0",
"]",
"return",
"charset"
] | Return charset from ``response`` or default charset.
:rtype: str | [
"Return",
"charset",
"from",
"response",
"or",
"default",
"charset",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L60-L73 | train | 236,704 |
alertot/detectem | detectem/response.py | create_lua_script | def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data)) | python | def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data)) | [
"def",
"create_lua_script",
"(",
"plugins",
")",
":",
"lua_template",
"=",
"pkg_resources",
".",
"resource_string",
"(",
"'detectem'",
",",
"'script.lua'",
")",
"template",
"=",
"Template",
"(",
"lua_template",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"javascript_data",
"=",
"to_javascript_data",
"(",
"plugins",
")",
"return",
"template",
".",
"substitute",
"(",
"js_data",
"=",
"json",
".",
"dumps",
"(",
"javascript_data",
")",
")"
] | Return script template filled up with plugin javascript data.
:rtype: str | [
"Return",
"script",
"template",
"filled",
"up",
"with",
"plugin",
"javascript",
"data",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L76-L87 | train | 236,705 |
alertot/detectem | detectem/response.py | to_javascript_data | def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()] | python | def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()] | [
"def",
"to_javascript_data",
"(",
"plugins",
")",
":",
"def",
"escape",
"(",
"v",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\"'",
",",
"r'\\\\\"'",
",",
"v",
")",
"def",
"dom_matchers",
"(",
"p",
")",
":",
"dom_matchers",
"=",
"p",
".",
"get_matchers",
"(",
"'dom'",
")",
"escaped_dom_matchers",
"=",
"[",
"]",
"for",
"dm",
"in",
"dom_matchers",
":",
"check_statement",
",",
"version_statement",
"=",
"dm",
"escaped_dom_matchers",
".",
"append",
"(",
"{",
"'check_statement'",
":",
"escape",
"(",
"check_statement",
")",
",",
"# Escape '' and not None",
"'version_statement'",
":",
"escape",
"(",
"version_statement",
"or",
"''",
")",
",",
"}",
")",
"return",
"escaped_dom_matchers",
"return",
"[",
"{",
"'name'",
":",
"p",
".",
"name",
",",
"'matchers'",
":",
"dom_matchers",
"(",
"p",
")",
"}",
"for",
"p",
"in",
"plugins",
".",
"with_dom_matchers",
"(",
")",
"]"
] | Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict | [
"Return",
"a",
"dictionary",
"with",
"all",
"JavaScript",
"matchers",
".",
"Quotes",
"are",
"escaped",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L90-L117 | train | 236,706 |
alertot/detectem | detectem/response.py | get_response | def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares} | python | def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares} | [
"def",
"get_response",
"(",
"url",
",",
"plugins",
",",
"timeout",
"=",
"SPLASH_TIMEOUT",
")",
":",
"lua_script",
"=",
"create_lua_script",
"(",
"plugins",
")",
"lua",
"=",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"lua_script",
")",
"page_url",
"=",
"f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'",
"try",
":",
"with",
"docker_container",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"'[+] Sending request to Splash instance'",
")",
"res",
"=",
"requests",
".",
"get",
"(",
"page_url",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"raise",
"SplashError",
"(",
"\"Could not connect to Splash server {}\"",
".",
"format",
"(",
"SPLASH_URL",
")",
")",
"logger",
".",
"debug",
"(",
"'[+] Response received'",
")",
"json_data",
"=",
"res",
".",
"json",
"(",
")",
"if",
"res",
".",
"status_code",
"in",
"ERROR_STATUS_CODES",
":",
"raise",
"SplashError",
"(",
"get_splash_error",
"(",
"json_data",
")",
")",
"softwares",
"=",
"json_data",
"[",
"'softwares'",
"]",
"scripts",
"=",
"json_data",
"[",
"'scripts'",
"]",
".",
"values",
"(",
")",
"har",
"=",
"get_valid_har",
"(",
"json_data",
"[",
"'har'",
"]",
")",
"js_error",
"=",
"get_evaljs_error",
"(",
"json_data",
")",
"if",
"js_error",
":",
"logger",
".",
"debug",
"(",
"'[+] WARNING: failed to eval JS matchers: %(n)s'",
",",
"{",
"'n'",
":",
"js_error",
"}",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'[+] Detected %(n)d softwares from the DOM'",
",",
"{",
"'n'",
":",
"len",
"(",
"softwares",
")",
"}",
")",
"logger",
".",
"debug",
"(",
"'[+] Detected %(n)d scripts from the DOM'",
",",
"{",
"'n'",
":",
"len",
"(",
"scripts",
")",
"}",
")",
"logger",
".",
"debug",
"(",
"'[+] Final HAR has %(n)d valid entries'",
",",
"{",
"'n'",
":",
"len",
"(",
"har",
")",
"}",
")",
"return",
"{",
"'har'",
":",
"har",
",",
"'scripts'",
":",
"scripts",
",",
"'softwares'",
":",
"softwares",
"}"
] | Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict | [
"Return",
"response",
"with",
"HAR",
"inline",
"scritps",
"and",
"software",
"detected",
"by",
"JS",
"matchers",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L120-L157 | train | 236,707 |
alertot/detectem | detectem/response.py | get_valid_har | def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries | python | def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries | [
"def",
"get_valid_har",
"(",
"har_data",
")",
":",
"new_entries",
"=",
"[",
"]",
"entries",
"=",
"har_data",
".",
"get",
"(",
"'log'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'entries'",
",",
"[",
"]",
")",
"logger",
".",
"debug",
"(",
"'[+] Detected %(n)d entries in HAR'",
",",
"{",
"'n'",
":",
"len",
"(",
"entries",
")",
"}",
")",
"for",
"entry",
"in",
"entries",
":",
"url",
"=",
"entry",
"[",
"'request'",
"]",
"[",
"'url'",
"]",
"if",
"not",
"is_url_allowed",
"(",
"url",
")",
":",
"continue",
"response",
"=",
"entry",
"[",
"'response'",
"]",
"[",
"'content'",
"]",
"if",
"not",
"is_valid_mimetype",
"(",
"response",
")",
":",
"continue",
"if",
"response",
".",
"get",
"(",
"'text'",
")",
":",
"charset",
"=",
"get_charset",
"(",
"response",
")",
"response",
"[",
"'text'",
"]",
"=",
"base64",
".",
"b64decode",
"(",
"response",
"[",
"'text'",
"]",
")",
".",
"decode",
"(",
"charset",
")",
"else",
":",
"response",
"[",
"'text'",
"]",
"=",
"''",
"new_entries",
".",
"append",
"(",
"entry",
")",
"logger",
".",
"debug",
"(",
"'[+] Added URL: %(url)s ...'",
",",
"{",
"'url'",
":",
"url",
"[",
":",
"100",
"]",
"}",
")",
"return",
"new_entries"
] | Return list of valid HAR entries.
:rtype: list | [
"Return",
"list",
"of",
"valid",
"HAR",
"entries",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L194-L223 | train | 236,708 |
alertot/detectem | detectem/core.py | HarProcessor._script_to_har_entry | def _script_to_har_entry(cls, script, url):
''' Return entry for embed script '''
entry = {
'request': {'url': url},
'response': {'url': url, 'content': {'text': script}}
}
cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY)
return entry | python | def _script_to_har_entry(cls, script, url):
''' Return entry for embed script '''
entry = {
'request': {'url': url},
'response': {'url': url, 'content': {'text': script}}
}
cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY)
return entry | [
"def",
"_script_to_har_entry",
"(",
"cls",
",",
"script",
",",
"url",
")",
":",
"entry",
"=",
"{",
"'request'",
":",
"{",
"'url'",
":",
"url",
"}",
",",
"'response'",
":",
"{",
"'url'",
":",
"url",
",",
"'content'",
":",
"{",
"'text'",
":",
"script",
"}",
"}",
"}",
"cls",
".",
"_set_entry_type",
"(",
"entry",
",",
"INLINE_SCRIPT_ENTRY",
")",
"return",
"entry"
] | Return entry for embed script | [
"Return",
"entry",
"for",
"embed",
"script"
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L56-L65 | train | 236,709 |
alertot/detectem | detectem/core.py | HarProcessor.mark_entries | def mark_entries(self, entries):
''' Mark one entry as main entry and the rest as resource entry.
Main entry is the entry that contain response's body
of the requested URL.
'''
for entry in entries:
self._set_entry_type(entry, RESOURCE_ENTRY)
# If first entry doesn't have a redirect, set is as main entry
main_entry = entries[0]
main_location = self._get_location(main_entry)
if not main_location:
self._set_entry_type(main_entry, MAIN_ENTRY)
return
# Resolve redirected URL and see if it's in the rest of entries
main_url = urllib.parse.urljoin(get_url(main_entry), main_location)
for entry in entries[1:]:
url = get_url(entry)
if url == main_url:
self._set_entry_type(entry, MAIN_ENTRY)
break
else:
# In fail case, set the first entry
self._set_entry_type(main_entry, MAIN_ENTRY) | python | def mark_entries(self, entries):
''' Mark one entry as main entry and the rest as resource entry.
Main entry is the entry that contain response's body
of the requested URL.
'''
for entry in entries:
self._set_entry_type(entry, RESOURCE_ENTRY)
# If first entry doesn't have a redirect, set is as main entry
main_entry = entries[0]
main_location = self._get_location(main_entry)
if not main_location:
self._set_entry_type(main_entry, MAIN_ENTRY)
return
# Resolve redirected URL and see if it's in the rest of entries
main_url = urllib.parse.urljoin(get_url(main_entry), main_location)
for entry in entries[1:]:
url = get_url(entry)
if url == main_url:
self._set_entry_type(entry, MAIN_ENTRY)
break
else:
# In fail case, set the first entry
self._set_entry_type(main_entry, MAIN_ENTRY) | [
"def",
"mark_entries",
"(",
"self",
",",
"entries",
")",
":",
"for",
"entry",
"in",
"entries",
":",
"self",
".",
"_set_entry_type",
"(",
"entry",
",",
"RESOURCE_ENTRY",
")",
"# If first entry doesn't have a redirect, set is as main entry",
"main_entry",
"=",
"entries",
"[",
"0",
"]",
"main_location",
"=",
"self",
".",
"_get_location",
"(",
"main_entry",
")",
"if",
"not",
"main_location",
":",
"self",
".",
"_set_entry_type",
"(",
"main_entry",
",",
"MAIN_ENTRY",
")",
"return",
"# Resolve redirected URL and see if it's in the rest of entries",
"main_url",
"=",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"get_url",
"(",
"main_entry",
")",
",",
"main_location",
")",
"for",
"entry",
"in",
"entries",
"[",
"1",
":",
"]",
":",
"url",
"=",
"get_url",
"(",
"entry",
")",
"if",
"url",
"==",
"main_url",
":",
"self",
".",
"_set_entry_type",
"(",
"entry",
",",
"MAIN_ENTRY",
")",
"break",
"else",
":",
"# In fail case, set the first entry",
"self",
".",
"_set_entry_type",
"(",
"main_entry",
",",
"MAIN_ENTRY",
")"
] | Mark one entry as main entry and the rest as resource entry.
Main entry is the entry that contain response's body
of the requested URL. | [
"Mark",
"one",
"entry",
"as",
"main",
"entry",
"and",
"the",
"rest",
"as",
"resource",
"entry",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L67-L93 | train | 236,710 |
alertot/detectem | detectem/core.py | Detector.get_hints | def get_hints(self, plugin):
''' Return plugin hints from ``plugin``. '''
hints = []
for hint_name in getattr(plugin, 'hints', []):
hint_plugin = self._plugins.get(hint_name)
if hint_plugin:
hint_result = Result(
name=hint_plugin.name,
homepage=hint_plugin.homepage,
from_url=self.requested_url,
type=HINT_TYPE,
plugin=plugin.name,
)
hints.append(hint_result)
logger.debug(f'{plugin.name} & hint {hint_result.name} detected')
else:
logger.error(f'{plugin.name} hints an invalid plugin: {hint_name}')
return hints | python | def get_hints(self, plugin):
''' Return plugin hints from ``plugin``. '''
hints = []
for hint_name in getattr(plugin, 'hints', []):
hint_plugin = self._plugins.get(hint_name)
if hint_plugin:
hint_result = Result(
name=hint_plugin.name,
homepage=hint_plugin.homepage,
from_url=self.requested_url,
type=HINT_TYPE,
plugin=plugin.name,
)
hints.append(hint_result)
logger.debug(f'{plugin.name} & hint {hint_result.name} detected')
else:
logger.error(f'{plugin.name} hints an invalid plugin: {hint_name}')
return hints | [
"def",
"get_hints",
"(",
"self",
",",
"plugin",
")",
":",
"hints",
"=",
"[",
"]",
"for",
"hint_name",
"in",
"getattr",
"(",
"plugin",
",",
"'hints'",
",",
"[",
"]",
")",
":",
"hint_plugin",
"=",
"self",
".",
"_plugins",
".",
"get",
"(",
"hint_name",
")",
"if",
"hint_plugin",
":",
"hint_result",
"=",
"Result",
"(",
"name",
"=",
"hint_plugin",
".",
"name",
",",
"homepage",
"=",
"hint_plugin",
".",
"homepage",
",",
"from_url",
"=",
"self",
".",
"requested_url",
",",
"type",
"=",
"HINT_TYPE",
",",
"plugin",
"=",
"plugin",
".",
"name",
",",
")",
"hints",
".",
"append",
"(",
"hint_result",
")",
"logger",
".",
"debug",
"(",
"f'{plugin.name} & hint {hint_result.name} detected'",
")",
"else",
":",
"logger",
".",
"error",
"(",
"f'{plugin.name} hints an invalid plugin: {hint_name}'",
")",
"return",
"hints"
] | Return plugin hints from ``plugin``. | [
"Return",
"plugin",
"hints",
"from",
"plugin",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L121-L141 | train | 236,711 |
alertot/detectem | detectem/core.py | Detector.process_from_splash | def process_from_splash(self):
''' Add softwares found in the DOM '''
for software in self._softwares_from_splash:
plugin = self._plugins.get(software['name'])
# Determine if it's a version or presence result
try:
additional_data = {'version': software['version']}
except KeyError:
additional_data = {'type': INDICATOR_TYPE}
self._results.add_result(
Result(
name=plugin.name,
homepage=plugin.homepage,
from_url=self.requested_url,
plugin=plugin.name,
**additional_data,
)
)
for hint in self.get_hints(plugin):
self._results.add_result(hint) | python | def process_from_splash(self):
''' Add softwares found in the DOM '''
for software in self._softwares_from_splash:
plugin = self._plugins.get(software['name'])
# Determine if it's a version or presence result
try:
additional_data = {'version': software['version']}
except KeyError:
additional_data = {'type': INDICATOR_TYPE}
self._results.add_result(
Result(
name=plugin.name,
homepage=plugin.homepage,
from_url=self.requested_url,
plugin=plugin.name,
**additional_data,
)
)
for hint in self.get_hints(plugin):
self._results.add_result(hint) | [
"def",
"process_from_splash",
"(",
"self",
")",
":",
"for",
"software",
"in",
"self",
".",
"_softwares_from_splash",
":",
"plugin",
"=",
"self",
".",
"_plugins",
".",
"get",
"(",
"software",
"[",
"'name'",
"]",
")",
"# Determine if it's a version or presence result",
"try",
":",
"additional_data",
"=",
"{",
"'version'",
":",
"software",
"[",
"'version'",
"]",
"}",
"except",
"KeyError",
":",
"additional_data",
"=",
"{",
"'type'",
":",
"INDICATOR_TYPE",
"}",
"self",
".",
"_results",
".",
"add_result",
"(",
"Result",
"(",
"name",
"=",
"plugin",
".",
"name",
",",
"homepage",
"=",
"plugin",
".",
"homepage",
",",
"from_url",
"=",
"self",
".",
"requested_url",
",",
"plugin",
"=",
"plugin",
".",
"name",
",",
"*",
"*",
"additional_data",
",",
")",
")",
"for",
"hint",
"in",
"self",
".",
"get_hints",
"(",
"plugin",
")",
":",
"self",
".",
"_results",
".",
"add_result",
"(",
"hint",
")"
] | Add softwares found in the DOM | [
"Add",
"softwares",
"found",
"in",
"the",
"DOM"
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L143-L165 | train | 236,712 |
alertot/detectem | detectem/core.py | Detector.process_har | def process_har(self):
""" Detect plugins present in the page. """
hints = []
version_plugins = self._plugins.with_version_matchers()
generic_plugins = self._plugins.with_generic_matchers()
for entry in self.har:
for plugin in version_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
# Set name if matchers could detect modular name
if pm.name:
name = '{}-{}'.format(plugin.name, pm.name)
else:
name = plugin.name
if pm.version:
self._results.add_result(
Result(
name=name,
version=pm.version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
elif pm.presence:
# Try to get version through file hashes
version = get_version_via_file_hashes(plugin, entry)
if version:
self._results.add_result(
Result(
name=name,
version=version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
else:
self._results.add_result(
Result(
name=name,
homepage=plugin.homepage,
from_url=get_url(entry),
type=INDICATOR_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for plugin in generic_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
plugin_data = plugin.get_information(entry)
# Only add to results if it's a valid result
if 'name' in plugin_data:
self._results.add_result(
Result(
name=plugin_data['name'],
homepage=plugin_data['homepage'],
from_url=get_url(entry),
type=GENERIC_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for hint in hints:
self._results.add_result(hint) | python | def process_har(self):
""" Detect plugins present in the page. """
hints = []
version_plugins = self._plugins.with_version_matchers()
generic_plugins = self._plugins.with_generic_matchers()
for entry in self.har:
for plugin in version_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
# Set name if matchers could detect modular name
if pm.name:
name = '{}-{}'.format(plugin.name, pm.name)
else:
name = plugin.name
if pm.version:
self._results.add_result(
Result(
name=name,
version=pm.version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
elif pm.presence:
# Try to get version through file hashes
version = get_version_via_file_hashes(plugin, entry)
if version:
self._results.add_result(
Result(
name=name,
version=version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
else:
self._results.add_result(
Result(
name=name,
homepage=plugin.homepage,
from_url=get_url(entry),
type=INDICATOR_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for plugin in generic_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
plugin_data = plugin.get_information(entry)
# Only add to results if it's a valid result
if 'name' in plugin_data:
self._results.add_result(
Result(
name=plugin_data['name'],
homepage=plugin_data['homepage'],
from_url=get_url(entry),
type=GENERIC_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for hint in hints:
self._results.add_result(hint) | [
"def",
"process_har",
"(",
"self",
")",
":",
"hints",
"=",
"[",
"]",
"version_plugins",
"=",
"self",
".",
"_plugins",
".",
"with_version_matchers",
"(",
")",
"generic_plugins",
"=",
"self",
".",
"_plugins",
".",
"with_generic_matchers",
"(",
")",
"for",
"entry",
"in",
"self",
".",
"har",
":",
"for",
"plugin",
"in",
"version_plugins",
":",
"pm",
"=",
"self",
".",
"apply_plugin_matchers",
"(",
"plugin",
",",
"entry",
")",
"if",
"not",
"pm",
":",
"continue",
"# Set name if matchers could detect modular name",
"if",
"pm",
".",
"name",
":",
"name",
"=",
"'{}-{}'",
".",
"format",
"(",
"plugin",
".",
"name",
",",
"pm",
".",
"name",
")",
"else",
":",
"name",
"=",
"plugin",
".",
"name",
"if",
"pm",
".",
"version",
":",
"self",
".",
"_results",
".",
"add_result",
"(",
"Result",
"(",
"name",
"=",
"name",
",",
"version",
"=",
"pm",
".",
"version",
",",
"homepage",
"=",
"plugin",
".",
"homepage",
",",
"from_url",
"=",
"get_url",
"(",
"entry",
")",
",",
"plugin",
"=",
"plugin",
".",
"name",
",",
")",
")",
"elif",
"pm",
".",
"presence",
":",
"# Try to get version through file hashes",
"version",
"=",
"get_version_via_file_hashes",
"(",
"plugin",
",",
"entry",
")",
"if",
"version",
":",
"self",
".",
"_results",
".",
"add_result",
"(",
"Result",
"(",
"name",
"=",
"name",
",",
"version",
"=",
"version",
",",
"homepage",
"=",
"plugin",
".",
"homepage",
",",
"from_url",
"=",
"get_url",
"(",
"entry",
")",
",",
"plugin",
"=",
"plugin",
".",
"name",
",",
")",
")",
"else",
":",
"self",
".",
"_results",
".",
"add_result",
"(",
"Result",
"(",
"name",
"=",
"name",
",",
"homepage",
"=",
"plugin",
".",
"homepage",
",",
"from_url",
"=",
"get_url",
"(",
"entry",
")",
",",
"type",
"=",
"INDICATOR_TYPE",
",",
"plugin",
"=",
"plugin",
".",
"name",
",",
")",
")",
"hints",
"+=",
"self",
".",
"get_hints",
"(",
"plugin",
")",
"for",
"plugin",
"in",
"generic_plugins",
":",
"pm",
"=",
"self",
".",
"apply_plugin_matchers",
"(",
"plugin",
",",
"entry",
")",
"if",
"not",
"pm",
":",
"continue",
"plugin_data",
"=",
"plugin",
".",
"get_information",
"(",
"entry",
")",
"# Only add to results if it's a valid result",
"if",
"'name'",
"in",
"plugin_data",
":",
"self",
".",
"_results",
".",
"add_result",
"(",
"Result",
"(",
"name",
"=",
"plugin_data",
"[",
"'name'",
"]",
",",
"homepage",
"=",
"plugin_data",
"[",
"'homepage'",
"]",
",",
"from_url",
"=",
"get_url",
"(",
"entry",
")",
",",
"type",
"=",
"GENERIC_TYPE",
",",
"plugin",
"=",
"plugin",
".",
"name",
",",
")",
")",
"hints",
"+=",
"self",
".",
"get_hints",
"(",
"plugin",
")",
"for",
"hint",
"in",
"hints",
":",
"self",
".",
"_results",
".",
"add_result",
"(",
"hint",
")"
] | Detect plugins present in the page. | [
"Detect",
"plugins",
"present",
"in",
"the",
"page",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L197-L273 | train | 236,713 |
alertot/detectem | detectem/core.py | Detector.get_results | def get_results(self, metadata=False):
""" Return results of the analysis. """
results_data = []
self.process_har()
self.process_from_splash()
for rt in sorted(self._results.get_results()):
rdict = {'name': rt.name}
if rt.version:
rdict['version'] = rt.version
if metadata:
rdict['homepage'] = rt.homepage
rdict['type'] = rt.type
rdict['from_url'] = rt.from_url
rdict['plugin'] = rt.plugin
results_data.append(rdict)
return results_data | python | def get_results(self, metadata=False):
""" Return results of the analysis. """
results_data = []
self.process_har()
self.process_from_splash()
for rt in sorted(self._results.get_results()):
rdict = {'name': rt.name}
if rt.version:
rdict['version'] = rt.version
if metadata:
rdict['homepage'] = rt.homepage
rdict['type'] = rt.type
rdict['from_url'] = rt.from_url
rdict['plugin'] = rt.plugin
results_data.append(rdict)
return results_data | [
"def",
"get_results",
"(",
"self",
",",
"metadata",
"=",
"False",
")",
":",
"results_data",
"=",
"[",
"]",
"self",
".",
"process_har",
"(",
")",
"self",
".",
"process_from_splash",
"(",
")",
"for",
"rt",
"in",
"sorted",
"(",
"self",
".",
"_results",
".",
"get_results",
"(",
")",
")",
":",
"rdict",
"=",
"{",
"'name'",
":",
"rt",
".",
"name",
"}",
"if",
"rt",
".",
"version",
":",
"rdict",
"[",
"'version'",
"]",
"=",
"rt",
".",
"version",
"if",
"metadata",
":",
"rdict",
"[",
"'homepage'",
"]",
"=",
"rt",
".",
"homepage",
"rdict",
"[",
"'type'",
"]",
"=",
"rt",
".",
"type",
"rdict",
"[",
"'from_url'",
"]",
"=",
"rt",
".",
"from_url",
"rdict",
"[",
"'plugin'",
"]",
"=",
"rt",
".",
"plugin",
"results_data",
".",
"append",
"(",
"rdict",
")",
"return",
"results_data"
] | Return results of the analysis. | [
"Return",
"results",
"of",
"the",
"analysis",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L275-L295 | train | 236,714 |
alertot/detectem | detectem/plugin.py | load_plugins | def load_plugins():
""" Return the list of plugin instances. """
loader = _PluginLoader()
for pkg in PLUGIN_PACKAGES:
loader.load_plugins(pkg)
return loader.plugins | python | def load_plugins():
""" Return the list of plugin instances. """
loader = _PluginLoader()
for pkg in PLUGIN_PACKAGES:
loader.load_plugins(pkg)
return loader.plugins | [
"def",
"load_plugins",
"(",
")",
":",
"loader",
"=",
"_PluginLoader",
"(",
")",
"for",
"pkg",
"in",
"PLUGIN_PACKAGES",
":",
"loader",
".",
"load_plugins",
"(",
"pkg",
")",
"return",
"loader",
".",
"plugins"
] | Return the list of plugin instances. | [
"Return",
"the",
"list",
"of",
"plugin",
"instances",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L158-L165 | train | 236,715 |
alertot/detectem | detectem/plugin.py | _PluginLoader._get_plugin_module_paths | def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', '', fp) for fp in filepaths]
module_paths = [rp.replace('/', '.').replace('.py', '') for rp in rel_paths]
return module_paths | python | def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', '', fp) for fp in filepaths]
module_paths = [rp.replace('/', '.').replace('.py', '') for rp in rel_paths]
return module_paths | [
"def",
"_get_plugin_module_paths",
"(",
"self",
",",
"plugin_dir",
")",
":",
"filepaths",
"=",
"[",
"fp",
"for",
"fp",
"in",
"glob",
".",
"glob",
"(",
"'{}/**/*.py'",
".",
"format",
"(",
"plugin_dir",
")",
",",
"recursive",
"=",
"True",
")",
"if",
"not",
"fp",
".",
"endswith",
"(",
"'__init__.py'",
")",
"]",
"rel_paths",
"=",
"[",
"re",
".",
"sub",
"(",
"plugin_dir",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
",",
"''",
",",
"fp",
")",
"for",
"fp",
"in",
"filepaths",
"]",
"module_paths",
"=",
"[",
"rp",
".",
"replace",
"(",
"'/'",
",",
"'.'",
")",
".",
"replace",
"(",
"'.py'",
",",
"''",
")",
"for",
"rp",
"in",
"rel_paths",
"]",
"return",
"module_paths"
] | Return a list of every module in `plugin_dir`. | [
"Return",
"a",
"list",
"of",
"every",
"module",
"in",
"plugin_dir",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L75-L84 | train | 236,716 |
alertot/detectem | detectem/plugin.py | _PluginLoader.load_plugins | def load_plugins(self, plugins_package):
''' Load plugins from `plugins_package` module. '''
try:
# Resolve directory in the filesystem
plugin_dir = find_spec(plugins_package).submodule_search_locations[0]
except ImportError:
logger.error(
"Could not load plugins package '%(pkg)s'", {'pkg': plugins_package}
)
return
for module_path in self._get_plugin_module_paths(plugin_dir):
# Load the module dynamically
spec = find_spec('{}.{}'.format(plugins_package, module_path))
m = module_from_spec(spec)
spec.loader.exec_module(m)
# Get classes from module and extract the plugin classes
classes = inspect.getmembers(m, predicate=inspect.isclass)
for _, klass in classes:
# Avoid imports processing
if klass.__module__ != spec.name:
continue
# Avoid classes not ending in Plugin
if not klass.__name__.endswith('Plugin'):
continue
instance = klass()
if self._is_plugin_ok(instance):
self.plugins.add(instance) | python | def load_plugins(self, plugins_package):
''' Load plugins from `plugins_package` module. '''
try:
# Resolve directory in the filesystem
plugin_dir = find_spec(plugins_package).submodule_search_locations[0]
except ImportError:
logger.error(
"Could not load plugins package '%(pkg)s'", {'pkg': plugins_package}
)
return
for module_path in self._get_plugin_module_paths(plugin_dir):
# Load the module dynamically
spec = find_spec('{}.{}'.format(plugins_package, module_path))
m = module_from_spec(spec)
spec.loader.exec_module(m)
# Get classes from module and extract the plugin classes
classes = inspect.getmembers(m, predicate=inspect.isclass)
for _, klass in classes:
# Avoid imports processing
if klass.__module__ != spec.name:
continue
# Avoid classes not ending in Plugin
if not klass.__name__.endswith('Plugin'):
continue
instance = klass()
if self._is_plugin_ok(instance):
self.plugins.add(instance) | [
"def",
"load_plugins",
"(",
"self",
",",
"plugins_package",
")",
":",
"try",
":",
"# Resolve directory in the filesystem",
"plugin_dir",
"=",
"find_spec",
"(",
"plugins_package",
")",
".",
"submodule_search_locations",
"[",
"0",
"]",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Could not load plugins package '%(pkg)s'\"",
",",
"{",
"'pkg'",
":",
"plugins_package",
"}",
")",
"return",
"for",
"module_path",
"in",
"self",
".",
"_get_plugin_module_paths",
"(",
"plugin_dir",
")",
":",
"# Load the module dynamically",
"spec",
"=",
"find_spec",
"(",
"'{}.{}'",
".",
"format",
"(",
"plugins_package",
",",
"module_path",
")",
")",
"m",
"=",
"module_from_spec",
"(",
"spec",
")",
"spec",
".",
"loader",
".",
"exec_module",
"(",
"m",
")",
"# Get classes from module and extract the plugin classes",
"classes",
"=",
"inspect",
".",
"getmembers",
"(",
"m",
",",
"predicate",
"=",
"inspect",
".",
"isclass",
")",
"for",
"_",
",",
"klass",
"in",
"classes",
":",
"# Avoid imports processing",
"if",
"klass",
".",
"__module__",
"!=",
"spec",
".",
"name",
":",
"continue",
"# Avoid classes not ending in Plugin",
"if",
"not",
"klass",
".",
"__name__",
".",
"endswith",
"(",
"'Plugin'",
")",
":",
"continue",
"instance",
"=",
"klass",
"(",
")",
"if",
"self",
".",
"_is_plugin_ok",
"(",
"instance",
")",
":",
"self",
".",
"plugins",
".",
"add",
"(",
"instance",
")"
] | Load plugins from `plugins_package` module. | [
"Load",
"plugins",
"from",
"plugins_package",
"module",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L125-L155 | train | 236,717 |
alertot/detectem | detectem/matchers.py | extract_named_group | def extract_named_group(text, named_group, matchers, return_presence=False):
''' Return ``named_group`` match from ``text`` reached
by using a matcher from ``matchers``.
It also supports matching without a ``named_group`` in a matcher,
which sets ``presence=True``.
``presence`` is only returned if ``return_presence=True``.
'''
presence = False
for matcher in matchers:
if isinstance(matcher, str):
v = re.search(matcher, text, flags=re.DOTALL)
if v:
dict_result = v.groupdict()
try:
return dict_result[named_group]
except KeyError:
if dict_result:
# It's other named group matching, discard
continue
else:
# It's a matcher without named_group
# but we can't return it until every matcher pass
# because a following matcher could have a named group
presence = True
elif callable(matcher):
v = matcher(text)
if v:
return v
if return_presence and presence:
return 'presence'
return None | python | def extract_named_group(text, named_group, matchers, return_presence=False):
''' Return ``named_group`` match from ``text`` reached
by using a matcher from ``matchers``.
It also supports matching without a ``named_group`` in a matcher,
which sets ``presence=True``.
``presence`` is only returned if ``return_presence=True``.
'''
presence = False
for matcher in matchers:
if isinstance(matcher, str):
v = re.search(matcher, text, flags=re.DOTALL)
if v:
dict_result = v.groupdict()
try:
return dict_result[named_group]
except KeyError:
if dict_result:
# It's other named group matching, discard
continue
else:
# It's a matcher without named_group
# but we can't return it until every matcher pass
# because a following matcher could have a named group
presence = True
elif callable(matcher):
v = matcher(text)
if v:
return v
if return_presence and presence:
return 'presence'
return None | [
"def",
"extract_named_group",
"(",
"text",
",",
"named_group",
",",
"matchers",
",",
"return_presence",
"=",
"False",
")",
":",
"presence",
"=",
"False",
"for",
"matcher",
"in",
"matchers",
":",
"if",
"isinstance",
"(",
"matcher",
",",
"str",
")",
":",
"v",
"=",
"re",
".",
"search",
"(",
"matcher",
",",
"text",
",",
"flags",
"=",
"re",
".",
"DOTALL",
")",
"if",
"v",
":",
"dict_result",
"=",
"v",
".",
"groupdict",
"(",
")",
"try",
":",
"return",
"dict_result",
"[",
"named_group",
"]",
"except",
"KeyError",
":",
"if",
"dict_result",
":",
"# It's other named group matching, discard",
"continue",
"else",
":",
"# It's a matcher without named_group",
"# but we can't return it until every matcher pass",
"# because a following matcher could have a named group",
"presence",
"=",
"True",
"elif",
"callable",
"(",
"matcher",
")",
":",
"v",
"=",
"matcher",
"(",
"text",
")",
"if",
"v",
":",
"return",
"v",
"if",
"return_presence",
"and",
"presence",
":",
"return",
"'presence'",
"return",
"None"
] | Return ``named_group`` match from ``text`` reached
by using a matcher from ``matchers``.
It also supports matching without a ``named_group`` in a matcher,
which sets ``presence=True``.
``presence`` is only returned if ``return_presence=True``. | [
"Return",
"named_group",
"match",
"from",
"text",
"reached",
"by",
"using",
"a",
"matcher",
"from",
"matchers",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/matchers.py#L12-L48 | train | 236,718 |
jmcarp/robobrowser | robobrowser/browser.py | RoboState.parsed | def parsed(self):
"""Lazily parse response content, using HTML parser specified by the
browser.
"""
return BeautifulSoup(
self.response.content,
features=self.browser.parser,
) | python | def parsed(self):
"""Lazily parse response content, using HTML parser specified by the
browser.
"""
return BeautifulSoup(
self.response.content,
features=self.browser.parser,
) | [
"def",
"parsed",
"(",
"self",
")",
":",
"return",
"BeautifulSoup",
"(",
"self",
".",
"response",
".",
"content",
",",
"features",
"=",
"self",
".",
"browser",
".",
"parser",
",",
")"
] | Lazily parse response content, using HTML parser specified by the
browser. | [
"Lazily",
"parse",
"response",
"content",
"using",
"HTML",
"parser",
"specified",
"by",
"the",
"browser",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L34-L41 | train | 236,719 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser._build_send_args | def _build_send_args(self, **kwargs):
"""Merge optional arguments with defaults.
:param kwargs: Keyword arguments to `Session::send`
"""
out = {}
out.update(self._default_send_args)
out.update(kwargs)
return out | python | def _build_send_args(self, **kwargs):
"""Merge optional arguments with defaults.
:param kwargs: Keyword arguments to `Session::send`
"""
out = {}
out.update(self._default_send_args)
out.update(kwargs)
return out | [
"def",
"_build_send_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"{",
"}",
"out",
".",
"update",
"(",
"self",
".",
"_default_send_args",
")",
"out",
".",
"update",
"(",
"kwargs",
")",
"return",
"out"
] | Merge optional arguments with defaults.
:param kwargs: Keyword arguments to `Session::send` | [
"Merge",
"optional",
"arguments",
"with",
"defaults",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L186-L195 | train | 236,720 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser.open | def open(self, url, method='get', **kwargs):
"""Open a URL.
:param str url: URL to open
:param str method: Optional method; defaults to `'get'`
:param kwargs: Keyword arguments to `Session::request`
"""
response = self.session.request(method, url, **self._build_send_args(**kwargs))
self._update_state(response) | python | def open(self, url, method='get', **kwargs):
"""Open a URL.
:param str url: URL to open
:param str method: Optional method; defaults to `'get'`
:param kwargs: Keyword arguments to `Session::request`
"""
response = self.session.request(method, url, **self._build_send_args(**kwargs))
self._update_state(response) | [
"def",
"open",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'get'",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"self",
".",
"_build_send_args",
"(",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_update_state",
"(",
"response",
")"
] | Open a URL.
:param str url: URL to open
:param str method: Optional method; defaults to `'get'`
:param kwargs: Keyword arguments to `Session::request` | [
"Open",
"a",
"URL",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L197-L206 | train | 236,721 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser._update_state | def _update_state(self, response):
"""Update the state of the browser. Create a new state object, and
append to or overwrite the browser's state history.
:param requests.MockResponse: New response object
"""
# Clear trailing states
self._states = self._states[:self._cursor + 1]
# Append new state
state = RoboState(self, response)
self._states.append(state)
self._cursor += 1
# Clear leading states
if self._maxlen:
decrement = len(self._states) - self._maxlen
if decrement > 0:
self._states = self._states[decrement:]
self._cursor -= decrement | python | def _update_state(self, response):
"""Update the state of the browser. Create a new state object, and
append to or overwrite the browser's state history.
:param requests.MockResponse: New response object
"""
# Clear trailing states
self._states = self._states[:self._cursor + 1]
# Append new state
state = RoboState(self, response)
self._states.append(state)
self._cursor += 1
# Clear leading states
if self._maxlen:
decrement = len(self._states) - self._maxlen
if decrement > 0:
self._states = self._states[decrement:]
self._cursor -= decrement | [
"def",
"_update_state",
"(",
"self",
",",
"response",
")",
":",
"# Clear trailing states",
"self",
".",
"_states",
"=",
"self",
".",
"_states",
"[",
":",
"self",
".",
"_cursor",
"+",
"1",
"]",
"# Append new state",
"state",
"=",
"RoboState",
"(",
"self",
",",
"response",
")",
"self",
".",
"_states",
".",
"append",
"(",
"state",
")",
"self",
".",
"_cursor",
"+=",
"1",
"# Clear leading states",
"if",
"self",
".",
"_maxlen",
":",
"decrement",
"=",
"len",
"(",
"self",
".",
"_states",
")",
"-",
"self",
".",
"_maxlen",
"if",
"decrement",
">",
"0",
":",
"self",
".",
"_states",
"=",
"self",
".",
"_states",
"[",
"decrement",
":",
"]",
"self",
".",
"_cursor",
"-=",
"decrement"
] | Update the state of the browser. Create a new state object, and
append to or overwrite the browser's state history.
:param requests.MockResponse: New response object | [
"Update",
"the",
"state",
"of",
"the",
"browser",
".",
"Create",
"a",
"new",
"state",
"object",
"and",
"append",
"to",
"or",
"overwrite",
"the",
"browser",
"s",
"state",
"history",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L208-L228 | train | 236,722 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser._traverse | def _traverse(self, n=1):
"""Traverse state history. Used by `back` and `forward` methods.
:param int n: Cursor increment. Positive values move forward in the
browser history; negative values move backward.
"""
if not self.history:
raise exceptions.RoboError('Not tracking history')
cursor = self._cursor + n
if cursor >= len(self._states) or cursor < 0:
raise exceptions.RoboError('Index out of range')
self._cursor = cursor | python | def _traverse(self, n=1):
"""Traverse state history. Used by `back` and `forward` methods.
:param int n: Cursor increment. Positive values move forward in the
browser history; negative values move backward.
"""
if not self.history:
raise exceptions.RoboError('Not tracking history')
cursor = self._cursor + n
if cursor >= len(self._states) or cursor < 0:
raise exceptions.RoboError('Index out of range')
self._cursor = cursor | [
"def",
"_traverse",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"history",
":",
"raise",
"exceptions",
".",
"RoboError",
"(",
"'Not tracking history'",
")",
"cursor",
"=",
"self",
".",
"_cursor",
"+",
"n",
"if",
"cursor",
">=",
"len",
"(",
"self",
".",
"_states",
")",
"or",
"cursor",
"<",
"0",
":",
"raise",
"exceptions",
".",
"RoboError",
"(",
"'Index out of range'",
")",
"self",
".",
"_cursor",
"=",
"cursor"
] | Traverse state history. Used by `back` and `forward` methods.
:param int n: Cursor increment. Positive values move forward in the
browser history; negative values move backward. | [
"Traverse",
"state",
"history",
".",
"Used",
"by",
"back",
"and",
"forward",
"methods",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L230-L242 | train | 236,723 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser.get_link | def get_link(self, text=None, *args, **kwargs):
"""Find an anchor or button by containing text, as well as standard
BeautifulSoup arguments.
:param text: String or regex to be matched in link text
:return: BeautifulSoup tag if found, else None
"""
return helpers.find(
self.parsed, _link_ptn, text=text, *args, **kwargs
) | python | def get_link(self, text=None, *args, **kwargs):
"""Find an anchor or button by containing text, as well as standard
BeautifulSoup arguments.
:param text: String or regex to be matched in link text
:return: BeautifulSoup tag if found, else None
"""
return helpers.find(
self.parsed, _link_ptn, text=text, *args, **kwargs
) | [
"def",
"get_link",
"(",
"self",
",",
"text",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"helpers",
".",
"find",
"(",
"self",
".",
"parsed",
",",
"_link_ptn",
",",
"text",
"=",
"text",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Find an anchor or button by containing text, as well as standard
BeautifulSoup arguments.
:param text: String or regex to be matched in link text
:return: BeautifulSoup tag if found, else None | [
"Find",
"an",
"anchor",
"or",
"button",
"by",
"containing",
"text",
"as",
"well",
"as",
"standard",
"BeautifulSoup",
"arguments",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L260-L270 | train | 236,724 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser.get_links | def get_links(self, text=None, *args, **kwargs):
"""Find anchors or buttons by containing text, as well as standard
BeautifulSoup arguments.
:param text: String or regex to be matched in link text
:return: List of BeautifulSoup tags
"""
return helpers.find_all(
self.parsed, _link_ptn, text=text, *args, **kwargs
) | python | def get_links(self, text=None, *args, **kwargs):
"""Find anchors or buttons by containing text, as well as standard
BeautifulSoup arguments.
:param text: String or regex to be matched in link text
:return: List of BeautifulSoup tags
"""
return helpers.find_all(
self.parsed, _link_ptn, text=text, *args, **kwargs
) | [
"def",
"get_links",
"(",
"self",
",",
"text",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"helpers",
".",
"find_all",
"(",
"self",
".",
"parsed",
",",
"_link_ptn",
",",
"text",
"=",
"text",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Find anchors or buttons by containing text, as well as standard
BeautifulSoup arguments.
:param text: String or regex to be matched in link text
:return: List of BeautifulSoup tags | [
"Find",
"anchors",
"or",
"buttons",
"by",
"containing",
"text",
"as",
"well",
"as",
"standard",
"BeautifulSoup",
"arguments",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L272-L282 | train | 236,725 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser.get_form | def get_form(self, id=None, *args, **kwargs):
"""Find form by ID, as well as standard BeautifulSoup arguments.
:param str id: Form ID
:return: BeautifulSoup tag if found, else None
"""
if id:
kwargs['id'] = id
form = self.find(_form_ptn, *args, **kwargs)
if form is not None:
return Form(form) | python | def get_form(self, id=None, *args, **kwargs):
"""Find form by ID, as well as standard BeautifulSoup arguments.
:param str id: Form ID
:return: BeautifulSoup tag if found, else None
"""
if id:
kwargs['id'] = id
form = self.find(_form_ptn, *args, **kwargs)
if form is not None:
return Form(form) | [
"def",
"get_form",
"(",
"self",
",",
"id",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
":",
"kwargs",
"[",
"'id'",
"]",
"=",
"id",
"form",
"=",
"self",
".",
"find",
"(",
"_form_ptn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"form",
"is",
"not",
"None",
":",
"return",
"Form",
"(",
"form",
")"
] | Find form by ID, as well as standard BeautifulSoup arguments.
:param str id: Form ID
:return: BeautifulSoup tag if found, else None | [
"Find",
"form",
"by",
"ID",
"as",
"well",
"as",
"standard",
"BeautifulSoup",
"arguments",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L284-L295 | train | 236,726 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser.follow_link | def follow_link(self, link, **kwargs):
"""Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send`
"""
try:
href = link['href']
except KeyError:
raise exceptions.RoboError('Link element must have "href" '
'attribute')
self.open(self._build_url(href), **kwargs) | python | def follow_link(self, link, **kwargs):
"""Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send`
"""
try:
href = link['href']
except KeyError:
raise exceptions.RoboError('Link element must have "href" '
'attribute')
self.open(self._build_url(href), **kwargs) | [
"def",
"follow_link",
"(",
"self",
",",
"link",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"href",
"=",
"link",
"[",
"'href'",
"]",
"except",
"KeyError",
":",
"raise",
"exceptions",
".",
"RoboError",
"(",
"'Link element must have \"href\" '",
"'attribute'",
")",
"self",
".",
"open",
"(",
"self",
".",
"_build_url",
"(",
"href",
")",
",",
"*",
"*",
"kwargs",
")"
] | Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send` | [
"Click",
"a",
"link",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L311-L323 | train | 236,727 |
jmcarp/robobrowser | robobrowser/browser.py | RoboBrowser.submit_form | def submit_form(self, form, submit=None, **kwargs):
"""Submit a form.
:param Form form: Filled-out form object
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:param kwargs: Keyword arguments to `Session::send`
"""
# Get HTTP verb
method = form.method.upper()
# Send request
url = self._build_url(form.action) or self.url
payload = form.serialize(submit=submit)
serialized = payload.to_requests(method)
send_args = self._build_send_args(**kwargs)
send_args.update(serialized)
response = self.session.request(method, url, **send_args)
# Update history
self._update_state(response) | python | def submit_form(self, form, submit=None, **kwargs):
"""Submit a form.
:param Form form: Filled-out form object
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:param kwargs: Keyword arguments to `Session::send`
"""
# Get HTTP verb
method = form.method.upper()
# Send request
url = self._build_url(form.action) or self.url
payload = form.serialize(submit=submit)
serialized = payload.to_requests(method)
send_args = self._build_send_args(**kwargs)
send_args.update(serialized)
response = self.session.request(method, url, **send_args)
# Update history
self._update_state(response) | [
"def",
"submit_form",
"(",
"self",
",",
"form",
",",
"submit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get HTTP verb",
"method",
"=",
"form",
".",
"method",
".",
"upper",
"(",
")",
"# Send request",
"url",
"=",
"self",
".",
"_build_url",
"(",
"form",
".",
"action",
")",
"or",
"self",
".",
"url",
"payload",
"=",
"form",
".",
"serialize",
"(",
"submit",
"=",
"submit",
")",
"serialized",
"=",
"payload",
".",
"to_requests",
"(",
"method",
")",
"send_args",
"=",
"self",
".",
"_build_send_args",
"(",
"*",
"*",
"kwargs",
")",
"send_args",
".",
"update",
"(",
"serialized",
")",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"send_args",
")",
"# Update history",
"self",
".",
"_update_state",
"(",
"response",
")"
] | Submit a form.
:param Form form: Filled-out form object
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:param kwargs: Keyword arguments to `Session::send` | [
"Submit",
"a",
"form",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L325-L346 | train | 236,728 |
jmcarp/robobrowser | robobrowser/helpers.py | find | def find(soup, name=None, attrs=None, recursive=True, text=None, **kwargs):
"""Modified find method; see `find_all`, above.
"""
tags = find_all(
soup, name, attrs or {}, recursive, text, 1, **kwargs
)
if tags:
return tags[0] | python | def find(soup, name=None, attrs=None, recursive=True, text=None, **kwargs):
"""Modified find method; see `find_all`, above.
"""
tags = find_all(
soup, name, attrs or {}, recursive, text, 1, **kwargs
)
if tags:
return tags[0] | [
"def",
"find",
"(",
"soup",
",",
"name",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"text",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"tags",
"=",
"find_all",
"(",
"soup",
",",
"name",
",",
"attrs",
"or",
"{",
"}",
",",
"recursive",
",",
"text",
",",
"1",
",",
"*",
"*",
"kwargs",
")",
"if",
"tags",
":",
"return",
"tags",
"[",
"0",
"]"
] | Modified find method; see `find_all`, above. | [
"Modified",
"find",
"method",
";",
"see",
"find_all",
"above",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/helpers.py#L46-L54 | train | 236,729 |
jmcarp/robobrowser | robobrowser/forms/fields.py | Select._set_initial | def _set_initial(self, initial):
"""If no option is selected initially, select the first option.
"""
super(Select, self)._set_initial(initial)
if not self._value and self.options:
self.value = self.options[0] | python | def _set_initial(self, initial):
"""If no option is selected initially, select the first option.
"""
super(Select, self)._set_initial(initial)
if not self._value and self.options:
self.value = self.options[0] | [
"def",
"_set_initial",
"(",
"self",
",",
"initial",
")",
":",
"super",
"(",
"Select",
",",
"self",
")",
".",
"_set_initial",
"(",
"initial",
")",
"if",
"not",
"self",
".",
"_value",
"and",
"self",
".",
"options",
":",
"self",
".",
"value",
"=",
"self",
".",
"options",
"[",
"0",
"]"
] | If no option is selected initially, select the first option. | [
"If",
"no",
"option",
"is",
"selected",
"initially",
"select",
"the",
"first",
"option",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/forms/fields.py#L209-L214 | train | 236,730 |
jmcarp/robobrowser | robobrowser/compat.py | encode_if_py2 | def encode_if_py2(func):
"""If Python 2.x, return decorated function encoding unicode return value
to UTF-8; else noop.
"""
if not PY2:
return func
def wrapped(*args, **kwargs):
ret = func(*args, **kwargs)
if not isinstance(ret, unicode):
raise TypeError('Wrapped function must return `unicode`')
return ret.encode('utf-8', 'ignore')
return wrapped | python | def encode_if_py2(func):
"""If Python 2.x, return decorated function encoding unicode return value
to UTF-8; else noop.
"""
if not PY2:
return func
def wrapped(*args, **kwargs):
ret = func(*args, **kwargs)
if not isinstance(ret, unicode):
raise TypeError('Wrapped function must return `unicode`')
return ret.encode('utf-8', 'ignore')
return wrapped | [
"def",
"encode_if_py2",
"(",
"func",
")",
":",
"if",
"not",
"PY2",
":",
"return",
"func",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"isinstance",
"(",
"ret",
",",
"unicode",
")",
":",
"raise",
"TypeError",
"(",
"'Wrapped function must return `unicode`'",
")",
"return",
"ret",
".",
"encode",
"(",
"'utf-8'",
",",
"'ignore'",
")",
"return",
"wrapped"
] | If Python 2.x, return decorated function encoding unicode return value
to UTF-8; else noop. | [
"If",
"Python",
"2",
".",
"x",
"return",
"decorated",
"function",
"encoding",
"unicode",
"return",
"value",
"to",
"UTF",
"-",
"8",
";",
"else",
"noop",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/compat.py#L35-L46 | train | 236,731 |
jmcarp/robobrowser | robobrowser/cache.py | RoboCache._reduce_age | def _reduce_age(self, now):
"""Reduce size of cache by date.
:param datetime.datetime now: Current time
"""
if self.max_age:
keys = [
key for key, value in iteritems(self.data)
if now - value['date'] > self.max_age
]
for key in keys:
del self.data[key] | python | def _reduce_age(self, now):
"""Reduce size of cache by date.
:param datetime.datetime now: Current time
"""
if self.max_age:
keys = [
key for key, value in iteritems(self.data)
if now - value['date'] > self.max_age
]
for key in keys:
del self.data[key] | [
"def",
"_reduce_age",
"(",
"self",
",",
"now",
")",
":",
"if",
"self",
".",
"max_age",
":",
"keys",
"=",
"[",
"key",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"data",
")",
"if",
"now",
"-",
"value",
"[",
"'date'",
"]",
">",
"self",
".",
"max_age",
"]",
"for",
"key",
"in",
"keys",
":",
"del",
"self",
".",
"data",
"[",
"key",
"]"
] | Reduce size of cache by date.
:param datetime.datetime now: Current time | [
"Reduce",
"size",
"of",
"cache",
"by",
"date",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/cache.py#L26-L38 | train | 236,732 |
jmcarp/robobrowser | robobrowser/cache.py | RoboCache._reduce_count | def _reduce_count(self):
"""Reduce size of cache by count.
"""
if self.max_count:
while len(self.data) > self.max_count:
self.data.popitem(last=False) | python | def _reduce_count(self):
"""Reduce size of cache by count.
"""
if self.max_count:
while len(self.data) > self.max_count:
self.data.popitem(last=False) | [
"def",
"_reduce_count",
"(",
"self",
")",
":",
"if",
"self",
".",
"max_count",
":",
"while",
"len",
"(",
"self",
".",
"data",
")",
">",
"self",
".",
"max_count",
":",
"self",
".",
"data",
".",
"popitem",
"(",
"last",
"=",
"False",
")"
] | Reduce size of cache by count. | [
"Reduce",
"size",
"of",
"cache",
"by",
"count",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/cache.py#L40-L46 | train | 236,733 |
jmcarp/robobrowser | robobrowser/cache.py | RoboCache.store | def store(self, response):
"""Store response in cache, skipping if code is forbidden.
:param requests.Response response: HTTP response
"""
if response.status_code not in CACHE_CODES:
return
now = datetime.datetime.now()
self.data[response.url] = {
'date': now,
'response': response,
}
logger.info('Stored response in cache')
self._reduce_age(now)
self._reduce_count() | python | def store(self, response):
"""Store response in cache, skipping if code is forbidden.
:param requests.Response response: HTTP response
"""
if response.status_code not in CACHE_CODES:
return
now = datetime.datetime.now()
self.data[response.url] = {
'date': now,
'response': response,
}
logger.info('Stored response in cache')
self._reduce_age(now)
self._reduce_count() | [
"def",
"store",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"not",
"in",
"CACHE_CODES",
":",
"return",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"data",
"[",
"response",
".",
"url",
"]",
"=",
"{",
"'date'",
":",
"now",
",",
"'response'",
":",
"response",
",",
"}",
"logger",
".",
"info",
"(",
"'Stored response in cache'",
")",
"self",
".",
"_reduce_age",
"(",
"now",
")",
"self",
".",
"_reduce_count",
"(",
")"
] | Store response in cache, skipping if code is forbidden.
:param requests.Response response: HTTP response | [
"Store",
"response",
"in",
"cache",
"skipping",
"if",
"code",
"is",
"forbidden",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/cache.py#L48-L63 | train | 236,734 |
jmcarp/robobrowser | robobrowser/cache.py | RoboCache.retrieve | def retrieve(self, request):
"""Look up request in cache, skipping if verb is forbidden.
:param requests.Request request: HTTP request
"""
if request.method not in CACHE_VERBS:
return
try:
response = self.data[request.url]['response']
logger.info('Retrieved response from cache')
return response
except KeyError:
return None | python | def retrieve(self, request):
"""Look up request in cache, skipping if verb is forbidden.
:param requests.Request request: HTTP request
"""
if request.method not in CACHE_VERBS:
return
try:
response = self.data[request.url]['response']
logger.info('Retrieved response from cache')
return response
except KeyError:
return None | [
"def",
"retrieve",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"method",
"not",
"in",
"CACHE_VERBS",
":",
"return",
"try",
":",
"response",
"=",
"self",
".",
"data",
"[",
"request",
".",
"url",
"]",
"[",
"'response'",
"]",
"logger",
".",
"info",
"(",
"'Retrieved response from cache'",
")",
"return",
"response",
"except",
"KeyError",
":",
"return",
"None"
] | Look up request in cache, skipping if verb is forbidden.
:param requests.Request request: HTTP request | [
"Look",
"up",
"request",
"in",
"cache",
"skipping",
"if",
"verb",
"is",
"forbidden",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/cache.py#L65-L78 | train | 236,735 |
jmcarp/robobrowser | robobrowser/forms/form.py | _group_flat_tags | def _group_flat_tags(tag, tags):
"""Extract tags sharing the same name as the provided tag. Used to collect
options for radio and checkbox inputs.
:param Tag tag: BeautifulSoup tag
:param list tags: List of tags
:return: List of matching tags
"""
grouped = [tag]
name = tag.get('name', '').lower()
while tags and tags[0].get('name', '').lower() == name:
grouped.append(tags.pop(0))
return grouped | python | def _group_flat_tags(tag, tags):
"""Extract tags sharing the same name as the provided tag. Used to collect
options for radio and checkbox inputs.
:param Tag tag: BeautifulSoup tag
:param list tags: List of tags
:return: List of matching tags
"""
grouped = [tag]
name = tag.get('name', '').lower()
while tags and tags[0].get('name', '').lower() == name:
grouped.append(tags.pop(0))
return grouped | [
"def",
"_group_flat_tags",
"(",
"tag",
",",
"tags",
")",
":",
"grouped",
"=",
"[",
"tag",
"]",
"name",
"=",
"tag",
".",
"get",
"(",
"'name'",
",",
"''",
")",
".",
"lower",
"(",
")",
"while",
"tags",
"and",
"tags",
"[",
"0",
"]",
".",
"get",
"(",
"'name'",
",",
"''",
")",
".",
"lower",
"(",
")",
"==",
"name",
":",
"grouped",
".",
"append",
"(",
"tags",
".",
"pop",
"(",
"0",
")",
")",
"return",
"grouped"
] | Extract tags sharing the same name as the provided tag. Used to collect
options for radio and checkbox inputs.
:param Tag tag: BeautifulSoup tag
:param list tags: List of tags
:return: List of matching tags | [
"Extract",
"tags",
"sharing",
"the",
"same",
"name",
"as",
"the",
"provided",
"tag",
".",
"Used",
"to",
"collect",
"options",
"for",
"radio",
"and",
"checkbox",
"inputs",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/forms/form.py#L23-L36 | train | 236,736 |
jmcarp/robobrowser | robobrowser/forms/form.py | _parse_fields | def _parse_fields(parsed):
"""Parse form fields from HTML.
:param BeautifulSoup parsed: Parsed HTML
:return OrderedDict: Collection of field objects
"""
# Note: Call this `out` to avoid name conflict with `fields` module
out = []
# Prepare field tags
tags = parsed.find_all(_tag_ptn)
for tag in tags:
helpers.lowercase_attr_names(tag)
while tags:
tag = tags.pop(0)
try:
field = _parse_field(tag, tags)
except exceptions.InvalidNameError:
continue
if field is not None:
out.append(field)
return out | python | def _parse_fields(parsed):
"""Parse form fields from HTML.
:param BeautifulSoup parsed: Parsed HTML
:return OrderedDict: Collection of field objects
"""
# Note: Call this `out` to avoid name conflict with `fields` module
out = []
# Prepare field tags
tags = parsed.find_all(_tag_ptn)
for tag in tags:
helpers.lowercase_attr_names(tag)
while tags:
tag = tags.pop(0)
try:
field = _parse_field(tag, tags)
except exceptions.InvalidNameError:
continue
if field is not None:
out.append(field)
return out | [
"def",
"_parse_fields",
"(",
"parsed",
")",
":",
"# Note: Call this `out` to avoid name conflict with `fields` module",
"out",
"=",
"[",
"]",
"# Prepare field tags",
"tags",
"=",
"parsed",
".",
"find_all",
"(",
"_tag_ptn",
")",
"for",
"tag",
"in",
"tags",
":",
"helpers",
".",
"lowercase_attr_names",
"(",
"tag",
")",
"while",
"tags",
":",
"tag",
"=",
"tags",
".",
"pop",
"(",
"0",
")",
"try",
":",
"field",
"=",
"_parse_field",
"(",
"tag",
",",
"tags",
")",
"except",
"exceptions",
".",
"InvalidNameError",
":",
"continue",
"if",
"field",
"is",
"not",
"None",
":",
"out",
".",
"append",
"(",
"field",
")",
"return",
"out"
] | Parse form fields from HTML.
:param BeautifulSoup parsed: Parsed HTML
:return OrderedDict: Collection of field objects | [
"Parse",
"form",
"fields",
"from",
"HTML",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/forms/form.py#L64-L88 | train | 236,737 |
jmcarp/robobrowser | robobrowser/forms/form.py | Payload.add | def add(self, data, key=None):
"""Add field values to container.
:param dict data: Serialized values for field
:param str key: Optional key; if not provided, values will be added
to `self.payload`.
"""
sink = self.options[key] if key is not None else self.data
for key, value in iteritems(data):
sink.add(key, value) | python | def add(self, data, key=None):
"""Add field values to container.
:param dict data: Serialized values for field
:param str key: Optional key; if not provided, values will be added
to `self.payload`.
"""
sink = self.options[key] if key is not None else self.data
for key, value in iteritems(data):
sink.add(key, value) | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"key",
"=",
"None",
")",
":",
"sink",
"=",
"self",
".",
"options",
"[",
"key",
"]",
"if",
"key",
"is",
"not",
"None",
"else",
"self",
".",
"data",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"data",
")",
":",
"sink",
".",
"add",
"(",
"key",
",",
"value",
")"
] | Add field values to container.
:param dict data: Serialized values for field
:param str key: Optional key; if not provided, values will be added
to `self.payload`. | [
"Add",
"field",
"values",
"to",
"container",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/forms/form.py#L122-L132 | train | 236,738 |
jmcarp/robobrowser | robobrowser/forms/form.py | Payload.to_requests | def to_requests(self, method='get'):
"""Export to Requests format.
:param str method: Request method
:return: Dict of keyword arguments formatted for `requests.request`
"""
out = {}
data_key = 'params' if method.lower() == 'get' else 'data'
out[data_key] = self.data
out.update(self.options)
return dict([
(key, list(value.items(multi=True)))
for key, value in iteritems(out)
]) | python | def to_requests(self, method='get'):
"""Export to Requests format.
:param str method: Request method
:return: Dict of keyword arguments formatted for `requests.request`
"""
out = {}
data_key = 'params' if method.lower() == 'get' else 'data'
out[data_key] = self.data
out.update(self.options)
return dict([
(key, list(value.items(multi=True)))
for key, value in iteritems(out)
]) | [
"def",
"to_requests",
"(",
"self",
",",
"method",
"=",
"'get'",
")",
":",
"out",
"=",
"{",
"}",
"data_key",
"=",
"'params'",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'get'",
"else",
"'data'",
"out",
"[",
"data_key",
"]",
"=",
"self",
".",
"data",
"out",
".",
"update",
"(",
"self",
".",
"options",
")",
"return",
"dict",
"(",
"[",
"(",
"key",
",",
"list",
"(",
"value",
".",
"items",
"(",
"multi",
"=",
"True",
")",
")",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"out",
")",
"]",
")"
] | Export to Requests format.
:param str method: Request method
:return: Dict of keyword arguments formatted for `requests.request` | [
"Export",
"to",
"Requests",
"format",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/forms/form.py#L134-L148 | train | 236,739 |
jmcarp/robobrowser | robobrowser/forms/form.py | Form.add_field | def add_field(self, field):
"""Add a field.
:param field: Field to add
:raise: ValueError if `field` is not an instance of `BaseField`.
"""
if not isinstance(field, fields.BaseField):
raise ValueError('Argument "field" must be an instance of '
'BaseField')
self.fields.add(field.name, field) | python | def add_field(self, field):
"""Add a field.
:param field: Field to add
:raise: ValueError if `field` is not an instance of `BaseField`.
"""
if not isinstance(field, fields.BaseField):
raise ValueError('Argument "field" must be an instance of '
'BaseField')
self.fields.add(field.name, field) | [
"def",
"add_field",
"(",
"self",
",",
"field",
")",
":",
"if",
"not",
"isinstance",
"(",
"field",
",",
"fields",
".",
"BaseField",
")",
":",
"raise",
"ValueError",
"(",
"'Argument \"field\" must be an instance of '",
"'BaseField'",
")",
"self",
".",
"fields",
".",
"add",
"(",
"field",
".",
"name",
",",
"field",
")"
] | Add a field.
:param field: Field to add
:raise: ValueError if `field` is not an instance of `BaseField`. | [
"Add",
"a",
"field",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/forms/form.py#L178-L188 | train | 236,740 |
jmcarp/robobrowser | robobrowser/forms/form.py | Form.serialize | def serialize(self, submit=None):
"""Serialize each form field to a Payload container.
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:return: Payload instance
"""
include_fields = prepare_fields(self.fields, self.submit_fields, submit)
return Payload.from_fields(include_fields) | python | def serialize(self, submit=None):
"""Serialize each form field to a Payload container.
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:return: Payload instance
"""
include_fields = prepare_fields(self.fields, self.submit_fields, submit)
return Payload.from_fields(include_fields) | [
"def",
"serialize",
"(",
"self",
",",
"submit",
"=",
"None",
")",
":",
"include_fields",
"=",
"prepare_fields",
"(",
"self",
".",
"fields",
",",
"self",
".",
"submit_fields",
",",
"submit",
")",
"return",
"Payload",
".",
"from_fields",
"(",
"include_fields",
")"
] | Serialize each form field to a Payload container.
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:return: Payload instance | [
"Serialize",
"each",
"form",
"field",
"to",
"a",
"Payload",
"container",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/forms/form.py#L218-L227 | train | 236,741 |
paxosglobal/subconscious | subconscious/model.py | RedisModel.save | async def save(self, db):
"""Save the object to Redis.
"""
kwargs = {}
for col in self._auto_columns:
if not self.has_real_data(col.name):
kwargs[col.name] = await col.auto_generate(db, self)
self.__dict__.update(kwargs)
# we have to delete the old index key
stale_object = await self.__class__.load(db, identifier=self.identifier())
d = {
k: (v.strftime(DATETIME_FORMAT) if isinstance(v, datetime) else v)
for k, v in self.__dict__.items()
}
success = await db.hmset_dict(self.redis_key(), d)
await self.save_index(db, stale_object=stale_object)
return success | python | async def save(self, db):
"""Save the object to Redis.
"""
kwargs = {}
for col in self._auto_columns:
if not self.has_real_data(col.name):
kwargs[col.name] = await col.auto_generate(db, self)
self.__dict__.update(kwargs)
# we have to delete the old index key
stale_object = await self.__class__.load(db, identifier=self.identifier())
d = {
k: (v.strftime(DATETIME_FORMAT) if isinstance(v, datetime) else v)
for k, v in self.__dict__.items()
}
success = await db.hmset_dict(self.redis_key(), d)
await self.save_index(db, stale_object=stale_object)
return success | [
"async",
"def",
"save",
"(",
"self",
",",
"db",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"col",
"in",
"self",
".",
"_auto_columns",
":",
"if",
"not",
"self",
".",
"has_real_data",
"(",
"col",
".",
"name",
")",
":",
"kwargs",
"[",
"col",
".",
"name",
"]",
"=",
"await",
"col",
".",
"auto_generate",
"(",
"db",
",",
"self",
")",
"self",
".",
"__dict__",
".",
"update",
"(",
"kwargs",
")",
"# we have to delete the old index key",
"stale_object",
"=",
"await",
"self",
".",
"__class__",
".",
"load",
"(",
"db",
",",
"identifier",
"=",
"self",
".",
"identifier",
"(",
")",
")",
"d",
"=",
"{",
"k",
":",
"(",
"v",
".",
"strftime",
"(",
"DATETIME_FORMAT",
")",
"if",
"isinstance",
"(",
"v",
",",
"datetime",
")",
"else",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"}",
"success",
"=",
"await",
"db",
".",
"hmset_dict",
"(",
"self",
".",
"redis_key",
"(",
")",
",",
"d",
")",
"await",
"self",
".",
"save_index",
"(",
"db",
",",
"stale_object",
"=",
"stale_object",
")",
"return",
"success"
] | Save the object to Redis. | [
"Save",
"the",
"object",
"to",
"Redis",
"."
] | bc4feabde574462ff59009b32181d12867f0aa3d | https://github.com/paxosglobal/subconscious/blob/bc4feabde574462ff59009b32181d12867f0aa3d/subconscious/model.py#L204-L221 | train | 236,742 |
pahaz/sshtunnel | sshtunnel.py | check_address | def check_address(address):
"""
Check if the format of the address is correct
Arguments:
address (tuple):
(``str``, ``int``) representing an IP address and port,
respectively
.. note::
alternatively a local ``address`` can be a ``str`` when working
with UNIX domain sockets, if supported by the platform
Raises:
ValueError:
raised when address has an incorrect format
Example:
>>> check_address(('127.0.0.1', 22))
"""
if isinstance(address, tuple):
check_host(address[0])
check_port(address[1])
elif isinstance(address, string_types):
if os.name != 'posix':
raise ValueError('Platform does not support UNIX domain sockets')
if not (os.path.exists(address) or
os.access(os.path.dirname(address), os.W_OK)):
raise ValueError('ADDRESS not a valid socket domain socket ({0})'
.format(address))
else:
raise ValueError('ADDRESS is not a tuple, string, or character buffer '
'({0})'.format(type(address).__name__)) | python | def check_address(address):
"""
Check if the format of the address is correct
Arguments:
address (tuple):
(``str``, ``int``) representing an IP address and port,
respectively
.. note::
alternatively a local ``address`` can be a ``str`` when working
with UNIX domain sockets, if supported by the platform
Raises:
ValueError:
raised when address has an incorrect format
Example:
>>> check_address(('127.0.0.1', 22))
"""
if isinstance(address, tuple):
check_host(address[0])
check_port(address[1])
elif isinstance(address, string_types):
if os.name != 'posix':
raise ValueError('Platform does not support UNIX domain sockets')
if not (os.path.exists(address) or
os.access(os.path.dirname(address), os.W_OK)):
raise ValueError('ADDRESS not a valid socket domain socket ({0})'
.format(address))
else:
raise ValueError('ADDRESS is not a tuple, string, or character buffer '
'({0})'.format(type(address).__name__)) | [
"def",
"check_address",
"(",
"address",
")",
":",
"if",
"isinstance",
"(",
"address",
",",
"tuple",
")",
":",
"check_host",
"(",
"address",
"[",
"0",
"]",
")",
"check_port",
"(",
"address",
"[",
"1",
"]",
")",
"elif",
"isinstance",
"(",
"address",
",",
"string_types",
")",
":",
"if",
"os",
".",
"name",
"!=",
"'posix'",
":",
"raise",
"ValueError",
"(",
"'Platform does not support UNIX domain sockets'",
")",
"if",
"not",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"address",
")",
"or",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"address",
")",
",",
"os",
".",
"W_OK",
")",
")",
":",
"raise",
"ValueError",
"(",
"'ADDRESS not a valid socket domain socket ({0})'",
".",
"format",
"(",
"address",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'ADDRESS is not a tuple, string, or character buffer '",
"'({0})'",
".",
"format",
"(",
"type",
"(",
"address",
")",
".",
"__name__",
")",
")"
] | Check if the format of the address is correct
Arguments:
address (tuple):
(``str``, ``int``) representing an IP address and port,
respectively
.. note::
alternatively a local ``address`` can be a ``str`` when working
with UNIX domain sockets, if supported by the platform
Raises:
ValueError:
raised when address has an incorrect format
Example:
>>> check_address(('127.0.0.1', 22)) | [
"Check",
"if",
"the",
"format",
"of",
"the",
"address",
"is",
"correct"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L88-L119 | train | 236,743 |
pahaz/sshtunnel | sshtunnel.py | check_addresses | def check_addresses(address_list, is_remote=False):
"""
Check if the format of the addresses is correct
Arguments:
address_list (list[tuple]):
Sequence of (``str``, ``int``) pairs, each representing an IP
address and port respectively
.. note::
when supported by the platform, one or more of the elements in
the list can be of type ``str``, representing a valid UNIX
domain socket
is_remote (boolean):
Whether or not the address list
Raises:
AssertionError:
raised when ``address_list`` contains an invalid element
ValueError:
raised when any address in the list has an incorrect format
Example:
>>> check_addresses([('127.0.0.1', 22), ('127.0.0.1', 2222)])
"""
assert all(isinstance(x, (tuple, string_types)) for x in address_list)
if (is_remote and any(isinstance(x, string_types) for x in address_list)):
raise AssertionError('UNIX domain sockets not allowed for remote'
'addresses')
for address in address_list:
check_address(address) | python | def check_addresses(address_list, is_remote=False):
"""
Check if the format of the addresses is correct
Arguments:
address_list (list[tuple]):
Sequence of (``str``, ``int``) pairs, each representing an IP
address and port respectively
.. note::
when supported by the platform, one or more of the elements in
the list can be of type ``str``, representing a valid UNIX
domain socket
is_remote (boolean):
Whether or not the address list
Raises:
AssertionError:
raised when ``address_list`` contains an invalid element
ValueError:
raised when any address in the list has an incorrect format
Example:
>>> check_addresses([('127.0.0.1', 22), ('127.0.0.1', 2222)])
"""
assert all(isinstance(x, (tuple, string_types)) for x in address_list)
if (is_remote and any(isinstance(x, string_types) for x in address_list)):
raise AssertionError('UNIX domain sockets not allowed for remote'
'addresses')
for address in address_list:
check_address(address) | [
"def",
"check_addresses",
"(",
"address_list",
",",
"is_remote",
"=",
"False",
")",
":",
"assert",
"all",
"(",
"isinstance",
"(",
"x",
",",
"(",
"tuple",
",",
"string_types",
")",
")",
"for",
"x",
"in",
"address_list",
")",
"if",
"(",
"is_remote",
"and",
"any",
"(",
"isinstance",
"(",
"x",
",",
"string_types",
")",
"for",
"x",
"in",
"address_list",
")",
")",
":",
"raise",
"AssertionError",
"(",
"'UNIX domain sockets not allowed for remote'",
"'addresses'",
")",
"for",
"address",
"in",
"address_list",
":",
"check_address",
"(",
"address",
")"
] | Check if the format of the addresses is correct
Arguments:
address_list (list[tuple]):
Sequence of (``str``, ``int``) pairs, each representing an IP
address and port respectively
.. note::
when supported by the platform, one or more of the elements in
the list can be of type ``str``, representing a valid UNIX
domain socket
is_remote (boolean):
Whether or not the address list
Raises:
AssertionError:
raised when ``address_list`` contains an invalid element
ValueError:
raised when any address in the list has an incorrect format
Example:
>>> check_addresses([('127.0.0.1', 22), ('127.0.0.1', 2222)]) | [
"Check",
"if",
"the",
"format",
"of",
"the",
"addresses",
"is",
"correct"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L122-L154 | train | 236,744 |
pahaz/sshtunnel | sshtunnel.py | create_logger | def create_logger(logger=None,
loglevel=None,
capture_warnings=True,
add_paramiko_handler=True):
"""
Attach or create a new logger and add a console handler if not present
Arguments:
logger (Optional[logging.Logger]):
:class:`logging.Logger` instance; a new one is created if this
argument is empty
loglevel (Optional[str or int]):
:class:`logging.Logger`'s level, either as a string (i.e.
``ERROR``) or in numeric format (10 == ``DEBUG``)
.. note:: a value of 1 == ``TRACE`` enables Tracing mode
capture_warnings (boolean):
Enable/disable capturing the events logged by the warnings module
into ``logger``'s handlers
Default: True
.. note:: ignored in python 2.6
add_paramiko_handler (boolean):
Whether or not add a console handler for ``paramiko.transport``'s
logger if no handler present
Default: True
Return:
:class:`logging.Logger`
"""
logger = logger or logging.getLogger(
'{0}.SSHTunnelForwarder'.format(__name__)
)
if not any(isinstance(x, logging.Handler) for x in logger.handlers):
logger.setLevel(loglevel or DEFAULT_LOGLEVEL)
console_handler = logging.StreamHandler()
_add_handler(logger,
handler=console_handler,
loglevel=loglevel or DEFAULT_LOGLEVEL)
if loglevel: # override if loglevel was set
logger.setLevel(loglevel)
for handler in logger.handlers:
handler.setLevel(loglevel)
if add_paramiko_handler:
_check_paramiko_handlers(logger=logger)
if capture_warnings and sys.version_info >= (2, 7):
logging.captureWarnings(True)
pywarnings = logging.getLogger('py.warnings')
pywarnings.handlers.extend(logger.handlers)
return logger | python | def create_logger(logger=None,
loglevel=None,
capture_warnings=True,
add_paramiko_handler=True):
"""
Attach or create a new logger and add a console handler if not present
Arguments:
logger (Optional[logging.Logger]):
:class:`logging.Logger` instance; a new one is created if this
argument is empty
loglevel (Optional[str or int]):
:class:`logging.Logger`'s level, either as a string (i.e.
``ERROR``) or in numeric format (10 == ``DEBUG``)
.. note:: a value of 1 == ``TRACE`` enables Tracing mode
capture_warnings (boolean):
Enable/disable capturing the events logged by the warnings module
into ``logger``'s handlers
Default: True
.. note:: ignored in python 2.6
add_paramiko_handler (boolean):
Whether or not add a console handler for ``paramiko.transport``'s
logger if no handler present
Default: True
Return:
:class:`logging.Logger`
"""
logger = logger or logging.getLogger(
'{0}.SSHTunnelForwarder'.format(__name__)
)
if not any(isinstance(x, logging.Handler) for x in logger.handlers):
logger.setLevel(loglevel or DEFAULT_LOGLEVEL)
console_handler = logging.StreamHandler()
_add_handler(logger,
handler=console_handler,
loglevel=loglevel or DEFAULT_LOGLEVEL)
if loglevel: # override if loglevel was set
logger.setLevel(loglevel)
for handler in logger.handlers:
handler.setLevel(loglevel)
if add_paramiko_handler:
_check_paramiko_handlers(logger=logger)
if capture_warnings and sys.version_info >= (2, 7):
logging.captureWarnings(True)
pywarnings = logging.getLogger('py.warnings')
pywarnings.handlers.extend(logger.handlers)
return logger | [
"def",
"create_logger",
"(",
"logger",
"=",
"None",
",",
"loglevel",
"=",
"None",
",",
"capture_warnings",
"=",
"True",
",",
"add_paramiko_handler",
"=",
"True",
")",
":",
"logger",
"=",
"logger",
"or",
"logging",
".",
"getLogger",
"(",
"'{0}.SSHTunnelForwarder'",
".",
"format",
"(",
"__name__",
")",
")",
"if",
"not",
"any",
"(",
"isinstance",
"(",
"x",
",",
"logging",
".",
"Handler",
")",
"for",
"x",
"in",
"logger",
".",
"handlers",
")",
":",
"logger",
".",
"setLevel",
"(",
"loglevel",
"or",
"DEFAULT_LOGLEVEL",
")",
"console_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"_add_handler",
"(",
"logger",
",",
"handler",
"=",
"console_handler",
",",
"loglevel",
"=",
"loglevel",
"or",
"DEFAULT_LOGLEVEL",
")",
"if",
"loglevel",
":",
"# override if loglevel was set",
"logger",
".",
"setLevel",
"(",
"loglevel",
")",
"for",
"handler",
"in",
"logger",
".",
"handlers",
":",
"handler",
".",
"setLevel",
"(",
"loglevel",
")",
"if",
"add_paramiko_handler",
":",
"_check_paramiko_handlers",
"(",
"logger",
"=",
"logger",
")",
"if",
"capture_warnings",
"and",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"7",
")",
":",
"logging",
".",
"captureWarnings",
"(",
"True",
")",
"pywarnings",
"=",
"logging",
".",
"getLogger",
"(",
"'py.warnings'",
")",
"pywarnings",
".",
"handlers",
".",
"extend",
"(",
"logger",
".",
"handlers",
")",
"return",
"logger"
] | Attach or create a new logger and add a console handler if not present
Arguments:
logger (Optional[logging.Logger]):
:class:`logging.Logger` instance; a new one is created if this
argument is empty
loglevel (Optional[str or int]):
:class:`logging.Logger`'s level, either as a string (i.e.
``ERROR``) or in numeric format (10 == ``DEBUG``)
.. note:: a value of 1 == ``TRACE`` enables Tracing mode
capture_warnings (boolean):
Enable/disable capturing the events logged by the warnings module
into ``logger``'s handlers
Default: True
.. note:: ignored in python 2.6
add_paramiko_handler (boolean):
Whether or not add a console handler for ``paramiko.transport``'s
logger if no handler present
Default: True
Return:
:class:`logging.Logger` | [
"Attach",
"or",
"create",
"a",
"new",
"logger",
"and",
"add",
"a",
"console",
"handler",
"if",
"not",
"present"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L157-L213 | train | 236,745 |
pahaz/sshtunnel | sshtunnel.py | _add_handler | def _add_handler(logger, handler=None, loglevel=None):
"""
Add a handler to an existing logging.Logger object
"""
handler.setLevel(loglevel or DEFAULT_LOGLEVEL)
if handler.level <= logging.DEBUG:
_fmt = '%(asctime)s| %(levelname)-4.3s|%(threadName)10.9s/' \
'%(lineno)04d@%(module)-10.9s| %(message)s'
handler.setFormatter(logging.Formatter(_fmt))
else:
handler.setFormatter(logging.Formatter(
'%(asctime)s| %(levelname)-8s| %(message)s'
))
logger.addHandler(handler) | python | def _add_handler(logger, handler=None, loglevel=None):
"""
Add a handler to an existing logging.Logger object
"""
handler.setLevel(loglevel or DEFAULT_LOGLEVEL)
if handler.level <= logging.DEBUG:
_fmt = '%(asctime)s| %(levelname)-4.3s|%(threadName)10.9s/' \
'%(lineno)04d@%(module)-10.9s| %(message)s'
handler.setFormatter(logging.Formatter(_fmt))
else:
handler.setFormatter(logging.Formatter(
'%(asctime)s| %(levelname)-8s| %(message)s'
))
logger.addHandler(handler) | [
"def",
"_add_handler",
"(",
"logger",
",",
"handler",
"=",
"None",
",",
"loglevel",
"=",
"None",
")",
":",
"handler",
".",
"setLevel",
"(",
"loglevel",
"or",
"DEFAULT_LOGLEVEL",
")",
"if",
"handler",
".",
"level",
"<=",
"logging",
".",
"DEBUG",
":",
"_fmt",
"=",
"'%(asctime)s| %(levelname)-4.3s|%(threadName)10.9s/'",
"'%(lineno)04d@%(module)-10.9s| %(message)s'",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"_fmt",
")",
")",
"else",
":",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s| %(levelname)-8s| %(message)s'",
")",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")"
] | Add a handler to an existing logging.Logger object | [
"Add",
"a",
"handler",
"to",
"an",
"existing",
"logging",
".",
"Logger",
"object"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L216-L229 | train | 236,746 |
pahaz/sshtunnel | sshtunnel.py | _check_paramiko_handlers | def _check_paramiko_handlers(logger=None):
"""
Add a console handler for paramiko.transport's logger if not present
"""
paramiko_logger = logging.getLogger('paramiko.transport')
if not paramiko_logger.handlers:
if logger:
paramiko_logger.handlers = logger.handlers
else:
console_handler = logging.StreamHandler()
console_handler.setFormatter(
logging.Formatter('%(asctime)s | %(levelname)-8s| PARAMIKO: '
'%(lineno)03d@%(module)-10s| %(message)s')
)
paramiko_logger.addHandler(console_handler) | python | def _check_paramiko_handlers(logger=None):
"""
Add a console handler for paramiko.transport's logger if not present
"""
paramiko_logger = logging.getLogger('paramiko.transport')
if not paramiko_logger.handlers:
if logger:
paramiko_logger.handlers = logger.handlers
else:
console_handler = logging.StreamHandler()
console_handler.setFormatter(
logging.Formatter('%(asctime)s | %(levelname)-8s| PARAMIKO: '
'%(lineno)03d@%(module)-10s| %(message)s')
)
paramiko_logger.addHandler(console_handler) | [
"def",
"_check_paramiko_handlers",
"(",
"logger",
"=",
"None",
")",
":",
"paramiko_logger",
"=",
"logging",
".",
"getLogger",
"(",
"'paramiko.transport'",
")",
"if",
"not",
"paramiko_logger",
".",
"handlers",
":",
"if",
"logger",
":",
"paramiko_logger",
".",
"handlers",
"=",
"logger",
".",
"handlers",
"else",
":",
"console_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"console_handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s | %(levelname)-8s| PARAMIKO: '",
"'%(lineno)03d@%(module)-10s| %(message)s'",
")",
")",
"paramiko_logger",
".",
"addHandler",
"(",
"console_handler",
")"
] | Add a console handler for paramiko.transport's logger if not present | [
"Add",
"a",
"console",
"handler",
"for",
"paramiko",
".",
"transport",
"s",
"logger",
"if",
"not",
"present"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L232-L246 | train | 236,747 |
pahaz/sshtunnel | sshtunnel.py | _remove_none_values | def _remove_none_values(dictionary):
""" Remove dictionary keys whose value is None """
return list(map(dictionary.pop,
[i for i in dictionary if dictionary[i] is None])) | python | def _remove_none_values(dictionary):
""" Remove dictionary keys whose value is None """
return list(map(dictionary.pop,
[i for i in dictionary if dictionary[i] is None])) | [
"def",
"_remove_none_values",
"(",
"dictionary",
")",
":",
"return",
"list",
"(",
"map",
"(",
"dictionary",
".",
"pop",
",",
"[",
"i",
"for",
"i",
"in",
"dictionary",
"if",
"dictionary",
"[",
"i",
"]",
"is",
"None",
"]",
")",
")"
] | Remove dictionary keys whose value is None | [
"Remove",
"dictionary",
"keys",
"whose",
"value",
"is",
"None"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L263-L266 | train | 236,748 |
pahaz/sshtunnel | sshtunnel.py | _cli_main | def _cli_main(args=None):
""" Pass input arguments to open_tunnel
Mandatory: ssh_address, -R (remote bind address list)
Optional:
-U (username) we may gather it from SSH_CONFIG_FILE or current username
-p (server_port), defaults to 22
-P (password)
-L (local_bind_address), default to 0.0.0.0:22
-k (ssh_host_key)
-K (private_key_file), may be gathered from SSH_CONFIG_FILE
-S (private_key_password)
-t (threaded), allow concurrent connections over tunnels
-v (verbose), up to 3 (-vvv) to raise loglevel from ERROR to DEBUG
-V (version)
-x (proxy), ProxyCommand's IP:PORT, may be gathered from config file
-c (ssh_config), ssh configuration file (defaults to SSH_CONFIG_FILE)
-z (compress)
-n (noagent), disable looking for keys from an Agent
-d (host_pkey_directories), look for keys on these folders
"""
arguments = _parse_arguments(args)
# Remove all "None" input values
_remove_none_values(arguments)
verbosity = min(arguments.pop('verbose'), 4)
levels = [logging.ERROR,
logging.WARNING,
logging.INFO,
logging.DEBUG,
TRACE_LEVEL]
arguments.setdefault('debug_level', levels[verbosity])
with open_tunnel(**arguments) as tunnel:
if tunnel.is_alive:
input_('''
Press <Ctrl-C> or <Enter> to stop!
''') | python | def _cli_main(args=None):
""" Pass input arguments to open_tunnel
Mandatory: ssh_address, -R (remote bind address list)
Optional:
-U (username) we may gather it from SSH_CONFIG_FILE or current username
-p (server_port), defaults to 22
-P (password)
-L (local_bind_address), default to 0.0.0.0:22
-k (ssh_host_key)
-K (private_key_file), may be gathered from SSH_CONFIG_FILE
-S (private_key_password)
-t (threaded), allow concurrent connections over tunnels
-v (verbose), up to 3 (-vvv) to raise loglevel from ERROR to DEBUG
-V (version)
-x (proxy), ProxyCommand's IP:PORT, may be gathered from config file
-c (ssh_config), ssh configuration file (defaults to SSH_CONFIG_FILE)
-z (compress)
-n (noagent), disable looking for keys from an Agent
-d (host_pkey_directories), look for keys on these folders
"""
arguments = _parse_arguments(args)
# Remove all "None" input values
_remove_none_values(arguments)
verbosity = min(arguments.pop('verbose'), 4)
levels = [logging.ERROR,
logging.WARNING,
logging.INFO,
logging.DEBUG,
TRACE_LEVEL]
arguments.setdefault('debug_level', levels[verbosity])
with open_tunnel(**arguments) as tunnel:
if tunnel.is_alive:
input_('''
Press <Ctrl-C> or <Enter> to stop!
''') | [
"def",
"_cli_main",
"(",
"args",
"=",
"None",
")",
":",
"arguments",
"=",
"_parse_arguments",
"(",
"args",
")",
"# Remove all \"None\" input values",
"_remove_none_values",
"(",
"arguments",
")",
"verbosity",
"=",
"min",
"(",
"arguments",
".",
"pop",
"(",
"'verbose'",
")",
",",
"4",
")",
"levels",
"=",
"[",
"logging",
".",
"ERROR",
",",
"logging",
".",
"WARNING",
",",
"logging",
".",
"INFO",
",",
"logging",
".",
"DEBUG",
",",
"TRACE_LEVEL",
"]",
"arguments",
".",
"setdefault",
"(",
"'debug_level'",
",",
"levels",
"[",
"verbosity",
"]",
")",
"with",
"open_tunnel",
"(",
"*",
"*",
"arguments",
")",
"as",
"tunnel",
":",
"if",
"tunnel",
".",
"is_alive",
":",
"input_",
"(",
"'''\n\n Press <Ctrl-C> or <Enter> to stop!\n\n '''",
")"
] | Pass input arguments to open_tunnel
Mandatory: ssh_address, -R (remote bind address list)
Optional:
-U (username) we may gather it from SSH_CONFIG_FILE or current username
-p (server_port), defaults to 22
-P (password)
-L (local_bind_address), default to 0.0.0.0:22
-k (ssh_host_key)
-K (private_key_file), may be gathered from SSH_CONFIG_FILE
-S (private_key_password)
-t (threaded), allow concurrent connections over tunnels
-v (verbose), up to 3 (-vvv) to raise loglevel from ERROR to DEBUG
-V (version)
-x (proxy), ProxyCommand's IP:PORT, may be gathered from config file
-c (ssh_config), ssh configuration file (defaults to SSH_CONFIG_FILE)
-z (compress)
-n (noagent), disable looking for keys from an Agent
-d (host_pkey_directories), look for keys on these folders | [
"Pass",
"input",
"arguments",
"to",
"open_tunnel"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1811-L1849 | train | 236,749 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._make_ssh_forward_handler_class | def _make_ssh_forward_handler_class(self, remote_address_):
"""
Make SSH Handler class
"""
class Handler(_ForwardHandler):
remote_address = remote_address_
ssh_transport = self._transport
logger = self.logger
return Handler | python | def _make_ssh_forward_handler_class(self, remote_address_):
"""
Make SSH Handler class
"""
class Handler(_ForwardHandler):
remote_address = remote_address_
ssh_transport = self._transport
logger = self.logger
return Handler | [
"def",
"_make_ssh_forward_handler_class",
"(",
"self",
",",
"remote_address_",
")",
":",
"class",
"Handler",
"(",
"_ForwardHandler",
")",
":",
"remote_address",
"=",
"remote_address_",
"ssh_transport",
"=",
"self",
".",
"_transport",
"logger",
"=",
"self",
".",
"logger",
"return",
"Handler"
] | Make SSH Handler class | [
"Make",
"SSH",
"Handler",
"class"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L756-L764 | train | 236,750 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._make_ssh_forward_server | def _make_ssh_forward_server(self, remote_address, local_bind_address):
"""
Make SSH forward proxy Server class
"""
_Handler = self._make_ssh_forward_handler_class(remote_address)
try:
if isinstance(local_bind_address, string_types):
forward_maker_class = self._make_unix_ssh_forward_server_class
else:
forward_maker_class = self._make_ssh_forward_server_class
_Server = forward_maker_class(remote_address)
ssh_forward_server = _Server(
local_bind_address,
_Handler,
logger=self.logger,
)
if ssh_forward_server:
ssh_forward_server.daemon_threads = self.daemon_forward_servers
self._server_list.append(ssh_forward_server)
self.tunnel_is_up[ssh_forward_server.server_address] = False
else:
self._raise(
BaseSSHTunnelForwarderError,
'Problem setting up ssh {0} <> {1} forwarder. You can '
'suppress this exception by using the `mute_exceptions`'
'argument'.format(address_to_str(local_bind_address),
address_to_str(remote_address))
)
except IOError:
self._raise(
BaseSSHTunnelForwarderError,
"Couldn't open tunnel {0} <> {1} might be in use or "
"destination not reachable".format(
address_to_str(local_bind_address),
address_to_str(remote_address)
)
) | python | def _make_ssh_forward_server(self, remote_address, local_bind_address):
"""
Make SSH forward proxy Server class
"""
_Handler = self._make_ssh_forward_handler_class(remote_address)
try:
if isinstance(local_bind_address, string_types):
forward_maker_class = self._make_unix_ssh_forward_server_class
else:
forward_maker_class = self._make_ssh_forward_server_class
_Server = forward_maker_class(remote_address)
ssh_forward_server = _Server(
local_bind_address,
_Handler,
logger=self.logger,
)
if ssh_forward_server:
ssh_forward_server.daemon_threads = self.daemon_forward_servers
self._server_list.append(ssh_forward_server)
self.tunnel_is_up[ssh_forward_server.server_address] = False
else:
self._raise(
BaseSSHTunnelForwarderError,
'Problem setting up ssh {0} <> {1} forwarder. You can '
'suppress this exception by using the `mute_exceptions`'
'argument'.format(address_to_str(local_bind_address),
address_to_str(remote_address))
)
except IOError:
self._raise(
BaseSSHTunnelForwarderError,
"Couldn't open tunnel {0} <> {1} might be in use or "
"destination not reachable".format(
address_to_str(local_bind_address),
address_to_str(remote_address)
)
) | [
"def",
"_make_ssh_forward_server",
"(",
"self",
",",
"remote_address",
",",
"local_bind_address",
")",
":",
"_Handler",
"=",
"self",
".",
"_make_ssh_forward_handler_class",
"(",
"remote_address",
")",
"try",
":",
"if",
"isinstance",
"(",
"local_bind_address",
",",
"string_types",
")",
":",
"forward_maker_class",
"=",
"self",
".",
"_make_unix_ssh_forward_server_class",
"else",
":",
"forward_maker_class",
"=",
"self",
".",
"_make_ssh_forward_server_class",
"_Server",
"=",
"forward_maker_class",
"(",
"remote_address",
")",
"ssh_forward_server",
"=",
"_Server",
"(",
"local_bind_address",
",",
"_Handler",
",",
"logger",
"=",
"self",
".",
"logger",
",",
")",
"if",
"ssh_forward_server",
":",
"ssh_forward_server",
".",
"daemon_threads",
"=",
"self",
".",
"daemon_forward_servers",
"self",
".",
"_server_list",
".",
"append",
"(",
"ssh_forward_server",
")",
"self",
".",
"tunnel_is_up",
"[",
"ssh_forward_server",
".",
"server_address",
"]",
"=",
"False",
"else",
":",
"self",
".",
"_raise",
"(",
"BaseSSHTunnelForwarderError",
",",
"'Problem setting up ssh {0} <> {1} forwarder. You can '",
"'suppress this exception by using the `mute_exceptions`'",
"'argument'",
".",
"format",
"(",
"address_to_str",
"(",
"local_bind_address",
")",
",",
"address_to_str",
"(",
"remote_address",
")",
")",
")",
"except",
"IOError",
":",
"self",
".",
"_raise",
"(",
"BaseSSHTunnelForwarderError",
",",
"\"Couldn't open tunnel {0} <> {1} might be in use or \"",
"\"destination not reachable\"",
".",
"format",
"(",
"address_to_str",
"(",
"local_bind_address",
")",
",",
"address_to_str",
"(",
"remote_address",
")",
")",
")"
] | Make SSH forward proxy Server class | [
"Make",
"SSH",
"forward",
"proxy",
"Server",
"class"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L773-L810 | train | 236,751 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.get_agent_keys | def get_agent_keys(logger=None):
""" Load public keys from any available SSH agent
Arguments:
logger (Optional[logging.Logger])
Return:
list
"""
paramiko_agent = paramiko.Agent()
agent_keys = paramiko_agent.get_keys()
if logger:
logger.info('{0} keys loaded from agent'.format(len(agent_keys)))
return list(agent_keys) | python | def get_agent_keys(logger=None):
""" Load public keys from any available SSH agent
Arguments:
logger (Optional[logging.Logger])
Return:
list
"""
paramiko_agent = paramiko.Agent()
agent_keys = paramiko_agent.get_keys()
if logger:
logger.info('{0} keys loaded from agent'.format(len(agent_keys)))
return list(agent_keys) | [
"def",
"get_agent_keys",
"(",
"logger",
"=",
"None",
")",
":",
"paramiko_agent",
"=",
"paramiko",
".",
"Agent",
"(",
")",
"agent_keys",
"=",
"paramiko_agent",
".",
"get_keys",
"(",
")",
"if",
"logger",
":",
"logger",
".",
"info",
"(",
"'{0} keys loaded from agent'",
".",
"format",
"(",
"len",
"(",
"agent_keys",
")",
")",
")",
"return",
"list",
"(",
"agent_keys",
")"
] | Load public keys from any available SSH agent
Arguments:
logger (Optional[logging.Logger])
Return:
list | [
"Load",
"public",
"keys",
"from",
"any",
"available",
"SSH",
"agent"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L981-L994 | train | 236,752 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.get_keys | def get_keys(logger=None, host_pkey_directories=None, allow_agent=False):
"""
Load public keys from any available SSH agent or local
.ssh directory.
Arguments:
logger (Optional[logging.Logger])
host_pkey_directories (Optional[list[str]]):
List of local directories where host SSH pkeys in the format
"id_*" are searched. For example, ['~/.ssh']
.. versionadded:: 0.1.0
allow_agent (Optional[boolean]):
Whether or not load keys from agent
Default: False
Return:
list
"""
keys = SSHTunnelForwarder.get_agent_keys(logger=logger) \
if allow_agent else []
if host_pkey_directories is not None:
paramiko_key_types = {'rsa': paramiko.RSAKey,
'dsa': paramiko.DSSKey,
'ecdsa': paramiko.ECDSAKey,
'ed25519': paramiko.Ed25519Key}
for directory in host_pkey_directories or [DEFAULT_SSH_DIRECTORY]:
for keytype in paramiko_key_types.keys():
ssh_pkey_expanded = os.path.expanduser(
os.path.join(directory, 'id_{}'.format(keytype))
)
if os.path.isfile(ssh_pkey_expanded):
ssh_pkey = SSHTunnelForwarder.read_private_key_file(
pkey_file=ssh_pkey_expanded,
logger=logger,
key_type=paramiko_key_types[keytype]
)
if ssh_pkey:
keys.append(ssh_pkey)
if logger:
logger.info('{0} keys loaded from host directory'.format(
len(keys))
)
return keys | python | def get_keys(logger=None, host_pkey_directories=None, allow_agent=False):
"""
Load public keys from any available SSH agent or local
.ssh directory.
Arguments:
logger (Optional[logging.Logger])
host_pkey_directories (Optional[list[str]]):
List of local directories where host SSH pkeys in the format
"id_*" are searched. For example, ['~/.ssh']
.. versionadded:: 0.1.0
allow_agent (Optional[boolean]):
Whether or not load keys from agent
Default: False
Return:
list
"""
keys = SSHTunnelForwarder.get_agent_keys(logger=logger) \
if allow_agent else []
if host_pkey_directories is not None:
paramiko_key_types = {'rsa': paramiko.RSAKey,
'dsa': paramiko.DSSKey,
'ecdsa': paramiko.ECDSAKey,
'ed25519': paramiko.Ed25519Key}
for directory in host_pkey_directories or [DEFAULT_SSH_DIRECTORY]:
for keytype in paramiko_key_types.keys():
ssh_pkey_expanded = os.path.expanduser(
os.path.join(directory, 'id_{}'.format(keytype))
)
if os.path.isfile(ssh_pkey_expanded):
ssh_pkey = SSHTunnelForwarder.read_private_key_file(
pkey_file=ssh_pkey_expanded,
logger=logger,
key_type=paramiko_key_types[keytype]
)
if ssh_pkey:
keys.append(ssh_pkey)
if logger:
logger.info('{0} keys loaded from host directory'.format(
len(keys))
)
return keys | [
"def",
"get_keys",
"(",
"logger",
"=",
"None",
",",
"host_pkey_directories",
"=",
"None",
",",
"allow_agent",
"=",
"False",
")",
":",
"keys",
"=",
"SSHTunnelForwarder",
".",
"get_agent_keys",
"(",
"logger",
"=",
"logger",
")",
"if",
"allow_agent",
"else",
"[",
"]",
"if",
"host_pkey_directories",
"is",
"not",
"None",
":",
"paramiko_key_types",
"=",
"{",
"'rsa'",
":",
"paramiko",
".",
"RSAKey",
",",
"'dsa'",
":",
"paramiko",
".",
"DSSKey",
",",
"'ecdsa'",
":",
"paramiko",
".",
"ECDSAKey",
",",
"'ed25519'",
":",
"paramiko",
".",
"Ed25519Key",
"}",
"for",
"directory",
"in",
"host_pkey_directories",
"or",
"[",
"DEFAULT_SSH_DIRECTORY",
"]",
":",
"for",
"keytype",
"in",
"paramiko_key_types",
".",
"keys",
"(",
")",
":",
"ssh_pkey_expanded",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'id_{}'",
".",
"format",
"(",
"keytype",
")",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"ssh_pkey_expanded",
")",
":",
"ssh_pkey",
"=",
"SSHTunnelForwarder",
".",
"read_private_key_file",
"(",
"pkey_file",
"=",
"ssh_pkey_expanded",
",",
"logger",
"=",
"logger",
",",
"key_type",
"=",
"paramiko_key_types",
"[",
"keytype",
"]",
")",
"if",
"ssh_pkey",
":",
"keys",
".",
"append",
"(",
"ssh_pkey",
")",
"if",
"logger",
":",
"logger",
".",
"info",
"(",
"'{0} keys loaded from host directory'",
".",
"format",
"(",
"len",
"(",
"keys",
")",
")",
")",
"return",
"keys"
] | Load public keys from any available SSH agent or local
.ssh directory.
Arguments:
logger (Optional[logging.Logger])
host_pkey_directories (Optional[list[str]]):
List of local directories where host SSH pkeys in the format
"id_*" are searched. For example, ['~/.ssh']
.. versionadded:: 0.1.0
allow_agent (Optional[boolean]):
Whether or not load keys from agent
Default: False
Return:
list | [
"Load",
"public",
"keys",
"from",
"any",
"available",
"SSH",
"agent",
"or",
"local",
".",
"ssh",
"directory",
"."
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L997-L1045 | train | 236,753 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._get_transport | def _get_transport(self):
""" Return the SSH transport to the remote gateway """
if self.ssh_proxy:
if isinstance(self.ssh_proxy, paramiko.proxy.ProxyCommand):
proxy_repr = repr(self.ssh_proxy.cmd[1])
else:
proxy_repr = repr(self.ssh_proxy)
self.logger.debug('Connecting via proxy: {0}'.format(proxy_repr))
_socket = self.ssh_proxy
else:
_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if isinstance(_socket, socket.socket):
_socket.settimeout(SSH_TIMEOUT)
_socket.connect((self.ssh_host, self.ssh_port))
transport = paramiko.Transport(_socket)
transport.set_keepalive(self.set_keepalive)
transport.use_compression(compress=self.compression)
transport.daemon = self.daemon_transport
return transport | python | def _get_transport(self):
""" Return the SSH transport to the remote gateway """
if self.ssh_proxy:
if isinstance(self.ssh_proxy, paramiko.proxy.ProxyCommand):
proxy_repr = repr(self.ssh_proxy.cmd[1])
else:
proxy_repr = repr(self.ssh_proxy)
self.logger.debug('Connecting via proxy: {0}'.format(proxy_repr))
_socket = self.ssh_proxy
else:
_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if isinstance(_socket, socket.socket):
_socket.settimeout(SSH_TIMEOUT)
_socket.connect((self.ssh_host, self.ssh_port))
transport = paramiko.Transport(_socket)
transport.set_keepalive(self.set_keepalive)
transport.use_compression(compress=self.compression)
transport.daemon = self.daemon_transport
return transport | [
"def",
"_get_transport",
"(",
"self",
")",
":",
"if",
"self",
".",
"ssh_proxy",
":",
"if",
"isinstance",
"(",
"self",
".",
"ssh_proxy",
",",
"paramiko",
".",
"proxy",
".",
"ProxyCommand",
")",
":",
"proxy_repr",
"=",
"repr",
"(",
"self",
".",
"ssh_proxy",
".",
"cmd",
"[",
"1",
"]",
")",
"else",
":",
"proxy_repr",
"=",
"repr",
"(",
"self",
".",
"ssh_proxy",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Connecting via proxy: {0}'",
".",
"format",
"(",
"proxy_repr",
")",
")",
"_socket",
"=",
"self",
".",
"ssh_proxy",
"else",
":",
"_socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"if",
"isinstance",
"(",
"_socket",
",",
"socket",
".",
"socket",
")",
":",
"_socket",
".",
"settimeout",
"(",
"SSH_TIMEOUT",
")",
"_socket",
".",
"connect",
"(",
"(",
"self",
".",
"ssh_host",
",",
"self",
".",
"ssh_port",
")",
")",
"transport",
"=",
"paramiko",
".",
"Transport",
"(",
"_socket",
")",
"transport",
".",
"set_keepalive",
"(",
"self",
".",
"set_keepalive",
")",
"transport",
".",
"use_compression",
"(",
"compress",
"=",
"self",
".",
"compression",
")",
"transport",
".",
"daemon",
"=",
"self",
".",
"daemon_transport",
"return",
"transport"
] | Return the SSH transport to the remote gateway | [
"Return",
"the",
"SSH",
"transport",
"to",
"the",
"remote",
"gateway"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1105-L1124 | train | 236,754 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._create_tunnels | def _create_tunnels(self):
"""
Create SSH tunnels on top of a transport to the remote gateway
"""
if not self.is_active:
try:
self._connect_to_gateway()
except socket.gaierror: # raised by paramiko.Transport
msg = 'Could not resolve IP address for {0}, aborting!' \
.format(self.ssh_host)
self.logger.error(msg)
return
except (paramiko.SSHException, socket.error) as e:
template = 'Could not connect to gateway {0}:{1} : {2}'
msg = template.format(self.ssh_host, self.ssh_port, e.args[0])
self.logger.error(msg)
return
for (rem, loc) in zip(self._remote_binds, self._local_binds):
try:
self._make_ssh_forward_server(rem, loc)
except BaseSSHTunnelForwarderError as e:
msg = 'Problem setting SSH Forwarder up: {0}'.format(e.value)
self.logger.error(msg) | python | def _create_tunnels(self):
"""
Create SSH tunnels on top of a transport to the remote gateway
"""
if not self.is_active:
try:
self._connect_to_gateway()
except socket.gaierror: # raised by paramiko.Transport
msg = 'Could not resolve IP address for {0}, aborting!' \
.format(self.ssh_host)
self.logger.error(msg)
return
except (paramiko.SSHException, socket.error) as e:
template = 'Could not connect to gateway {0}:{1} : {2}'
msg = template.format(self.ssh_host, self.ssh_port, e.args[0])
self.logger.error(msg)
return
for (rem, loc) in zip(self._remote_binds, self._local_binds):
try:
self._make_ssh_forward_server(rem, loc)
except BaseSSHTunnelForwarderError as e:
msg = 'Problem setting SSH Forwarder up: {0}'.format(e.value)
self.logger.error(msg) | [
"def",
"_create_tunnels",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_active",
":",
"try",
":",
"self",
".",
"_connect_to_gateway",
"(",
")",
"except",
"socket",
".",
"gaierror",
":",
"# raised by paramiko.Transport",
"msg",
"=",
"'Could not resolve IP address for {0}, aborting!'",
".",
"format",
"(",
"self",
".",
"ssh_host",
")",
"self",
".",
"logger",
".",
"error",
"(",
"msg",
")",
"return",
"except",
"(",
"paramiko",
".",
"SSHException",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"template",
"=",
"'Could not connect to gateway {0}:{1} : {2}'",
"msg",
"=",
"template",
".",
"format",
"(",
"self",
".",
"ssh_host",
",",
"self",
".",
"ssh_port",
",",
"e",
".",
"args",
"[",
"0",
"]",
")",
"self",
".",
"logger",
".",
"error",
"(",
"msg",
")",
"return",
"for",
"(",
"rem",
",",
"loc",
")",
"in",
"zip",
"(",
"self",
".",
"_remote_binds",
",",
"self",
".",
"_local_binds",
")",
":",
"try",
":",
"self",
".",
"_make_ssh_forward_server",
"(",
"rem",
",",
"loc",
")",
"except",
"BaseSSHTunnelForwarderError",
"as",
"e",
":",
"msg",
"=",
"'Problem setting SSH Forwarder up: {0}'",
".",
"format",
"(",
"e",
".",
"value",
")",
"self",
".",
"logger",
".",
"error",
"(",
"msg",
")"
] | Create SSH tunnels on top of a transport to the remote gateway | [
"Create",
"SSH",
"tunnels",
"on",
"top",
"of",
"a",
"transport",
"to",
"the",
"remote",
"gateway"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1126-L1148 | train | 236,755 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._process_deprecated | def _process_deprecated(attrib, deprecated_attrib, kwargs):
"""
Processes optional deprecate arguments
"""
if deprecated_attrib not in DEPRECATIONS:
raise ValueError('{0} not included in deprecations list'
.format(deprecated_attrib))
if deprecated_attrib in kwargs:
warnings.warn("'{0}' is DEPRECATED use '{1}' instead"
.format(deprecated_attrib,
DEPRECATIONS[deprecated_attrib]),
DeprecationWarning)
if attrib:
raise ValueError("You can't use both '{0}' and '{1}'. "
"Please only use one of them"
.format(deprecated_attrib,
DEPRECATIONS[deprecated_attrib]))
else:
return kwargs.pop(deprecated_attrib)
return attrib | python | def _process_deprecated(attrib, deprecated_attrib, kwargs):
"""
Processes optional deprecate arguments
"""
if deprecated_attrib not in DEPRECATIONS:
raise ValueError('{0} not included in deprecations list'
.format(deprecated_attrib))
if deprecated_attrib in kwargs:
warnings.warn("'{0}' is DEPRECATED use '{1}' instead"
.format(deprecated_attrib,
DEPRECATIONS[deprecated_attrib]),
DeprecationWarning)
if attrib:
raise ValueError("You can't use both '{0}' and '{1}'. "
"Please only use one of them"
.format(deprecated_attrib,
DEPRECATIONS[deprecated_attrib]))
else:
return kwargs.pop(deprecated_attrib)
return attrib | [
"def",
"_process_deprecated",
"(",
"attrib",
",",
"deprecated_attrib",
",",
"kwargs",
")",
":",
"if",
"deprecated_attrib",
"not",
"in",
"DEPRECATIONS",
":",
"raise",
"ValueError",
"(",
"'{0} not included in deprecations list'",
".",
"format",
"(",
"deprecated_attrib",
")",
")",
"if",
"deprecated_attrib",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"'{0}' is DEPRECATED use '{1}' instead\"",
".",
"format",
"(",
"deprecated_attrib",
",",
"DEPRECATIONS",
"[",
"deprecated_attrib",
"]",
")",
",",
"DeprecationWarning",
")",
"if",
"attrib",
":",
"raise",
"ValueError",
"(",
"\"You can't use both '{0}' and '{1}'. \"",
"\"Please only use one of them\"",
".",
"format",
"(",
"deprecated_attrib",
",",
"DEPRECATIONS",
"[",
"deprecated_attrib",
"]",
")",
")",
"else",
":",
"return",
"kwargs",
".",
"pop",
"(",
"deprecated_attrib",
")",
"return",
"attrib"
] | Processes optional deprecate arguments | [
"Processes",
"optional",
"deprecate",
"arguments"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1176-L1195 | train | 236,756 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.read_private_key_file | def read_private_key_file(pkey_file,
pkey_password=None,
key_type=None,
logger=None):
"""
Get SSH Public key from a private key file, given an optional password
Arguments:
pkey_file (str):
File containing a private key (RSA, DSS or ECDSA)
Keyword Arguments:
pkey_password (Optional[str]):
Password to decrypt the private key
logger (Optional[logging.Logger])
Return:
paramiko.Pkey
"""
ssh_pkey = None
for pkey_class in (key_type,) if key_type else (
paramiko.RSAKey,
paramiko.DSSKey,
paramiko.ECDSAKey,
paramiko.Ed25519Key
):
try:
ssh_pkey = pkey_class.from_private_key_file(
pkey_file,
password=pkey_password
)
if logger:
logger.debug('Private key file ({0}, {1}) successfully '
'loaded'.format(pkey_file, pkey_class))
break
except paramiko.PasswordRequiredException:
if logger:
logger.error('Password is required for key {0}'
.format(pkey_file))
break
except paramiko.SSHException:
if logger:
logger.debug('Private key file ({0}) could not be loaded '
'as type {1} or bad password'
.format(pkey_file, pkey_class))
return ssh_pkey | python | def read_private_key_file(pkey_file,
pkey_password=None,
key_type=None,
logger=None):
"""
Get SSH Public key from a private key file, given an optional password
Arguments:
pkey_file (str):
File containing a private key (RSA, DSS or ECDSA)
Keyword Arguments:
pkey_password (Optional[str]):
Password to decrypt the private key
logger (Optional[logging.Logger])
Return:
paramiko.Pkey
"""
ssh_pkey = None
for pkey_class in (key_type,) if key_type else (
paramiko.RSAKey,
paramiko.DSSKey,
paramiko.ECDSAKey,
paramiko.Ed25519Key
):
try:
ssh_pkey = pkey_class.from_private_key_file(
pkey_file,
password=pkey_password
)
if logger:
logger.debug('Private key file ({0}, {1}) successfully '
'loaded'.format(pkey_file, pkey_class))
break
except paramiko.PasswordRequiredException:
if logger:
logger.error('Password is required for key {0}'
.format(pkey_file))
break
except paramiko.SSHException:
if logger:
logger.debug('Private key file ({0}) could not be loaded '
'as type {1} or bad password'
.format(pkey_file, pkey_class))
return ssh_pkey | [
"def",
"read_private_key_file",
"(",
"pkey_file",
",",
"pkey_password",
"=",
"None",
",",
"key_type",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"ssh_pkey",
"=",
"None",
"for",
"pkey_class",
"in",
"(",
"key_type",
",",
")",
"if",
"key_type",
"else",
"(",
"paramiko",
".",
"RSAKey",
",",
"paramiko",
".",
"DSSKey",
",",
"paramiko",
".",
"ECDSAKey",
",",
"paramiko",
".",
"Ed25519Key",
")",
":",
"try",
":",
"ssh_pkey",
"=",
"pkey_class",
".",
"from_private_key_file",
"(",
"pkey_file",
",",
"password",
"=",
"pkey_password",
")",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'Private key file ({0}, {1}) successfully '",
"'loaded'",
".",
"format",
"(",
"pkey_file",
",",
"pkey_class",
")",
")",
"break",
"except",
"paramiko",
".",
"PasswordRequiredException",
":",
"if",
"logger",
":",
"logger",
".",
"error",
"(",
"'Password is required for key {0}'",
".",
"format",
"(",
"pkey_file",
")",
")",
"break",
"except",
"paramiko",
".",
"SSHException",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'Private key file ({0}) could not be loaded '",
"'as type {1} or bad password'",
".",
"format",
"(",
"pkey_file",
",",
"pkey_class",
")",
")",
"return",
"ssh_pkey"
] | Get SSH Public key from a private key file, given an optional password
Arguments:
pkey_file (str):
File containing a private key (RSA, DSS or ECDSA)
Keyword Arguments:
pkey_password (Optional[str]):
Password to decrypt the private key
logger (Optional[logging.Logger])
Return:
paramiko.Pkey | [
"Get",
"SSH",
"Public",
"key",
"from",
"a",
"private",
"key",
"file",
"given",
"an",
"optional",
"password"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1198-L1241 | train | 236,757 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._check_tunnel | def _check_tunnel(self, _srv):
""" Check if tunnel is already established """
if self.skip_tunnel_checkup:
self.tunnel_is_up[_srv.local_address] = True
return
self.logger.info('Checking tunnel to: {0}'.format(_srv.remote_address))
if isinstance(_srv.local_address, string_types): # UNIX stream
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TUNNEL_TIMEOUT)
try:
# Windows raises WinError 10049 if trying to connect to 0.0.0.0
connect_to = ('127.0.0.1', _srv.local_port) \
if _srv.local_host == '0.0.0.0' else _srv.local_address
s.connect(connect_to)
self.tunnel_is_up[_srv.local_address] = _srv.tunnel_ok.get(
timeout=TUNNEL_TIMEOUT * 1.1
)
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
except socket.error:
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = False
except queue.Empty:
self.logger.debug(
'Tunnel to {0} is UP'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = True
finally:
s.close() | python | def _check_tunnel(self, _srv):
""" Check if tunnel is already established """
if self.skip_tunnel_checkup:
self.tunnel_is_up[_srv.local_address] = True
return
self.logger.info('Checking tunnel to: {0}'.format(_srv.remote_address))
if isinstance(_srv.local_address, string_types): # UNIX stream
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TUNNEL_TIMEOUT)
try:
# Windows raises WinError 10049 if trying to connect to 0.0.0.0
connect_to = ('127.0.0.1', _srv.local_port) \
if _srv.local_host == '0.0.0.0' else _srv.local_address
s.connect(connect_to)
self.tunnel_is_up[_srv.local_address] = _srv.tunnel_ok.get(
timeout=TUNNEL_TIMEOUT * 1.1
)
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
except socket.error:
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = False
except queue.Empty:
self.logger.debug(
'Tunnel to {0} is UP'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = True
finally:
s.close() | [
"def",
"_check_tunnel",
"(",
"self",
",",
"_srv",
")",
":",
"if",
"self",
".",
"skip_tunnel_checkup",
":",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"True",
"return",
"self",
".",
"logger",
".",
"info",
"(",
"'Checking tunnel to: {0}'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"if",
"isinstance",
"(",
"_srv",
".",
"local_address",
",",
"string_types",
")",
":",
"# UNIX stream",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",
"socket",
".",
"SOCK_STREAM",
")",
"else",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s",
".",
"settimeout",
"(",
"TUNNEL_TIMEOUT",
")",
"try",
":",
"# Windows raises WinError 10049 if trying to connect to 0.0.0.0",
"connect_to",
"=",
"(",
"'127.0.0.1'",
",",
"_srv",
".",
"local_port",
")",
"if",
"_srv",
".",
"local_host",
"==",
"'0.0.0.0'",
"else",
"_srv",
".",
"local_address",
"s",
".",
"connect",
"(",
"connect_to",
")",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"_srv",
".",
"tunnel_ok",
".",
"get",
"(",
"timeout",
"=",
"TUNNEL_TIMEOUT",
"*",
"1.1",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Tunnel to {0} is DOWN'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"except",
"socket",
".",
"error",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Tunnel to {0} is DOWN'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"False",
"except",
"queue",
".",
"Empty",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Tunnel to {0} is UP'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"True",
"finally",
":",
"s",
".",
"close",
"(",
")"
] | Check if tunnel is already established | [
"Check",
"if",
"tunnel",
"is",
"already",
"established"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1243-L1277 | train | 236,758 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.start | def start(self):
""" Start the SSH tunnels """
if self.is_alive:
self.logger.warning('Already started!')
return
self._create_tunnels()
if not self.is_active:
self._raise(BaseSSHTunnelForwarderError,
reason='Could not establish session to SSH gateway')
for _srv in self._server_list:
thread = threading.Thread(
target=self._serve_forever_wrapper,
args=(_srv, ),
name='Srv-{0}'.format(address_to_str(_srv.local_port))
)
thread.daemon = self.daemon_forward_servers
thread.start()
self._check_tunnel(_srv)
self.is_alive = any(self.tunnel_is_up.values())
if not self.is_alive:
self._raise(HandlerSSHTunnelForwarderError,
'An error occurred while opening tunnels.') | python | def start(self):
""" Start the SSH tunnels """
if self.is_alive:
self.logger.warning('Already started!')
return
self._create_tunnels()
if not self.is_active:
self._raise(BaseSSHTunnelForwarderError,
reason='Could not establish session to SSH gateway')
for _srv in self._server_list:
thread = threading.Thread(
target=self._serve_forever_wrapper,
args=(_srv, ),
name='Srv-{0}'.format(address_to_str(_srv.local_port))
)
thread.daemon = self.daemon_forward_servers
thread.start()
self._check_tunnel(_srv)
self.is_alive = any(self.tunnel_is_up.values())
if not self.is_alive:
self._raise(HandlerSSHTunnelForwarderError,
'An error occurred while opening tunnels.') | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_alive",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Already started!'",
")",
"return",
"self",
".",
"_create_tunnels",
"(",
")",
"if",
"not",
"self",
".",
"is_active",
":",
"self",
".",
"_raise",
"(",
"BaseSSHTunnelForwarderError",
",",
"reason",
"=",
"'Could not establish session to SSH gateway'",
")",
"for",
"_srv",
"in",
"self",
".",
"_server_list",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_serve_forever_wrapper",
",",
"args",
"=",
"(",
"_srv",
",",
")",
",",
"name",
"=",
"'Srv-{0}'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_port",
")",
")",
")",
"thread",
".",
"daemon",
"=",
"self",
".",
"daemon_forward_servers",
"thread",
".",
"start",
"(",
")",
"self",
".",
"_check_tunnel",
"(",
"_srv",
")",
"self",
".",
"is_alive",
"=",
"any",
"(",
"self",
".",
"tunnel_is_up",
".",
"values",
"(",
")",
")",
"if",
"not",
"self",
".",
"is_alive",
":",
"self",
".",
"_raise",
"(",
"HandlerSSHTunnelForwarderError",
",",
"'An error occurred while opening tunnels.'",
")"
] | Start the SSH tunnels | [
"Start",
"the",
"SSH",
"tunnels"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1287-L1308 | train | 236,759 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.stop | def stop(self):
"""
Shut the tunnel down.
.. note:: This **had** to be handled with care before ``0.1.0``:
- if a port redirection is opened
- the destination is not reachable
- we attempt a connection to that tunnel (``SYN`` is sent and
acknowledged, then a ``FIN`` packet is sent and never
acknowledged... weird)
- we try to shutdown: it will not succeed until ``FIN_WAIT_2`` and
``CLOSE_WAIT`` time out.
.. note::
Handle these scenarios with :attr:`.tunnel_is_up`: if False, server
``shutdown()`` will be skipped on that tunnel
"""
self.logger.info('Closing all open connections...')
opened_address_text = ', '.join(
(address_to_str(k.local_address) for k in self._server_list)
) or 'None'
self.logger.debug('Listening tunnels: ' + opened_address_text)
self._stop_transport()
self._server_list = [] # reset server list
self.tunnel_is_up = {} | python | def stop(self):
"""
Shut the tunnel down.
.. note:: This **had** to be handled with care before ``0.1.0``:
- if a port redirection is opened
- the destination is not reachable
- we attempt a connection to that tunnel (``SYN`` is sent and
acknowledged, then a ``FIN`` packet is sent and never
acknowledged... weird)
- we try to shutdown: it will not succeed until ``FIN_WAIT_2`` and
``CLOSE_WAIT`` time out.
.. note::
Handle these scenarios with :attr:`.tunnel_is_up`: if False, server
``shutdown()`` will be skipped on that tunnel
"""
self.logger.info('Closing all open connections...')
opened_address_text = ', '.join(
(address_to_str(k.local_address) for k in self._server_list)
) or 'None'
self.logger.debug('Listening tunnels: ' + opened_address_text)
self._stop_transport()
self._server_list = [] # reset server list
self.tunnel_is_up = {} | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Closing all open connections...'",
")",
"opened_address_text",
"=",
"', '",
".",
"join",
"(",
"(",
"address_to_str",
"(",
"k",
".",
"local_address",
")",
"for",
"k",
"in",
"self",
".",
"_server_list",
")",
")",
"or",
"'None'",
"self",
".",
"logger",
".",
"debug",
"(",
"'Listening tunnels: '",
"+",
"opened_address_text",
")",
"self",
".",
"_stop_transport",
"(",
")",
"self",
".",
"_server_list",
"=",
"[",
"]",
"# reset server list",
"self",
".",
"tunnel_is_up",
"=",
"{",
"}"
] | Shut the tunnel down.
.. note:: This **had** to be handled with care before ``0.1.0``:
- if a port redirection is opened
- the destination is not reachable
- we attempt a connection to that tunnel (``SYN`` is sent and
acknowledged, then a ``FIN`` packet is sent and never
acknowledged... weird)
- we try to shutdown: it will not succeed until ``FIN_WAIT_2`` and
``CLOSE_WAIT`` time out.
.. note::
Handle these scenarios with :attr:`.tunnel_is_up`: if False, server
``shutdown()`` will be skipped on that tunnel | [
"Shut",
"the",
"tunnel",
"down",
"."
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1310-L1335 | train | 236,760 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._serve_forever_wrapper | def _serve_forever_wrapper(self, _srv, poll_interval=0.1):
"""
Wrapper for the server created for a SSH forward
"""
self.logger.info('Opening tunnel: {0} <> {1}'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
)
_srv.serve_forever(poll_interval) # blocks until finished
self.logger.info('Tunnel: {0} <> {1} released'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
) | python | def _serve_forever_wrapper(self, _srv, poll_interval=0.1):
"""
Wrapper for the server created for a SSH forward
"""
self.logger.info('Opening tunnel: {0} <> {1}'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
)
_srv.serve_forever(poll_interval) # blocks until finished
self.logger.info('Tunnel: {0} <> {1} released'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
) | [
"def",
"_serve_forever_wrapper",
"(",
"self",
",",
"_srv",
",",
"poll_interval",
"=",
"0.1",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Opening tunnel: {0} <> {1}'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_address",
")",
",",
"address_to_str",
"(",
"_srv",
".",
"remote_address",
")",
")",
")",
"_srv",
".",
"serve_forever",
"(",
"poll_interval",
")",
"# blocks until finished",
"self",
".",
"logger",
".",
"info",
"(",
"'Tunnel: {0} <> {1} released'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_address",
")",
",",
"address_to_str",
"(",
"_srv",
".",
"remote_address",
")",
")",
")"
] | Wrapper for the server created for a SSH forward | [
"Wrapper",
"for",
"the",
"server",
"created",
"for",
"a",
"SSH",
"forward"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1383-L1396 | train | 236,761 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._stop_transport | def _stop_transport(self):
""" Close the underlying transport when nothing more is needed """
try:
self._check_is_started()
except (BaseSSHTunnelForwarderError,
HandlerSSHTunnelForwarderError) as e:
self.logger.warning(e)
for _srv in self._server_list:
tunnel = _srv.local_address
if self.tunnel_is_up[tunnel]:
self.logger.info('Shutting down tunnel {0}'.format(tunnel))
_srv.shutdown()
_srv.server_close()
# clean up the UNIX domain socket if we're using one
if isinstance(_srv, _UnixStreamForwardServer):
try:
os.unlink(_srv.local_address)
except Exception as e:
self.logger.error('Unable to unlink socket {0}: {1}'
.format(self.local_address, repr(e)))
self.is_alive = False
if self.is_active:
self._transport.close()
self._transport.stop_thread()
self.logger.debug('Transport is closed') | python | def _stop_transport(self):
""" Close the underlying transport when nothing more is needed """
try:
self._check_is_started()
except (BaseSSHTunnelForwarderError,
HandlerSSHTunnelForwarderError) as e:
self.logger.warning(e)
for _srv in self._server_list:
tunnel = _srv.local_address
if self.tunnel_is_up[tunnel]:
self.logger.info('Shutting down tunnel {0}'.format(tunnel))
_srv.shutdown()
_srv.server_close()
# clean up the UNIX domain socket if we're using one
if isinstance(_srv, _UnixStreamForwardServer):
try:
os.unlink(_srv.local_address)
except Exception as e:
self.logger.error('Unable to unlink socket {0}: {1}'
.format(self.local_address, repr(e)))
self.is_alive = False
if self.is_active:
self._transport.close()
self._transport.stop_thread()
self.logger.debug('Transport is closed') | [
"def",
"_stop_transport",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_check_is_started",
"(",
")",
"except",
"(",
"BaseSSHTunnelForwarderError",
",",
"HandlerSSHTunnelForwarderError",
")",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"e",
")",
"for",
"_srv",
"in",
"self",
".",
"_server_list",
":",
"tunnel",
"=",
"_srv",
".",
"local_address",
"if",
"self",
".",
"tunnel_is_up",
"[",
"tunnel",
"]",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Shutting down tunnel {0}'",
".",
"format",
"(",
"tunnel",
")",
")",
"_srv",
".",
"shutdown",
"(",
")",
"_srv",
".",
"server_close",
"(",
")",
"# clean up the UNIX domain socket if we're using one",
"if",
"isinstance",
"(",
"_srv",
",",
"_UnixStreamForwardServer",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"_srv",
".",
"local_address",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Unable to unlink socket {0}: {1}'",
".",
"format",
"(",
"self",
".",
"local_address",
",",
"repr",
"(",
"e",
")",
")",
")",
"self",
".",
"is_alive",
"=",
"False",
"if",
"self",
".",
"is_active",
":",
"self",
".",
"_transport",
".",
"close",
"(",
")",
"self",
".",
"_transport",
".",
"stop_thread",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Transport is closed'",
")"
] | Close the underlying transport when nothing more is needed | [
"Close",
"the",
"underlying",
"transport",
"when",
"nothing",
"more",
"is",
"needed"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1398-L1422 | train | 236,762 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.local_bind_ports | def local_bind_ports(self):
"""
Return a list containing the ports of local side of the TCP tunnels
"""
self._check_is_started()
return [_server.local_port for _server in self._server_list if
_server.local_port is not None] | python | def local_bind_ports(self):
"""
Return a list containing the ports of local side of the TCP tunnels
"""
self._check_is_started()
return [_server.local_port for _server in self._server_list if
_server.local_port is not None] | [
"def",
"local_bind_ports",
"(",
"self",
")",
":",
"self",
".",
"_check_is_started",
"(",
")",
"return",
"[",
"_server",
".",
"local_port",
"for",
"_server",
"in",
"self",
".",
"_server_list",
"if",
"_server",
".",
"local_port",
"is",
"not",
"None",
"]"
] | Return a list containing the ports of local side of the TCP tunnels | [
"Return",
"a",
"list",
"containing",
"the",
"ports",
"of",
"local",
"side",
"of",
"the",
"TCP",
"tunnels"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1455-L1461 | train | 236,763 |
pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.local_bind_hosts | def local_bind_hosts(self):
"""
Return a list containing the IP addresses listening for the tunnels
"""
self._check_is_started()
return [_server.local_host for _server in self._server_list if
_server.local_host is not None] | python | def local_bind_hosts(self):
"""
Return a list containing the IP addresses listening for the tunnels
"""
self._check_is_started()
return [_server.local_host for _server in self._server_list if
_server.local_host is not None] | [
"def",
"local_bind_hosts",
"(",
"self",
")",
":",
"self",
".",
"_check_is_started",
"(",
")",
"return",
"[",
"_server",
".",
"local_host",
"for",
"_server",
"in",
"self",
".",
"_server_list",
"if",
"_server",
".",
"local_host",
"is",
"not",
"None",
"]"
] | Return a list containing the IP addresses listening for the tunnels | [
"Return",
"a",
"list",
"containing",
"the",
"IP",
"addresses",
"listening",
"for",
"the",
"tunnels"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1464-L1470 | train | 236,764 |
DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | get_submodules | def get_submodules(module):
"""
This function imports all sub-modules of the supplied module and returns a dictionary
with module names as keys and the sub-module objects as values. If the supplied parameter
is not a module object, a RuntimeError is raised.
:param module: Module object from which to import sub-modules.
:return: Dict with name-module pairs.
"""
if not inspect.ismodule(module):
raise RuntimeError(
'Can only extract submodules from a module object, '
'for example imported via importlib.import_module')
submodules = get_members(module, inspect.ismodule)
module_path = list(getattr(module, '__path__', [None]))[0]
if module_path is not None:
for item in listdir(module_path):
module_name = extract_module_name(osp.join(module_path, item))
if module_name is not None:
try:
submodules[module_name] = importlib.import_module(
'.{}'.format(module_name), package=module.__name__)
except ImportError:
# This is necessary in case random directories are in the path or things can
# just not be imported due to other ImportErrors.
pass
return submodules | python | def get_submodules(module):
"""
This function imports all sub-modules of the supplied module and returns a dictionary
with module names as keys and the sub-module objects as values. If the supplied parameter
is not a module object, a RuntimeError is raised.
:param module: Module object from which to import sub-modules.
:return: Dict with name-module pairs.
"""
if not inspect.ismodule(module):
raise RuntimeError(
'Can only extract submodules from a module object, '
'for example imported via importlib.import_module')
submodules = get_members(module, inspect.ismodule)
module_path = list(getattr(module, '__path__', [None]))[0]
if module_path is not None:
for item in listdir(module_path):
module_name = extract_module_name(osp.join(module_path, item))
if module_name is not None:
try:
submodules[module_name] = importlib.import_module(
'.{}'.format(module_name), package=module.__name__)
except ImportError:
# This is necessary in case random directories are in the path or things can
# just not be imported due to other ImportErrors.
pass
return submodules | [
"def",
"get_submodules",
"(",
"module",
")",
":",
"if",
"not",
"inspect",
".",
"ismodule",
"(",
"module",
")",
":",
"raise",
"RuntimeError",
"(",
"'Can only extract submodules from a module object, '",
"'for example imported via importlib.import_module'",
")",
"submodules",
"=",
"get_members",
"(",
"module",
",",
"inspect",
".",
"ismodule",
")",
"module_path",
"=",
"list",
"(",
"getattr",
"(",
"module",
",",
"'__path__'",
",",
"[",
"None",
"]",
")",
")",
"[",
"0",
"]",
"if",
"module_path",
"is",
"not",
"None",
":",
"for",
"item",
"in",
"listdir",
"(",
"module_path",
")",
":",
"module_name",
"=",
"extract_module_name",
"(",
"osp",
".",
"join",
"(",
"module_path",
",",
"item",
")",
")",
"if",
"module_name",
"is",
"not",
"None",
":",
"try",
":",
"submodules",
"[",
"module_name",
"]",
"=",
"importlib",
".",
"import_module",
"(",
"'.{}'",
".",
"format",
"(",
"module_name",
")",
",",
"package",
"=",
"module",
".",
"__name__",
")",
"except",
"ImportError",
":",
"# This is necessary in case random directories are in the path or things can",
"# just not be imported due to other ImportErrors.",
"pass",
"return",
"submodules"
] | This function imports all sub-modules of the supplied module and returns a dictionary
with module names as keys and the sub-module objects as values. If the supplied parameter
is not a module object, a RuntimeError is raised.
:param module: Module object from which to import sub-modules.
:return: Dict with name-module pairs. | [
"This",
"function",
"imports",
"all",
"sub",
"-",
"modules",
"of",
"the",
"supplied",
"module",
"and",
"returns",
"a",
"dictionary",
"with",
"module",
"names",
"as",
"keys",
"and",
"the",
"sub",
"-",
"module",
"objects",
"as",
"values",
".",
"If",
"the",
"supplied",
"parameter",
"is",
"not",
"a",
"module",
"object",
"a",
"RuntimeError",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L42-L73 | train | 236,765 |
DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | extract_module_name | def extract_module_name(absolute_path):
"""
This function tries to extract a valid module name from the basename of the supplied path.
If it's a directory, the directory name is returned, if it's a file, the file name
without extension is returned. If the basename starts with _ or . or it's a file with an
ending different from .py, the function returns None
:param absolute_path: Absolute path of something that might be a module.
:return: Module name or None.
"""
base_name = osp.basename(osp.normpath(absolute_path))
# If the basename starts with _ it's probably __init__.py or __pycache__ or something internal.
# At the moment there seems to be no use case for those
if base_name[0] in ('.', '_'):
return None
# If it's a directory, there's nothing else to check, so it can be returned directly
if osp.isdir(absolute_path):
return base_name
module_name, extension = osp.splitext(base_name)
# If it's a file, it must have a .py ending
if extension == '.py':
return module_name
return None | python | def extract_module_name(absolute_path):
"""
This function tries to extract a valid module name from the basename of the supplied path.
If it's a directory, the directory name is returned, if it's a file, the file name
without extension is returned. If the basename starts with _ or . or it's a file with an
ending different from .py, the function returns None
:param absolute_path: Absolute path of something that might be a module.
:return: Module name or None.
"""
base_name = osp.basename(osp.normpath(absolute_path))
# If the basename starts with _ it's probably __init__.py or __pycache__ or something internal.
# At the moment there seems to be no use case for those
if base_name[0] in ('.', '_'):
return None
# If it's a directory, there's nothing else to check, so it can be returned directly
if osp.isdir(absolute_path):
return base_name
module_name, extension = osp.splitext(base_name)
# If it's a file, it must have a .py ending
if extension == '.py':
return module_name
return None | [
"def",
"extract_module_name",
"(",
"absolute_path",
")",
":",
"base_name",
"=",
"osp",
".",
"basename",
"(",
"osp",
".",
"normpath",
"(",
"absolute_path",
")",
")",
"# If the basename starts with _ it's probably __init__.py or __pycache__ or something internal.",
"# At the moment there seems to be no use case for those",
"if",
"base_name",
"[",
"0",
"]",
"in",
"(",
"'.'",
",",
"'_'",
")",
":",
"return",
"None",
"# If it's a directory, there's nothing else to check, so it can be returned directly",
"if",
"osp",
".",
"isdir",
"(",
"absolute_path",
")",
":",
"return",
"base_name",
"module_name",
",",
"extension",
"=",
"osp",
".",
"splitext",
"(",
"base_name",
")",
"# If it's a file, it must have a .py ending",
"if",
"extension",
"==",
"'.py'",
":",
"return",
"module_name",
"return",
"None"
] | This function tries to extract a valid module name from the basename of the supplied path.
If it's a directory, the directory name is returned, if it's a file, the file name
without extension is returned. If the basename starts with _ or . or it's a file with an
ending different from .py, the function returns None
:param absolute_path: Absolute path of something that might be a module.
:return: Module name or None. | [
"This",
"function",
"tries",
"to",
"extract",
"a",
"valid",
"module",
"name",
"from",
"the",
"basename",
"of",
"the",
"supplied",
"path",
".",
"If",
"it",
"s",
"a",
"directory",
"the",
"directory",
"name",
"is",
"returned",
"if",
"it",
"s",
"a",
"file",
"the",
"file",
"name",
"without",
"extension",
"is",
"returned",
".",
"If",
"the",
"basename",
"starts",
"with",
"_",
"or",
".",
"or",
"it",
"s",
"a",
"file",
"with",
"an",
"ending",
"different",
"from",
".",
"py",
"the",
"function",
"returns",
"None"
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L97-L124 | train | 236,766 |
DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | dict_strict_update | def dict_strict_update(base_dict, update_dict):
"""
This function updates base_dict with update_dict if and only if update_dict does not contain
keys that are not already in base_dict. It is essentially a more strict interpretation of the
term "updating" the dict.
If update_dict contains keys that are not in base_dict, a RuntimeError is raised.
:param base_dict: The dict that is to be updated. This dict is modified.
:param update_dict: The dict containing the new values.
"""
additional_keys = set(update_dict.keys()) - set(base_dict.keys())
if len(additional_keys) > 0:
raise RuntimeError(
'The update dictionary contains keys that are not part of '
'the base dictionary: {}'.format(str(additional_keys)),
additional_keys)
base_dict.update(update_dict) | python | def dict_strict_update(base_dict, update_dict):
"""
This function updates base_dict with update_dict if and only if update_dict does not contain
keys that are not already in base_dict. It is essentially a more strict interpretation of the
term "updating" the dict.
If update_dict contains keys that are not in base_dict, a RuntimeError is raised.
:param base_dict: The dict that is to be updated. This dict is modified.
:param update_dict: The dict containing the new values.
"""
additional_keys = set(update_dict.keys()) - set(base_dict.keys())
if len(additional_keys) > 0:
raise RuntimeError(
'The update dictionary contains keys that are not part of '
'the base dictionary: {}'.format(str(additional_keys)),
additional_keys)
base_dict.update(update_dict) | [
"def",
"dict_strict_update",
"(",
"base_dict",
",",
"update_dict",
")",
":",
"additional_keys",
"=",
"set",
"(",
"update_dict",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"base_dict",
".",
"keys",
"(",
")",
")",
"if",
"len",
"(",
"additional_keys",
")",
">",
"0",
":",
"raise",
"RuntimeError",
"(",
"'The update dictionary contains keys that are not part of '",
"'the base dictionary: {}'",
".",
"format",
"(",
"str",
"(",
"additional_keys",
")",
")",
",",
"additional_keys",
")",
"base_dict",
".",
"update",
"(",
"update_dict",
")"
] | This function updates base_dict with update_dict if and only if update_dict does not contain
keys that are not already in base_dict. It is essentially a more strict interpretation of the
term "updating" the dict.
If update_dict contains keys that are not in base_dict, a RuntimeError is raised.
:param base_dict: The dict that is to be updated. This dict is modified.
:param update_dict: The dict containing the new values. | [
"This",
"function",
"updates",
"base_dict",
"with",
"update_dict",
"if",
"and",
"only",
"if",
"update_dict",
"does",
"not",
"contain",
"keys",
"that",
"are",
"not",
"already",
"in",
"base_dict",
".",
"It",
"is",
"essentially",
"a",
"more",
"strict",
"interpretation",
"of",
"the",
"term",
"updating",
"the",
"dict",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L127-L145 | train | 236,767 |
DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | format_doc_text | def format_doc_text(text):
"""
A very thin wrapper around textwrap.fill to consistently wrap documentation text
for display in a command line environment. The text is wrapped to 99 characters with an
indentation depth of 4 spaces. Each line is wrapped independently in order to preserve
manually added line breaks.
:param text: The text to format, it is cleaned by inspect.cleandoc.
:return: The formatted doc text.
"""
return '\n'.join(
textwrap.fill(line, width=99, initial_indent=' ', subsequent_indent=' ')
for line in inspect.cleandoc(text).splitlines()) | python | def format_doc_text(text):
"""
A very thin wrapper around textwrap.fill to consistently wrap documentation text
for display in a command line environment. The text is wrapped to 99 characters with an
indentation depth of 4 spaces. Each line is wrapped independently in order to preserve
manually added line breaks.
:param text: The text to format, it is cleaned by inspect.cleandoc.
:return: The formatted doc text.
"""
return '\n'.join(
textwrap.fill(line, width=99, initial_indent=' ', subsequent_indent=' ')
for line in inspect.cleandoc(text).splitlines()) | [
"def",
"format_doc_text",
"(",
"text",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"textwrap",
".",
"fill",
"(",
"line",
",",
"width",
"=",
"99",
",",
"initial_indent",
"=",
"' '",
",",
"subsequent_indent",
"=",
"' '",
")",
"for",
"line",
"in",
"inspect",
".",
"cleandoc",
"(",
"text",
")",
".",
"splitlines",
"(",
")",
")"
] | A very thin wrapper around textwrap.fill to consistently wrap documentation text
for display in a command line environment. The text is wrapped to 99 characters with an
indentation depth of 4 spaces. Each line is wrapped independently in order to preserve
manually added line breaks.
:param text: The text to format, it is cleaned by inspect.cleandoc.
:return: The formatted doc text. | [
"A",
"very",
"thin",
"wrapper",
"around",
"textwrap",
".",
"fill",
"to",
"consistently",
"wrap",
"documentation",
"text",
"for",
"display",
"in",
"a",
"command",
"line",
"environment",
".",
"The",
"text",
"is",
"wrapped",
"to",
"99",
"characters",
"with",
"an",
"indentation",
"depth",
"of",
"4",
"spaces",
".",
"Each",
"line",
"is",
"wrapped",
"independently",
"in",
"order",
"to",
"preserve",
"manually",
"added",
"line",
"breaks",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L250-L263 | train | 236,768 |
DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | FromOptionalDependency.do_import | def do_import(self, *names):
"""
Tries to import names from the module specified on initialization
of the FromOptionalDependency-object. In case an ImportError occurs,
the requested names are replaced with stub objects.
:param names: List of strings that are used as type names.
:return: Tuple of actual symbols or stub types with provided names. If there is only one
element in the tuple, that element is returned.
"""
try:
module_object = importlib.import_module(self._module)
objects = tuple(getattr(module_object, name) for name in names)
except ImportError:
def failing_init(obj, *args, **kwargs):
raise self._exception
objects = tuple(type(name, (object,), {'__init__': failing_init})
for name in names)
return objects if len(objects) != 1 else objects[0] | python | def do_import(self, *names):
"""
Tries to import names from the module specified on initialization
of the FromOptionalDependency-object. In case an ImportError occurs,
the requested names are replaced with stub objects.
:param names: List of strings that are used as type names.
:return: Tuple of actual symbols or stub types with provided names. If there is only one
element in the tuple, that element is returned.
"""
try:
module_object = importlib.import_module(self._module)
objects = tuple(getattr(module_object, name) for name in names)
except ImportError:
def failing_init(obj, *args, **kwargs):
raise self._exception
objects = tuple(type(name, (object,), {'__init__': failing_init})
for name in names)
return objects if len(objects) != 1 else objects[0] | [
"def",
"do_import",
"(",
"self",
",",
"*",
"names",
")",
":",
"try",
":",
"module_object",
"=",
"importlib",
".",
"import_module",
"(",
"self",
".",
"_module",
")",
"objects",
"=",
"tuple",
"(",
"getattr",
"(",
"module_object",
",",
"name",
")",
"for",
"name",
"in",
"names",
")",
"except",
"ImportError",
":",
"def",
"failing_init",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"self",
".",
"_exception",
"objects",
"=",
"tuple",
"(",
"type",
"(",
"name",
",",
"(",
"object",
",",
")",
",",
"{",
"'__init__'",
":",
"failing_init",
"}",
")",
"for",
"name",
"in",
"names",
")",
"return",
"objects",
"if",
"len",
"(",
"objects",
")",
"!=",
"1",
"else",
"objects",
"[",
"0",
"]"
] | Tries to import names from the module specified on initialization
of the FromOptionalDependency-object. In case an ImportError occurs,
the requested names are replaced with stub objects.
:param names: List of strings that are used as type names.
:return: Tuple of actual symbols or stub types with provided names. If there is only one
element in the tuple, that element is returned. | [
"Tries",
"to",
"import",
"names",
"from",
"the",
"module",
"specified",
"on",
"initialization",
"of",
"the",
"FromOptionalDependency",
"-",
"object",
".",
"In",
"case",
"an",
"ImportError",
"occurs",
"the",
"requested",
"names",
"are",
"replaced",
"with",
"stub",
"objects",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L226-L247 | train | 236,769 |
DMSC-Instrument-Data/lewis | src/lewis/core/control_server.py | ExposedObject.get_api | def get_api(self):
"""
This method returns the class name and a list of exposed methods.
It is exposed to RPC-clients by an instance of ExposedObjectCollection.
:return: A dictionary describing the exposed API (consisting of a class name and methods).
"""
return {'class': type(self._object).__name__, 'methods': list(self._function_map.keys())} | python | def get_api(self):
"""
This method returns the class name and a list of exposed methods.
It is exposed to RPC-clients by an instance of ExposedObjectCollection.
:return: A dictionary describing the exposed API (consisting of a class name and methods).
"""
return {'class': type(self._object).__name__, 'methods': list(self._function_map.keys())} | [
"def",
"get_api",
"(",
"self",
")",
":",
"return",
"{",
"'class'",
":",
"type",
"(",
"self",
".",
"_object",
")",
".",
"__name__",
",",
"'methods'",
":",
"list",
"(",
"self",
".",
"_function_map",
".",
"keys",
"(",
")",
")",
"}"
] | This method returns the class name and a list of exposed methods.
It is exposed to RPC-clients by an instance of ExposedObjectCollection.
:return: A dictionary describing the exposed API (consisting of a class name and methods). | [
"This",
"method",
"returns",
"the",
"class",
"name",
"and",
"a",
"list",
"of",
"exposed",
"methods",
".",
"It",
"is",
"exposed",
"to",
"RPC",
"-",
"clients",
"by",
"an",
"instance",
"of",
"ExposedObjectCollection",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/control_server.py#L121-L128 | train | 236,770 |
DMSC-Instrument-Data/lewis | src/lewis/core/control_server.py | ExposedObjectCollection.remove_object | def remove_object(self, name):
"""
Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed.
"""
if name not in self._object_map:
raise RuntimeError('No object with name {} is registered.'.format(name))
for fn_name in list(self._function_map.keys()):
if fn_name.startswith(name + '.') or fn_name.startswith(name + ':'):
self._remove_function(fn_name)
del self._object_map[name] | python | def remove_object(self, name):
"""
Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed.
"""
if name not in self._object_map:
raise RuntimeError('No object with name {} is registered.'.format(name))
for fn_name in list(self._function_map.keys()):
if fn_name.startswith(name + '.') or fn_name.startswith(name + ':'):
self._remove_function(fn_name)
del self._object_map[name] | [
"def",
"remove_object",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_object_map",
":",
"raise",
"RuntimeError",
"(",
"'No object with name {} is registered.'",
".",
"format",
"(",
"name",
")",
")",
"for",
"fn_name",
"in",
"list",
"(",
"self",
".",
"_function_map",
".",
"keys",
"(",
")",
")",
":",
"if",
"fn_name",
".",
"startswith",
"(",
"name",
"+",
"'.'",
")",
"or",
"fn_name",
".",
"startswith",
"(",
"name",
"+",
"':'",
")",
":",
"self",
".",
"_remove_function",
"(",
"fn_name",
")",
"del",
"self",
".",
"_object_map",
"[",
"name",
"]"
] | Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed. | [
"Remove",
"the",
"object",
"exposed",
"under",
"that",
"name",
".",
"If",
"no",
"object",
"is",
"registered",
"under",
"the",
"supplied",
"name",
"a",
"RuntimeError",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/control_server.py#L219-L233 | train | 236,771 |
DMSC-Instrument-Data/lewis | src/lewis/devices/julabo/devices/device.py | SimulatedJulabo.set_set_point | def set_set_point(self, param):
"""
Sets the target temperature.
:param param: The new temperature in C. Must be positive.
:return: Empty string.
"""
if self.temperature_low_limit <= param <= self.temperature_high_limit:
self.set_point_temperature = param
return "" | python | def set_set_point(self, param):
"""
Sets the target temperature.
:param param: The new temperature in C. Must be positive.
:return: Empty string.
"""
if self.temperature_low_limit <= param <= self.temperature_high_limit:
self.set_point_temperature = param
return "" | [
"def",
"set_set_point",
"(",
"self",
",",
"param",
")",
":",
"if",
"self",
".",
"temperature_low_limit",
"<=",
"param",
"<=",
"self",
".",
"temperature_high_limit",
":",
"self",
".",
"set_point_temperature",
"=",
"param",
"return",
"\"\""
] | Sets the target temperature.
:param param: The new temperature in C. Must be positive.
:return: Empty string. | [
"Sets",
"the",
"target",
"temperature",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/julabo/devices/device.py#L73-L82 | train | 236,772 |
DMSC-Instrument-Data/lewis | src/lewis/devices/julabo/devices/device.py | SimulatedJulabo.set_circulating | def set_circulating(self, param):
"""
Sets whether to circulate - in effect whether the heater is on.
:param param: The mode to set, must be 0 or 1.
:return: Empty string.
"""
if param == 0:
self.is_circulating = param
self.circulate_commanded = False
elif param == 1:
self.is_circulating = param
self.circulate_commanded = True
return "" | python | def set_circulating(self, param):
"""
Sets whether to circulate - in effect whether the heater is on.
:param param: The mode to set, must be 0 or 1.
:return: Empty string.
"""
if param == 0:
self.is_circulating = param
self.circulate_commanded = False
elif param == 1:
self.is_circulating = param
self.circulate_commanded = True
return "" | [
"def",
"set_circulating",
"(",
"self",
",",
"param",
")",
":",
"if",
"param",
"==",
"0",
":",
"self",
".",
"is_circulating",
"=",
"param",
"self",
".",
"circulate_commanded",
"=",
"False",
"elif",
"param",
"==",
"1",
":",
"self",
".",
"is_circulating",
"=",
"param",
"self",
".",
"circulate_commanded",
"=",
"True",
"return",
"\"\""
] | Sets whether to circulate - in effect whether the heater is on.
:param param: The mode to set, must be 0 or 1.
:return: Empty string. | [
"Sets",
"whether",
"to",
"circulate",
"-",
"in",
"effect",
"whether",
"the",
"heater",
"is",
"on",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/julabo/devices/device.py#L84-L97 | train | 236,773 |
DMSC-Instrument-Data/lewis | src/lewis/core/simulation.py | SimulationFactory.get_protocols | def get_protocols(self, device):
"""Returns a list of available protocols for the specified device."""
return self._reg.device_builder(device, self._rv).protocols | python | def get_protocols(self, device):
"""Returns a list of available protocols for the specified device."""
return self._reg.device_builder(device, self._rv).protocols | [
"def",
"get_protocols",
"(",
"self",
",",
"device",
")",
":",
"return",
"self",
".",
"_reg",
".",
"device_builder",
"(",
"device",
",",
"self",
".",
"_rv",
")",
".",
"protocols"
] | Returns a list of available protocols for the specified device. | [
"Returns",
"a",
"list",
"of",
"available",
"protocols",
"for",
"the",
"specified",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/simulation.py#L433-L435 | train | 236,774 |
DMSC-Instrument-Data/lewis | src/lewis/core/approaches.py | linear | def linear(current, target, rate, dt):
"""
This function returns the new value after moving towards
target at the given speed constantly for the time dt.
If for example the current position is 10 and the target is -20,
the returned value will be less than 10 if rate and dt are greater
than 0:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 0.1) # new_pos = 9
The function makes sure that the returned value never overshoots:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 100) # new_pos = -20
:param current: The current value of the variable to be changed.
:param target: The target value to approach.
:param rate: The rate at which the parameter should move towards target.
:param dt: The time for which to calculate the change.
:return: The new variable value.
"""
sign = (target > current) - (target < current)
if not sign:
return current
new_value = current + sign * rate * dt
if sign * new_value > sign * target:
return target
return new_value | python | def linear(current, target, rate, dt):
"""
This function returns the new value after moving towards
target at the given speed constantly for the time dt.
If for example the current position is 10 and the target is -20,
the returned value will be less than 10 if rate and dt are greater
than 0:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 0.1) # new_pos = 9
The function makes sure that the returned value never overshoots:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 100) # new_pos = -20
:param current: The current value of the variable to be changed.
:param target: The target value to approach.
:param rate: The rate at which the parameter should move towards target.
:param dt: The time for which to calculate the change.
:return: The new variable value.
"""
sign = (target > current) - (target < current)
if not sign:
return current
new_value = current + sign * rate * dt
if sign * new_value > sign * target:
return target
return new_value | [
"def",
"linear",
"(",
"current",
",",
"target",
",",
"rate",
",",
"dt",
")",
":",
"sign",
"=",
"(",
"target",
">",
"current",
")",
"-",
"(",
"target",
"<",
"current",
")",
"if",
"not",
"sign",
":",
"return",
"current",
"new_value",
"=",
"current",
"+",
"sign",
"*",
"rate",
"*",
"dt",
"if",
"sign",
"*",
"new_value",
">",
"sign",
"*",
"target",
":",
"return",
"target",
"return",
"new_value"
] | This function returns the new value after moving towards
target at the given speed constantly for the time dt.
If for example the current position is 10 and the target is -20,
the returned value will be less than 10 if rate and dt are greater
than 0:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 0.1) # new_pos = 9
The function makes sure that the returned value never overshoots:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 100) # new_pos = -20
:param current: The current value of the variable to be changed.
:param target: The target value to approach.
:param rate: The rate at which the parameter should move towards target.
:param dt: The time for which to calculate the change.
:return: The new variable value. | [
"This",
"function",
"returns",
"the",
"new",
"value",
"after",
"moving",
"towards",
"target",
"at",
"the",
"given",
"speed",
"constantly",
"for",
"the",
"time",
"dt",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/approaches.py#L26-L61 | train | 236,775 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | BoundPV.meta | def meta(self):
"""Value of the bound meta-property on the target."""
if not self._pv.meta_data_property or not self._meta_target:
return {}
return getattr(self._meta_target, self._pv.meta_data_property) | python | def meta(self):
"""Value of the bound meta-property on the target."""
if not self._pv.meta_data_property or not self._meta_target:
return {}
return getattr(self._meta_target, self._pv.meta_data_property) | [
"def",
"meta",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pv",
".",
"meta_data_property",
"or",
"not",
"self",
".",
"_meta_target",
":",
"return",
"{",
"}",
"return",
"getattr",
"(",
"self",
".",
"_meta_target",
",",
"self",
".",
"_pv",
".",
"meta_data_property",
")"
] | Value of the bound meta-property on the target. | [
"Value",
"of",
"the",
"bound",
"meta",
"-",
"property",
"on",
"the",
"target",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L93-L98 | train | 236,776 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | BoundPV.doc | def doc(self):
"""Docstring of property on target or override specified on PV-object."""
return self._pv.doc or inspect.getdoc(
getattr(type(self._target), self._pv.property, None)) or '' | python | def doc(self):
"""Docstring of property on target or override specified on PV-object."""
return self._pv.doc or inspect.getdoc(
getattr(type(self._target), self._pv.property, None)) or '' | [
"def",
"doc",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pv",
".",
"doc",
"or",
"inspect",
".",
"getdoc",
"(",
"getattr",
"(",
"type",
"(",
"self",
".",
"_target",
")",
",",
"self",
".",
"_pv",
".",
"property",
",",
"None",
")",
")",
"or",
"''"
] | Docstring of property on target or override specified on PV-object. | [
"Docstring",
"of",
"property",
"on",
"target",
"or",
"override",
"specified",
"on",
"PV",
"-",
"object",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L116-L119 | train | 236,777 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | PV.bind | def bind(self, *targets):
"""
Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property.
"""
self.property = 'value'
self.meta_data_property = 'meta'
return BoundPV(self,
self._get_target(self.property, *targets),
self._get_target(self.meta_data_property, *targets)) | python | def bind(self, *targets):
"""
Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property.
"""
self.property = 'value'
self.meta_data_property = 'meta'
return BoundPV(self,
self._get_target(self.property, *targets),
self._get_target(self.meta_data_property, *targets)) | [
"def",
"bind",
"(",
"self",
",",
"*",
"targets",
")",
":",
"self",
".",
"property",
"=",
"'value'",
"self",
".",
"meta_data_property",
"=",
"'meta'",
"return",
"BoundPV",
"(",
"self",
",",
"self",
".",
"_get_target",
"(",
"self",
".",
"property",
",",
"*",
"targets",
")",
",",
"self",
".",
"_get_target",
"(",
"self",
".",
"meta_data_property",
",",
"*",
"targets",
")",
")"
] | Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property. | [
"Tries",
"to",
"bind",
"the",
"PV",
"to",
"one",
"of",
"the",
"supplied",
"targets",
".",
"Targets",
"are",
"inspected",
"according",
"to",
"the",
"order",
"in",
"which",
"they",
"are",
"supplied",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L224-L237 | train | 236,778 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | PV._get_callable | def _get_callable(self, func, *targets):
"""
If func is already a callable, it is returned directly. If it's a string, it is assumed
to be a method on one of the objects supplied in targets and that is returned. If no
method with the specified name is found, an AttributeError is raised.
:param func: Callable or name of method on one object in targets.
:param targets: List of targets with decreasing priority for finding func.
:return: Callable.
"""
if not callable(func):
func_name = func
func = next((getattr(obj, func, None) for obj in targets if func in dir(obj)),
None)
if not func:
raise AttributeError(
'No method with the name \'{}\' could be found on any of the target objects '
'(device, interface). Please check the spelling.'.format(func_name))
return func | python | def _get_callable(self, func, *targets):
"""
If func is already a callable, it is returned directly. If it's a string, it is assumed
to be a method on one of the objects supplied in targets and that is returned. If no
method with the specified name is found, an AttributeError is raised.
:param func: Callable or name of method on one object in targets.
:param targets: List of targets with decreasing priority for finding func.
:return: Callable.
"""
if not callable(func):
func_name = func
func = next((getattr(obj, func, None) for obj in targets if func in dir(obj)),
None)
if not func:
raise AttributeError(
'No method with the name \'{}\' could be found on any of the target objects '
'(device, interface). Please check the spelling.'.format(func_name))
return func | [
"def",
"_get_callable",
"(",
"self",
",",
"func",
",",
"*",
"targets",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"func_name",
"=",
"func",
"func",
"=",
"next",
"(",
"(",
"getattr",
"(",
"obj",
",",
"func",
",",
"None",
")",
"for",
"obj",
"in",
"targets",
"if",
"func",
"in",
"dir",
"(",
"obj",
")",
")",
",",
"None",
")",
"if",
"not",
"func",
":",
"raise",
"AttributeError",
"(",
"'No method with the name \\'{}\\' could be found on any of the target objects '",
"'(device, interface). Please check the spelling.'",
".",
"format",
"(",
"func_name",
")",
")",
"return",
"func"
] | If func is already a callable, it is returned directly. If it's a string, it is assumed
to be a method on one of the objects supplied in targets and that is returned. If no
method with the specified name is found, an AttributeError is raised.
:param func: Callable or name of method on one object in targets.
:param targets: List of targets with decreasing priority for finding func.
:return: Callable. | [
"If",
"func",
"is",
"already",
"a",
"callable",
"it",
"is",
"returned",
"directly",
".",
"If",
"it",
"s",
"a",
"string",
"it",
"is",
"assumed",
"to",
"be",
"a",
"method",
"on",
"one",
"of",
"the",
"objects",
"supplied",
"in",
"targets",
"and",
"that",
"is",
"returned",
".",
"If",
"no",
"method",
"with",
"the",
"specified",
"name",
"is",
"found",
"an",
"AttributeError",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L361-L381 | train | 236,779 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | PV._function_has_n_args | def _function_has_n_args(self, func, n):
"""
Returns true if func has n arguments. Arguments with default and self for
methods are not considered.
"""
if inspect.ismethod(func):
n += 1
argspec = inspect.getargspec(func)
defaults = argspec.defaults or ()
return len(argspec.args) - len(defaults) == n | python | def _function_has_n_args(self, func, n):
"""
Returns true if func has n arguments. Arguments with default and self for
methods are not considered.
"""
if inspect.ismethod(func):
n += 1
argspec = inspect.getargspec(func)
defaults = argspec.defaults or ()
return len(argspec.args) - len(defaults) == n | [
"def",
"_function_has_n_args",
"(",
"self",
",",
"func",
",",
"n",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"n",
"+=",
"1",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"defaults",
"=",
"argspec",
".",
"defaults",
"or",
"(",
")",
"return",
"len",
"(",
"argspec",
".",
"args",
")",
"-",
"len",
"(",
"defaults",
")",
"==",
"n"
] | Returns true if func has n arguments. Arguments with default and self for
methods are not considered. | [
"Returns",
"true",
"if",
"func",
"has",
"n",
"arguments",
".",
"Arguments",
"with",
"default",
"and",
"self",
"for",
"methods",
"are",
"not",
"considered",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L383-L394 | train | 236,780 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | EpicsAdapter.start_server | def start_server(self):
"""
Creates a pcaspy-server.
.. note::
The server does not process requests unless :meth:`handle` is called regularly.
"""
if self._server is None:
self._server = SimpleServer()
self._server.createPV(prefix=self._options.prefix,
pvdb={k: v.config for k, v in self.interface.bound_pvs.items()})
self._driver = PropertyExposingDriver(interface=self.interface,
device_lock=self.device_lock)
self._driver.process_pv_updates(force=True)
self.log.info('Started serving PVs: %s',
', '.join((self._options.prefix + pv for pv in
self.interface.bound_pvs.keys()))) | python | def start_server(self):
"""
Creates a pcaspy-server.
.. note::
The server does not process requests unless :meth:`handle` is called regularly.
"""
if self._server is None:
self._server = SimpleServer()
self._server.createPV(prefix=self._options.prefix,
pvdb={k: v.config for k, v in self.interface.bound_pvs.items()})
self._driver = PropertyExposingDriver(interface=self.interface,
device_lock=self.device_lock)
self._driver.process_pv_updates(force=True)
self.log.info('Started serving PVs: %s',
', '.join((self._options.prefix + pv for pv in
self.interface.bound_pvs.keys()))) | [
"def",
"start_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"self",
".",
"_server",
"=",
"SimpleServer",
"(",
")",
"self",
".",
"_server",
".",
"createPV",
"(",
"prefix",
"=",
"self",
".",
"_options",
".",
"prefix",
",",
"pvdb",
"=",
"{",
"k",
":",
"v",
".",
"config",
"for",
"k",
",",
"v",
"in",
"self",
".",
"interface",
".",
"bound_pvs",
".",
"items",
"(",
")",
"}",
")",
"self",
".",
"_driver",
"=",
"PropertyExposingDriver",
"(",
"interface",
"=",
"self",
".",
"interface",
",",
"device_lock",
"=",
"self",
".",
"device_lock",
")",
"self",
".",
"_driver",
".",
"process_pv_updates",
"(",
"force",
"=",
"True",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Started serving PVs: %s'",
",",
"', '",
".",
"join",
"(",
"(",
"self",
".",
"_options",
".",
"prefix",
"+",
"pv",
"for",
"pv",
"in",
"self",
".",
"interface",
".",
"bound_pvs",
".",
"keys",
"(",
")",
")",
")",
")"
] | Creates a pcaspy-server.
.. note::
The server does not process requests unless :meth:`handle` is called regularly. | [
"Creates",
"a",
"pcaspy",
"-",
"server",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L550-L568 | train | 236,781 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | EpicsAdapter.handle | def handle(self, cycle_delay=0.1):
"""
Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not corrected for.
:param cycle_delay: Approximate time to be spent processing requests in pcaspy server.
"""
if self._server is not None:
self._server.process(cycle_delay)
self._driver.process_pv_updates() | python | def handle(self, cycle_delay=0.1):
"""
Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not corrected for.
:param cycle_delay: Approximate time to be spent processing requests in pcaspy server.
"""
if self._server is not None:
self._server.process(cycle_delay)
self._driver.process_pv_updates() | [
"def",
"handle",
"(",
"self",
",",
"cycle_delay",
"=",
"0.1",
")",
":",
"if",
"self",
".",
"_server",
"is",
"not",
"None",
":",
"self",
".",
"_server",
".",
"process",
"(",
"cycle_delay",
")",
"self",
".",
"_driver",
".",
"process_pv_updates",
"(",
")"
] | Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not corrected for.
:param cycle_delay: Approximate time to be spent processing requests in pcaspy server. | [
"Call",
"this",
"method",
"to",
"spend",
"about",
"cycle_delay",
"seconds",
"processing",
"requests",
"in",
"the",
"pcaspy",
"server",
".",
"Under",
"load",
"for",
"example",
"when",
"running",
"caget",
"at",
"a",
"high",
"frequency",
"the",
"actual",
"time",
"spent",
"in",
"the",
"method",
"may",
"be",
"much",
"shorter",
".",
"This",
"effect",
"is",
"not",
"corrected",
"for",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L578-L589 | train | 236,782 |
DMSC-Instrument-Data/lewis | src/lewis/core/control_client.py | ObjectProxy._make_request | def _make_request(self, method, *args):
"""
This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptions-module.
Otherwise, a RemoteException is raised.
:param method: Method of the object to call on the remote.
:param args: Positional arguments to the method call.
:return: Result of the remote call if successful.
"""
response, request_id = self._connection.json_rpc(self._prefix + method, *args)
if 'id' not in response:
raise ProtocolException('JSON-RPC response does not contain ID field.')
if response['id'] != request_id:
raise ProtocolException(
'ID of JSON-RPC request ({}) did not match response ({}).'.format(
request_id, response['id']))
if 'result' in response:
return response['result']
if 'error' in response:
if 'data' in response['error']:
exception_type = response['error']['data']['type']
exception_message = response['error']['data']['message']
if not hasattr(exceptions, exception_type):
raise RemoteException(exception_type, exception_message)
else:
exception = getattr(exceptions, exception_type)
raise exception(exception_message)
else:
raise ProtocolException(response['error']['message']) | python | def _make_request(self, method, *args):
"""
This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptions-module.
Otherwise, a RemoteException is raised.
:param method: Method of the object to call on the remote.
:param args: Positional arguments to the method call.
:return: Result of the remote call if successful.
"""
response, request_id = self._connection.json_rpc(self._prefix + method, *args)
if 'id' not in response:
raise ProtocolException('JSON-RPC response does not contain ID field.')
if response['id'] != request_id:
raise ProtocolException(
'ID of JSON-RPC request ({}) did not match response ({}).'.format(
request_id, response['id']))
if 'result' in response:
return response['result']
if 'error' in response:
if 'data' in response['error']:
exception_type = response['error']['data']['type']
exception_message = response['error']['data']['message']
if not hasattr(exceptions, exception_type):
raise RemoteException(exception_type, exception_message)
else:
exception = getattr(exceptions, exception_type)
raise exception(exception_message)
else:
raise ProtocolException(response['error']['message']) | [
"def",
"_make_request",
"(",
"self",
",",
"method",
",",
"*",
"args",
")",
":",
"response",
",",
"request_id",
"=",
"self",
".",
"_connection",
".",
"json_rpc",
"(",
"self",
".",
"_prefix",
"+",
"method",
",",
"*",
"args",
")",
"if",
"'id'",
"not",
"in",
"response",
":",
"raise",
"ProtocolException",
"(",
"'JSON-RPC response does not contain ID field.'",
")",
"if",
"response",
"[",
"'id'",
"]",
"!=",
"request_id",
":",
"raise",
"ProtocolException",
"(",
"'ID of JSON-RPC request ({}) did not match response ({}).'",
".",
"format",
"(",
"request_id",
",",
"response",
"[",
"'id'",
"]",
")",
")",
"if",
"'result'",
"in",
"response",
":",
"return",
"response",
"[",
"'result'",
"]",
"if",
"'error'",
"in",
"response",
":",
"if",
"'data'",
"in",
"response",
"[",
"'error'",
"]",
":",
"exception_type",
"=",
"response",
"[",
"'error'",
"]",
"[",
"'data'",
"]",
"[",
"'type'",
"]",
"exception_message",
"=",
"response",
"[",
"'error'",
"]",
"[",
"'data'",
"]",
"[",
"'message'",
"]",
"if",
"not",
"hasattr",
"(",
"exceptions",
",",
"exception_type",
")",
":",
"raise",
"RemoteException",
"(",
"exception_type",
",",
"exception_message",
")",
"else",
":",
"exception",
"=",
"getattr",
"(",
"exceptions",
",",
"exception_type",
")",
"raise",
"exception",
"(",
"exception_message",
")",
"else",
":",
"raise",
"ProtocolException",
"(",
"response",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
")"
] | This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptions-module.
Otherwise, a RemoteException is raised.
:param method: Method of the object to call on the remote.
:param args: Positional arguments to the method call.
:return: Result of the remote call if successful. | [
"This",
"method",
"performs",
"a",
"JSON",
"-",
"RPC",
"request",
"via",
"the",
"object",
"s",
"ZMQ",
"socket",
".",
"If",
"successful",
"the",
"result",
"is",
"returned",
"otherwise",
"exceptions",
"are",
"raised",
".",
"Server",
"side",
"exceptions",
"are",
"raised",
"using",
"the",
"same",
"type",
"as",
"on",
"the",
"server",
"if",
"they",
"are",
"part",
"of",
"the",
"exceptions",
"-",
"module",
".",
"Otherwise",
"a",
"RemoteException",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/control_client.py#L194-L229 | train | 236,783 |
DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.get_status | def get_status(self):
"""
Models "T Command" functionality of device.
Returns all available status information about the device as single byte array.
:return: Byte array consisting of 10 status bytes.
"""
# "The first command sent must be a 'T' command" from T95 manual
self.device.serial_command_mode = True
Tarray = [0x80] * 10
# Status byte (SB1)
Tarray[0] = {
'stopped': 0x01,
'heat': 0x10,
'cool': 0x20,
'hold': 0x30,
}.get(self.device._csm.state, 0x01)
if Tarray[0] == 0x30 and self.device.hold_commanded:
Tarray[0] = 0x50
# Error status byte (EB1)
if self.device.pump_overspeed:
Tarray[1] |= 0x01
# TODO: Add support for other error conditions?
# Pump status byte (PB1)
Tarray[2] = 0x80 + self.device.pump_speed
# Temperature
Tarray[6:10] = [ord(x) for x in "%04x" % (int(self.device.temperature * 10) & 0xFFFF)]
return ''.join(chr(c) for c in Tarray) | python | def get_status(self):
"""
Models "T Command" functionality of device.
Returns all available status information about the device as single byte array.
:return: Byte array consisting of 10 status bytes.
"""
# "The first command sent must be a 'T' command" from T95 manual
self.device.serial_command_mode = True
Tarray = [0x80] * 10
# Status byte (SB1)
Tarray[0] = {
'stopped': 0x01,
'heat': 0x10,
'cool': 0x20,
'hold': 0x30,
}.get(self.device._csm.state, 0x01)
if Tarray[0] == 0x30 and self.device.hold_commanded:
Tarray[0] = 0x50
# Error status byte (EB1)
if self.device.pump_overspeed:
Tarray[1] |= 0x01
# TODO: Add support for other error conditions?
# Pump status byte (PB1)
Tarray[2] = 0x80 + self.device.pump_speed
# Temperature
Tarray[6:10] = [ord(x) for x in "%04x" % (int(self.device.temperature * 10) & 0xFFFF)]
return ''.join(chr(c) for c in Tarray) | [
"def",
"get_status",
"(",
"self",
")",
":",
"# \"The first command sent must be a 'T' command\" from T95 manual",
"self",
".",
"device",
".",
"serial_command_mode",
"=",
"True",
"Tarray",
"=",
"[",
"0x80",
"]",
"*",
"10",
"# Status byte (SB1)",
"Tarray",
"[",
"0",
"]",
"=",
"{",
"'stopped'",
":",
"0x01",
",",
"'heat'",
":",
"0x10",
",",
"'cool'",
":",
"0x20",
",",
"'hold'",
":",
"0x30",
",",
"}",
".",
"get",
"(",
"self",
".",
"device",
".",
"_csm",
".",
"state",
",",
"0x01",
")",
"if",
"Tarray",
"[",
"0",
"]",
"==",
"0x30",
"and",
"self",
".",
"device",
".",
"hold_commanded",
":",
"Tarray",
"[",
"0",
"]",
"=",
"0x50",
"# Error status byte (EB1)",
"if",
"self",
".",
"device",
".",
"pump_overspeed",
":",
"Tarray",
"[",
"1",
"]",
"|=",
"0x01",
"# TODO: Add support for other error conditions?",
"# Pump status byte (PB1)",
"Tarray",
"[",
"2",
"]",
"=",
"0x80",
"+",
"self",
".",
"device",
".",
"pump_speed",
"# Temperature",
"Tarray",
"[",
"6",
":",
"10",
"]",
"=",
"[",
"ord",
"(",
"x",
")",
"for",
"x",
"in",
"\"%04x\"",
"%",
"(",
"int",
"(",
"self",
".",
"device",
".",
"temperature",
"*",
"10",
")",
"&",
"0xFFFF",
")",
"]",
"return",
"''",
".",
"join",
"(",
"chr",
"(",
"c",
")",
"for",
"c",
"in",
"Tarray",
")"
] | Models "T Command" functionality of device.
Returns all available status information about the device as single byte array.
:return: Byte array consisting of 10 status bytes. | [
"Models",
"T",
"Command",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L49-L85 | train | 236,784 |
DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.set_rate | def set_rate(self, param):
"""
Models "Rate Command" functionality of device.
Sets the target rate of temperature change.
:param param: Rate of temperature change in C/min, multiplied by 100, as a string.
Must be positive.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
rate = int(param)
if 1 <= rate <= 15000:
self.device.temperature_rate = rate / 100.0
return "" | python | def set_rate(self, param):
"""
Models "Rate Command" functionality of device.
Sets the target rate of temperature change.
:param param: Rate of temperature change in C/min, multiplied by 100, as a string.
Must be positive.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
rate = int(param)
if 1 <= rate <= 15000:
self.device.temperature_rate = rate / 100.0
return "" | [
"def",
"set_rate",
"(",
"self",
",",
"param",
")",
":",
"# TODO: Is not having leading zeroes / 4 digits an error?",
"rate",
"=",
"int",
"(",
"param",
")",
"if",
"1",
"<=",
"rate",
"<=",
"15000",
":",
"self",
".",
"device",
".",
"temperature_rate",
"=",
"rate",
"/",
"100.0",
"return",
"\"\""
] | Models "Rate Command" functionality of device.
Sets the target rate of temperature change.
:param param: Rate of temperature change in C/min, multiplied by 100, as a string.
Must be positive.
:return: Empty string. | [
"Models",
"Rate",
"Command",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L87-L101 | train | 236,785 |
DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.set_limit | def set_limit(self, param):
"""
Models "Limit Command" functionality of device.
Sets the target temperate to be reached.
:param param: Target temperature in C, multiplied by 10, as a string. Can be negative.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
limit = int(param)
if -2000 <= limit <= 6000:
self.device.temperature_limit = limit / 10.0
return "" | python | def set_limit(self, param):
"""
Models "Limit Command" functionality of device.
Sets the target temperate to be reached.
:param param: Target temperature in C, multiplied by 10, as a string. Can be negative.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
limit = int(param)
if -2000 <= limit <= 6000:
self.device.temperature_limit = limit / 10.0
return "" | [
"def",
"set_limit",
"(",
"self",
",",
"param",
")",
":",
"# TODO: Is not having leading zeroes / 4 digits an error?",
"limit",
"=",
"int",
"(",
"param",
")",
"if",
"-",
"2000",
"<=",
"limit",
"<=",
"6000",
":",
"self",
".",
"device",
".",
"temperature_limit",
"=",
"limit",
"/",
"10.0",
"return",
"\"\""
] | Models "Limit Command" functionality of device.
Sets the target temperate to be reached.
:param param: Target temperature in C, multiplied by 10, as a string. Can be negative.
:return: Empty string. | [
"Models",
"Limit",
"Command",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L103-L116 | train | 236,786 |
DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.pump_command | def pump_command(self, param):
"""
Models "LNP Pump Commands" functionality of device.
Switches between automatic or manual pump mode, and adjusts speed when in manual mode.
:param param: 'a0' for auto, 'm0' for manual, [0-N] for speed.
:return:
"""
lookup = [c for c in "0123456789:;<=>?@ABCDEFGHIJKLMN"]
if param == "a0":
self.device.pump_manual_mode = False
elif param == "m0":
self.device.pump_manual_mode = True
elif param in lookup:
self.device.manual_target_speed = lookup.index(param)
return "" | python | def pump_command(self, param):
"""
Models "LNP Pump Commands" functionality of device.
Switches between automatic or manual pump mode, and adjusts speed when in manual mode.
:param param: 'a0' for auto, 'm0' for manual, [0-N] for speed.
:return:
"""
lookup = [c for c in "0123456789:;<=>?@ABCDEFGHIJKLMN"]
if param == "a0":
self.device.pump_manual_mode = False
elif param == "m0":
self.device.pump_manual_mode = True
elif param in lookup:
self.device.manual_target_speed = lookup.index(param)
return "" | [
"def",
"pump_command",
"(",
"self",
",",
"param",
")",
":",
"lookup",
"=",
"[",
"c",
"for",
"c",
"in",
"\"0123456789:;<=>?@ABCDEFGHIJKLMN\"",
"]",
"if",
"param",
"==",
"\"a0\"",
":",
"self",
".",
"device",
".",
"pump_manual_mode",
"=",
"False",
"elif",
"param",
"==",
"\"m0\"",
":",
"self",
".",
"device",
".",
"pump_manual_mode",
"=",
"True",
"elif",
"param",
"in",
"lookup",
":",
"self",
".",
"device",
".",
"manual_target_speed",
"=",
"lookup",
".",
"index",
"(",
"param",
")",
"return",
"\"\""
] | Models "LNP Pump Commands" functionality of device.
Switches between automatic or manual pump mode, and adjusts speed when in manual mode.
:param param: 'a0' for auto, 'm0' for manual, [0-N] for speed.
:return: | [
"Models",
"LNP",
"Pump",
"Commands",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L172-L190 | train | 236,787 |
DMSC-Instrument-Data/lewis | src/lewis/core/statemachine.py | HasContext.set_context | def set_context(self, new_context):
"""Assigns the new context to the member variable ``_context``."""
self._context = new_context
if hasattr(self, '_set_logging_context'):
self._set_logging_context(self._context) | python | def set_context(self, new_context):
"""Assigns the new context to the member variable ``_context``."""
self._context = new_context
if hasattr(self, '_set_logging_context'):
self._set_logging_context(self._context) | [
"def",
"set_context",
"(",
"self",
",",
"new_context",
")",
":",
"self",
".",
"_context",
"=",
"new_context",
"if",
"hasattr",
"(",
"self",
",",
"'_set_logging_context'",
")",
":",
"self",
".",
"_set_logging_context",
"(",
"self",
".",
"_context",
")"
] | Assigns the new context to the member variable ``_context``. | [
"Assigns",
"the",
"new",
"context",
"to",
"the",
"member",
"variable",
"_context",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/statemachine.py#L56-L61 | train | 236,788 |
DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/devices/device.py | SimulatedLinkamT95._initialize_data | def _initialize_data(self):
"""
This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member variable will
raise an exception. This is to prevent typos from inadvertently
and silently adding new members instead of accessing existing ones.
"""
self.serial_command_mode = False
self.pump_overspeed = False
self.start_commanded = False
self.stop_commanded = False
self.hold_commanded = False
# Real device remembers values from last run, we use arbitrary defaults
self.temperature_rate = 5.0 # Rate of change of temperature in C/min
self.temperature_limit = 0.0 # Target temperature in C
self.pump_speed = 0 # Pump speed in arbitrary unit, ranging 0 to 30
self.temperature = 24.0 # Current temperature in C
self.pump_manual_mode = False
self.manual_target_speed = 0 | python | def _initialize_data(self):
"""
This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member variable will
raise an exception. This is to prevent typos from inadvertently
and silently adding new members instead of accessing existing ones.
"""
self.serial_command_mode = False
self.pump_overspeed = False
self.start_commanded = False
self.stop_commanded = False
self.hold_commanded = False
# Real device remembers values from last run, we use arbitrary defaults
self.temperature_rate = 5.0 # Rate of change of temperature in C/min
self.temperature_limit = 0.0 # Target temperature in C
self.pump_speed = 0 # Pump speed in arbitrary unit, ranging 0 to 30
self.temperature = 24.0 # Current temperature in C
self.pump_manual_mode = False
self.manual_target_speed = 0 | [
"def",
"_initialize_data",
"(",
"self",
")",
":",
"self",
".",
"serial_command_mode",
"=",
"False",
"self",
".",
"pump_overspeed",
"=",
"False",
"self",
".",
"start_commanded",
"=",
"False",
"self",
".",
"stop_commanded",
"=",
"False",
"self",
".",
"hold_commanded",
"=",
"False",
"# Real device remembers values from last run, we use arbitrary defaults",
"self",
".",
"temperature_rate",
"=",
"5.0",
"# Rate of change of temperature in C/min",
"self",
".",
"temperature_limit",
"=",
"0.0",
"# Target temperature in C",
"self",
".",
"pump_speed",
"=",
"0",
"# Pump speed in arbitrary unit, ranging 0 to 30",
"self",
".",
"temperature",
"=",
"24.0",
"# Current temperature in C",
"self",
".",
"pump_manual_mode",
"=",
"False",
"self",
".",
"manual_target_speed",
"=",
"0"
] | This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member variable will
raise an exception. This is to prevent typos from inadvertently
and silently adding new members instead of accessing existing ones. | [
"This",
"method",
"is",
"called",
"once",
"on",
"construction",
".",
"After",
"that",
"it",
"may",
"be",
"manually",
"called",
"again",
"to",
"reset",
"the",
"device",
"to",
"its",
"default",
"state",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/devices/device.py#L28-L54 | train | 236,789 |
DMSC-Instrument-Data/lewis | src/lewis/core/logging.py | has_log | def has_log(target):
"""
This is a decorator to add logging functionality to a class or function.
Applying this decorator to a class or function will add two new members:
- ``log`` is an instance of ``logging.Logger``. The name of the logger is
set to ``lewis.Foo`` for a class named Foo.
- ``_set_logging_context`` is a method that modifies the name of the logger
when the class is used in a certain context.
If ``context`` is a string, that string is directly inserted between ``lewis``
and ``Foo``, so that the logger name would be ``lewis.bar.Foo`` if context
was ``'bar'``. The more common case is probably ``context`` being an object of
some class, in which case the class name is inserted. If ``context`` is an object
of type ``Bar``, the logger name of ``Foo`` would be ``lewis.Bar.Foo``.
To provide a more concrete example in terms of Lewis, this is used for the state
machine logger in a device. So the logs of the state machine belonging to a certain
device appear in the log as originating from ``lewis.DeviceName.StateMachine``, which
makes it possible to distinguish between messages from different state machines.
Example for how to use logging in a class:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
class Foo(Base):
def __init__(self):
super(Foo, self).__init__()
def bar(self, baz):
self.log.debug('Called bar with parameter baz=%s', baz)
return baz is not None
It works similarly for free functions, although the actual logging calls are a bit different:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
def foo(bar):
foo.log.info('Called with argument bar=%s', bar)
return bar
The name of the logger is ``lewis.foo``, the context could also be modified by calling
``foo._set_logging_context``.
:param target: Target to decorate with logging functionality.
"""
logger_name = target.__name__
def get_logger_name(context=None):
log_names = [root_logger_name, logger_name]
if context is not None:
log_names.insert(1,
context if isinstance(context,
string_types) else context.__class__.__name__)
return '.'.join(log_names)
def _set_logging_context(obj, context):
"""
Changes the logger name of this class using the supplied context
according to the rules described in the documentation of :func:`has_log`. To
clear the context of a class logger, supply ``None`` as the argument.
:param context: String or object, ``None`` to clear context.
"""
obj.log.name = get_logger_name(context)
target.log = logging.getLogger(get_logger_name())
target._set_logging_context = _set_logging_context
return target | python | def has_log(target):
"""
This is a decorator to add logging functionality to a class or function.
Applying this decorator to a class or function will add two new members:
- ``log`` is an instance of ``logging.Logger``. The name of the logger is
set to ``lewis.Foo`` for a class named Foo.
- ``_set_logging_context`` is a method that modifies the name of the logger
when the class is used in a certain context.
If ``context`` is a string, that string is directly inserted between ``lewis``
and ``Foo``, so that the logger name would be ``lewis.bar.Foo`` if context
was ``'bar'``. The more common case is probably ``context`` being an object of
some class, in which case the class name is inserted. If ``context`` is an object
of type ``Bar``, the logger name of ``Foo`` would be ``lewis.Bar.Foo``.
To provide a more concrete example in terms of Lewis, this is used for the state
machine logger in a device. So the logs of the state machine belonging to a certain
device appear in the log as originating from ``lewis.DeviceName.StateMachine``, which
makes it possible to distinguish between messages from different state machines.
Example for how to use logging in a class:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
class Foo(Base):
def __init__(self):
super(Foo, self).__init__()
def bar(self, baz):
self.log.debug('Called bar with parameter baz=%s', baz)
return baz is not None
It works similarly for free functions, although the actual logging calls are a bit different:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
def foo(bar):
foo.log.info('Called with argument bar=%s', bar)
return bar
The name of the logger is ``lewis.foo``, the context could also be modified by calling
``foo._set_logging_context``.
:param target: Target to decorate with logging functionality.
"""
logger_name = target.__name__
def get_logger_name(context=None):
log_names = [root_logger_name, logger_name]
if context is not None:
log_names.insert(1,
context if isinstance(context,
string_types) else context.__class__.__name__)
return '.'.join(log_names)
def _set_logging_context(obj, context):
"""
Changes the logger name of this class using the supplied context
according to the rules described in the documentation of :func:`has_log`. To
clear the context of a class logger, supply ``None`` as the argument.
:param context: String or object, ``None`` to clear context.
"""
obj.log.name = get_logger_name(context)
target.log = logging.getLogger(get_logger_name())
target._set_logging_context = _set_logging_context
return target | [
"def",
"has_log",
"(",
"target",
")",
":",
"logger_name",
"=",
"target",
".",
"__name__",
"def",
"get_logger_name",
"(",
"context",
"=",
"None",
")",
":",
"log_names",
"=",
"[",
"root_logger_name",
",",
"logger_name",
"]",
"if",
"context",
"is",
"not",
"None",
":",
"log_names",
".",
"insert",
"(",
"1",
",",
"context",
"if",
"isinstance",
"(",
"context",
",",
"string_types",
")",
"else",
"context",
".",
"__class__",
".",
"__name__",
")",
"return",
"'.'",
".",
"join",
"(",
"log_names",
")",
"def",
"_set_logging_context",
"(",
"obj",
",",
"context",
")",
":",
"\"\"\"\n Changes the logger name of this class using the supplied context\n according to the rules described in the documentation of :func:`has_log`. To\n clear the context of a class logger, supply ``None`` as the argument.\n\n :param context: String or object, ``None`` to clear context.\n \"\"\"",
"obj",
".",
"log",
".",
"name",
"=",
"get_logger_name",
"(",
"context",
")",
"target",
".",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"get_logger_name",
"(",
")",
")",
"target",
".",
"_set_logging_context",
"=",
"_set_logging_context",
"return",
"target"
] | This is a decorator to add logging functionality to a class or function.
Applying this decorator to a class or function will add two new members:
- ``log`` is an instance of ``logging.Logger``. The name of the logger is
set to ``lewis.Foo`` for a class named Foo.
- ``_set_logging_context`` is a method that modifies the name of the logger
when the class is used in a certain context.
If ``context`` is a string, that string is directly inserted between ``lewis``
and ``Foo``, so that the logger name would be ``lewis.bar.Foo`` if context
was ``'bar'``. The more common case is probably ``context`` being an object of
some class, in which case the class name is inserted. If ``context`` is an object
of type ``Bar``, the logger name of ``Foo`` would be ``lewis.Bar.Foo``.
To provide a more concrete example in terms of Lewis, this is used for the state
machine logger in a device. So the logs of the state machine belonging to a certain
device appear in the log as originating from ``lewis.DeviceName.StateMachine``, which
makes it possible to distinguish between messages from different state machines.
Example for how to use logging in a class:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
class Foo(Base):
def __init__(self):
super(Foo, self).__init__()
def bar(self, baz):
self.log.debug('Called bar with parameter baz=%s', baz)
return baz is not None
It works similarly for free functions, although the actual logging calls are a bit different:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
def foo(bar):
foo.log.info('Called with argument bar=%s', bar)
return bar
The name of the logger is ``lewis.foo``, the context could also be modified by calling
``foo._set_logging_context``.
:param target: Target to decorate with logging functionality. | [
"This",
"is",
"a",
"decorator",
"to",
"add",
"logging",
"functionality",
"to",
"a",
"class",
"or",
"function",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/logging.py#L44-L122 | train | 236,790 |
DMSC-Instrument-Data/lewis | src/lewis/scripts/__init__.py | get_usage_text | def get_usage_text(parser, indent=None):
"""
This small helper function extracts the help information from an ArgumentParser instance
and indents the text by the number of spaces supplied in the indent-argument.
:param parser: ArgumentParser object.
:param indent: Number of spaces to put before each line or None.
:return: Formatted help string of the supplied parser.
"""
usage_text = StringIO()
parser.print_help(usage_text)
usage_string = usage_text.getvalue()
if indent is None:
return usage_string
return '\n'.join([' ' * indent + line for line in usage_string.split('\n')]) | python | def get_usage_text(parser, indent=None):
"""
This small helper function extracts the help information from an ArgumentParser instance
and indents the text by the number of spaces supplied in the indent-argument.
:param parser: ArgumentParser object.
:param indent: Number of spaces to put before each line or None.
:return: Formatted help string of the supplied parser.
"""
usage_text = StringIO()
parser.print_help(usage_text)
usage_string = usage_text.getvalue()
if indent is None:
return usage_string
return '\n'.join([' ' * indent + line for line in usage_string.split('\n')]) | [
"def",
"get_usage_text",
"(",
"parser",
",",
"indent",
"=",
"None",
")",
":",
"usage_text",
"=",
"StringIO",
"(",
")",
"parser",
".",
"print_help",
"(",
"usage_text",
")",
"usage_string",
"=",
"usage_text",
".",
"getvalue",
"(",
")",
"if",
"indent",
"is",
"None",
":",
"return",
"usage_string",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"' '",
"*",
"indent",
"+",
"line",
"for",
"line",
"in",
"usage_string",
".",
"split",
"(",
"'\\n'",
")",
"]",
")"
] | This small helper function extracts the help information from an ArgumentParser instance
and indents the text by the number of spaces supplied in the indent-argument.
:param parser: ArgumentParser object.
:param indent: Number of spaces to put before each line or None.
:return: Formatted help string of the supplied parser. | [
"This",
"small",
"helper",
"function",
"extracts",
"the",
"help",
"information",
"from",
"an",
"ArgumentParser",
"instance",
"and",
"indents",
"the",
"text",
"by",
"the",
"number",
"of",
"spaces",
"supplied",
"in",
"the",
"indent",
"-",
"argument",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/scripts/__init__.py#L23-L40 | train | 236,791 |
DMSC-Instrument-Data/lewis | src/lewis/examples/example_motor/__init__.py | SimulatedExampleMotor.stop | def stop(self):
"""Stops the motor and returns the new target and position, which are equal"""
self._target = self.position
self.log.info('Stopping movement after user request.')
return self.target, self.position | python | def stop(self):
"""Stops the motor and returns the new target and position, which are equal"""
self._target = self.position
self.log.info('Stopping movement after user request.')
return self.target, self.position | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_target",
"=",
"self",
".",
"position",
"self",
".",
"log",
".",
"info",
"(",
"'Stopping movement after user request.'",
")",
"return",
"self",
".",
"target",
",",
"self",
".",
"position"
] | Stops the motor and returns the new target and position, which are equal | [
"Stops",
"the",
"motor",
"and",
"returns",
"the",
"new",
"target",
"and",
"position",
"which",
"are",
"equal"
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/examples/example_motor/__init__.py#L75-L82 | train | 236,792 |
DMSC-Instrument-Data/lewis | src/lewis/scripts/run.py | run_simulation | def run_simulation(argument_list=None): # noqa: C901
"""
This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list: Argument list to pass to the argument parser declared in this module.
"""
try:
arguments = parser.parse_args(argument_list or sys.argv[1:])
if arguments.version:
print(__version__)
return
if arguments.relaxed_versions:
print('Unknown option --relaxed-versions. Did you mean --ignore-versions?')
return
loglevel = 'debug' if arguments.verify else arguments.output_level
if loglevel != 'none':
logging.basicConfig(
level=getattr(logging, loglevel.upper()), format=default_log_format)
if arguments.add_path is not None:
additional_path = os.path.abspath(arguments.add_path)
logging.getLogger().debug('Extending path with: %s', additional_path)
sys.path.append(additional_path)
strict_versions = use_strict_versions(arguments.strict_versions, arguments.ignore_versions)
simulation_factory = SimulationFactory(arguments.device_package, strict_versions)
if not arguments.device:
devices = ['Please specify a device to simulate. The following devices are available:']
for dev in simulation_factory.devices:
devices.append(' ' + dev)
print('\n'.join(devices))
return
if arguments.list_protocols:
print('\n'.join(simulation_factory.get_protocols(arguments.device)))
return
protocols = parse_adapter_options(arguments.adapter_options) \
if not arguments.no_interface else {}
simulation = simulation_factory.create(
arguments.device, arguments.setup, protocols, arguments.rpc_host)
if arguments.show_interface:
print(simulation._adapters.documentation())
return
if arguments.list_adapter_options:
configurations = simulation._adapters.configuration()
for protocol, options in configurations.items():
print('{}:'.format(protocol))
for opt, val in options.items():
print(' {} = {}'.format(opt, val))
return
simulation.cycle_delay = arguments.cycle_delay
simulation.speed = arguments.speed
if not arguments.verify:
try:
simulation.start()
except KeyboardInterrupt:
print('\nInterrupt received; shutting down. Goodbye, cruel world!')
simulation.log.critical('Simulation aborted by user interaction')
finally:
simulation.stop()
except LewisException as e:
print('\n'.join(('An error occurred:', str(e)))) | python | def run_simulation(argument_list=None): # noqa: C901
"""
This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list: Argument list to pass to the argument parser declared in this module.
"""
try:
arguments = parser.parse_args(argument_list or sys.argv[1:])
if arguments.version:
print(__version__)
return
if arguments.relaxed_versions:
print('Unknown option --relaxed-versions. Did you mean --ignore-versions?')
return
loglevel = 'debug' if arguments.verify else arguments.output_level
if loglevel != 'none':
logging.basicConfig(
level=getattr(logging, loglevel.upper()), format=default_log_format)
if arguments.add_path is not None:
additional_path = os.path.abspath(arguments.add_path)
logging.getLogger().debug('Extending path with: %s', additional_path)
sys.path.append(additional_path)
strict_versions = use_strict_versions(arguments.strict_versions, arguments.ignore_versions)
simulation_factory = SimulationFactory(arguments.device_package, strict_versions)
if not arguments.device:
devices = ['Please specify a device to simulate. The following devices are available:']
for dev in simulation_factory.devices:
devices.append(' ' + dev)
print('\n'.join(devices))
return
if arguments.list_protocols:
print('\n'.join(simulation_factory.get_protocols(arguments.device)))
return
protocols = parse_adapter_options(arguments.adapter_options) \
if not arguments.no_interface else {}
simulation = simulation_factory.create(
arguments.device, arguments.setup, protocols, arguments.rpc_host)
if arguments.show_interface:
print(simulation._adapters.documentation())
return
if arguments.list_adapter_options:
configurations = simulation._adapters.configuration()
for protocol, options in configurations.items():
print('{}:'.format(protocol))
for opt, val in options.items():
print(' {} = {}'.format(opt, val))
return
simulation.cycle_delay = arguments.cycle_delay
simulation.speed = arguments.speed
if not arguments.verify:
try:
simulation.start()
except KeyboardInterrupt:
print('\nInterrupt received; shutting down. Goodbye, cruel world!')
simulation.log.critical('Simulation aborted by user interaction')
finally:
simulation.stop()
except LewisException as e:
print('\n'.join(('An error occurred:', str(e)))) | [
"def",
"run_simulation",
"(",
"argument_list",
"=",
"None",
")",
":",
"# noqa: C901",
"try",
":",
"arguments",
"=",
"parser",
".",
"parse_args",
"(",
"argument_list",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"arguments",
".",
"version",
":",
"print",
"(",
"__version__",
")",
"return",
"if",
"arguments",
".",
"relaxed_versions",
":",
"print",
"(",
"'Unknown option --relaxed-versions. Did you mean --ignore-versions?'",
")",
"return",
"loglevel",
"=",
"'debug'",
"if",
"arguments",
".",
"verify",
"else",
"arguments",
".",
"output_level",
"if",
"loglevel",
"!=",
"'none'",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"getattr",
"(",
"logging",
",",
"loglevel",
".",
"upper",
"(",
")",
")",
",",
"format",
"=",
"default_log_format",
")",
"if",
"arguments",
".",
"add_path",
"is",
"not",
"None",
":",
"additional_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"arguments",
".",
"add_path",
")",
"logging",
".",
"getLogger",
"(",
")",
".",
"debug",
"(",
"'Extending path with: %s'",
",",
"additional_path",
")",
"sys",
".",
"path",
".",
"append",
"(",
"additional_path",
")",
"strict_versions",
"=",
"use_strict_versions",
"(",
"arguments",
".",
"strict_versions",
",",
"arguments",
".",
"ignore_versions",
")",
"simulation_factory",
"=",
"SimulationFactory",
"(",
"arguments",
".",
"device_package",
",",
"strict_versions",
")",
"if",
"not",
"arguments",
".",
"device",
":",
"devices",
"=",
"[",
"'Please specify a device to simulate. The following devices are available:'",
"]",
"for",
"dev",
"in",
"simulation_factory",
".",
"devices",
":",
"devices",
".",
"append",
"(",
"' '",
"+",
"dev",
")",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"devices",
")",
")",
"return",
"if",
"arguments",
".",
"list_protocols",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"simulation_factory",
".",
"get_protocols",
"(",
"arguments",
".",
"device",
")",
")",
")",
"return",
"protocols",
"=",
"parse_adapter_options",
"(",
"arguments",
".",
"adapter_options",
")",
"if",
"not",
"arguments",
".",
"no_interface",
"else",
"{",
"}",
"simulation",
"=",
"simulation_factory",
".",
"create",
"(",
"arguments",
".",
"device",
",",
"arguments",
".",
"setup",
",",
"protocols",
",",
"arguments",
".",
"rpc_host",
")",
"if",
"arguments",
".",
"show_interface",
":",
"print",
"(",
"simulation",
".",
"_adapters",
".",
"documentation",
"(",
")",
")",
"return",
"if",
"arguments",
".",
"list_adapter_options",
":",
"configurations",
"=",
"simulation",
".",
"_adapters",
".",
"configuration",
"(",
")",
"for",
"protocol",
",",
"options",
"in",
"configurations",
".",
"items",
"(",
")",
":",
"print",
"(",
"'{}:'",
".",
"format",
"(",
"protocol",
")",
")",
"for",
"opt",
",",
"val",
"in",
"options",
".",
"items",
"(",
")",
":",
"print",
"(",
"' {} = {}'",
".",
"format",
"(",
"opt",
",",
"val",
")",
")",
"return",
"simulation",
".",
"cycle_delay",
"=",
"arguments",
".",
"cycle_delay",
"simulation",
".",
"speed",
"=",
"arguments",
".",
"speed",
"if",
"not",
"arguments",
".",
"verify",
":",
"try",
":",
"simulation",
".",
"start",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"'\\nInterrupt received; shutting down. Goodbye, cruel world!'",
")",
"simulation",
".",
"log",
".",
"critical",
"(",
"'Simulation aborted by user interaction'",
")",
"finally",
":",
"simulation",
".",
"stop",
"(",
")",
"except",
"LewisException",
"as",
"e",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"(",
"'An error occurred:'",
",",
"str",
"(",
"e",
")",
")",
")",
")"
] | This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list: Argument list to pass to the argument parser declared in this module. | [
"This",
"is",
"effectively",
"the",
"main",
"function",
"of",
"a",
"typical",
"simulation",
"run",
".",
"Arguments",
"passed",
"in",
"are",
"parsed",
"and",
"used",
"to",
"construct",
"and",
"run",
"the",
"simulation",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/scripts/run.py#L172-L253 | train | 236,793 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | Func.map_arguments | def map_arguments(self, arguments):
"""
Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments.
"""
if self.argument_mappings is None:
return arguments
return [f(a) for f, a in zip(self.argument_mappings, arguments)] | python | def map_arguments(self, arguments):
"""
Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments.
"""
if self.argument_mappings is None:
return arguments
return [f(a) for f, a in zip(self.argument_mappings, arguments)] | [
"def",
"map_arguments",
"(",
"self",
",",
"arguments",
")",
":",
"if",
"self",
".",
"argument_mappings",
"is",
"None",
":",
"return",
"arguments",
"return",
"[",
"f",
"(",
"a",
")",
"for",
"f",
",",
"a",
"in",
"zip",
"(",
"self",
".",
"argument_mappings",
",",
"arguments",
")",
"]"
] | Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments. | [
"Returns",
"the",
"mapped",
"function",
"arguments",
".",
"If",
"no",
"mapping",
"functions",
"are",
"defined",
"the",
"arguments",
"are",
"returned",
"as",
"they",
"were",
"supplied",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L368-L379 | train | 236,794 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | Func.map_return_value | def map_return_value(self, return_value):
"""
Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_value: Value to map.
:return: Mapped return value.
"""
if callable(self.return_mapping):
return self.return_mapping(return_value)
if self.return_mapping is not None:
return self.return_mapping
return return_value | python | def map_return_value(self, return_value):
"""
Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_value: Value to map.
:return: Mapped return value.
"""
if callable(self.return_mapping):
return self.return_mapping(return_value)
if self.return_mapping is not None:
return self.return_mapping
return return_value | [
"def",
"map_return_value",
"(",
"self",
",",
"return_value",
")",
":",
"if",
"callable",
"(",
"self",
".",
"return_mapping",
")",
":",
"return",
"self",
".",
"return_mapping",
"(",
"return_value",
")",
"if",
"self",
".",
"return_mapping",
"is",
"not",
"None",
":",
"return",
"self",
".",
"return_mapping",
"return",
"return_value"
] | Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_value: Value to map.
:return: Mapped return value. | [
"Returns",
"the",
"mapped",
"return_value",
"of",
"a",
"processed",
"request",
".",
"If",
"no",
"return_mapping",
"has",
"been",
"defined",
"the",
"value",
"is",
"returned",
"as",
"is",
".",
"If",
"return_mapping",
"is",
"a",
"static",
"value",
"that",
"value",
"is",
"returned",
"ignoring",
"return_value",
"completely",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L381-L396 | train | 236,795 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | StreamAdapter.start_server | def start_server(self):
"""
Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals.
"""
if self._server is None:
if self._options.telnet_mode:
self.interface.in_terminator = '\r\n'
self.interface.out_terminator = '\r\n'
self._server = StreamServer(self._options.bind_address, self._options.port,
self.interface, self.device_lock) | python | def start_server(self):
"""
Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals.
"""
if self._server is None:
if self._options.telnet_mode:
self.interface.in_terminator = '\r\n'
self.interface.out_terminator = '\r\n'
self._server = StreamServer(self._options.bind_address, self._options.port,
self.interface, self.device_lock) | [
"def",
"start_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"if",
"self",
".",
"_options",
".",
"telnet_mode",
":",
"self",
".",
"interface",
".",
"in_terminator",
"=",
"'\\r\\n'",
"self",
".",
"interface",
".",
"out_terminator",
"=",
"'\\r\\n'",
"self",
".",
"_server",
"=",
"StreamServer",
"(",
"self",
".",
"_options",
".",
"bind_address",
",",
"self",
".",
"_options",
".",
"port",
",",
"self",
".",
"interface",
",",
"self",
".",
"device_lock",
")"
] | Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals. | [
"Starts",
"the",
"TCP",
"stream",
"server",
"binding",
"to",
"the",
"configured",
"host",
"and",
"port",
".",
"Host",
"and",
"port",
"are",
"configured",
"via",
"the",
"command",
"line",
"arguments",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L632-L647 | train | 236,796 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | StreamAdapter.handle | def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) | python | def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) | [
"def",
"handle",
"(",
"self",
",",
"cycle_delay",
"=",
"0.1",
")",
":",
"asyncore",
".",
"loop",
"(",
"cycle_delay",
",",
"count",
"=",
"1",
")",
"self",
".",
"_server",
".",
"process",
"(",
"int",
"(",
"cycle_delay",
"*",
"1000",
")",
")"
] | Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S | [
"Spend",
"approximately",
"cycle_delay",
"seconds",
"to",
"process",
"requests",
"to",
"the",
"server",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L658-L665 | train | 236,797 |
DMSC-Instrument-Data/lewis | src/lewis/devices/__init__.py | StateMachineDevice._override_data | def _override_data(self, overrides):
"""
This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides.
"""
if overrides is not None:
for name, val in overrides.items():
self.log.debug('Trying to override initial data (%s=%s)', name, val)
if name not in dir(self):
raise AttributeError(
'Can not override non-existing attribute'
'\'{}\' of class \'{}\'.'.format(name, type(self).__name__))
setattr(self, name, val) | python | def _override_data(self, overrides):
"""
This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides.
"""
if overrides is not None:
for name, val in overrides.items():
self.log.debug('Trying to override initial data (%s=%s)', name, val)
if name not in dir(self):
raise AttributeError(
'Can not override non-existing attribute'
'\'{}\' of class \'{}\'.'.format(name, type(self).__name__))
setattr(self, name, val) | [
"def",
"_override_data",
"(",
"self",
",",
"overrides",
")",
":",
"if",
"overrides",
"is",
"not",
"None",
":",
"for",
"name",
",",
"val",
"in",
"overrides",
".",
"items",
"(",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Trying to override initial data (%s=%s)'",
",",
"name",
",",
"val",
")",
"if",
"name",
"not",
"in",
"dir",
"(",
"self",
")",
":",
"raise",
"AttributeError",
"(",
"'Can not override non-existing attribute'",
"'\\'{}\\' of class \\'{}\\'.'",
".",
"format",
"(",
"name",
",",
"type",
"(",
"self",
")",
".",
"__name__",
")",
")",
"setattr",
"(",
"self",
",",
"name",
",",
"val",
")"
] | This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides. | [
"This",
"method",
"overrides",
"data",
"members",
"of",
"the",
"class",
"but",
"does",
"not",
"allow",
"for",
"adding",
"new",
"members",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/__init__.py#L177-L191 | train | 236,798 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusDataBank.get | def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_addr
data = self._data[addr:addr + count]
if len(data) != count:
addr += self._start_addr
raise IndexError("Invalid address range [{:#06x} - {:#06x}]"
.format(addr, addr + count))
return data | python | def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_addr
data = self._data[addr:addr + count]
if len(data) != count:
addr += self._start_addr
raise IndexError("Invalid address range [{:#06x} - {:#06x}]"
.format(addr, addr + count))
return data | [
"def",
"get",
"(",
"self",
",",
"addr",
",",
"count",
")",
":",
"addr",
"-=",
"self",
".",
"_start_addr",
"data",
"=",
"self",
".",
"_data",
"[",
"addr",
":",
"addr",
"+",
"count",
"]",
"if",
"len",
"(",
"data",
")",
"!=",
"count",
":",
"addr",
"+=",
"self",
".",
"_start_addr",
"raise",
"IndexError",
"(",
"\"Invalid address range [{:#06x} - {:#06x}]\"",
".",
"format",
"(",
"addr",
",",
"addr",
"+",
"count",
")",
")",
"return",
"data"
] | Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range | [
"Read",
"list",
"of",
"count",
"values",
"at",
"addr",
"memory",
"location",
"in",
"DataBank",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L64-L79 | train | 236,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.