repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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 sel... | 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 sel... | [
"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_versio... | 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 |
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.e... | 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.e... | [
"def",
"docker_container",
"(",
")",
":",
"if",
"SETUP_SPLASH",
":",
"dm",
"=",
"DockerManager",
"(",
")",
"dm",
".",
"start_container",
"(",
")",
"try",
":",
"requests",
".",
"post",
"(",
"f'{SPLASH_URL}/_gc'",
")",
"except",
"requests",
".",
"exceptions",
... | 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 |
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 Fal... | 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 Fal... | [
"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",
... | 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 |
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 Fals... | 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 Fals... | [
"def",
"is_valid_mimetype",
"(",
"response",
")",
":",
"blacklist",
"=",
"[",
"'image/'",
",",
"]",
"mimetype",
"=",
"response",
".",
"get",
"(",
"'mimeType'",
")",
"if",
"not",
"mimetype",
":",
"return",
"True",
"for",
"bw",
"in",
"blacklist",
":",
"if"... | 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 |
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",
")",
":",
"charset",
"=",
"DEFAULT_CHARSET",
"m",
"=",
"re",
".",
"findall",
"(",
"r';charset=(.*)'",
",",
"response",
".",
"get",
"(",
"'mimeType'",
",",
"''",
")",
")",
"if",
"m",
":",
"charset",
"=",
"m",
"[",
... | 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 |
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 ... | 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 ... | [
"def",
"create_lua_script",
"(",
"plugins",
")",
":",
"lua_template",
"=",
"pkg_resources",
".",
"resource_string",
"(",
"'detectem'",
",",
"'script.lua'",
")",
"template",
"=",
"Template",
"(",
"lua_template",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"javascrip... | 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 |
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 d... | 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 d... | [
"def",
"to_javascript_data",
"(",
"plugins",
")",
":",
"def",
"escape",
"(",
"v",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\"'",
",",
"r'\\\\\"'",
",",
"v",
")",
"def",
"dom_matchers",
"(",
"p",
")",
":",
"dom_matchers",
"=",
"p",
".",
"get_matc... | 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 |
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=... | 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=... | [
"def",
"get_response",
"(",
"url",
",",
"plugins",
",",
"timeout",
"=",
"SPLASH_TIMEOUT",
")",
":",
"lua_script",
"=",
"create_lua_script",
"(",
"plugins",
")",
"lua",
"=",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"lua_script",
")",
"page_url",
"=",
... | 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 |
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']
... | 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']
... | [
"def",
"get_valid_har",
"(",
"har_data",
")",
":",
"new_entries",
"=",
"[",
"]",
"entries",
"=",
"har_data",
".",
"get",
"(",
"'log'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'entries'",
",",
"[",
"]",
")",
"logger",
".",
"debug",
"(",
"'[+] Detected %... | 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 |
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",... | Return entry for embed script | [
"Return",
"entry",
"for",
"embed",
"script"
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L56-L65 | train |
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 f... | 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 f... | [
"def",
"mark_entries",
"(",
"self",
",",
"entries",
")",
":",
"for",
"entry",
"in",
"entries",
":",
"self",
".",
"_set_entry_type",
"(",
"entry",
",",
"RESOURCE_ENTRY",
")",
"main_entry",
"=",
"entries",
"[",
"0",
"]",
"main_location",
"=",
"self",
".",
... | 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 |
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,... | 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,... | [
"def",
"get_hints",
"(",
"self",
",",
"plugin",
")",
":",
"hints",
"=",
"[",
"]",
"for",
"hint_name",
"in",
"getattr",
"(",
"plugin",
",",
"'hints'",
",",
"[",
"]",
")",
":",
"hint_plugin",
"=",
"self",
".",
"_plugins",
".",
"get",
"(",
"hint_name",
... | Return plugin hints from ``plugin``. | [
"Return",
"plugin",
"hints",
"from",
"plugin",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L121-L141 | train |
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': softwar... | 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': softwar... | [
"def",
"process_from_splash",
"(",
"self",
")",
":",
"for",
"software",
"in",
"self",
".",
"_softwares_from_splash",
":",
"plugin",
"=",
"self",
".",
"_plugins",
".",
"get",
"(",
"software",
"[",
"'name'",
"]",
")",
"try",
":",
"additional_data",
"=",
"{",... | 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 |
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 = s... | 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 = s... | [
"def",
"process_har",
"(",
"self",
")",
":",
"hints",
"=",
"[",
"]",
"version_plugins",
"=",
"self",
".",
"_plugins",
".",
"with_version_matchers",
"(",
")",
"generic_plugins",
"=",
"self",
".",
"_plugins",
".",
"with_generic_matchers",
"(",
")",
"for",
"ent... | 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 |
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['... | 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['... | [
"def",
"get_results",
"(",
"self",
",",
"metadata",
"=",
"False",
")",
":",
"results_data",
"=",
"[",
"]",
"self",
".",
"process_har",
"(",
")",
"self",
".",
"process_from_splash",
"(",
")",
"for",
"rt",
"in",
"sorted",
"(",
"self",
".",
"_results",
".... | Return results of the analysis. | [
"Return",
"results",
"of",
"the",
"analysis",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L275-L295 | train |
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 |
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('... | 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('... | [
"def",
"_get_plugin_module_paths",
"(",
"self",
",",
"plugin_dir",
")",
":",
"filepaths",
"=",
"[",
"fp",
"for",
"fp",
"in",
"glob",
".",
"glob",
"(",
"'{}/**/*.py'",
".",
"format",
"(",
"plugin_dir",
")",
",",
"recursive",
"=",
"True",
")",
"if",
"not",... | 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 |
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(
"Cou... | 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(
"Cou... | [
"def",
"load_plugins",
"(",
"self",
",",
"plugins_package",
")",
":",
"try",
":",
"plugin_dir",
"=",
"find_spec",
"(",
"plugins_package",
")",
".",
"submodule_search_locations",
"[",
"0",
"]",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Could... | 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 |
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 ... | 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 ... | [
"def",
"extract_named_group",
"(",
"text",
",",
"named_group",
",",
"matchers",
",",
"return_presence",
"=",
"False",
")",
":",
"presence",
"=",
"False",
"for",
"matcher",
"in",
"matchers",
":",
"if",
"isinstance",
"(",
"matcher",
",",
"str",
")",
":",
"v"... | 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 |
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 |
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 |
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_arg... | 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_arg... | [
"def",
"open",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'get'",
",",
"**",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
",",
"url",
",",
"**",
"self",
".",
"_build_send_args",
"(",
"**",
"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` | [
"Open",
"a",
"URL",
"."
] | 4284c11d00ae1397983e269aa180e5cf7ee5f4cf | https://github.com/jmcarp/robobrowser/blob/4284c11d00ae1397983e269aa180e5cf7ee5f4cf/robobrowser/browser.py#L197-L206 | train |
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._cur... | 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._cur... | [
"def",
"_update_state",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_states",
"=",
"self",
".",
"_states",
"[",
":",
"self",
".",
"_cursor",
"+",
"1",
"]",
"state",
"=",
"RoboState",
"(",
"self",
",",
"response",
")",
"self",
".",
"_states"... | 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 |
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('No... | 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('No... | [
"def",
"_traverse",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"history",
":",
"raise",
"exceptions",
".",
"RoboError",
"(",
"'Not tracking history'",
")",
"cursor",
"=",
"self",
".",
"_cursor",
"+",
"n",
"if",
"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 |
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(
... | 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(
... | [
"def",
"get_link",
"(",
"self",
",",
"text",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"helpers",
".",
"find",
"(",
"self",
".",
"parsed",
",",
"_link_ptn",
",",
"text",
"=",
"text",
",",
"*",
"args",
",",
"**",
"kwa... | 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 |
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(
... | 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(
... | [
"def",
"get_links",
"(",
"self",
",",
"text",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"helpers",
".",
"find_all",
"(",
"self",
".",
"parsed",
",",
"_link_ptn",
",",
"text",
"=",
"text",
",",
"*",
"args",
",",
"**",
... | 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 |
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)
... | 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)
... | [
"def",
"get_form",
"(",
"self",
",",
"id",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"id",
":",
"kwargs",
"[",
"'id'",
"]",
"=",
"id",
"form",
"=",
"self",
".",
"find",
"(",
"_form_ptn",
",",
"*",
"args",
",",
"**",
... | 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 |
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" '
... | 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" '
... | [
"def",
"follow_link",
"(",
"self",
",",
"link",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"href",
"=",
"link",
"[",
"'href'",
"]",
"except",
"KeyError",
":",
"raise",
"exceptions",
".",
"RoboError",
"(",
"'Link element must have \"href\" '",
"'attribute'",
... | 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 |
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 H... | 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 H... | [
"def",
"submit_form",
"(",
"self",
",",
"form",
",",
"submit",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"method",
"=",
"form",
".",
"method",
".",
"upper",
"(",
")",
"url",
"=",
"self",
".",
"_build_url",
"(",
"form",
".",
"action",
")",
"or",
... | 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 |
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",
"{",
... | 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 |
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... | 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 |
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 ... | 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 ... | [
"def",
"encode_if_py2",
"(",
"func",
")",
":",
"if",
"not",
"PY2",
":",
"return",
"func",
"def",
"wrapped",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"if",
"not",
"isinstance",
... | 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 |
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
]
f... | 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
]
f... | [
"def",
"_reduce_age",
"(",
"self",
",",
"now",
")",
":",
"if",
"self",
".",
"max_age",
":",
"keys",
"=",
"[",
"key",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"data",
")",
"if",
"now",
"-",
"value",
"[",
"'date'",
"]",
">",... | 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 |
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 |
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] = {
... | 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] = {
... | [
"def",
"store",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"not",
"in",
"CACHE_CODES",
":",
"return",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"data",
"[",
"response",
".",
"url",
... | 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 |
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.... | 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.... | [
"def",
"retrieve",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"method",
"not",
"in",
"CACHE_VERBS",
":",
"return",
"try",
":",
"response",
"=",
"self",
".",
"data",
"[",
"request",
".",
"url",
"]",
"[",
"'response'",
"]",
"logger",
... | 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 |
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', ... | 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', ... | [
"def",
"_group_flat_tags",
"(",
"tag",
",",
"tags",
")",
":",
"grouped",
"=",
"[",
"tag",
"]",
"name",
"=",
"tag",
".",
"get",
"(",
"'name'",
",",
"''",
")",
".",
"lower",
"(",
")",
"while",
"tags",
"and",
"tags",
"[",
"0",
"]",
".",
"get",
"("... | 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 |
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)
... | 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)
... | [
"def",
"_parse_fields",
"(",
"parsed",
")",
":",
"out",
"=",
"[",
"]",
"tags",
"=",
"parsed",
".",
"find_all",
"(",
"_tag_ptn",
")",
"for",
"tag",
"in",
"tags",
":",
"helpers",
".",
"lowercase_attr_names",
"(",
"tag",
")",
"while",
"tags",
":",
"tag",
... | 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 |
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
... | 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
... | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"key",
"=",
"None",
")",
":",
"sink",
"=",
"self",
".",
"options",
"[",
"key",
"]",
"if",
"key",
"is",
"not",
"None",
"else",
"self",
".",
"data",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
... | 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 |
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.... | 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.... | [
"def",
"to_requests",
"(",
"self",
",",
"method",
"=",
"'get'",
")",
":",
"out",
"=",
"{",
"}",
"data_key",
"=",
"'params'",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'get'",
"else",
"'data'",
"out",
"[",
"data_key",
"]",
"=",
"self",
".",
"da... | 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 |
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 '
... | 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 '
... | [
"def",
"add_field",
"(",
"self",
",",
"field",
")",
":",
"if",
"not",
"isinstance",
"(",
"field",
",",
"fields",
".",
"BaseField",
")",
":",
"raise",
"ValueError",
"(",
"'Argument \"field\" must be an instance of '",
"'BaseField'",
")",
"self",
".",
"fields",
... | 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 |
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, ... | 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, ... | [
"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 |
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 th... | 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 th... | [
"async",
"def",
"save",
"(",
"self",
",",
"db",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"col",
"in",
"self",
".",
"_auto_columns",
":",
"if",
"not",
"self",
".",
"has_real_data",
"(",
"col",
".",
"name",
")",
":",
"kwargs",
"[",
"col",
".",
"na... | Save the object to Redis. | [
"Save",
"the",
"object",
"to",
"Redis",
"."
] | bc4feabde574462ff59009b32181d12867f0aa3d | https://github.com/paxosglobal/subconscious/blob/bc4feabde574462ff59009b32181d12867f0aa3d/subconscious/model.py#L204-L221 | train |
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 worki... | 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 worki... | [
"def",
"check_address",
"(",
"address",
")",
":",
"if",
"isinstance",
"(",
"address",
",",
"tuple",
")",
":",
"check_host",
"(",
"address",
"[",
"0",
"]",
")",
"check_port",
"(",
"address",
"[",
"1",
"]",
")",
"elif",
"isinstance",
"(",
"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 sock... | [
"Check",
"if",
"the",
"format",
"of",
"the",
"address",
"is",
"correct"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L88-L119 | train |
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::
w... | 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::
w... | [
"def",
"check_addresses",
"(",
"address_list",
",",
"is_remote",
"=",
"False",
")",
":",
"assert",
"all",
"(",
"isinstance",
"(",
"x",
",",
"(",
"tuple",
",",
"string_types",
")",
")",
"for",
"x",
"in",
"address_list",
")",
"if",
"(",
"is_remote",
"and",... | 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
... | [
"Check",
"if",
"the",
"format",
"of",
"the",
"addresses",
"is",
"correct"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L122-L154 | train |
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:`loggin... | 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:`loggin... | [
"def",
"create_logger",
"(",
"logger",
"=",
"None",
",",
"loglevel",
"=",
"None",
",",
"capture_warnings",
"=",
"True",
",",
"add_paramiko_handler",
"=",
"True",
")",
":",
"logger",
"=",
"logger",
"or",
"logging",
".",
"getLogger",
"(",
"'{0}.SSHTunnelForwarde... | 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 leve... | [
"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 |
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@%(mod... | 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@%(mod... | [
"def",
"_add_handler",
"(",
"logger",
",",
"handler",
"=",
"None",
",",
"loglevel",
"=",
"None",
")",
":",
"handler",
".",
"setLevel",
"(",
"loglevel",
"or",
"DEFAULT_LOGLEVEL",
")",
"if",
"handler",
".",
"level",
"<=",
"logging",
".",
"DEBUG",
":",
"_fm... | 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 |
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:
... | 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:
... | [
"def",
"_check_paramiko_handlers",
"(",
"logger",
"=",
"None",
")",
":",
"paramiko_logger",
"=",
"logging",
".",
"getLogger",
"(",
"'paramiko.transport'",
")",
"if",
"not",
"paramiko_logger",
".",
"handlers",
":",
"if",
"logger",
":",
"paramiko_logger",
".",
"ha... | 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 |
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 |
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_ad... | 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_ad... | [
"def",
"_cli_main",
"(",
"args",
"=",
"None",
")",
":",
"arguments",
"=",
"_parse_arguments",
"(",
"args",
")",
"_remove_none_values",
"(",
"arguments",
")",
"verbosity",
"=",
"min",
"(",
"arguments",
".",
"pop",
"(",
"'verbose'",
")",
",",
"4",
")",
"le... | 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
... | [
"Pass",
"input",
"arguments",
"to",
"open_tunnel"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1811-L1849 | train |
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",
".",
"l... | Make SSH Handler class | [
"Make",
"SSH",
"Handler",
"class"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L756-L764 | train |
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_clas... | 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_clas... | [
"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",
",",
"... | 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 |
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:
... | 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:
... | [
"def",
"get_agent_keys",
"(",
"logger",
"=",
"None",
")",
":",
"paramiko_agent",
"=",
"paramiko",
".",
"Agent",
"(",
")",
"agent_keys",
"=",
"paramiko_agent",
".",
"get_keys",
"(",
")",
"if",
"logger",
":",
"logger",
".",
"info",
"(",
"'{0} keys loaded from ... | 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 |
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... | 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... | [
"def",
"get_keys",
"(",
"logger",
"=",
"None",
",",
"host_pkey_directories",
"=",
"None",
",",
"allow_agent",
"=",
"False",
")",
":",
"keys",
"=",
"SSHTunnelForwarder",
".",
"get_agent_keys",
"(",
"logger",
"=",
"logger",
")",
"if",
"allow_agent",
"else",
"[... | 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... | [
"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 |
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)
... | 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)
... | [
"def",
"_get_transport",
"(",
"self",
")",
":",
"if",
"self",
".",
"ssh_proxy",
":",
"if",
"isinstance",
"(",
"self",
".",
"ssh_proxy",
",",
"paramiko",
".",
"proxy",
".",
"ProxyCommand",
")",
":",
"proxy_repr",
"=",
"repr",
"(",
"self",
".",
"ssh_proxy"... | 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 |
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 resolv... | 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 resolv... | [
"def",
"_create_tunnels",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_active",
":",
"try",
":",
"self",
".",
"_connect_to_gateway",
"(",
")",
"except",
"socket",
".",
"gaierror",
":",
"msg",
"=",
"'Could not resolve IP address for {0}, aborting!'",
".",... | 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 |
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 de... | 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 de... | [
"def",
"_process_deprecated",
"(",
"attrib",
",",
"deprecated_attrib",
",",
"kwargs",
")",
":",
"if",
"deprecated_attrib",
"not",
"in",
"DEPRECATIONS",
":",
"raise",
"ValueError",
"(",
"'{0} not included in deprecations list'",
".",
"format",
"(",
"deprecated_attrib",
... | Processes optional deprecate arguments | [
"Processes",
"optional",
"deprecate",
"arguments"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1176-L1195 | train |
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):
... | 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):
... | [
"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"... | 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
... | [
"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 |
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,... | 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,... | [
"def",
"_check_tunnel",
"(",
"self",
",",
"_srv",
")",
":",
"if",
"self",
".",
"skip_tunnel_checkup",
":",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"True",
"return",
"self",
".",
"logger",
".",
"info",
"(",
"'Checking tunne... | 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 |
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 s... | 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 s... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_alive",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Already started!'",
")",
"return",
"self",
".",
"_create_tunnels",
"(",
")",
"if",
"not",
"self",
".",
"is_active",
":",
"self",
".... | Start the SSH tunnels | [
"Start",
"the",
"SSH",
"tunnels"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1287-L1308 | train |
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
acknow... | 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
acknow... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Closing all open connections...'",
")",
"opened_address_text",
"=",
"', '",
".",
"join",
"(",
"(",
"address_to_str",
"(",
"k",
".",
"local_address",
")",
"for",
"k",
"in",
"se... | 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 sen... | [
"Shut",
"the",
"tunnel",
"down",
"."
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1310-L1335 | train |
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))
)
_sr... | 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))
)
_sr... | [
"def",
"_serve_forever_wrapper",
"(",
"self",
",",
"_srv",
",",
"poll_interval",
"=",
"0.1",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Opening tunnel: {0} <> {1}'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_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 |
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_l... | 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_l... | [
"def",
"_stop_transport",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_check_is_started",
"(",
")",
"except",
"(",
"BaseSSHTunnelForwarderError",
",",
"HandlerSSHTunnelForwarderError",
")",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"e",
... | 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 |
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 |
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 |
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 t... | 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 t... | [
"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",... | 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 ... | [
"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",
... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L42-L73 | train |
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 ... | 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 ... | [
"def",
"extract_module_name",
"(",
"absolute_path",
")",
":",
"base_name",
"=",
"osp",
".",
"basename",
"(",
"osp",
".",
"normpath",
"(",
"absolute_path",
")",
")",
"if",
"base_name",
"[",
"0",
"]",
"in",
"(",
"'.'",
",",
"'_'",
")",
":",
"return",
"No... | 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 retur... | [
"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",
... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L97-L124 | train |
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 ... | 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 ... | [
"def",
"dict_strict_update",
"(",
"base_dict",
",",
"update_dict",
")",
":",
"additional_keys",
"=",
"set",
"(",
"update_dict",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"base_dict",
".",
"keys",
"(",
")",
")",
"if",
"len",
"(",
"additional_keys",
")"... | 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 ... | [
"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",
"interpret... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L127-L145 | train |
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 adde... | 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 adde... | [
"def",
"format_doc_text",
"(",
"text",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"textwrap",
".",
"fill",
"(",
"line",
",",
"width",
"=",
"99",
",",
"initial_indent",
"=",
"' '",
",",
"subsequent_indent",
"=",
"' '",
")",
"for",
"line",
"in",
... | 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 te... | [
"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",
"a... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L250-L263 | train |
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.
... | 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.
... | [
"def",
"do_import",
"(",
"self",
",",
"*",
"names",
")",
":",
"try",
":",
"module_object",
"=",
"importlib",
".",
"import_module",
"(",
"self",
".",
"_module",
")",
"objects",
"=",
"tuple",
"(",
"getattr",
"(",
"module_object",
",",
"name",
")",
"for",
... | 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 ... | [
"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"... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L226-L247 | train |
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'... | 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'... | [
"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 |
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 ... | 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 ... | [
"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",
"li... | 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 |
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
... | 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
... | [
"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 |
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 = F... | 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 = F... | [
"def",
"set_circulating",
"(",
"self",
",",
"param",
")",
":",
"if",
"param",
"==",
"0",
":",
"self",
".",
"is_circulating",
"=",
"param",
"self",
".",
"circulate_commanded",
"=",
"False",
"elif",
"param",
"==",
"1",
":",
"self",
".",
"is_circulating",
"... | 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 |
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 |
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:
... | 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:
... | [
"def",
"linear",
"(",
"current",
",",
"target",
",",
"rate",
",",
"dt",
")",
":",
"sign",
"=",
"(",
"target",
">",
"current",
")",
"-",
"(",
"target",
"<",
"current",
")",
"if",
"not",
"sign",
":",
"return",
"current",
"new_value",
"=",
"current",
... | 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 = linea... | [
"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 |
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",
".",
... | 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 |
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 |
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.
"""
... | 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.
"""
... | [
"def",
"bind",
"(",
"self",
",",
"*",
"targets",
")",
":",
"self",
".",
"property",
"=",
"'value'",
"self",
".",
"meta_data_property",
"=",
"'meta'",
"return",
"BoundPV",
"(",
"self",
",",
"self",
".",
"_get_target",
"(",
"self",
".",
"property",
",",
... | 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 |
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.
... | 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.
... | [
"def",
"_get_callable",
"(",
"self",
",",
"func",
",",
"*",
"targets",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"func_name",
"=",
"func",
"func",
"=",
"next",
"(",
"(",
"getattr",
"(",
"obj",
",",
"func",
",",
"None",
")",
"for",
... | 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 objec... | [
"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",
... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L361-L381 | train |
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 ... | 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 ... | [
"def",
"_function_has_n_args",
"(",
"self",
",",
"func",
",",
"n",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"n",
"+=",
"1",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"defaults",
"=",
"argspec",
".",
"de... | 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 |
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._optio... | 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._optio... | [
"def",
"start_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"self",
".",
"_server",
"=",
"SimpleServer",
"(",
")",
"self",
".",
"_server",
".",
"createPV",
"(",
"prefix",
"=",
"self",
".",
"_options",
".",
"prefix",
... | 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 |
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... | 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... | [
"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: Approximat... | [
"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",
... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L578-L589 | train |
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 exceptio... | 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 exceptio... | [
"def",
"_make_request",
"(",
"self",
",",
"method",
",",
"*",
"args",
")",
":",
"response",
",",
"request_id",
"=",
"self",
".",
"_connection",
".",
"json_rpc",
"(",
"self",
".",
"_prefix",
"+",
"method",
",",
"*",
"args",
")",
"if",
"'id'",
"not",
"... | 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.
... | [
"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"... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/control_client.py#L194-L229 | train |
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... | 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... | [
"def",
"get_status",
"(",
"self",
")",
":",
"self",
".",
"device",
".",
"serial_command_mode",
"=",
"True",
"Tarray",
"=",
"[",
"0x80",
"]",
"*",
"10",
"Tarray",
"[",
"0",
"]",
"=",
"{",
"'stopped'",
":",
"0x01",
",",
"'heat'",
":",
"0x10",
",",
"'... | 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 |
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.
"""
# TO... | 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.
"""
# TO... | [
"def",
"set_rate",
"(",
"self",
",",
"param",
")",
":",
"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 |
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 leadi... | 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 leadi... | [
"def",
"set_limit",
"(",
"self",
",",
"param",
")",
":",
"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 |
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 ... | 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 ... | [
"def",
"pump_command",
"(",
"self",
",",
"param",
")",
":",
"lookup",
"=",
"[",
"c",
"for",
"c",
"in",
"\"0123456789:;<=>?@ABCDEFGHIJKLMN\"",
"]",
"if",
"param",
"==",
"\"a0\"",
":",
"self",
".",
"device",
".",
"pump_manual_mode",
"=",
"False",
"elif",
"pa... | 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 |
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 |
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 var... | 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 var... | [
"def",
"_initialize_data",
"(",
"self",
")",
":",
"self",
".",
"serial_command_mode",
"=",
"False",
"self",
".",
"pump_overspeed",
"=",
"False",
"self",
".",
"start_commanded",
"=",
"False",
"self",
".",
"stop_commanded",
"=",
"False",
"self",
".",
"hold_comma... | 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 t... | [
"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 |
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.
... | 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.
... | [
"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",
"No... | 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 m... | [
"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 |
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 eac... | 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 eac... | [
"def",
"get_usage_text",
"(",
"parser",
",",
"indent",
"=",
"None",
")",
":",
"usage_text",
"=",
"StringIO",
"(",
")",
"parser",
".",
"print_help",
"(",
"usage_text",
")",
"usage_string",
"=",
"usage_text",
".",
"getvalue",
"(",
")",
"if",
"indent",
"is",
... | 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... | [
"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 |
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 |
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:... | 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:... | [
"def",
"run_simulation",
"(",
"argument_list",
"=",
"None",
")",
":",
"try",
":",
"arguments",
"=",
"parser",
".",
"parse_args",
"(",
"argument_list",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"arguments",
".",
"version",
":",
"print",
"... | 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 mod... | [
"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 |
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.
"""
... | 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.
"""
... | [
"def",
"map_arguments",
"(",
"self",
",",
"arguments",
")",
":",
"if",
"self",
".",
"argument_mappings",
"is",
"None",
":",
"return",
"arguments",
"return",
"[",
"f",
"(",
"a",
")",
"for",
"f",
",",
"a",
"in",
"zip",
"(",
"self",
".",
"argument_mapping... | 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 |
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_... | 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_... | [
"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"... | 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",
"valu... | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L381-L396 | train |
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.
... | 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.
... | [
"def",
"start_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"if",
"self",
".",
"_options",
".",
"telnet_mode",
":",
"self",
".",
"interface",
".",
"in_terminator",
"=",
"'\\r\\n'",
"self",
".",
"interface",
".",
"out_te... | 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 |
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 |
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... | 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... | [
"def",
"_override_data",
"(",
"self",
",",
"overrides",
")",
":",
"if",
"overrides",
"is",
"not",
"None",
":",
"for",
"name",
",",
"val",
"in",
"overrides",
".",
"items",
"(",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Trying to override initial ... | 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 |
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 va... | 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 va... | [
"def",
"get",
"(",
"self",
",",
"addr",
",",
"count",
")",
":",
"addr",
"-=",
"self",
".",
"_start_addr",
"data",
"=",
"self",
".",
"_data",
"[",
"addr",
":",
"addr",
"+",
"count",
"]",
"if",
"len",
"(",
"data",
")",
"!=",
"count",
":",
"addr",
... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.