repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ARMmbed/icetea | icetea_lib/IceteaManager.py | IceteaManager._cleanup_resourceprovider | def _cleanup_resourceprovider(self):
"""
Calls cleanup for ResourceProvider of this run.
:return: Nothing
"""
# Disable too broad exception warning
# pylint: disable=W0703
self.resourceprovider = ResourceProvider(self.args)
try:
self.resourceprovider.cleanup()
self.logger.info("Cleanup done.")
except Exception as error:
self.logger.error("Cleanup failed! %s", error) | python | def _cleanup_resourceprovider(self):
"""
Calls cleanup for ResourceProvider of this run.
:return: Nothing
"""
# Disable too broad exception warning
# pylint: disable=W0703
self.resourceprovider = ResourceProvider(self.args)
try:
self.resourceprovider.cleanup()
self.logger.info("Cleanup done.")
except Exception as error:
self.logger.error("Cleanup failed! %s", error) | [
"def",
"_cleanup_resourceprovider",
"(",
"self",
")",
":",
"# Disable too broad exception warning",
"# pylint: disable=W0703",
"self",
".",
"resourceprovider",
"=",
"ResourceProvider",
"(",
"self",
".",
"args",
")",
"try",
":",
"self",
".",
"resourceprovider",
".",
"c... | Calls cleanup for ResourceProvider of this run.
:return: Nothing | [
"Calls",
"cleanup",
"for",
"ResourceProvider",
"of",
"this",
"run",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L292-L305 | train | 25,800 |
ARMmbed/icetea | icetea_lib/IceteaManager.py | IceteaManager._init_cloud | def _init_cloud(self, cloud_arg):
"""
Initializes Cloud module if cloud_arg is set.
:param cloud_arg: taken from args.cloud
:return: cloud module object instance
"""
# Disable too broad exception warning
# pylint: disable=W0703
cloud = None
if cloud_arg:
try:
if hasattr(self.args, "cm"):
cloud_module = self.args.cm if self.args.cm else None
self.logger.info("Creating cloud module {}.".format(cloud_module))
else:
cloud_module = None
cloud = Cloud(host=None, module=cloud_module, logger=self.logger, args=self.args)
except Exception as error:
self.logger.warning("Cloud module could not be initialized: {}".format(error))
cloud = None
return cloud | python | def _init_cloud(self, cloud_arg):
"""
Initializes Cloud module if cloud_arg is set.
:param cloud_arg: taken from args.cloud
:return: cloud module object instance
"""
# Disable too broad exception warning
# pylint: disable=W0703
cloud = None
if cloud_arg:
try:
if hasattr(self.args, "cm"):
cloud_module = self.args.cm if self.args.cm else None
self.logger.info("Creating cloud module {}.".format(cloud_module))
else:
cloud_module = None
cloud = Cloud(host=None, module=cloud_module, logger=self.logger, args=self.args)
except Exception as error:
self.logger.warning("Cloud module could not be initialized: {}".format(error))
cloud = None
return cloud | [
"def",
"_init_cloud",
"(",
"self",
",",
"cloud_arg",
")",
":",
"# Disable too broad exception warning",
"# pylint: disable=W0703",
"cloud",
"=",
"None",
"if",
"cloud_arg",
":",
"try",
":",
"if",
"hasattr",
"(",
"self",
".",
"args",
",",
"\"cm\"",
")",
":",
"cl... | Initializes Cloud module if cloud_arg is set.
:param cloud_arg: taken from args.cloud
:return: cloud module object instance | [
"Initializes",
"Cloud",
"module",
"if",
"cloud_arg",
"is",
"set",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/IceteaManager.py#L307-L329 | train | 25,801 |
ARMmbed/icetea | icetea_lib/Reports/ReportHtml.py | ReportHtml.generate | def generate(self, *args, **kwargs):
"""
Implementation for the generate method defined in ReportBase.
Generates a html report and saves it.
:param args: 1 argument, which is the filename
:param kwargs: 3 keyword arguments with keys 'title', 'heads' and 'refresh'
:return: Nothing.
"""
title = kwargs.get("title")
heads = kwargs.get("heads")
refresh = kwargs.get("refresh")
filename = args[0]
report = self._create(title, heads, refresh, path_start=os.path.dirname(filename))
ReportHtml.save(report, filename) | python | def generate(self, *args, **kwargs):
"""
Implementation for the generate method defined in ReportBase.
Generates a html report and saves it.
:param args: 1 argument, which is the filename
:param kwargs: 3 keyword arguments with keys 'title', 'heads' and 'refresh'
:return: Nothing.
"""
title = kwargs.get("title")
heads = kwargs.get("heads")
refresh = kwargs.get("refresh")
filename = args[0]
report = self._create(title, heads, refresh, path_start=os.path.dirname(filename))
ReportHtml.save(report, filename) | [
"def",
"generate",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"title",
"=",
"kwargs",
".",
"get",
"(",
"\"title\"",
")",
"heads",
"=",
"kwargs",
".",
"get",
"(",
"\"heads\"",
")",
"refresh",
"=",
"kwargs",
".",
"get",
"(",
... | Implementation for the generate method defined in ReportBase.
Generates a html report and saves it.
:param args: 1 argument, which is the filename
:param kwargs: 3 keyword arguments with keys 'title', 'heads' and 'refresh'
:return: Nothing. | [
"Implementation",
"for",
"the",
"generate",
"method",
"defined",
"in",
"ReportBase",
".",
"Generates",
"a",
"html",
"report",
"and",
"saves",
"it",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Reports/ReportHtml.py#L35-L49 | train | 25,802 |
ARMmbed/icetea | icetea_lib/tools/tools.py | check_int | def check_int(integer):
"""
Check if number is integer or not.
:param integer: Number as str
:return: Boolean
"""
if not isinstance(integer, str):
return False
if integer[0] in ('-', '+'):
return integer[1:].isdigit()
return integer.isdigit() | python | def check_int(integer):
"""
Check if number is integer or not.
:param integer: Number as str
:return: Boolean
"""
if not isinstance(integer, str):
return False
if integer[0] in ('-', '+'):
return integer[1:].isdigit()
return integer.isdigit() | [
"def",
"check_int",
"(",
"integer",
")",
":",
"if",
"not",
"isinstance",
"(",
"integer",
",",
"str",
")",
":",
"return",
"False",
"if",
"integer",
"[",
"0",
"]",
"in",
"(",
"'-'",
",",
"'+'",
")",
":",
"return",
"integer",
"[",
"1",
":",
"]",
"."... | Check if number is integer or not.
:param integer: Number as str
:return: Boolean | [
"Check",
"if",
"number",
"is",
"integer",
"or",
"not",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L92-L103 | train | 25,803 |
ARMmbed/icetea | icetea_lib/tools/tools.py | _is_pid_running_on_unix | def _is_pid_running_on_unix(pid):
"""
Check if PID is running for Unix systems.
"""
try:
os.kill(pid, 0)
except OSError as err:
# if error is ESRCH, it means the process doesn't exist
return not err.errno == os.errno.ESRCH
return True | python | def _is_pid_running_on_unix(pid):
"""
Check if PID is running for Unix systems.
"""
try:
os.kill(pid, 0)
except OSError as err:
# if error is ESRCH, it means the process doesn't exist
return not err.errno == os.errno.ESRCH
return True | [
"def",
"_is_pid_running_on_unix",
"(",
"pid",
")",
":",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"0",
")",
"except",
"OSError",
"as",
"err",
":",
"# if error is ESRCH, it means the process doesn't exist",
"return",
"not",
"err",
".",
"errno",
"==",
"os"... | Check if PID is running for Unix systems. | [
"Check",
"if",
"PID",
"is",
"running",
"for",
"Unix",
"systems",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L135-L144 | train | 25,804 |
ARMmbed/icetea | icetea_lib/tools/tools.py | _is_pid_running_on_windows | def _is_pid_running_on_windows(pid):
"""
Check if PID is running for Windows systems
"""
import ctypes.wintypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(1, 0, pid)
if handle == 0:
return False
exit_code = ctypes.wintypes.DWORD()
ret = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code))
is_alive = (ret == 0 or exit_code.value == _STILL_ALIVE) # pylint: disable=undefined-variable
kernel32.CloseHandle(handle)
return is_alive | python | def _is_pid_running_on_windows(pid):
"""
Check if PID is running for Windows systems
"""
import ctypes.wintypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(1, 0, pid)
if handle == 0:
return False
exit_code = ctypes.wintypes.DWORD()
ret = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code))
is_alive = (ret == 0 or exit_code.value == _STILL_ALIVE) # pylint: disable=undefined-variable
kernel32.CloseHandle(handle)
return is_alive | [
"def",
"_is_pid_running_on_windows",
"(",
"pid",
")",
":",
"import",
"ctypes",
".",
"wintypes",
"kernel32",
"=",
"ctypes",
".",
"windll",
".",
"kernel32",
"handle",
"=",
"kernel32",
".",
"OpenProcess",
"(",
"1",
",",
"0",
",",
"pid",
")",
"if",
"handle",
... | Check if PID is running for Windows systems | [
"Check",
"if",
"PID",
"is",
"running",
"for",
"Windows",
"systems"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L147-L161 | train | 25,805 |
ARMmbed/icetea | icetea_lib/tools/tools.py | strip_escape | def strip_escape(string='', encoding="utf-8"): # pylint: disable=redefined-outer-name
"""
Strip escape characters from string.
:param string: string to work on
:param encoding: string name of the encoding used.
:return: stripped string
"""
matches = []
try:
if hasattr(string, "decode"):
string = string.decode(encoding)
except Exception: # pylint: disable=broad-except
# Tried to decode something that is not decodeable in the specified encoding. Let's just
# move on.
pass
try:
for match in ansi_eng.finditer(string):
matches.append(match)
except TypeError as error:
raise TypeError("Unable to strip escape characters from data {}: {}".format(
string, error))
matches.reverse()
for match in matches:
start = match.start()
end = match.end()
string = string[0:start] + string[end:]
return string | python | def strip_escape(string='', encoding="utf-8"): # pylint: disable=redefined-outer-name
"""
Strip escape characters from string.
:param string: string to work on
:param encoding: string name of the encoding used.
:return: stripped string
"""
matches = []
try:
if hasattr(string, "decode"):
string = string.decode(encoding)
except Exception: # pylint: disable=broad-except
# Tried to decode something that is not decodeable in the specified encoding. Let's just
# move on.
pass
try:
for match in ansi_eng.finditer(string):
matches.append(match)
except TypeError as error:
raise TypeError("Unable to strip escape characters from data {}: {}".format(
string, error))
matches.reverse()
for match in matches:
start = match.start()
end = match.end()
string = string[0:start] + string[end:]
return string | [
"def",
"strip_escape",
"(",
"string",
"=",
"''",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"# pylint: disable=redefined-outer-name",
"matches",
"=",
"[",
"]",
"try",
":",
"if",
"hasattr",
"(",
"string",
",",
"\"decode\"",
")",
":",
"string",
"=",
"string"... | Strip escape characters from string.
:param string: string to work on
:param encoding: string name of the encoding used.
:return: stripped string | [
"Strip",
"escape",
"characters",
"from",
"string",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L167-L194 | train | 25,806 |
ARMmbed/icetea | icetea_lib/tools/tools.py | import_module | def import_module(modulename):
"""
Static method for importing module modulename. Can handle relative imports as well.
:param modulename: Name of module to import. Can be relative
:return: imported module instance.
"""
module = None
try:
module = importlib.import_module(modulename)
except ImportError:
# If importing fails we see if the modulename has dots in it, split the name.
if "." in modulename:
modules = modulename.split(".")
package = ".".join(modules[1:len(modules)])
# Might raise an ImportError again. If so, we really failed to import the module.
module = importlib.import_module(package)
else:
# No dots, really unable to import the module. Raise.
raise
return module | python | def import_module(modulename):
"""
Static method for importing module modulename. Can handle relative imports as well.
:param modulename: Name of module to import. Can be relative
:return: imported module instance.
"""
module = None
try:
module = importlib.import_module(modulename)
except ImportError:
# If importing fails we see if the modulename has dots in it, split the name.
if "." in modulename:
modules = modulename.split(".")
package = ".".join(modules[1:len(modules)])
# Might raise an ImportError again. If so, we really failed to import the module.
module = importlib.import_module(package)
else:
# No dots, really unable to import the module. Raise.
raise
return module | [
"def",
"import_module",
"(",
"modulename",
")",
":",
"module",
"=",
"None",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"modulename",
")",
"except",
"ImportError",
":",
"# If importing fails we see if the modulename has dots in it, split the name.",... | Static method for importing module modulename. Can handle relative imports as well.
:param modulename: Name of module to import. Can be relative
:return: imported module instance. | [
"Static",
"method",
"for",
"importing",
"module",
"modulename",
".",
"Can",
"handle",
"relative",
"imports",
"as",
"well",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L222-L242 | train | 25,807 |
ARMmbed/icetea | icetea_lib/tools/tools.py | get_abs_path | def get_abs_path(relative_path):
"""
Get absolute path for relative path.
:param relative_path: Relative path
:return: absolute path
"""
abs_path = os.path.sep.join(
os.path.abspath(sys.modules[__name__].__file__).split(os.path.sep)[:-1])
abs_path = os.path.abspath(abs_path + os.path.sep + relative_path)
return abs_path | python | def get_abs_path(relative_path):
"""
Get absolute path for relative path.
:param relative_path: Relative path
:return: absolute path
"""
abs_path = os.path.sep.join(
os.path.abspath(sys.modules[__name__].__file__).split(os.path.sep)[:-1])
abs_path = os.path.abspath(abs_path + os.path.sep + relative_path)
return abs_path | [
"def",
"get_abs_path",
"(",
"relative_path",
")",
":",
"abs_path",
"=",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
".",
"__file__",
")",
".",
"split",
"(",
"... | Get absolute path for relative path.
:param relative_path: Relative path
:return: absolute path | [
"Get",
"absolute",
"path",
"for",
"relative",
"path",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L259-L269 | train | 25,808 |
ARMmbed/icetea | icetea_lib/tools/tools.py | get_pkg_version | def get_pkg_version(pkg_name, parse=False):
"""
Verify and get installed python package version.
:param pkg_name: python package name
:param parse: parse version number with pkg_resourc.parse_version -function
:return: None if pkg is not installed,
otherwise version as a string or parsed version when parse=True
"""
import pkg_resources # part of setuptools
try:
version = pkg_resources.require(pkg_name)[0].version
return pkg_resources.parse_version(version) if parse else version
except pkg_resources.DistributionNotFound:
return None | python | def get_pkg_version(pkg_name, parse=False):
"""
Verify and get installed python package version.
:param pkg_name: python package name
:param parse: parse version number with pkg_resourc.parse_version -function
:return: None if pkg is not installed,
otherwise version as a string or parsed version when parse=True
"""
import pkg_resources # part of setuptools
try:
version = pkg_resources.require(pkg_name)[0].version
return pkg_resources.parse_version(version) if parse else version
except pkg_resources.DistributionNotFound:
return None | [
"def",
"get_pkg_version",
"(",
"pkg_name",
",",
"parse",
"=",
"False",
")",
":",
"import",
"pkg_resources",
"# part of setuptools",
"try",
":",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"pkg_name",
")",
"[",
"0",
"]",
".",
"version",
"return",
"p... | Verify and get installed python package version.
:param pkg_name: python package name
:param parse: parse version number with pkg_resourc.parse_version -function
:return: None if pkg is not installed,
otherwise version as a string or parsed version when parse=True | [
"Verify",
"and",
"get",
"installed",
"python",
"package",
"version",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L272-L286 | train | 25,809 |
ARMmbed/icetea | icetea_lib/tools/tools.py | generate_object_graphs_by_class | def generate_object_graphs_by_class(classlist):
"""
Generate reference and backreference graphs
for objects of type class for each class given in classlist.
Useful for debugging reference leaks in framework etc.
Usage example to generate graphs for class "someclass":
>>> import someclass
>>> someclassobject = someclass()
>>> generate_object_graphs_by_class(someclass)
Needs "objgraph" module installed.
"""
try:
import objgraph
import gc
except ImportError:
return
graphcount = 0
if not isinstance(classlist, list):
classlist = [classlist]
for class_item in classlist:
for obj in gc.get_objects():
if isinstance(obj, class_item):
graphcount += 1
objgraph.show_refs([obj], filename='%d_%s_%d_refs.png' % (
ogcounter, obj.__class__.__name__, graphcount))
objgraph.show_backrefs([obj], filename='%d_%s_%d_backrefs.png' % (
ogcounter, obj.__class__.__name__, graphcount)) | python | def generate_object_graphs_by_class(classlist):
"""
Generate reference and backreference graphs
for objects of type class for each class given in classlist.
Useful for debugging reference leaks in framework etc.
Usage example to generate graphs for class "someclass":
>>> import someclass
>>> someclassobject = someclass()
>>> generate_object_graphs_by_class(someclass)
Needs "objgraph" module installed.
"""
try:
import objgraph
import gc
except ImportError:
return
graphcount = 0
if not isinstance(classlist, list):
classlist = [classlist]
for class_item in classlist:
for obj in gc.get_objects():
if isinstance(obj, class_item):
graphcount += 1
objgraph.show_refs([obj], filename='%d_%s_%d_refs.png' % (
ogcounter, obj.__class__.__name__, graphcount))
objgraph.show_backrefs([obj], filename='%d_%s_%d_backrefs.png' % (
ogcounter, obj.__class__.__name__, graphcount)) | [
"def",
"generate_object_graphs_by_class",
"(",
"classlist",
")",
":",
"try",
":",
"import",
"objgraph",
"import",
"gc",
"except",
"ImportError",
":",
"return",
"graphcount",
"=",
"0",
"if",
"not",
"isinstance",
"(",
"classlist",
",",
"list",
")",
":",
"classli... | Generate reference and backreference graphs
for objects of type class for each class given in classlist.
Useful for debugging reference leaks in framework etc.
Usage example to generate graphs for class "someclass":
>>> import someclass
>>> someclassobject = someclass()
>>> generate_object_graphs_by_class(someclass)
Needs "objgraph" module installed. | [
"Generate",
"reference",
"and",
"backreference",
"graphs",
"for",
"objects",
"of",
"type",
"class",
"for",
"each",
"class",
"given",
"in",
"classlist",
".",
"Useful",
"for",
"debugging",
"reference",
"leaks",
"in",
"framework",
"etc",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L303-L331 | train | 25,810 |
ARMmbed/icetea | icetea_lib/tools/tools.py | remove_empty_from_dict | def remove_empty_from_dict(dictionary):
"""
Remove empty items from dictionary d
:param dictionary:
:return:
"""
if isinstance(dictionary, dict):
return dict(
(k,
remove_empty_from_dict(v)) for k, v in iteritems(
dictionary) if v and remove_empty_from_dict(v))
elif isinstance(dictionary, list):
return [remove_empty_from_dict(v) for v in dictionary if v and remove_empty_from_dict(v)]
return dictionary | python | def remove_empty_from_dict(dictionary):
"""
Remove empty items from dictionary d
:param dictionary:
:return:
"""
if isinstance(dictionary, dict):
return dict(
(k,
remove_empty_from_dict(v)) for k, v in iteritems(
dictionary) if v and remove_empty_from_dict(v))
elif isinstance(dictionary, list):
return [remove_empty_from_dict(v) for v in dictionary if v and remove_empty_from_dict(v)]
return dictionary | [
"def",
"remove_empty_from_dict",
"(",
"dictionary",
")",
":",
"if",
"isinstance",
"(",
"dictionary",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"remove_empty_from_dict",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
... | Remove empty items from dictionary d
:param dictionary:
:return: | [
"Remove",
"empty",
"items",
"from",
"dictionary",
"d"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L396-L410 | train | 25,811 |
ARMmbed/icetea | icetea_lib/tools/tools.py | set_or_delete | def set_or_delete(dictionary, key, value):
"""
Set value as value of dict key key. If value is None, delete key key from dict.
:param dictionary: Dictionary to work on.
:param key: Key to set or delete. If deleting and key does not exist in dict, nothing is done.
:param value: Value to set. If value is None, delete key.
:return: Nothing, modifies dict in place.
"""
if value:
dictionary[key] = value
else:
if dictionary.get(key):
del dictionary[key] | python | def set_or_delete(dictionary, key, value):
"""
Set value as value of dict key key. If value is None, delete key key from dict.
:param dictionary: Dictionary to work on.
:param key: Key to set or delete. If deleting and key does not exist in dict, nothing is done.
:param value: Value to set. If value is None, delete key.
:return: Nothing, modifies dict in place.
"""
if value:
dictionary[key] = value
else:
if dictionary.get(key):
del dictionary[key] | [
"def",
"set_or_delete",
"(",
"dictionary",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
":",
"dictionary",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"if",
"dictionary",
".",
"get",
"(",
"key",
")",
":",
"del",
"dictionary",
"[",
"key",
"]"
] | Set value as value of dict key key. If value is None, delete key key from dict.
:param dictionary: Dictionary to work on.
:param key: Key to set or delete. If deleting and key does not exist in dict, nothing is done.
:param value: Value to set. If value is None, delete key.
:return: Nothing, modifies dict in place. | [
"Set",
"value",
"as",
"value",
"of",
"dict",
"key",
"key",
".",
"If",
"value",
"is",
"None",
"delete",
"key",
"key",
"from",
"dict",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L434-L447 | train | 25,812 |
ARMmbed/icetea | icetea_lib/tools/tools.py | initLogger | def initLogger(name): # pylint: disable=invalid-name
'''
Initializes a basic logger. Can be replaced when constructing the
HttpApi object or afterwards with setter
'''
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# Skip attaching StreamHandler if one is already attached to logger
if not getattr(logger, "streamhandler_set", None):
consolehandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
consolehandler.setFormatter(formatter)
consolehandler.setLevel(logging.INFO)
logger.addHandler(consolehandler)
logger.streamhandler_set = True
return logger | python | def initLogger(name): # pylint: disable=invalid-name
'''
Initializes a basic logger. Can be replaced when constructing the
HttpApi object or afterwards with setter
'''
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# Skip attaching StreamHandler if one is already attached to logger
if not getattr(logger, "streamhandler_set", None):
consolehandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
consolehandler.setFormatter(formatter)
consolehandler.setLevel(logging.INFO)
logger.addHandler(consolehandler)
logger.streamhandler_set = True
return logger | [
"def",
"initLogger",
"(",
"name",
")",
":",
"# pylint: disable=invalid-name",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"# Skip attaching StreamHandler if one is already attached to logger"... | Initializes a basic logger. Can be replaced when constructing the
HttpApi object or afterwards with setter | [
"Initializes",
"a",
"basic",
"logger",
".",
"Can",
"be",
"replaced",
"when",
"constructing",
"the",
"HttpApi",
"object",
"or",
"afterwards",
"with",
"setter"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L499-L514 | train | 25,813 |
ARMmbed/icetea | icetea_lib/tools/tools.py | find_duplicate_keys | def find_duplicate_keys(data):
"""
Find duplicate keys in a layer of ordered pairs. Intended as the object_pairs_hook callable
for json.load or loads.
:param data: ordered pairs
:return: Dictionary with no duplicate keys
:raises ValueError if duplicate keys are found
"""
out_dict = {}
for key, value in data:
if key in out_dict:
raise ValueError("Duplicate key: {}".format(key))
out_dict[key] = value
return out_dict | python | def find_duplicate_keys(data):
"""
Find duplicate keys in a layer of ordered pairs. Intended as the object_pairs_hook callable
for json.load or loads.
:param data: ordered pairs
:return: Dictionary with no duplicate keys
:raises ValueError if duplicate keys are found
"""
out_dict = {}
for key, value in data:
if key in out_dict:
raise ValueError("Duplicate key: {}".format(key))
out_dict[key] = value
return out_dict | [
"def",
"find_duplicate_keys",
"(",
"data",
")",
":",
"out_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"data",
":",
"if",
"key",
"in",
"out_dict",
":",
"raise",
"ValueError",
"(",
"\"Duplicate key: {}\"",
".",
"format",
"(",
"key",
")",
")",
... | Find duplicate keys in a layer of ordered pairs. Intended as the object_pairs_hook callable
for json.load or loads.
:param data: ordered pairs
:return: Dictionary with no duplicate keys
:raises ValueError if duplicate keys are found | [
"Find",
"duplicate",
"keys",
"in",
"a",
"layer",
"of",
"ordered",
"pairs",
".",
"Intended",
"as",
"the",
"object_pairs_hook",
"callable",
"for",
"json",
".",
"load",
"or",
"loads",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L613-L627 | train | 25,814 |
ARMmbed/icetea | icetea_lib/build/build.py | BuildFile._load | def _load(self):
"""
Function load.
:return: file contents
:raises: NotFoundError if file not found
"""
if self.is_exists():
return open(self._ref, "rb").read()
raise NotFoundError("File %s not found" % self._ref) | python | def _load(self):
"""
Function load.
:return: file contents
:raises: NotFoundError if file not found
"""
if self.is_exists():
return open(self._ref, "rb").read()
raise NotFoundError("File %s not found" % self._ref) | [
"def",
"_load",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_exists",
"(",
")",
":",
"return",
"open",
"(",
"self",
".",
"_ref",
",",
"\"rb\"",
")",
".",
"read",
"(",
")",
"raise",
"NotFoundError",
"(",
"\"File %s not found\"",
"%",
"self",
".",
"_r... | Function load.
:return: file contents
:raises: NotFoundError if file not found | [
"Function",
"load",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/build/build.py#L152-L161 | train | 25,815 |
ARMmbed/icetea | icetea_lib/build/build.py | BuildHttp.get_file | def get_file(self):
"""
Load data into a file and return file path.
:return: path to file as string
"""
content = self._load()
if not content:
return None
filename = "temporary_file.bin"
with open(filename, "wb") as file_name:
file_name.write(content)
return filename | python | def get_file(self):
"""
Load data into a file and return file path.
:return: path to file as string
"""
content = self._load()
if not content:
return None
filename = "temporary_file.bin"
with open(filename, "wb") as file_name:
file_name.write(content)
return filename | [
"def",
"get_file",
"(",
"self",
")",
":",
"content",
"=",
"self",
".",
"_load",
"(",
")",
"if",
"not",
"content",
":",
"return",
"None",
"filename",
"=",
"\"temporary_file.bin\"",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"file_name",
":... | Load data into a file and return file path.
:return: path to file as string | [
"Load",
"data",
"into",
"a",
"file",
"and",
"return",
"file",
"path",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/build/build.py#L200-L212 | train | 25,816 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/DutInformation.py | DutInformation.as_dict | def as_dict(self):
"""
Generate a dictionary of the contents of this DutInformation object.
:return: dict
"""
my_info = {}
if self.platform:
my_info["model"] = self.platform
if self.resource_id:
my_info["sn"] = self.resource_id
if self.vendor:
my_info["vendor"] = self.vendor
if self.provider:
my_info["provider"] = self.provider
return my_info | python | def as_dict(self):
"""
Generate a dictionary of the contents of this DutInformation object.
:return: dict
"""
my_info = {}
if self.platform:
my_info["model"] = self.platform
if self.resource_id:
my_info["sn"] = self.resource_id
if self.vendor:
my_info["vendor"] = self.vendor
if self.provider:
my_info["provider"] = self.provider
return my_info | [
"def",
"as_dict",
"(",
"self",
")",
":",
"my_info",
"=",
"{",
"}",
"if",
"self",
".",
"platform",
":",
"my_info",
"[",
"\"model\"",
"]",
"=",
"self",
".",
"platform",
"if",
"self",
".",
"resource_id",
":",
"my_info",
"[",
"\"sn\"",
"]",
"=",
"self",
... | Generate a dictionary of the contents of this DutInformation object.
:return: dict | [
"Generate",
"a",
"dictionary",
"of",
"the",
"contents",
"of",
"this",
"DutInformation",
"object",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L44-L59 | train | 25,817 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/DutInformation.py | DutInformationList.get_resource_ids | def get_resource_ids(self):
"""
Get resource ids as a list.
:return: List of resource id:s or "unknown"
"""
resids = []
if self.dutinformations:
for info in self.dutinformations:
resids.append(info.resource_id)
return resids
return "unknown" | python | def get_resource_ids(self):
"""
Get resource ids as a list.
:return: List of resource id:s or "unknown"
"""
resids = []
if self.dutinformations:
for info in self.dutinformations:
resids.append(info.resource_id)
return resids
return "unknown" | [
"def",
"get_resource_ids",
"(",
"self",
")",
":",
"resids",
"=",
"[",
"]",
"if",
"self",
".",
"dutinformations",
":",
"for",
"info",
"in",
"self",
".",
"dutinformations",
":",
"resids",
".",
"append",
"(",
"info",
".",
"resource_id",
")",
"return",
"resi... | Get resource ids as a list.
:return: List of resource id:s or "unknown" | [
"Get",
"resource",
"ids",
"as",
"a",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L133-L144 | train | 25,818 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/DutInformation.py | DutInformationList.push_resource_cache | def push_resource_cache(resourceid, info):
"""
Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing
"""
if not resourceid:
raise ResourceInitError("Resource id missing")
if not DutInformationList._cache.get(resourceid):
DutInformationList._cache[resourceid] = dict()
DutInformationList._cache[resourceid] = merge(DutInformationList._cache[resourceid], info) | python | def push_resource_cache(resourceid, info):
"""
Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing
"""
if not resourceid:
raise ResourceInitError("Resource id missing")
if not DutInformationList._cache.get(resourceid):
DutInformationList._cache[resourceid] = dict()
DutInformationList._cache[resourceid] = merge(DutInformationList._cache[resourceid], info) | [
"def",
"push_resource_cache",
"(",
"resourceid",
",",
"info",
")",
":",
"if",
"not",
"resourceid",
":",
"raise",
"ResourceInitError",
"(",
"\"Resource id missing\"",
")",
"if",
"not",
"DutInformationList",
".",
"_cache",
".",
"get",
"(",
"resourceid",
")",
":",
... | Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing | [
"Cache",
"resource",
"specific",
"information"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L164-L176 | train | 25,819 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/DutInformation.py | DutInformationList.get_resource_cache | def get_resource_cache(resourceid):
"""
Get a cached dictionary related to an individual resourceid.
:param resourceid: String resource id.
:return: dict
"""
if not resourceid:
raise ResourceInitError("Resource id missing")
if not DutInformationList._cache.get(resourceid):
DutInformationList._cache[resourceid] = dict()
return DutInformationList._cache[resourceid] | python | def get_resource_cache(resourceid):
"""
Get a cached dictionary related to an individual resourceid.
:param resourceid: String resource id.
:return: dict
"""
if not resourceid:
raise ResourceInitError("Resource id missing")
if not DutInformationList._cache.get(resourceid):
DutInformationList._cache[resourceid] = dict()
return DutInformationList._cache[resourceid] | [
"def",
"get_resource_cache",
"(",
"resourceid",
")",
":",
"if",
"not",
"resourceid",
":",
"raise",
"ResourceInitError",
"(",
"\"Resource id missing\"",
")",
"if",
"not",
"DutInformationList",
".",
"_cache",
".",
"get",
"(",
"resourceid",
")",
":",
"DutInformationL... | Get a cached dictionary related to an individual resourceid.
:param resourceid: String resource id.
:return: dict | [
"Get",
"a",
"cached",
"dictionary",
"related",
"to",
"an",
"individual",
"resourceid",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/DutInformation.py#L179-L190 | train | 25,820 |
ARMmbed/icetea | icetea_lib/cloud.py | create_result_object | def create_result_object(result):
"""
Create cloud result object from Result.
:param result: Result
:return: dictionary
"""
_result = {
'tcid': result.get_tc_name(),
'campaign': result.campaign,
'cre': {
'user': result.tester
},
'job': {
'id': result.job_id
},
'exec': {
'verdict': result.get_verdict(),
'duration': result.duration,
'note': result.get_fail_reason(),
'dut': {
'count': result.dut_count,
'type': result.dut_type
},
'sut': {
'branch': result.build_branch,
'commitId': result.buildcommit,
'buildDate': result.build_date,
'buildSha1': result.build_sha1,
'buildUrl': result.build_url,
'gitUrl': result.build_git_url,
'cut': result.component, # Component Under Uest
'fut': result.feature # Feature Under Test
},
'env': {
'framework': {
'name': result.fw_name,
'ver': result.fw_version
}
},
"logs": []
}
}
if result.dut_resource_id:
_result["exec"]["dut"]["sn"] = result.dut_resource_id
if result.dut_vendor and result.dut_vendor[0]:
_result["exec"]["dut"]["vendor"] = result.dut_vendor[0]
if result.dut_models and result.dut_models[0]:
_result["exec"]["dut"]["model"] = result.dut_models[0]
# pylint: disable=len-as-condition
if len(result.dut_models) == 1 and len(result.dut_resource_id) == 1:
_result["exec"]["dut"]["sn"] = result.dut_resource_id[0]
return remove_empty_from_dict(_result) | python | def create_result_object(result):
"""
Create cloud result object from Result.
:param result: Result
:return: dictionary
"""
_result = {
'tcid': result.get_tc_name(),
'campaign': result.campaign,
'cre': {
'user': result.tester
},
'job': {
'id': result.job_id
},
'exec': {
'verdict': result.get_verdict(),
'duration': result.duration,
'note': result.get_fail_reason(),
'dut': {
'count': result.dut_count,
'type': result.dut_type
},
'sut': {
'branch': result.build_branch,
'commitId': result.buildcommit,
'buildDate': result.build_date,
'buildSha1': result.build_sha1,
'buildUrl': result.build_url,
'gitUrl': result.build_git_url,
'cut': result.component, # Component Under Uest
'fut': result.feature # Feature Under Test
},
'env': {
'framework': {
'name': result.fw_name,
'ver': result.fw_version
}
},
"logs": []
}
}
if result.dut_resource_id:
_result["exec"]["dut"]["sn"] = result.dut_resource_id
if result.dut_vendor and result.dut_vendor[0]:
_result["exec"]["dut"]["vendor"] = result.dut_vendor[0]
if result.dut_models and result.dut_models[0]:
_result["exec"]["dut"]["model"] = result.dut_models[0]
# pylint: disable=len-as-condition
if len(result.dut_models) == 1 and len(result.dut_resource_id) == 1:
_result["exec"]["dut"]["sn"] = result.dut_resource_id[0]
return remove_empty_from_dict(_result) | [
"def",
"create_result_object",
"(",
"result",
")",
":",
"_result",
"=",
"{",
"'tcid'",
":",
"result",
".",
"get_tc_name",
"(",
")",
",",
"'campaign'",
":",
"result",
".",
"campaign",
",",
"'cre'",
":",
"{",
"'user'",
":",
"result",
".",
"tester",
"}",
... | Create cloud result object from Result.
:param result: Result
:return: dictionary | [
"Create",
"cloud",
"result",
"object",
"from",
"Result",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/cloud.py#L25-L80 | train | 25,821 |
ARMmbed/icetea | icetea_lib/cloud.py | append_logs_to_result_object | def append_logs_to_result_object(result_obj, result):
"""
Append log files to cloud result object from Result.
:param result_obj: Target result object
:param result: Result
:return: Nothing, modifies result_obj in place.
"""
logs = result.has_logs()
result_obj["exec"]["logs"] = []
if logs and result.logfiles:
for log in logs:
typ = None
parts = log.split(os.sep)
if "bench" in parts[len(parts) - 1]:
typ = "framework"
# elif "Dut" in parts[len(parts)-1]:
# typ = "dut"
if typ is not None:
name = parts[len(parts) - 1]
try:
with open(log, "r") as file_name:
data = file_name.read()
dic = {"data": data, "name": name, "from": typ}
result_obj["exec"]["logs"].append(dic)
except OSError:
pass
else:
continue | python | def append_logs_to_result_object(result_obj, result):
"""
Append log files to cloud result object from Result.
:param result_obj: Target result object
:param result: Result
:return: Nothing, modifies result_obj in place.
"""
logs = result.has_logs()
result_obj["exec"]["logs"] = []
if logs and result.logfiles:
for log in logs:
typ = None
parts = log.split(os.sep)
if "bench" in parts[len(parts) - 1]:
typ = "framework"
# elif "Dut" in parts[len(parts)-1]:
# typ = "dut"
if typ is not None:
name = parts[len(parts) - 1]
try:
with open(log, "r") as file_name:
data = file_name.read()
dic = {"data": data, "name": name, "from": typ}
result_obj["exec"]["logs"].append(dic)
except OSError:
pass
else:
continue | [
"def",
"append_logs_to_result_object",
"(",
"result_obj",
",",
"result",
")",
":",
"logs",
"=",
"result",
".",
"has_logs",
"(",
")",
"result_obj",
"[",
"\"exec\"",
"]",
"[",
"\"logs\"",
"]",
"=",
"[",
"]",
"if",
"logs",
"and",
"result",
".",
"logfiles",
... | Append log files to cloud result object from Result.
:param result_obj: Target result object
:param result: Result
:return: Nothing, modifies result_obj in place. | [
"Append",
"log",
"files",
"to",
"cloud",
"result",
"object",
"from",
"Result",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/cloud.py#L83-L112 | train | 25,822 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py | DutDetection.get_available_devices | def get_available_devices(self):
"""
Gets available devices using mbedls and self.available_edbg_ports.
:return: List of connected devices as dictionaries.
"""
connected_devices = self.mbeds.list_mbeds() if self.mbeds else []
# Check non mbedOS supported devices.
# Just for backward compatible reason - is obsolete..
edbg_ports = self.available_edbg_ports()
for port in edbg_ports:
connected_devices.append({
"platform_name": "SAM4E",
"serial_port": port,
"mount_point": None,
"target_id": None,
"baud_rate": 460800
})
for dev in connected_devices:
dev['state'] = "unknown"
return connected_devices | python | def get_available_devices(self):
"""
Gets available devices using mbedls and self.available_edbg_ports.
:return: List of connected devices as dictionaries.
"""
connected_devices = self.mbeds.list_mbeds() if self.mbeds else []
# Check non mbedOS supported devices.
# Just for backward compatible reason - is obsolete..
edbg_ports = self.available_edbg_ports()
for port in edbg_ports:
connected_devices.append({
"platform_name": "SAM4E",
"serial_port": port,
"mount_point": None,
"target_id": None,
"baud_rate": 460800
})
for dev in connected_devices:
dev['state'] = "unknown"
return connected_devices | [
"def",
"get_available_devices",
"(",
"self",
")",
":",
"connected_devices",
"=",
"self",
".",
"mbeds",
".",
"list_mbeds",
"(",
")",
"if",
"self",
".",
"mbeds",
"else",
"[",
"]",
"# Check non mbedOS supported devices.",
"# Just for backward compatible reason - is obsolet... | Gets available devices using mbedls and self.available_edbg_ports.
:return: List of connected devices as dictionaries. | [
"Gets",
"available",
"devices",
"using",
"mbedls",
"and",
"self",
".",
"available_edbg_ports",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py#L58-L79 | train | 25,823 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py | DutDetection.available_edbg_ports | def available_edbg_ports(self):
"""
Finds available EDBG COM ports.
:return: list of available ports
"""
ports_available = sorted(list(list_ports.comports()))
edbg_ports = []
for iport in ports_available:
port = iport[0]
desc = iport[1]
hwid = iport[2]
if str(desc).startswith("EDBG Virtual COM Port") or \
"VID:PID=03EB:2111" in str(hwid).upper():
# print("%-10s: %s (%s)\n" % (port, desc, hwid))
try:
edbg_ports.index(port, 0)
print("There is multiple %s ports with same number!" % port)
except ValueError:
edbg_ports.append(port)
# print("Detected %i DUT's" % len(edbg_ports))
return edbg_ports | python | def available_edbg_ports(self):
"""
Finds available EDBG COM ports.
:return: list of available ports
"""
ports_available = sorted(list(list_ports.comports()))
edbg_ports = []
for iport in ports_available:
port = iport[0]
desc = iport[1]
hwid = iport[2]
if str(desc).startswith("EDBG Virtual COM Port") or \
"VID:PID=03EB:2111" in str(hwid).upper():
# print("%-10s: %s (%s)\n" % (port, desc, hwid))
try:
edbg_ports.index(port, 0)
print("There is multiple %s ports with same number!" % port)
except ValueError:
edbg_ports.append(port)
# print("Detected %i DUT's" % len(edbg_ports))
return edbg_ports | [
"def",
"available_edbg_ports",
"(",
"self",
")",
":",
"ports_available",
"=",
"sorted",
"(",
"list",
"(",
"list_ports",
".",
"comports",
"(",
")",
")",
")",
"edbg_ports",
"=",
"[",
"]",
"for",
"iport",
"in",
"ports_available",
":",
"port",
"=",
"iport",
... | Finds available EDBG COM ports.
:return: list of available ports | [
"Finds",
"available",
"EDBG",
"COM",
"ports",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutDetection.py#L81-L102 | train | 25,824 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.store_traces | def store_traces(self, value):
"""
Setter for _store_traces. _store_traces controls in memory storing of received lines.
Also logs the change for the user.
:param value: Boolean
:return: Nothing
"""
if not value:
self.logger.debug("Stopping storing received lines for dut %d", self.index)
self._store_traces = False
else:
self.logger.debug("Resuming storing received lines for dut %d", self.index)
self._store_traces = True | python | def store_traces(self, value):
"""
Setter for _store_traces. _store_traces controls in memory storing of received lines.
Also logs the change for the user.
:param value: Boolean
:return: Nothing
"""
if not value:
self.logger.debug("Stopping storing received lines for dut %d", self.index)
self._store_traces = False
else:
self.logger.debug("Resuming storing received lines for dut %d", self.index)
self._store_traces = True | [
"def",
"store_traces",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Stopping storing received lines for dut %d\"",
",",
"self",
".",
"index",
")",
"self",
".",
"_store_traces",
"=",
"False",
"el... | Setter for _store_traces. _store_traces controls in memory storing of received lines.
Also logs the change for the user.
:param value: Boolean
:return: Nothing | [
"Setter",
"for",
"_store_traces",
".",
"_store_traces",
"controls",
"in",
"memory",
"storing",
"of",
"received",
"lines",
".",
"Also",
"logs",
"the",
"change",
"for",
"the",
"user",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L196-L209 | train | 25,825 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.init_wait_register | def init_wait_register(self):
"""
Initialize EventMatcher to wait for certain cli_ready_trigger to arrive from this Dut.
:return: None
"""
app = self.config.get("application")
if app:
bef_init_cmds = app.get("cli_ready_trigger")
if bef_init_cmds:
self.init_done.clear()
self.init_event_matcher = EventMatcher(EventTypes.DUT_LINE_RECEIVED,
bef_init_cmds, self, self.init_done)
self.init_wait_timeout = app.get("cli_ready_trigger_timeout", 30)
return
self.init_done.set()
return | python | def init_wait_register(self):
"""
Initialize EventMatcher to wait for certain cli_ready_trigger to arrive from this Dut.
:return: None
"""
app = self.config.get("application")
if app:
bef_init_cmds = app.get("cli_ready_trigger")
if bef_init_cmds:
self.init_done.clear()
self.init_event_matcher = EventMatcher(EventTypes.DUT_LINE_RECEIVED,
bef_init_cmds, self, self.init_done)
self.init_wait_timeout = app.get("cli_ready_trigger_timeout", 30)
return
self.init_done.set()
return | [
"def",
"init_wait_register",
"(",
"self",
")",
":",
"app",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"application\"",
")",
"if",
"app",
":",
"bef_init_cmds",
"=",
"app",
".",
"get",
"(",
"\"cli_ready_trigger\"",
")",
"if",
"bef_init_cmds",
":",
"self"... | Initialize EventMatcher to wait for certain cli_ready_trigger to arrive from this Dut.
:return: None | [
"Initialize",
"EventMatcher",
"to",
"wait",
"for",
"certain",
"cli_ready_trigger",
"to",
"arrive",
"from",
"this",
"Dut",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L362-L379 | train | 25,826 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.wait_init | def wait_init(self):
"""
Block until init_done flag is set or until init_wait_timeout happens.
:return: value of init_done
"""
init_done = self.init_done.wait(timeout=self.init_wait_timeout)
if not init_done:
if hasattr(self, "peek"):
app = self.config.get("application")
if app:
bef_init_cmds = app.get("cli_ready_trigger")
if bef_init_cmds in self.peek(): # pylint: disable=no-member
init_done = True
return init_done | python | def wait_init(self):
"""
Block until init_done flag is set or until init_wait_timeout happens.
:return: value of init_done
"""
init_done = self.init_done.wait(timeout=self.init_wait_timeout)
if not init_done:
if hasattr(self, "peek"):
app = self.config.get("application")
if app:
bef_init_cmds = app.get("cli_ready_trigger")
if bef_init_cmds in self.peek(): # pylint: disable=no-member
init_done = True
return init_done | [
"def",
"wait_init",
"(",
"self",
")",
":",
"init_done",
"=",
"self",
".",
"init_done",
".",
"wait",
"(",
"timeout",
"=",
"self",
".",
"init_wait_timeout",
")",
"if",
"not",
"init_done",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"peek\"",
")",
":",
"app... | Block until init_done flag is set or until init_wait_timeout happens.
:return: value of init_done | [
"Block",
"until",
"init_done",
"flag",
"is",
"set",
"or",
"until",
"init_wait_timeout",
"happens",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L381-L395 | train | 25,827 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.init_cli_human | def init_cli_human(self):
"""
Send post_cli_cmds to dut
:return: Nothing
"""
if self.post_cli_cmds is None:
self.post_cli_cmds = self.set_default_init_cli_human_cmds()
for cli_cmd in self.post_cli_cmds:
try:
if isinstance(cli_cmd, list) and len(cli_cmd) >= 2:
asynchronous = cli_cmd[1]
if len(cli_cmd) > 2:
wait = cli_cmd[2]
else:
wait = True
self.execute_command(cli_cmd[0], wait=wait, asynchronous=asynchronous)
else:
self.execute_command(cli_cmd)
except (TestStepFail, TestStepError, TestStepTimeout):
continue | python | def init_cli_human(self):
"""
Send post_cli_cmds to dut
:return: Nothing
"""
if self.post_cli_cmds is None:
self.post_cli_cmds = self.set_default_init_cli_human_cmds()
for cli_cmd in self.post_cli_cmds:
try:
if isinstance(cli_cmd, list) and len(cli_cmd) >= 2:
asynchronous = cli_cmd[1]
if len(cli_cmd) > 2:
wait = cli_cmd[2]
else:
wait = True
self.execute_command(cli_cmd[0], wait=wait, asynchronous=asynchronous)
else:
self.execute_command(cli_cmd)
except (TestStepFail, TestStepError, TestStepTimeout):
continue | [
"def",
"init_cli_human",
"(",
"self",
")",
":",
"if",
"self",
".",
"post_cli_cmds",
"is",
"None",
":",
"self",
".",
"post_cli_cmds",
"=",
"self",
".",
"set_default_init_cli_human_cmds",
"(",
")",
"for",
"cli_cmd",
"in",
"self",
".",
"post_cli_cmds",
":",
"tr... | Send post_cli_cmds to dut
:return: Nothing | [
"Send",
"post_cli_cmds",
"to",
"dut"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L397-L417 | train | 25,828 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.set_time_function | def set_time_function(self, function):
"""
Set time function to be used.
:param function: callable function
:return: Nothing
:raises: ValueError if function is not types.FunctionType.
"""
if isinstance(function, types.FunctionType):
self.get_time = function
else:
raise ValueError("Invalid value for DUT time function") | python | def set_time_function(self, function):
"""
Set time function to be used.
:param function: callable function
:return: Nothing
:raises: ValueError if function is not types.FunctionType.
"""
if isinstance(function, types.FunctionType):
self.get_time = function
else:
raise ValueError("Invalid value for DUT time function") | [
"def",
"set_time_function",
"(",
"self",
",",
"function",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"types",
".",
"FunctionType",
")",
":",
"self",
".",
"get_time",
"=",
"function",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for DUT ti... | Set time function to be used.
:param function: callable function
:return: Nothing
:raises: ValueError if function is not types.FunctionType. | [
"Set",
"time",
"function",
"to",
"be",
"used",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L419-L430 | train | 25,829 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.open_dut | def open_dut(self, port=None):
"""
Open connection to dut.
:param port: com port to use.
:return:
"""
if port is not None:
self.comport = port
try:
self.open_connection()
except (DutConnectionError, ValueError) as err:
self.close_dut(use_prepare=False)
raise DutConnectionError(str(err))
except KeyboardInterrupt:
self.close_dut(use_prepare=False)
self.close_connection()
raise | python | def open_dut(self, port=None):
"""
Open connection to dut.
:param port: com port to use.
:return:
"""
if port is not None:
self.comport = port
try:
self.open_connection()
except (DutConnectionError, ValueError) as err:
self.close_dut(use_prepare=False)
raise DutConnectionError(str(err))
except KeyboardInterrupt:
self.close_dut(use_prepare=False)
self.close_connection()
raise | [
"def",
"open_dut",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"if",
"port",
"is",
"not",
"None",
":",
"self",
".",
"comport",
"=",
"port",
"try",
":",
"self",
".",
"open_connection",
"(",
")",
"except",
"(",
"DutConnectionError",
",",
"ValueError... | Open connection to dut.
:param port: com port to use.
:return: | [
"Open",
"connection",
"to",
"dut",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L432-L450 | train | 25,830 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut._wait_for_exec_ready | def _wait_for_exec_ready(self):
"""
Wait for response.
:return: CliResponse object coming in
:raises: TestStepTimeout, TestStepError
"""
while not self.response_received.wait(1) and self.query_timeout != 0:
if self.query_timeout != 0 and self.query_timeout < self.get_time():
if self.prev:
cmd = self.prev.cmd
else:
cmd = "???"
self.logger.error("CMD timeout: "+ cmd)
self.query_timeout = 0
raise TestStepTimeout(self.name + " CMD timeout: " + cmd)
self.logger.debug("Waiting for response... "
"timeout=%d", self.query_timeout - self.get_time())
self._dut_is_alive()
if self.response_coming_in == -1:
if self.query_async_response is not None:
# fullfill the async response with a dummy response and clean the state
self.query_async_response.set_response(CliResponse())
self.query_async_response = None
# raise and log the error
self.logger.error("No response received, DUT died")
raise TestStepError("No response received, DUT "+self.name+" died")
# if an async response is pending, fullfill it with the result
if self.query_async_response is not None:
self.query_async_response.set_response(self.response_coming_in)
self.query_async_response = None
self.query_timeout = 0
return self.response_coming_in | python | def _wait_for_exec_ready(self):
"""
Wait for response.
:return: CliResponse object coming in
:raises: TestStepTimeout, TestStepError
"""
while not self.response_received.wait(1) and self.query_timeout != 0:
if self.query_timeout != 0 and self.query_timeout < self.get_time():
if self.prev:
cmd = self.prev.cmd
else:
cmd = "???"
self.logger.error("CMD timeout: "+ cmd)
self.query_timeout = 0
raise TestStepTimeout(self.name + " CMD timeout: " + cmd)
self.logger.debug("Waiting for response... "
"timeout=%d", self.query_timeout - self.get_time())
self._dut_is_alive()
if self.response_coming_in == -1:
if self.query_async_response is not None:
# fullfill the async response with a dummy response and clean the state
self.query_async_response.set_response(CliResponse())
self.query_async_response = None
# raise and log the error
self.logger.error("No response received, DUT died")
raise TestStepError("No response received, DUT "+self.name+" died")
# if an async response is pending, fullfill it with the result
if self.query_async_response is not None:
self.query_async_response.set_response(self.response_coming_in)
self.query_async_response = None
self.query_timeout = 0
return self.response_coming_in | [
"def",
"_wait_for_exec_ready",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"response_received",
".",
"wait",
"(",
"1",
")",
"and",
"self",
".",
"query_timeout",
"!=",
"0",
":",
"if",
"self",
".",
"query_timeout",
"!=",
"0",
"and",
"self",
".",
... | Wait for response.
:return: CliResponse object coming in
:raises: TestStepTimeout, TestStepError | [
"Wait",
"for",
"response",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L460-L495 | train | 25,831 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.execute_command | def execute_command(self, req, **kwargs):
"""
Execute command and return CliResponse
:param req: String, command to be executed in DUT, or CliRequest, command class which
contains all configurations like timeout.
:param kwargs: Configurations (wait, timeout) which will be used when string mode is in use.
:return: CliResponse, which contains all received data from Dut and parsed retcode.
"""
if isinstance(req, string_types):
# backward compatible
timeout = 50 # Use same default timeout as bench.py
wait = True
asynchronous = False
for key in kwargs:
if key == 'wait':
wait = kwargs[key]
elif key == 'timeout':
timeout = kwargs[key] # [ms]
elif key == 'asynchronous':
asynchronous = kwargs[key]
req = CliRequest(req,
timestamp=self.get_time(),
wait=wait,
timeout=timeout,
asynchronous=asynchronous)
# wait for previous command ready
if req.wait:
response = self._wait_for_exec_ready()
if response is not None and self.query_async_expected is not None:
if response.retcode != self.query_async_expected:
self.logger.error("Asynch call returned unexpected result, "
"expected %d was %d", self.query_async_expected,
response.retcode)
raise TestStepFail("Asynch call returned unexpected result")
self.query_async_expected = None
# Tell Query to worker thread
self.response_received.clear()
self.query_timeout = self.get_time() + req.timeout if req.wait else 0
self.query = req
msg = "Async CMD {}, " \
"timeout={}, time={}" if req.asynchronous else "CMD {}, timeout={}, time={}"
msg = msg.format(req.cmd, int(self.query_timeout), int(self.get_time()))
self.logger.debug(msg, extra={'type': '<->'})
Dut.process_dut(self)
if req.asynchronous is True:
self.query_async_expected = req.expected_retcode
async_response = CliAsyncResponse(self)
self.query_async_response = async_response
return async_response
if req.wait is False:
self.query_async_expected = req.expected_retcode
# if an async response was waiting, just discard the result
# since the new command has already been sent...
# This is not ideal but when a command has its flags "Wait == False"
# the result of the previous command is already discarded in previous
# stages
if self.query_async_response is not None:
self.query_async_response.set_response(CliResponse())
self.query_async_response = None
return CliResponse()
return self._wait_for_exec_ready() | python | def execute_command(self, req, **kwargs):
"""
Execute command and return CliResponse
:param req: String, command to be executed in DUT, or CliRequest, command class which
contains all configurations like timeout.
:param kwargs: Configurations (wait, timeout) which will be used when string mode is in use.
:return: CliResponse, which contains all received data from Dut and parsed retcode.
"""
if isinstance(req, string_types):
# backward compatible
timeout = 50 # Use same default timeout as bench.py
wait = True
asynchronous = False
for key in kwargs:
if key == 'wait':
wait = kwargs[key]
elif key == 'timeout':
timeout = kwargs[key] # [ms]
elif key == 'asynchronous':
asynchronous = kwargs[key]
req = CliRequest(req,
timestamp=self.get_time(),
wait=wait,
timeout=timeout,
asynchronous=asynchronous)
# wait for previous command ready
if req.wait:
response = self._wait_for_exec_ready()
if response is not None and self.query_async_expected is not None:
if response.retcode != self.query_async_expected:
self.logger.error("Asynch call returned unexpected result, "
"expected %d was %d", self.query_async_expected,
response.retcode)
raise TestStepFail("Asynch call returned unexpected result")
self.query_async_expected = None
# Tell Query to worker thread
self.response_received.clear()
self.query_timeout = self.get_time() + req.timeout if req.wait else 0
self.query = req
msg = "Async CMD {}, " \
"timeout={}, time={}" if req.asynchronous else "CMD {}, timeout={}, time={}"
msg = msg.format(req.cmd, int(self.query_timeout), int(self.get_time()))
self.logger.debug(msg, extra={'type': '<->'})
Dut.process_dut(self)
if req.asynchronous is True:
self.query_async_expected = req.expected_retcode
async_response = CliAsyncResponse(self)
self.query_async_response = async_response
return async_response
if req.wait is False:
self.query_async_expected = req.expected_retcode
# if an async response was waiting, just discard the result
# since the new command has already been sent...
# This is not ideal but when a command has its flags "Wait == False"
# the result of the previous command is already discarded in previous
# stages
if self.query_async_response is not None:
self.query_async_response.set_response(CliResponse())
self.query_async_response = None
return CliResponse()
return self._wait_for_exec_ready() | [
"def",
"execute_command",
"(",
"self",
",",
"req",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"req",
",",
"string_types",
")",
":",
"# backward compatible",
"timeout",
"=",
"50",
"# Use same default timeout as bench.py",
"wait",
"=",
"True",
"... | Execute command and return CliResponse
:param req: String, command to be executed in DUT, or CliRequest, command class which
contains all configurations like timeout.
:param kwargs: Configurations (wait, timeout) which will be used when string mode is in use.
:return: CliResponse, which contains all received data from Dut and parsed retcode. | [
"Execute",
"command",
"and",
"return",
"CliResponse"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L497-L565 | train | 25,832 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.close_dut | def close_dut(self, use_prepare=True):
"""
Close connection to dut.
:param use_prepare: Boolean, default is True. Call prepare_connection_close before
closing connection.
:return: Nothing
"""
if not self.stopped:
self.logger.debug("Close '%s' connection" % self.dut_name, extra={'type': '<->'})
if use_prepare:
try:
self.prepare_connection_close()
except TestStepFail:
# We can ignore this for dead Duts, just continue with cleanup
pass
self.stopped = True
Dut._dutlist.remove(self)
# Remove myself from signalled dut list, if I'm still there
if Dut._signalled_duts and Dut._signalled_duts.count(self):
try:
Dut._signalled_duts.remove(self)
except ValueError:
pass
try:
if not Dut._dutlist:
Dut._run = False
Dut._sem.release()
Dut._th.join()
del Dut._th
Dut._th = None
except AttributeError:
pass | python | def close_dut(self, use_prepare=True):
"""
Close connection to dut.
:param use_prepare: Boolean, default is True. Call prepare_connection_close before
closing connection.
:return: Nothing
"""
if not self.stopped:
self.logger.debug("Close '%s' connection" % self.dut_name, extra={'type': '<->'})
if use_prepare:
try:
self.prepare_connection_close()
except TestStepFail:
# We can ignore this for dead Duts, just continue with cleanup
pass
self.stopped = True
Dut._dutlist.remove(self)
# Remove myself from signalled dut list, if I'm still there
if Dut._signalled_duts and Dut._signalled_duts.count(self):
try:
Dut._signalled_duts.remove(self)
except ValueError:
pass
try:
if not Dut._dutlist:
Dut._run = False
Dut._sem.release()
Dut._th.join()
del Dut._th
Dut._th = None
except AttributeError:
pass | [
"def",
"close_dut",
"(",
"self",
",",
"use_prepare",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"stopped",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Close '%s' connection\"",
"%",
"self",
".",
"dut_name",
",",
"extra",
"=",
"{",
"'type'",
... | Close connection to dut.
:param use_prepare: Boolean, default is True. Call prepare_connection_close before
closing connection.
:return: Nothing | [
"Close",
"connection",
"to",
"dut",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L567-L600 | train | 25,833 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.process_dut | def process_dut(dut):
"""
Signal worker thread that specified Dut needs processing
"""
if dut.finished():
return
Dut._signalled_duts.appendleft(dut)
Dut._sem.release() | python | def process_dut(dut):
"""
Signal worker thread that specified Dut needs processing
"""
if dut.finished():
return
Dut._signalled_duts.appendleft(dut)
Dut._sem.release() | [
"def",
"process_dut",
"(",
"dut",
")",
":",
"if",
"dut",
".",
"finished",
"(",
")",
":",
"return",
"Dut",
".",
"_signalled_duts",
".",
"appendleft",
"(",
"dut",
")",
"Dut",
".",
"_sem",
".",
"release",
"(",
")"
] | Signal worker thread that specified Dut needs processing | [
"Signal",
"worker",
"thread",
"that",
"specified",
"Dut",
"needs",
"processing"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L621-L628 | train | 25,834 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.run | def run(): # pylint: disable=too-many-branches
"""
Main thread runner for all Duts.
:return: Nothing
"""
Dut._logger.debug("Start DUT communication", extra={'type': '<->'})
while Dut._run:
Dut._sem.acquire()
try:
dut = Dut._signalled_duts.pop()
# Check for pending requests
if dut.waiting_for_response is not None:
item = dut.waiting_for_response
# pylint: disable=protected-access
dut.response_coming_in = dut._read_response()
if dut.response_coming_in is None:
# Continue to next node
continue
if isinstance(dut.response_coming_in, CliResponse):
dut.response_coming_in.set_response_time(item.get_timedelta(dut.get_time()))
dut.waiting_for_response = None
dut.logger.debug("Got response", extra={'type': '<->'})
dut.response_received.set()
continue
# Check for new Request
if dut.query is not None:
item = dut.query
dut.query = None
dut.logger.info(item.cmd, extra={'type': '-->'})
try:
dut.writeline(item.cmd)
except RuntimeError:
dut.response_coming_in = -1
dut.response_received.set()
continue
dut.prev = item # Save previous command for logging purposes
if item.wait:
# Only caller will care if this was asynchronous.
dut.waiting_for_response = item
else:
dut.query_timeout = 0
dut.response_received.set()
continue
try:
line = dut.readline()
except RuntimeError:
dut.response_coming_in = -1
dut.response_received.set()
continue
if line:
if dut.store_traces:
dut.traces.append(line)
EventObject(EventTypes.DUT_LINE_RECEIVED, dut, line)
retcode = dut.check_retcode(line)
if retcode is not None:
dut.logger.warning("unrequested retcode", extra={'type': '!<-'})
dut.logger.debug(line, extra={'type': '<<<'})
except IndexError:
pass
Dut._logger.debug("End DUT communication", extra={'type': '<->'}) | python | def run(): # pylint: disable=too-many-branches
"""
Main thread runner for all Duts.
:return: Nothing
"""
Dut._logger.debug("Start DUT communication", extra={'type': '<->'})
while Dut._run:
Dut._sem.acquire()
try:
dut = Dut._signalled_duts.pop()
# Check for pending requests
if dut.waiting_for_response is not None:
item = dut.waiting_for_response
# pylint: disable=protected-access
dut.response_coming_in = dut._read_response()
if dut.response_coming_in is None:
# Continue to next node
continue
if isinstance(dut.response_coming_in, CliResponse):
dut.response_coming_in.set_response_time(item.get_timedelta(dut.get_time()))
dut.waiting_for_response = None
dut.logger.debug("Got response", extra={'type': '<->'})
dut.response_received.set()
continue
# Check for new Request
if dut.query is not None:
item = dut.query
dut.query = None
dut.logger.info(item.cmd, extra={'type': '-->'})
try:
dut.writeline(item.cmd)
except RuntimeError:
dut.response_coming_in = -1
dut.response_received.set()
continue
dut.prev = item # Save previous command for logging purposes
if item.wait:
# Only caller will care if this was asynchronous.
dut.waiting_for_response = item
else:
dut.query_timeout = 0
dut.response_received.set()
continue
try:
line = dut.readline()
except RuntimeError:
dut.response_coming_in = -1
dut.response_received.set()
continue
if line:
if dut.store_traces:
dut.traces.append(line)
EventObject(EventTypes.DUT_LINE_RECEIVED, dut, line)
retcode = dut.check_retcode(line)
if retcode is not None:
dut.logger.warning("unrequested retcode", extra={'type': '!<-'})
dut.logger.debug(line, extra={'type': '<<<'})
except IndexError:
pass
Dut._logger.debug("End DUT communication", extra={'type': '<->'}) | [
"def",
"run",
"(",
")",
":",
"# pylint: disable=too-many-branches",
"Dut",
".",
"_logger",
".",
"debug",
"(",
"\"Start DUT communication\"",
",",
"extra",
"=",
"{",
"'type'",
":",
"'<->'",
"}",
")",
"while",
"Dut",
".",
"_run",
":",
"Dut",
".",
"_sem",
"."... | Main thread runner for all Duts.
:return: Nothing | [
"Main",
"thread",
"runner",
"for",
"all",
"Duts",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L632-L695 | train | 25,835 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut._read_response | def _read_response(self):
"""
Internal response reader.
:return: CliResponse or None
"""
try:
line = self.readline()
except RuntimeError:
Dut._logger.warning("Failed to read PIPE", extra={'type': '!<-'})
return -1
if line:
if self.store_traces:
self.traces.append(line)
self.response_traces.append(line)
EventObject(EventTypes.DUT_LINE_RECEIVED, self, line)
match = re.search(r"^\[([\w\W]{4})\]\[([\W\w]{4,}?)\]\: (.*)", line)
if match:
self.logger.debug(line, extra={'type': '<<<'})
else:
self.logger.info(line, extra={'type': '<--'})
retcode = self.check_retcode(line)
if retcode is not None:
resp = CliResponse()
resp.retcode = retcode
resp.traces = self.response_traces
resp.lines = self.response_traces
self.response_traces = []
return resp
return None | python | def _read_response(self):
"""
Internal response reader.
:return: CliResponse or None
"""
try:
line = self.readline()
except RuntimeError:
Dut._logger.warning("Failed to read PIPE", extra={'type': '!<-'})
return -1
if line:
if self.store_traces:
self.traces.append(line)
self.response_traces.append(line)
EventObject(EventTypes.DUT_LINE_RECEIVED, self, line)
match = re.search(r"^\[([\w\W]{4})\]\[([\W\w]{4,}?)\]\: (.*)", line)
if match:
self.logger.debug(line, extra={'type': '<<<'})
else:
self.logger.info(line, extra={'type': '<--'})
retcode = self.check_retcode(line)
if retcode is not None:
resp = CliResponse()
resp.retcode = retcode
resp.traces = self.response_traces
resp.lines = self.response_traces
self.response_traces = []
return resp
return None | [
"def",
"_read_response",
"(",
"self",
")",
":",
"try",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"except",
"RuntimeError",
":",
"Dut",
".",
"_logger",
".",
"warning",
"(",
"\"Failed to read PIPE\"",
",",
"extra",
"=",
"{",
"'type'",
":",
"'!<-... | Internal response reader.
:return: CliResponse or None | [
"Internal",
"response",
"reader",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L697-L727 | train | 25,836 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.check_retcode | def check_retcode(self, line):
"""
Look for retcode on line line and return return code if found.
:param line: Line to search from
:return: integer return code or -1 if "cmd tasklet init" is found. None if retcode or cmd
tasklet init not found.
"""
retcode = None
match = re.search(r"retcode\: ([-\d]{1,})", line)
if match:
retcode = num(str(match.group(1)))
match = re.search("cmd tasklet init", line)
if match:
self.logger.debug("Device Boot up", extra={'type': ' '})
return -1
return retcode | python | def check_retcode(self, line):
"""
Look for retcode on line line and return return code if found.
:param line: Line to search from
:return: integer return code or -1 if "cmd tasklet init" is found. None if retcode or cmd
tasklet init not found.
"""
retcode = None
match = re.search(r"retcode\: ([-\d]{1,})", line)
if match:
retcode = num(str(match.group(1)))
match = re.search("cmd tasklet init", line)
if match:
self.logger.debug("Device Boot up", extra={'type': ' '})
return -1
return retcode | [
"def",
"check_retcode",
"(",
"self",
",",
"line",
")",
":",
"retcode",
"=",
"None",
"match",
"=",
"re",
".",
"search",
"(",
"r\"retcode\\: ([-\\d]{1,})\"",
",",
"line",
")",
"if",
"match",
":",
"retcode",
"=",
"num",
"(",
"str",
"(",
"match",
".",
"gro... | Look for retcode on line line and return return code if found.
:param line: Line to search from
:return: integer return code or -1 if "cmd tasklet init" is found. None if retcode or cmd
tasklet init not found. | [
"Look",
"for",
"retcode",
"on",
"line",
"line",
"and",
"return",
"return",
"code",
"if",
"found",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L730-L747 | train | 25,837 |
ARMmbed/icetea | icetea_lib/DeviceConnectors/Dut.py | Dut.start_dut_thread | def start_dut_thread(self): # pylint: disable=no-self-use
"""
Start Dut thread.
:return: Nothing
"""
if Dut._th is None:
Dut._run = True
Dut._sem = Semaphore(0)
Dut._signalled_duts = deque()
Dut._logger = LogManager.get_bench_logger('Dut')
Dut._th = Thread(target=Dut.run, name='DutThread')
Dut._th.daemon = True
Dut._th.start() | python | def start_dut_thread(self): # pylint: disable=no-self-use
"""
Start Dut thread.
:return: Nothing
"""
if Dut._th is None:
Dut._run = True
Dut._sem = Semaphore(0)
Dut._signalled_duts = deque()
Dut._logger = LogManager.get_bench_logger('Dut')
Dut._th = Thread(target=Dut.run, name='DutThread')
Dut._th.daemon = True
Dut._th.start() | [
"def",
"start_dut_thread",
"(",
"self",
")",
":",
"# pylint: disable=no-self-use",
"if",
"Dut",
".",
"_th",
"is",
"None",
":",
"Dut",
".",
"_run",
"=",
"True",
"Dut",
".",
"_sem",
"=",
"Semaphore",
"(",
"0",
")",
"Dut",
".",
"_signalled_duts",
"=",
"dequ... | Start Dut thread.
:return: Nothing | [
"Start",
"Dut",
"thread",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L757-L771 | train | 25,838 |
ARMmbed/icetea | icetea_lib/Events/EventMatcher.py | EventMatcher._event_received | def _event_received(self, ref, data):
"""
Handle received event.
:param ref: ref is the object that generated the event.
:param data: event data.
:return: Nothing.
"""
match = self._resolve_match_data(ref, data)
if match:
if self.flag_to_set:
self.flag_to_set.set()
if self.callback:
self.callback(EventMatch(ref, data, match))
if self.__forget:
self.forget() | python | def _event_received(self, ref, data):
"""
Handle received event.
:param ref: ref is the object that generated the event.
:param data: event data.
:return: Nothing.
"""
match = self._resolve_match_data(ref, data)
if match:
if self.flag_to_set:
self.flag_to_set.set()
if self.callback:
self.callback(EventMatch(ref, data, match))
if self.__forget:
self.forget() | [
"def",
"_event_received",
"(",
"self",
",",
"ref",
",",
"data",
")",
":",
"match",
"=",
"self",
".",
"_resolve_match_data",
"(",
"ref",
",",
"data",
")",
"if",
"match",
":",
"if",
"self",
".",
"flag_to_set",
":",
"self",
".",
"flag_to_set",
".",
"set",... | Handle received event.
:param ref: ref is the object that generated the event.
:param data: event data.
:return: Nothing. | [
"Handle",
"received",
"event",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Events/EventMatcher.py#L39-L54 | train | 25,839 |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | JsonFile.write_file | def write_file(self, content, filepath=None, filename=None, indent=None, keys_to_write=None):
'''
Write a Python dictionary as JSON to a file.
:param content: Dictionary of key-value pairs to save to a file
:param filepath: Path where the file is to be created
:param filename: Name of the file to be created
:param indent: You can use this to specify indent level for pretty printing the file
:param keys_to_write: array of keys that are to be picked from data and written to file.
Default is None, when all data is written to file.
:return: Path of file used
:raises OSError, EnvironmentError, ValueError
'''
path = filepath if filepath else self.filepath
name = filename if filename else self.filename
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as error:
self.logger.error("Error while creating directory: {}".format(error))
raise
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
if keys_to_write:
data_to_write = {}
for key in keys_to_write:
data_to_write[key] = content[key]
else:
data_to_write = content
try:
indent = indent if indent else 2
self._write_json(path, name, 'w', data_to_write, indent)
return os.path.join(path, name)
except EnvironmentError as error:
self.logger.error("Error while opening or writing to file: {}".format(error))
raise
except ValueError:
raise | python | def write_file(self, content, filepath=None, filename=None, indent=None, keys_to_write=None):
'''
Write a Python dictionary as JSON to a file.
:param content: Dictionary of key-value pairs to save to a file
:param filepath: Path where the file is to be created
:param filename: Name of the file to be created
:param indent: You can use this to specify indent level for pretty printing the file
:param keys_to_write: array of keys that are to be picked from data and written to file.
Default is None, when all data is written to file.
:return: Path of file used
:raises OSError, EnvironmentError, ValueError
'''
path = filepath if filepath else self.filepath
name = filename if filename else self.filename
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as error:
self.logger.error("Error while creating directory: {}".format(error))
raise
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
if keys_to_write:
data_to_write = {}
for key in keys_to_write:
data_to_write[key] = content[key]
else:
data_to_write = content
try:
indent = indent if indent else 2
self._write_json(path, name, 'w', data_to_write, indent)
return os.path.join(path, name)
except EnvironmentError as error:
self.logger.error("Error while opening or writing to file: {}".format(error))
raise
except ValueError:
raise | [
"def",
"write_file",
"(",
"self",
",",
"content",
",",
"filepath",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"keys_to_write",
"=",
"None",
")",
":",
"path",
"=",
"filepath",
"if",
"filepath",
"else",
"self",
".",
"file... | Write a Python dictionary as JSON to a file.
:param content: Dictionary of key-value pairs to save to a file
:param filepath: Path where the file is to be created
:param filename: Name of the file to be created
:param indent: You can use this to specify indent level for pretty printing the file
:param keys_to_write: array of keys that are to be picked from data and written to file.
Default is None, when all data is written to file.
:return: Path of file used
:raises OSError, EnvironmentError, ValueError | [
"Write",
"a",
"Python",
"dictionary",
"as",
"JSON",
"to",
"a",
"file",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L33-L73 | train | 25,840 |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | JsonFile.read_file | def read_file(self, filepath=None, filename=None):
"""
Tries to read JSON content from filename and convert it to a dict.
:param filepath: Path where the file is
:param filename: File name
:return: Dictionary read from the file
:raises EnvironmentError, ValueError
"""
name = filename if filename else self.filename
path = filepath if filepath else self.filepath
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
try:
return self._read_json(path, name)
except EnvironmentError as error:
self.logger.error("Error while opening or reading the file: {}".format(error))
raise
except ValueError as error:
self.logger.error("File contents cannot be decoded to JSON: {}".format(error))
raise | python | def read_file(self, filepath=None, filename=None):
"""
Tries to read JSON content from filename and convert it to a dict.
:param filepath: Path where the file is
:param filename: File name
:return: Dictionary read from the file
:raises EnvironmentError, ValueError
"""
name = filename if filename else self.filename
path = filepath if filepath else self.filepath
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
try:
return self._read_json(path, name)
except EnvironmentError as error:
self.logger.error("Error while opening or reading the file: {}".format(error))
raise
except ValueError as error:
self.logger.error("File contents cannot be decoded to JSON: {}".format(error))
raise | [
"def",
"read_file",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"name",
"=",
"filename",
"if",
"filename",
"else",
"self",
".",
"filename",
"path",
"=",
"filepath",
"if",
"filepath",
"else",
"self",
".",
"filepath",... | Tries to read JSON content from filename and convert it to a dict.
:param filepath: Path where the file is
:param filename: File name
:return: Dictionary read from the file
:raises EnvironmentError, ValueError | [
"Tries",
"to",
"read",
"JSON",
"content",
"from",
"filename",
"and",
"convert",
"it",
"to",
"a",
"dict",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L75-L96 | train | 25,841 |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | JsonFile.read_value | def read_value(self, key, filepath=None, filename=None):
"""
Tries to read the value of given key from JSON file filename.
:param filepath: Path to file
:param filename: Name of file
:param key: Key to search for
:return: Value corresponding to given key
:raises OSError, EnvironmentError, KeyError
"""
path = filepath if filepath else self.filepath
name = filename if filename else self.filename
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
try:
output = self._read_json(path, name)
if key not in output:
raise KeyError("Key '{}' not found in file {}".format(key, filename))
else:
return output[key]
except EnvironmentError as error:
self.logger.error("Error while opening or reading the file: {}".format(error))
raise | python | def read_value(self, key, filepath=None, filename=None):
"""
Tries to read the value of given key from JSON file filename.
:param filepath: Path to file
:param filename: Name of file
:param key: Key to search for
:return: Value corresponding to given key
:raises OSError, EnvironmentError, KeyError
"""
path = filepath if filepath else self.filepath
name = filename if filename else self.filename
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
try:
output = self._read_json(path, name)
if key not in output:
raise KeyError("Key '{}' not found in file {}".format(key, filename))
else:
return output[key]
except EnvironmentError as error:
self.logger.error("Error while opening or reading the file: {}".format(error))
raise | [
"def",
"read_value",
"(",
"self",
",",
"key",
",",
"filepath",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"path",
"=",
"filepath",
"if",
"filepath",
"else",
"self",
".",
"filepath",
"name",
"=",
"filename",
"if",
"filename",
"else",
"self",
"... | Tries to read the value of given key from JSON file filename.
:param filepath: Path to file
:param filename: Name of file
:param key: Key to search for
:return: Value corresponding to given key
:raises OSError, EnvironmentError, KeyError | [
"Tries",
"to",
"read",
"the",
"value",
"of",
"given",
"key",
"from",
"JSON",
"file",
"filename",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L98-L121 | train | 25,842 |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | JsonFile.write_values | def write_values(self, data, filepath=None, filename=None, indent=None, keys_to_write=None):
"""
Tries to write extra content to a JSON file.
Creates filename.temp with updated content, removes the old file and
finally renames the .temp to match the old file.
This is in effort to preserve the data in case of some weird errors cause problems.
:param filepath: Path to file
:param filename: Name of file
:param data: Data to write as a dictionary
:param indent: indent level for pretty printing the resulting file
:param keys_to_write: array of keys that are to be picked from data and written to file.
Default is None, when all data is written to file.
:return: Path to file used
:raises EnvironmentError ValueError
"""
name = filename if filename else self.filename
path = filepath if filepath else self.filepath
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
if not os.path.isfile(path + name):
try:
return self.write_file(data, path, name, indent, keys_to_write)
except EnvironmentError as error:
self.logger.error("Error while opening or writing to file: {}".format(error))
raise
except ValueError:
raise
if keys_to_write:
data_to_write = {}
for key in keys_to_write:
data_to_write[key] = data[key]
else:
data_to_write = data
try:
with open(path + name, 'r') as fil:
output = json.load(fil)
self.logger.info("Read contents of {}".format(filename))
for key in data_to_write:
try:
output[key] = data_to_write[key]
except TypeError as error:
self.logger.error(
"File contents could not be serialized into a dict. {}".format(error))
raise
self._write_json(path, name + ".temp", "w", output, indent)
FileUtils.remove_file(name, path)
FileUtils.rename_file(name + '.temp', name, path)
return os.path.join(path, name)
except EnvironmentError as error:
self.logger.error(
"Error while writing to, opening or reading the file: {}".format(error))
raise
except ValueError as error:
self.logger.error(
"File could not be decoded to JSON. It might be empty? {}".format(error))
try:
self._write_json(path, name, "w", data_to_write, indent)
return os.path.join(path, name)
except EnvironmentError:
raise | python | def write_values(self, data, filepath=None, filename=None, indent=None, keys_to_write=None):
"""
Tries to write extra content to a JSON file.
Creates filename.temp with updated content, removes the old file and
finally renames the .temp to match the old file.
This is in effort to preserve the data in case of some weird errors cause problems.
:param filepath: Path to file
:param filename: Name of file
:param data: Data to write as a dictionary
:param indent: indent level for pretty printing the resulting file
:param keys_to_write: array of keys that are to be picked from data and written to file.
Default is None, when all data is written to file.
:return: Path to file used
:raises EnvironmentError ValueError
"""
name = filename if filename else self.filename
path = filepath if filepath else self.filepath
name = self._ends_with(name, ".json")
path = self._ends_with(path, os.path.sep)
if not os.path.isfile(path + name):
try:
return self.write_file(data, path, name, indent, keys_to_write)
except EnvironmentError as error:
self.logger.error("Error while opening or writing to file: {}".format(error))
raise
except ValueError:
raise
if keys_to_write:
data_to_write = {}
for key in keys_to_write:
data_to_write[key] = data[key]
else:
data_to_write = data
try:
with open(path + name, 'r') as fil:
output = json.load(fil)
self.logger.info("Read contents of {}".format(filename))
for key in data_to_write:
try:
output[key] = data_to_write[key]
except TypeError as error:
self.logger.error(
"File contents could not be serialized into a dict. {}".format(error))
raise
self._write_json(path, name + ".temp", "w", output, indent)
FileUtils.remove_file(name, path)
FileUtils.rename_file(name + '.temp', name, path)
return os.path.join(path, name)
except EnvironmentError as error:
self.logger.error(
"Error while writing to, opening or reading the file: {}".format(error))
raise
except ValueError as error:
self.logger.error(
"File could not be decoded to JSON. It might be empty? {}".format(error))
try:
self._write_json(path, name, "w", data_to_write, indent)
return os.path.join(path, name)
except EnvironmentError:
raise | [
"def",
"write_values",
"(",
"self",
",",
"data",
",",
"filepath",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"keys_to_write",
"=",
"None",
")",
":",
"name",
"=",
"filename",
"if",
"filename",
"else",
"self",
".",
"filen... | Tries to write extra content to a JSON file.
Creates filename.temp with updated content, removes the old file and
finally renames the .temp to match the old file.
This is in effort to preserve the data in case of some weird errors cause problems.
:param filepath: Path to file
:param filename: Name of file
:param data: Data to write as a dictionary
:param indent: indent level for pretty printing the resulting file
:param keys_to_write: array of keys that are to be picked from data and written to file.
Default is None, when all data is written to file.
:return: Path to file used
:raises EnvironmentError ValueError | [
"Tries",
"to",
"write",
"extra",
"content",
"to",
"a",
"JSON",
"file",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L123-L188 | train | 25,843 |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | JsonFile._write_json | def _write_json(self, filepath, filename, writemode, content, indent):
"""
Helper for writing content to a file.
:param filepath: path to file
:param filename: name of file
:param writemode: writemode used
:param content: content to write
:param indent: value for dump indent parameter.
:return: Norhing
"""
with open(os.path.join(filepath, filename), writemode) as fil:
json.dump(content, fil, indent=indent)
self.logger.info("Wrote content to file {}".format(filename)) | python | def _write_json(self, filepath, filename, writemode, content, indent):
"""
Helper for writing content to a file.
:param filepath: path to file
:param filename: name of file
:param writemode: writemode used
:param content: content to write
:param indent: value for dump indent parameter.
:return: Norhing
"""
with open(os.path.join(filepath, filename), writemode) as fil:
json.dump(content, fil, indent=indent)
self.logger.info("Wrote content to file {}".format(filename)) | [
"def",
"_write_json",
"(",
"self",
",",
"filepath",
",",
"filename",
",",
"writemode",
",",
"content",
",",
"indent",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"filepath",
",",
"filename",
")",
",",
"writemode",
")",
"as",
"... | Helper for writing content to a file.
:param filepath: path to file
:param filename: name of file
:param writemode: writemode used
:param content: content to write
:param indent: value for dump indent parameter.
:return: Norhing | [
"Helper",
"for",
"writing",
"content",
"to",
"a",
"file",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L190-L203 | train | 25,844 |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | JsonFile._read_json | def _read_json(self, path, name):
"""
Load a json into a dictionary from a file.
:param path: path to file
:param name: name of file
:return: dict
"""
with open(os.path.join(path, name), 'r') as fil:
output = json.load(fil)
self.logger.info("Read contents of {}".format(name))
return output | python | def _read_json(self, path, name):
"""
Load a json into a dictionary from a file.
:param path: path to file
:param name: name of file
:return: dict
"""
with open(os.path.join(path, name), 'r') as fil:
output = json.load(fil)
self.logger.info("Read contents of {}".format(name))
return output | [
"def",
"_read_json",
"(",
"self",
",",
"path",
",",
"name",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
",",
"'r'",
")",
"as",
"fil",
":",
"output",
"=",
"json",
".",
"load",
"(",
"fil",
")",
... | Load a json into a dictionary from a file.
:param path: path to file
:param name: name of file
:return: dict | [
"Load",
"a",
"json",
"into",
"a",
"dictionary",
"from",
"a",
"file",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L205-L216 | train | 25,845 |
ARMmbed/icetea | icetea_lib/tools/file/SessionFiles.py | JsonFile._ends_with | def _ends_with(self, string_to_edit, end): # pylint: disable=no-self-use
"""
Check if string ends with characters in end, if not merge end to string.
:param string_to_edit: string to check and edit.
:param end: str
:return: string_to_edit or string_to_edit + end
"""
if not string_to_edit.endswith(end):
return string_to_edit + end
return string_to_edit | python | def _ends_with(self, string_to_edit, end): # pylint: disable=no-self-use
"""
Check if string ends with characters in end, if not merge end to string.
:param string_to_edit: string to check and edit.
:param end: str
:return: string_to_edit or string_to_edit + end
"""
if not string_to_edit.endswith(end):
return string_to_edit + end
return string_to_edit | [
"def",
"_ends_with",
"(",
"self",
",",
"string_to_edit",
",",
"end",
")",
":",
"# pylint: disable=no-self-use",
"if",
"not",
"string_to_edit",
".",
"endswith",
"(",
"end",
")",
":",
"return",
"string_to_edit",
"+",
"end",
"return",
"string_to_edit"
] | Check if string ends with characters in end, if not merge end to string.
:param string_to_edit: string to check and edit.
:param end: str
:return: string_to_edit or string_to_edit + end | [
"Check",
"if",
"string",
"ends",
"with",
"characters",
"in",
"end",
"if",
"not",
"merge",
"end",
"to",
"string",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L218-L228 | train | 25,846 |
ARMmbed/icetea | icetea_lib/CliResponseParser.py | ParserManager.parse | def parse(self, *args, **kwargs): # pylint: disable=unused-argument
"""
Parse response.
:param args: List. 2 first items used as parser name and response to parse
:param kwargs: dict, not used
:return: dictionary or return value of called callable from parser.
"""
# pylint: disable=W0703
cmd = args[0]
resp = args[1]
if cmd in self.parsers:
try:
return self.parsers[cmd](resp)
except Exception as err:
print(err)
return {} | python | def parse(self, *args, **kwargs): # pylint: disable=unused-argument
"""
Parse response.
:param args: List. 2 first items used as parser name and response to parse
:param kwargs: dict, not used
:return: dictionary or return value of called callable from parser.
"""
# pylint: disable=W0703
cmd = args[0]
resp = args[1]
if cmd in self.parsers:
try:
return self.parsers[cmd](resp)
except Exception as err:
print(err)
return {} | [
"def",
"parse",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"# pylint: disable=W0703",
"cmd",
"=",
"args",
"[",
"0",
"]",
"resp",
"=",
"args",
"[",
"1",
"]",
"if",
"cmd",
"in",
"self",
".",
"pa... | Parse response.
:param args: List. 2 first items used as parser name and response to parse
:param kwargs: dict, not used
:return: dictionary or return value of called callable from parser. | [
"Parse",
"response",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponseParser.py#L54-L70 | train | 25,847 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.append | def append(self, result):
"""
Append a new Result to the list.
:param result: Result to append
:return: Nothing
:raises: TypeError if result is not Result or ResultList
"""
if isinstance(result, Result):
self.data.append(result)
elif isinstance(result, ResultList):
self.data += result.data
else:
raise TypeError('unknown result type') | python | def append(self, result):
"""
Append a new Result to the list.
:param result: Result to append
:return: Nothing
:raises: TypeError if result is not Result or ResultList
"""
if isinstance(result, Result):
self.data.append(result)
elif isinstance(result, ResultList):
self.data += result.data
else:
raise TypeError('unknown result type') | [
"def",
"append",
"(",
"self",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"Result",
")",
":",
"self",
".",
"data",
".",
"append",
"(",
"result",
")",
"elif",
"isinstance",
"(",
"result",
",",
"ResultList",
")",
":",
"self",
".",
... | Append a new Result to the list.
:param result: Result to append
:return: Nothing
:raises: TypeError if result is not Result or ResultList | [
"Append",
"a",
"new",
"Result",
"to",
"the",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L46-L59 | train | 25,848 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.save | def save(self, heads, console=True):
"""
Create reports in different formats.
:param heads: html table extra values in title rows
:param console: Boolean, default is True. If set, also print out the console log.
"""
# Junit
self._save_junit()
# HTML
self._save_html_report(heads)
if console:
# Console print
self._print_console_summary() | python | def save(self, heads, console=True):
"""
Create reports in different formats.
:param heads: html table extra values in title rows
:param console: Boolean, default is True. If set, also print out the console log.
"""
# Junit
self._save_junit()
# HTML
self._save_html_report(heads)
if console:
# Console print
self._print_console_summary() | [
"def",
"save",
"(",
"self",
",",
"heads",
",",
"console",
"=",
"True",
")",
":",
"# Junit",
"self",
".",
"_save_junit",
"(",
")",
"# HTML",
"self",
".",
"_save_html_report",
"(",
"heads",
")",
"if",
"console",
":",
"# Console print",
"self",
".",
"_print... | Create reports in different formats.
:param heads: html table extra values in title rows
:param console: Boolean, default is True. If set, also print out the console log. | [
"Create",
"reports",
"in",
"different",
"formats",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L64-L77 | train | 25,849 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList._save_junit | def _save_junit(self):
"""
Save Junit report.
:return: Nothing
"""
report = ReportJunit(self)
file_name = report.get_latest_filename("result.junit.xml", "")
report.generate(file_name)
file_name = report.get_latest_filename("junit.xml", "../")
report.generate(file_name) | python | def _save_junit(self):
"""
Save Junit report.
:return: Nothing
"""
report = ReportJunit(self)
file_name = report.get_latest_filename("result.junit.xml", "")
report.generate(file_name)
file_name = report.get_latest_filename("junit.xml", "../")
report.generate(file_name) | [
"def",
"_save_junit",
"(",
"self",
")",
":",
"report",
"=",
"ReportJunit",
"(",
"self",
")",
"file_name",
"=",
"report",
".",
"get_latest_filename",
"(",
"\"result.junit.xml\"",
",",
"\"\"",
")",
"report",
".",
"generate",
"(",
"file_name",
")",
"file_name",
... | Save Junit report.
:return: Nothing | [
"Save",
"Junit",
"report",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L79-L90 | train | 25,850 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList._save_html_report | def _save_html_report(self, heads=None, refresh=None):
"""
Save html report.
:param heads: headers as dict
:param refresh: Boolean, if True will add a reload-tag to the report
:return: Nothing
"""
report = ReportHtml(self)
heads = heads if heads else {}
test_report_filename = report.get_current_filename("html")
report.generate(test_report_filename, title='Test Results', heads=heads, refresh=refresh)
# Update latest.html in the log root directory
latest_report_filename = report.get_latest_filename("html")
report.generate(latest_report_filename, title='Test Results', heads=heads, refresh=refresh) | python | def _save_html_report(self, heads=None, refresh=None):
"""
Save html report.
:param heads: headers as dict
:param refresh: Boolean, if True will add a reload-tag to the report
:return: Nothing
"""
report = ReportHtml(self)
heads = heads if heads else {}
test_report_filename = report.get_current_filename("html")
report.generate(test_report_filename, title='Test Results', heads=heads, refresh=refresh)
# Update latest.html in the log root directory
latest_report_filename = report.get_latest_filename("html")
report.generate(latest_report_filename, title='Test Results', heads=heads, refresh=refresh) | [
"def",
"_save_html_report",
"(",
"self",
",",
"heads",
"=",
"None",
",",
"refresh",
"=",
"None",
")",
":",
"report",
"=",
"ReportHtml",
"(",
"self",
")",
"heads",
"=",
"heads",
"if",
"heads",
"else",
"{",
"}",
"test_report_filename",
"=",
"report",
".",
... | Save html report.
:param heads: headers as dict
:param refresh: Boolean, if True will add a reload-tag to the report
:return: Nothing | [
"Save",
"html",
"report",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L92-L107 | train | 25,851 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.success_count | def success_count(self):
"""
Amount of passed test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.success]) | python | def success_count(self):
"""
Amount of passed test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.success]) | [
"def",
"success_count",
"(",
"self",
")",
":",
"return",
"len",
"(",
"[",
"i",
"for",
"i",
",",
"result",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
"if",
"result",
".",
"success",
"]",
")"
] | Amount of passed test cases in this list.
:return: integer | [
"Amount",
"of",
"passed",
"test",
"cases",
"in",
"this",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L117-L123 | train | 25,852 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.failure_count | def failure_count(self):
"""
Amount of failed test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.failure]) | python | def failure_count(self):
"""
Amount of failed test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.failure]) | [
"def",
"failure_count",
"(",
"self",
")",
":",
"return",
"len",
"(",
"[",
"i",
"for",
"i",
",",
"result",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
"if",
"result",
".",
"failure",
"]",
")"
] | Amount of failed test cases in this list.
:return: integer | [
"Amount",
"of",
"failed",
"test",
"cases",
"in",
"this",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L125-L131 | train | 25,853 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.inconclusive_count | def inconclusive_count(self):
"""
Amount of inconclusive test cases in this list.
:return: integer
"""
inconc_count = len([i for i, result in enumerate(self.data) if result.inconclusive])
unknown_count = len([i for i, result in enumerate(self.data) if result.get_verdict() ==
"unknown"])
return inconc_count + unknown_count | python | def inconclusive_count(self):
"""
Amount of inconclusive test cases in this list.
:return: integer
"""
inconc_count = len([i for i, result in enumerate(self.data) if result.inconclusive])
unknown_count = len([i for i, result in enumerate(self.data) if result.get_verdict() ==
"unknown"])
return inconc_count + unknown_count | [
"def",
"inconclusive_count",
"(",
"self",
")",
":",
"inconc_count",
"=",
"len",
"(",
"[",
"i",
"for",
"i",
",",
"result",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
"if",
"result",
".",
"inconclusive",
"]",
")",
"unknown_count",
"=",
"len",
"(",... | Amount of inconclusive test cases in this list.
:return: integer | [
"Amount",
"of",
"inconclusive",
"test",
"cases",
"in",
"this",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L133-L142 | train | 25,854 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.retry_count | def retry_count(self):
"""
Amount of retried test cases in this list.
:return: integer
"""
retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0])
return retries | python | def retry_count(self):
"""
Amount of retried test cases in this list.
:return: integer
"""
retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0])
return retries | [
"def",
"retry_count",
"(",
"self",
")",
":",
"retries",
"=",
"len",
"(",
"[",
"i",
"for",
"i",
",",
"result",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
"if",
"result",
".",
"retries_left",
">",
"0",
"]",
")",
"return",
"retries"
] | Amount of retried test cases in this list.
:return: integer | [
"Amount",
"of",
"retried",
"test",
"cases",
"in",
"this",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L144-L151 | train | 25,855 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.skip_count | def skip_count(self):
"""
Amount of skipped test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.skip]) | python | def skip_count(self):
"""
Amount of skipped test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.skip]) | [
"def",
"skip_count",
"(",
"self",
")",
":",
"return",
"len",
"(",
"[",
"i",
"for",
"i",
",",
"result",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
"if",
"result",
".",
"skip",
"]",
")"
] | Amount of skipped test cases in this list.
:return: integer | [
"Amount",
"of",
"skipped",
"test",
"cases",
"in",
"this",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L153-L159 | train | 25,856 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.clean_fails | def clean_fails(self):
"""
Check if there are any fails that were not subsequently retried.
:return: Boolean
"""
for item in self.data:
if item.failure and not item.retries_left > 0:
return True
return False | python | def clean_fails(self):
"""
Check if there are any fails that were not subsequently retried.
:return: Boolean
"""
for item in self.data:
if item.failure and not item.retries_left > 0:
return True
return False | [
"def",
"clean_fails",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"data",
":",
"if",
"item",
".",
"failure",
"and",
"not",
"item",
".",
"retries_left",
">",
"0",
":",
"return",
"True",
"return",
"False"
] | Check if there are any fails that were not subsequently retried.
:return: Boolean | [
"Check",
"if",
"there",
"are",
"any",
"fails",
"that",
"were",
"not",
"subsequently",
"retried",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L161-L170 | train | 25,857 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.clean_inconcs | def clean_inconcs(self):
"""
Check if there are any inconclusives or uknowns that were not subsequently retried.
:return: Boolean
"""
for item in self.data:
if (item.inconclusive or item.get_verdict() == "unknown") and not item.retries_left > 0:
return True
return False | python | def clean_inconcs(self):
"""
Check if there are any inconclusives or uknowns that were not subsequently retried.
:return: Boolean
"""
for item in self.data:
if (item.inconclusive or item.get_verdict() == "unknown") and not item.retries_left > 0:
return True
return False | [
"def",
"clean_inconcs",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"data",
":",
"if",
"(",
"item",
".",
"inconclusive",
"or",
"item",
".",
"get_verdict",
"(",
")",
"==",
"\"unknown\"",
")",
"and",
"not",
"item",
".",
"retries_left",
">",
... | Check if there are any inconclusives or uknowns that were not subsequently retried.
:return: Boolean | [
"Check",
"if",
"there",
"are",
"any",
"inconclusives",
"or",
"uknowns",
"that",
"were",
"not",
"subsequently",
"retried",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L172-L181 | train | 25,858 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.total_duration | def total_duration(self):
"""
Sum of the durations of the tests in this list.
:return: integer
"""
durations = [result.duration for result in self.data]
return sum(durations) | python | def total_duration(self):
"""
Sum of the durations of the tests in this list.
:return: integer
"""
durations = [result.duration for result in self.data]
return sum(durations) | [
"def",
"total_duration",
"(",
"self",
")",
":",
"durations",
"=",
"[",
"result",
".",
"duration",
"for",
"result",
"in",
"self",
".",
"data",
"]",
"return",
"sum",
"(",
"durations",
")"
] | Sum of the durations of the tests in this list.
:return: integer | [
"Sum",
"of",
"the",
"durations",
"of",
"the",
"tests",
"in",
"this",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L236-L243 | train | 25,859 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.pass_rate | def pass_rate(self, include_skips=False, include_inconclusive=False, include_retries=True):
"""
Calculate pass rate for tests in this list.
:param include_skips: Boolean, if True skipped tc:s will be included. Default is False
:param include_inconclusive: Boolean, if True inconclusive tc:s will be included.
Default is False.
:param include_retries: Boolean, if True retried tc:s will be included in percentages.
:return: Percentage in format .2f %
"""
total = self.count()
success = self.success_count()
retries = self.retry_count()
try:
if include_inconclusive and include_skips and include_retries:
val = 100.0*success/total
elif include_inconclusive and include_skips and not include_retries:
val = 100.0 * success / (total - retries)
elif include_skips and include_retries and not include_inconclusive:
inconcs = self.inconclusive_count()
val = 100.0 * success / (total - inconcs)
elif include_skips and not include_retries and not include_inconclusive:
inconcs = self.inconclusive_count()
val = 100.0 * success / (total - inconcs - retries)
elif include_inconclusive and include_retries and not include_skips:
skipped = self.skip_count()
val = 100.0 * success / (total - skipped)
elif include_inconclusive and not include_retries and not include_skips:
skipped = self.skip_count()
val = 100.0 * success / (total - skipped - retries)
elif not include_inconclusive and not include_skips and include_retries:
failures = self.failure_count()
val = 100.0 * success / (failures + success)
else:
failures = self.clean_fails()
val = 100.0 * success / (failures + success)
except ZeroDivisionError:
val = 0
return format(val, '.2f') + " %" | python | def pass_rate(self, include_skips=False, include_inconclusive=False, include_retries=True):
"""
Calculate pass rate for tests in this list.
:param include_skips: Boolean, if True skipped tc:s will be included. Default is False
:param include_inconclusive: Boolean, if True inconclusive tc:s will be included.
Default is False.
:param include_retries: Boolean, if True retried tc:s will be included in percentages.
:return: Percentage in format .2f %
"""
total = self.count()
success = self.success_count()
retries = self.retry_count()
try:
if include_inconclusive and include_skips and include_retries:
val = 100.0*success/total
elif include_inconclusive and include_skips and not include_retries:
val = 100.0 * success / (total - retries)
elif include_skips and include_retries and not include_inconclusive:
inconcs = self.inconclusive_count()
val = 100.0 * success / (total - inconcs)
elif include_skips and not include_retries and not include_inconclusive:
inconcs = self.inconclusive_count()
val = 100.0 * success / (total - inconcs - retries)
elif include_inconclusive and include_retries and not include_skips:
skipped = self.skip_count()
val = 100.0 * success / (total - skipped)
elif include_inconclusive and not include_retries and not include_skips:
skipped = self.skip_count()
val = 100.0 * success / (total - skipped - retries)
elif not include_inconclusive and not include_skips and include_retries:
failures = self.failure_count()
val = 100.0 * success / (failures + success)
else:
failures = self.clean_fails()
val = 100.0 * success / (failures + success)
except ZeroDivisionError:
val = 0
return format(val, '.2f') + " %" | [
"def",
"pass_rate",
"(",
"self",
",",
"include_skips",
"=",
"False",
",",
"include_inconclusive",
"=",
"False",
",",
"include_retries",
"=",
"True",
")",
":",
"total",
"=",
"self",
".",
"count",
"(",
")",
"success",
"=",
"self",
".",
"success_count",
"(",
... | Calculate pass rate for tests in this list.
:param include_skips: Boolean, if True skipped tc:s will be included. Default is False
:param include_inconclusive: Boolean, if True inconclusive tc:s will be included.
Default is False.
:param include_retries: Boolean, if True retried tc:s will be included in percentages.
:return: Percentage in format .2f % | [
"Calculate",
"pass",
"rate",
"for",
"tests",
"in",
"this",
"list",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L245-L283 | train | 25,860 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.get_summary | def get_summary(self):
"""
Get a summary of this ResultLists contents as dictionary.
:return: dictionary
"""
return {
"count": self.count(),
"pass": self.success_count(),
"fail": self.failure_count(),
"skip": self.skip_count(),
"inconclusive": self.inconclusive_count(),
"retries": self.retry_count(),
"duration": self.total_duration()
} | python | def get_summary(self):
"""
Get a summary of this ResultLists contents as dictionary.
:return: dictionary
"""
return {
"count": self.count(),
"pass": self.success_count(),
"fail": self.failure_count(),
"skip": self.skip_count(),
"inconclusive": self.inconclusive_count(),
"retries": self.retry_count(),
"duration": self.total_duration()
} | [
"def",
"get_summary",
"(",
"self",
")",
":",
"return",
"{",
"\"count\"",
":",
"self",
".",
"count",
"(",
")",
",",
"\"pass\"",
":",
"self",
".",
"success_count",
"(",
")",
",",
"\"fail\"",
":",
"self",
".",
"failure_count",
"(",
")",
",",
"\"skip\"",
... | Get a summary of this ResultLists contents as dictionary.
:return: dictionary | [
"Get",
"a",
"summary",
"of",
"this",
"ResultLists",
"contents",
"as",
"dictionary",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L285-L299 | train | 25,861 |
ARMmbed/icetea | icetea_lib/ResultList.py | ResultList.next | def next(self):
"""
Implementation of next method from Iterator.
:return: Result
:raises: StopIteration if IndexError occurs.
"""
try:
result = self.data[self.index]
except IndexError:
self.index = 0
raise StopIteration
self.index += 1
return result | python | def next(self):
"""
Implementation of next method from Iterator.
:return: Result
:raises: StopIteration if IndexError occurs.
"""
try:
result = self.data[self.index]
except IndexError:
self.index = 0
raise StopIteration
self.index += 1
return result | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"data",
"[",
"self",
".",
"index",
"]",
"except",
"IndexError",
":",
"self",
".",
"index",
"=",
"0",
"raise",
"StopIteration",
"self",
".",
"index",
"+=",
"1",
"return",
... | Implementation of next method from Iterator.
:return: Result
:raises: StopIteration if IndexError occurs. | [
"Implementation",
"of",
"next",
"method",
"from",
"Iterator",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L325-L338 | train | 25,862 |
ARMmbed/icetea | icetea_lib/tools/deprecated.py | deprecated | def deprecated(message=""):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used first time and filter is set for show DeprecationWarning.
"""
def decorator_wrapper(func):
"""
Generate decorator wrapper function
:param func: function to be decorated
:return: wrapper
"""
@functools.wraps(func)
def function_wrapper(*args, **kwargs):
"""
Wrapper which recognize deprecated line from source code
:param args: args for actual function
:param kwargs: kwargs for actual functions
:return: something that actual function might returns
"""
current_call_source = '|'.join(traceback.format_stack(inspect.currentframe()))
if current_call_source not in function_wrapper.last_call_source:
warnings.warn("Function {} is now deprecated! {}".format(func.__name__, message),
category=DeprecationWarning, stacklevel=2)
function_wrapper.last_call_source.add(current_call_source)
return func(*args, **kwargs)
function_wrapper.last_call_source = set()
return function_wrapper
return decorator_wrapper | python | def deprecated(message=""):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used first time and filter is set for show DeprecationWarning.
"""
def decorator_wrapper(func):
"""
Generate decorator wrapper function
:param func: function to be decorated
:return: wrapper
"""
@functools.wraps(func)
def function_wrapper(*args, **kwargs):
"""
Wrapper which recognize deprecated line from source code
:param args: args for actual function
:param kwargs: kwargs for actual functions
:return: something that actual function might returns
"""
current_call_source = '|'.join(traceback.format_stack(inspect.currentframe()))
if current_call_source not in function_wrapper.last_call_source:
warnings.warn("Function {} is now deprecated! {}".format(func.__name__, message),
category=DeprecationWarning, stacklevel=2)
function_wrapper.last_call_source.add(current_call_source)
return func(*args, **kwargs)
function_wrapper.last_call_source = set()
return function_wrapper
return decorator_wrapper | [
"def",
"deprecated",
"(",
"message",
"=",
"\"\"",
")",
":",
"def",
"decorator_wrapper",
"(",
"func",
")",
":",
"\"\"\"\n Generate decorator wrapper function\n :param func: function to be decorated\n :return: wrapper\n \"\"\"",
"@",
"functools",
".",
"w... | This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used first time and filter is set for show DeprecationWarning. | [
"This",
"is",
"a",
"decorator",
"which",
"can",
"be",
"used",
"to",
"mark",
"functions",
"as",
"deprecated",
".",
"It",
"will",
"result",
"in",
"a",
"warning",
"being",
"emitted",
"when",
"the",
"function",
"is",
"used",
"first",
"time",
"and",
"filter",
... | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/deprecated.py#L24-L55 | train | 25,863 |
ARMmbed/icetea | icetea_lib/tools/file/FileUtils.py | remove_file | def remove_file(filename, path=None):
"""
Remove file filename from path.
:param filename: Name of file to remove
:param path: Path where file is located
:return: True if successfull
:raises OSError if chdir or remove fails.
"""
cwd = os.getcwd()
try:
if path:
os.chdir(path)
except OSError:
raise
try:
os.remove(filename)
os.chdir(cwd)
return True
except OSError:
os.chdir(cwd)
raise | python | def remove_file(filename, path=None):
"""
Remove file filename from path.
:param filename: Name of file to remove
:param path: Path where file is located
:return: True if successfull
:raises OSError if chdir or remove fails.
"""
cwd = os.getcwd()
try:
if path:
os.chdir(path)
except OSError:
raise
try:
os.remove(filename)
os.chdir(cwd)
return True
except OSError:
os.chdir(cwd)
raise | [
"def",
"remove_file",
"(",
"filename",
",",
"path",
"=",
"None",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"if",
"path",
":",
"os",
".",
"chdir",
"(",
"path",
")",
"except",
"OSError",
":",
"raise",
"try",
":",
"os",
".",
... | Remove file filename from path.
:param filename: Name of file to remove
:param path: Path where file is located
:return: True if successfull
:raises OSError if chdir or remove fails. | [
"Remove",
"file",
"filename",
"from",
"path",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/FileUtils.py#L55-L76 | train | 25,864 |
ARMmbed/icetea | icetea_lib/CliResponse.py | CliResponse.verify_message | def verify_message(self, expected_response, break_in_fail=True):
"""
Verifies that expected_response is found in self.lines.
:param expected_response: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True,
re-raises exceptions caught or if message was not found
:return: True or False
:raises: LookupError if message was not found and break_in_fail was True. Other exceptions
might also be raised through searcher.verify_message.
"""
ok = True
try:
ok = verify_message(self.lines, expected_response)
except (TypeError, LookupError) as inst:
ok = False
if break_in_fail:
raise inst
if ok is False and break_in_fail:
raise LookupError("Unexpected message found")
return ok | python | def verify_message(self, expected_response, break_in_fail=True):
"""
Verifies that expected_response is found in self.lines.
:param expected_response: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True,
re-raises exceptions caught or if message was not found
:return: True or False
:raises: LookupError if message was not found and break_in_fail was True. Other exceptions
might also be raised through searcher.verify_message.
"""
ok = True
try:
ok = verify_message(self.lines, expected_response)
except (TypeError, LookupError) as inst:
ok = False
if break_in_fail:
raise inst
if ok is False and break_in_fail:
raise LookupError("Unexpected message found")
return ok | [
"def",
"verify_message",
"(",
"self",
",",
"expected_response",
",",
"break_in_fail",
"=",
"True",
")",
":",
"ok",
"=",
"True",
"try",
":",
"ok",
"=",
"verify_message",
"(",
"self",
".",
"lines",
",",
"expected_response",
")",
"except",
"(",
"TypeError",
"... | Verifies that expected_response is found in self.lines.
:param expected_response: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True,
re-raises exceptions caught or if message was not found
:return: True or False
:raises: LookupError if message was not found and break_in_fail was True. Other exceptions
might also be raised through searcher.verify_message. | [
"Verifies",
"that",
"expected_response",
"is",
"found",
"in",
"self",
".",
"lines",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L68-L88 | train | 25,865 |
ARMmbed/icetea | icetea_lib/CliResponse.py | CliResponse.verify_trace | def verify_trace(self, expected_traces, break_in_fail=True):
"""
Verifies that expectedResponse is found in self.traces
:param expected_traces: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True, re-raises exceptions caught or if message was
not found
:return: True or False
:raises: LookupError if message was not found and breakInFail was True. Other Exceptions
might also be raised through searcher.verify_message.
"""
ok = True
try:
ok = verify_message(self.traces, expected_traces)
except (TypeError, LookupError) as inst:
ok = False
if break_in_fail:
raise inst
if ok is False and break_in_fail:
raise LookupError("Unexpected message found")
return ok | python | def verify_trace(self, expected_traces, break_in_fail=True):
"""
Verifies that expectedResponse is found in self.traces
:param expected_traces: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True, re-raises exceptions caught or if message was
not found
:return: True or False
:raises: LookupError if message was not found and breakInFail was True. Other Exceptions
might also be raised through searcher.verify_message.
"""
ok = True
try:
ok = verify_message(self.traces, expected_traces)
except (TypeError, LookupError) as inst:
ok = False
if break_in_fail:
raise inst
if ok is False and break_in_fail:
raise LookupError("Unexpected message found")
return ok | [
"def",
"verify_trace",
"(",
"self",
",",
"expected_traces",
",",
"break_in_fail",
"=",
"True",
")",
":",
"ok",
"=",
"True",
"try",
":",
"ok",
"=",
"verify_message",
"(",
"self",
".",
"traces",
",",
"expected_traces",
")",
"except",
"(",
"TypeError",
",",
... | Verifies that expectedResponse is found in self.traces
:param expected_traces: response or responses to look for. Must be list or str.
:param break_in_fail: If set to True, re-raises exceptions caught or if message was
not found
:return: True or False
:raises: LookupError if message was not found and breakInFail was True. Other Exceptions
might also be raised through searcher.verify_message. | [
"Verifies",
"that",
"expectedResponse",
"is",
"found",
"in",
"self",
".",
"traces"
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L90-L110 | train | 25,866 |
ARMmbed/icetea | icetea_lib/CliResponse.py | CliResponse.verify_response_duration | def verify_response_duration(self, expected=None, zero=0, threshold_percent=0,
break_in_fail=True):
"""
Verify that response duration is in bounds.
:param expected: seconds what is expected duration
:param zero: seconds if one to normalize duration before calculating error rate
:param threshold_percent: allowed error in percents
:param break_in_fail: boolean, True if raise TestStepFail when out of bounds
:return: (duration, expected duration, error)
"""
was = self.timedelta - zero
error = abs(was/expected)*100.0 - 100.0 if expected > 0 else 0
msg = "should: %.3f, was: %.3f, error: %.3f %%" % (expected, was, error)
self.logger.debug(msg)
if abs(error) > threshold_percent:
msg = "Thread::wait error(%.2f %%) was out of bounds (%.2f %%)" \
% (error, threshold_percent)
self.logger.debug(msg)
if break_in_fail:
raise TestStepFail(msg)
return was, expected, error | python | def verify_response_duration(self, expected=None, zero=0, threshold_percent=0,
break_in_fail=True):
"""
Verify that response duration is in bounds.
:param expected: seconds what is expected duration
:param zero: seconds if one to normalize duration before calculating error rate
:param threshold_percent: allowed error in percents
:param break_in_fail: boolean, True if raise TestStepFail when out of bounds
:return: (duration, expected duration, error)
"""
was = self.timedelta - zero
error = abs(was/expected)*100.0 - 100.0 if expected > 0 else 0
msg = "should: %.3f, was: %.3f, error: %.3f %%" % (expected, was, error)
self.logger.debug(msg)
if abs(error) > threshold_percent:
msg = "Thread::wait error(%.2f %%) was out of bounds (%.2f %%)" \
% (error, threshold_percent)
self.logger.debug(msg)
if break_in_fail:
raise TestStepFail(msg)
return was, expected, error | [
"def",
"verify_response_duration",
"(",
"self",
",",
"expected",
"=",
"None",
",",
"zero",
"=",
"0",
",",
"threshold_percent",
"=",
"0",
",",
"break_in_fail",
"=",
"True",
")",
":",
"was",
"=",
"self",
".",
"timedelta",
"-",
"zero",
"error",
"=",
"abs",
... | Verify that response duration is in bounds.
:param expected: seconds what is expected duration
:param zero: seconds if one to normalize duration before calculating error rate
:param threshold_percent: allowed error in percents
:param break_in_fail: boolean, True if raise TestStepFail when out of bounds
:return: (duration, expected duration, error) | [
"Verify",
"that",
"response",
"duration",
"is",
"in",
"bounds",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L121-L142 | train | 25,867 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig._hardware_count | def _hardware_count(self):
"""
Amount of hardware resources.
:return: integer
"""
return self._counts.get("hardware") + self._counts.get("serial") + self._counts.get("mbed") | python | def _hardware_count(self):
"""
Amount of hardware resources.
:return: integer
"""
return self._counts.get("hardware") + self._counts.get("serial") + self._counts.get("mbed") | [
"def",
"_hardware_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"_counts",
".",
"get",
"(",
"\"hardware\"",
")",
"+",
"self",
".",
"_counts",
".",
"get",
"(",
"\"serial\"",
")",
"+",
"self",
".",
"_counts",
".",
"get",
"(",
"\"mbed\"",
")"
] | Amount of hardware resources.
:return: integer | [
"Amount",
"of",
"hardware",
"resources",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L41-L47 | train | 25,868 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig._resolve_requirements | def _resolve_requirements(self, requirements):
"""
Internal method for resolving requirements into resource configurations.
:param requirements: Resource requirements from test case configuration as dictionary.
:return: Empty list if dut_count cannot be resolved, or nothing
"""
try:
dut_count = requirements["duts"]["*"]["count"]
except KeyError:
return []
default_values = {
"type": "hardware",
"allowed_platforms": [],
"nick": None,
}
default_values.update(requirements["duts"]["*"])
del default_values["count"]
dut_keys = list(default_values.keys())
dut_keys.extend(["application", "location", "subtype"])
dut_requirements = self.__generate_indexed_requirements(dut_count,
default_values,
requirements)
# Match groups of duts defined with 1..40 notation.
for key in requirements["duts"].keys():
if not isinstance(key, string_types):
continue
match = re.search(r'([\d]{1,})\.\.([\d]{1,})', key)
if match:
first_dut_idx = int(match.group(1))
last_dut_idx = int(match.group(2))
for i in range(first_dut_idx, last_dut_idx+1):
for k in dut_keys:
if k in requirements["duts"][key]:
dut_requirements[i-1].set(k, copy.copy(requirements["duts"][key][k]))
for idx, req in enumerate(dut_requirements):
if isinstance(req.get("nick"), string_types):
nick = req.get("nick")
req.set("nick", ResourceConfig.__replace_base_variables(nick,
len(dut_requirements),
idx))
self._solve_location(req, len(dut_requirements), idx)
self._dut_requirements = dut_requirements
return None | python | def _resolve_requirements(self, requirements):
"""
Internal method for resolving requirements into resource configurations.
:param requirements: Resource requirements from test case configuration as dictionary.
:return: Empty list if dut_count cannot be resolved, or nothing
"""
try:
dut_count = requirements["duts"]["*"]["count"]
except KeyError:
return []
default_values = {
"type": "hardware",
"allowed_platforms": [],
"nick": None,
}
default_values.update(requirements["duts"]["*"])
del default_values["count"]
dut_keys = list(default_values.keys())
dut_keys.extend(["application", "location", "subtype"])
dut_requirements = self.__generate_indexed_requirements(dut_count,
default_values,
requirements)
# Match groups of duts defined with 1..40 notation.
for key in requirements["duts"].keys():
if not isinstance(key, string_types):
continue
match = re.search(r'([\d]{1,})\.\.([\d]{1,})', key)
if match:
first_dut_idx = int(match.group(1))
last_dut_idx = int(match.group(2))
for i in range(first_dut_idx, last_dut_idx+1):
for k in dut_keys:
if k in requirements["duts"][key]:
dut_requirements[i-1].set(k, copy.copy(requirements["duts"][key][k]))
for idx, req in enumerate(dut_requirements):
if isinstance(req.get("nick"), string_types):
nick = req.get("nick")
req.set("nick", ResourceConfig.__replace_base_variables(nick,
len(dut_requirements),
idx))
self._solve_location(req, len(dut_requirements), idx)
self._dut_requirements = dut_requirements
return None | [
"def",
"_resolve_requirements",
"(",
"self",
",",
"requirements",
")",
":",
"try",
":",
"dut_count",
"=",
"requirements",
"[",
"\"duts\"",
"]",
"[",
"\"*\"",
"]",
"[",
"\"count\"",
"]",
"except",
"KeyError",
":",
"return",
"[",
"]",
"default_values",
"=",
... | Internal method for resolving requirements into resource configurations.
:param requirements: Resource requirements from test case configuration as dictionary.
:return: Empty list if dut_count cannot be resolved, or nothing | [
"Internal",
"method",
"for",
"resolving",
"requirements",
"into",
"resource",
"configurations",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L109-L158 | train | 25,869 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig._solve_location | def _solve_location(self, req, dut_req_len, idx):
"""
Helper function for resolving the location for a resource.
:param req: Requirements dictionary
:param dut_req_len: Amount of required resources
:param idx: index, integer
:return: Nothing, modifies req object
"""
if not req.get("location"):
return
if len(req.get("location")) == 2:
for x_and_y, coord in enumerate(req.get("location")):
if isinstance(coord, string_types):
coord = ResourceConfig.__replace_coord_variables(coord,
x_and_y,
dut_req_len,
idx)
try:
loc = req.get("location")
loc[x_and_y] = eval(coord) # pylint: disable=eval-used
req.set("location", loc)
except SyntaxError as error:
self.logger.error(error)
loc = req.get("location")
loc[x_and_y] = 0.0
req.set("location", loc)
else:
self.logger.error("invalid location field!")
req.set("location", [0.0, 0.0]) | python | def _solve_location(self, req, dut_req_len, idx):
"""
Helper function for resolving the location for a resource.
:param req: Requirements dictionary
:param dut_req_len: Amount of required resources
:param idx: index, integer
:return: Nothing, modifies req object
"""
if not req.get("location"):
return
if len(req.get("location")) == 2:
for x_and_y, coord in enumerate(req.get("location")):
if isinstance(coord, string_types):
coord = ResourceConfig.__replace_coord_variables(coord,
x_and_y,
dut_req_len,
idx)
try:
loc = req.get("location")
loc[x_and_y] = eval(coord) # pylint: disable=eval-used
req.set("location", loc)
except SyntaxError as error:
self.logger.error(error)
loc = req.get("location")
loc[x_and_y] = 0.0
req.set("location", loc)
else:
self.logger.error("invalid location field!")
req.set("location", [0.0, 0.0]) | [
"def",
"_solve_location",
"(",
"self",
",",
"req",
",",
"dut_req_len",
",",
"idx",
")",
":",
"if",
"not",
"req",
".",
"get",
"(",
"\"location\"",
")",
":",
"return",
"if",
"len",
"(",
"req",
".",
"get",
"(",
"\"location\"",
")",
")",
"==",
"2",
":"... | Helper function for resolving the location for a resource.
:param req: Requirements dictionary
:param dut_req_len: Amount of required resources
:param idx: index, integer
:return: Nothing, modifies req object | [
"Helper",
"function",
"for",
"resolving",
"the",
"location",
"for",
"a",
"resource",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L160-L190 | train | 25,870 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig.__replace_base_variables | def __replace_base_variables(text, req_len, idx):
"""
Replace i and n in text with index+1 and req_len.
:param text: base text to modify
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: modified string
"""
return text \
.replace("{i}", str(idx + 1)) \
.replace("{n}", str(req_len)) | python | def __replace_base_variables(text, req_len, idx):
"""
Replace i and n in text with index+1 and req_len.
:param text: base text to modify
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: modified string
"""
return text \
.replace("{i}", str(idx + 1)) \
.replace("{n}", str(req_len)) | [
"def",
"__replace_base_variables",
"(",
"text",
",",
"req_len",
",",
"idx",
")",
":",
"return",
"text",
".",
"replace",
"(",
"\"{i}\"",
",",
"str",
"(",
"idx",
"+",
"1",
")",
")",
".",
"replace",
"(",
"\"{n}\"",
",",
"str",
"(",
"req_len",
")",
")"
] | Replace i and n in text with index+1 and req_len.
:param text: base text to modify
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: modified string | [
"Replace",
"i",
"and",
"n",
"in",
"text",
"with",
"index",
"+",
"1",
"and",
"req_len",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L193-L204 | train | 25,871 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig.__replace_coord_variables | def __replace_coord_variables(text, x_and_y, req_len, idx):
"""
Replace x and y with their coordinates and replace pi with value of pi.
:param text: text: base text to modify
:param x_and_y: location x and y
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: str
"""
return ResourceConfig.__replace_base_variables(text, req_len, idx) \
.replace("{xy}", str(x_and_y)) \
.replace("{pi}", str(math.pi)) | python | def __replace_coord_variables(text, x_and_y, req_len, idx):
"""
Replace x and y with their coordinates and replace pi with value of pi.
:param text: text: base text to modify
:param x_and_y: location x and y
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: str
"""
return ResourceConfig.__replace_base_variables(text, req_len, idx) \
.replace("{xy}", str(x_and_y)) \
.replace("{pi}", str(math.pi)) | [
"def",
"__replace_coord_variables",
"(",
"text",
",",
"x_and_y",
",",
"req_len",
",",
"idx",
")",
":",
"return",
"ResourceConfig",
".",
"__replace_base_variables",
"(",
"text",
",",
"req_len",
",",
"idx",
")",
".",
"replace",
"(",
"\"{xy}\"",
",",
"str",
"("... | Replace x and y with their coordinates and replace pi with value of pi.
:param text: text: base text to modify
:param x_and_y: location x and y
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: str | [
"Replace",
"x",
"and",
"y",
"with",
"their",
"coordinates",
"and",
"replace",
"pi",
"with",
"value",
"of",
"pi",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L207-L219 | train | 25,872 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig.__generate_indexed_requirements | def __generate_indexed_requirements(dut_count, basekeys, requirements):
"""
Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dict.
"""
dut_requirements = []
for i in range(1, dut_count + 1):
dut_requirement = ResourceRequirements(basekeys.copy())
if i in requirements["duts"]:
for k in requirements["duts"][i]:
dut_requirement.set(k, requirements["duts"][i][k])
elif str(i) in requirements["duts"]:
i = str(i)
for k in requirements["duts"][i]:
dut_requirement.set(k, requirements["duts"][i][k])
dut_requirements.append(dut_requirement)
return dut_requirements | python | def __generate_indexed_requirements(dut_count, basekeys, requirements):
"""
Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dict.
"""
dut_requirements = []
for i in range(1, dut_count + 1):
dut_requirement = ResourceRequirements(basekeys.copy())
if i in requirements["duts"]:
for k in requirements["duts"][i]:
dut_requirement.set(k, requirements["duts"][i][k])
elif str(i) in requirements["duts"]:
i = str(i)
for k in requirements["duts"][i]:
dut_requirement.set(k, requirements["duts"][i][k])
dut_requirements.append(dut_requirement)
return dut_requirements | [
"def",
"__generate_indexed_requirements",
"(",
"dut_count",
",",
"basekeys",
",",
"requirements",
")",
":",
"dut_requirements",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"dut_count",
"+",
"1",
")",
":",
"dut_requirement",
"=",
"ResourceRequireme... | Generate indexed requirements from general requirements.
:param dut_count: Amount of duts
:param basekeys: base keys as dict
:param requirements: requirements
:return: Indexed requirements as dict. | [
"Generate",
"indexed",
"requirements",
"from",
"general",
"requirements",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L222-L242 | train | 25,873 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig._resolve_hardware_count | def _resolve_hardware_count(self):
"""
Calculate amount of hardware resources.
:return: Nothing, adds results to self._hardware_count
"""
length = len([d for d in self._dut_requirements if d.get("type") in ["hardware",
"serial", "mbed"]])
self._hardware_count = length | python | def _resolve_hardware_count(self):
"""
Calculate amount of hardware resources.
:return: Nothing, adds results to self._hardware_count
"""
length = len([d for d in self._dut_requirements if d.get("type") in ["hardware",
"serial", "mbed"]])
self._hardware_count = length | [
"def",
"_resolve_hardware_count",
"(",
"self",
")",
":",
"length",
"=",
"len",
"(",
"[",
"d",
"for",
"d",
"in",
"self",
".",
"_dut_requirements",
"if",
"d",
".",
"get",
"(",
"\"type\"",
")",
"in",
"[",
"\"hardware\"",
",",
"\"serial\"",
",",
"\"mbed\"",
... | Calculate amount of hardware resources.
:return: Nothing, adds results to self._hardware_count | [
"Calculate",
"amount",
"of",
"hardware",
"resources",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L258-L266 | train | 25,874 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig._resolve_process_count | def _resolve_process_count(self):
"""
Calculate amount of process resources.
:return: Nothing, adds results to self._process_count
"""
length = len([d for d in self._dut_requirements if d.get("type") == "process"])
self._process_count = length | python | def _resolve_process_count(self):
"""
Calculate amount of process resources.
:return: Nothing, adds results to self._process_count
"""
length = len([d for d in self._dut_requirements if d.get("type") == "process"])
self._process_count = length | [
"def",
"_resolve_process_count",
"(",
"self",
")",
":",
"length",
"=",
"len",
"(",
"[",
"d",
"for",
"d",
"in",
"self",
".",
"_dut_requirements",
"if",
"d",
".",
"get",
"(",
"\"type\"",
")",
"==",
"\"process\"",
"]",
")",
"self",
".",
"_process_count",
... | Calculate amount of process resources.
:return: Nothing, adds results to self._process_count | [
"Calculate",
"amount",
"of",
"process",
"resources",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L274-L281 | train | 25,875 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig._resolve_dut_count | def _resolve_dut_count(self):
"""
Calculates total amount of resources required and their types.
:return: Nothing, modifies _dut_count, _hardware_count and
_process_count
:raises: ValueError if total count does not match counts of types separately.
"""
self._dut_count = len(self._dut_requirements)
self._resolve_process_count()
self._resolve_hardware_count()
if self._dut_count != self._hardware_count + self._process_count:
raise ValueError("Missing or invalid type fields in dut configuration!") | python | def _resolve_dut_count(self):
"""
Calculates total amount of resources required and their types.
:return: Nothing, modifies _dut_count, _hardware_count and
_process_count
:raises: ValueError if total count does not match counts of types separately.
"""
self._dut_count = len(self._dut_requirements)
self._resolve_process_count()
self._resolve_hardware_count()
if self._dut_count != self._hardware_count + self._process_count:
raise ValueError("Missing or invalid type fields in dut configuration!") | [
"def",
"_resolve_dut_count",
"(",
"self",
")",
":",
"self",
".",
"_dut_count",
"=",
"len",
"(",
"self",
".",
"_dut_requirements",
")",
"self",
".",
"_resolve_process_count",
"(",
")",
"self",
".",
"_resolve_hardware_count",
"(",
")",
"if",
"self",
".",
"_dut... | Calculates total amount of resources required and their types.
:return: Nothing, modifies _dut_count, _hardware_count and
_process_count
:raises: ValueError if total count does not match counts of types separately. | [
"Calculates",
"total",
"amount",
"of",
"resources",
"required",
"and",
"their",
"types",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L289-L301 | train | 25,876 |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | ResourceConfig.set_dut_configuration | def set_dut_configuration(self, ident, config):
"""
Set requirements for dut ident.
:param ident: Identity of dut.
:param config: If ResourceRequirements object, add object as requirements for resource
ident. If dictionary, create new ResourceRequirements object from dictionary.
:return: Nothing
"""
if hasattr(config, "get_requirements"):
self._dut_requirements[ident] = config
elif isinstance(config, dict):
self._dut_requirements[ident] = ResourceRequirements(config) | python | def set_dut_configuration(self, ident, config):
"""
Set requirements for dut ident.
:param ident: Identity of dut.
:param config: If ResourceRequirements object, add object as requirements for resource
ident. If dictionary, create new ResourceRequirements object from dictionary.
:return: Nothing
"""
if hasattr(config, "get_requirements"):
self._dut_requirements[ident] = config
elif isinstance(config, dict):
self._dut_requirements[ident] = ResourceRequirements(config) | [
"def",
"set_dut_configuration",
"(",
"self",
",",
"ident",
",",
"config",
")",
":",
"if",
"hasattr",
"(",
"config",
",",
"\"get_requirements\"",
")",
":",
"self",
".",
"_dut_requirements",
"[",
"ident",
"]",
"=",
"config",
"elif",
"isinstance",
"(",
"config"... | Set requirements for dut ident.
:param ident: Identity of dut.
:param config: If ResourceRequirements object, add object as requirements for resource
ident. If dictionary, create new ResourceRequirements object from dictionary.
:return: Nothing | [
"Set",
"requirements",
"for",
"dut",
"ident",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L313-L325 | train | 25,877 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py | DutMbed.flash | def flash(self, binary_location=None, forceflash=None):
"""
Flash a binary to the target device using mbed-flasher.
:param binary_location: Binary to flash to device.
:param forceflash: Not used.
:return: False if an unknown error was encountered during flashing.
True if flasher retcode == 0
:raises: ImportError if mbed-flasher not installed.
:raises: DutConnectionError if flashing fails.
"""
if not Flash:
self.logger.error("Mbed-flasher not installed!")
raise ImportError("Mbed-flasher not installed!")
try:
# create build object
self.build = Build.init(binary_location)
except NotImplementedError as error:
self.logger.error("Build initialization failed. "
"Check your build location.")
self.logger.debug(error)
raise DutConnectionError(error)
# check if need to flash - depend on forceflash -option
if not self._flash_needed(forceflash=forceflash):
self.logger.info("Skipping flash, not needed.")
return True
# initialize mbed-flasher with proper logger
logger = get_external_logger("mbed-flasher", "FLS")
flasher = Flash(logger=logger)
if not self.device:
self.logger.error("Trying to flash device but device is not there?")
return False
try:
buildfile = self.build.get_file()
if not buildfile:
raise DutConnectionError("Binary {} not found".format(buildfile))
self.logger.info('Flashing dev: %s', self.device['target_id'])
target_id = self.device.get("target_id")
retcode = flasher.flash(build=buildfile, target_id=target_id,
device_mapping_table=[self.device])
except FLASHER_ERRORS as error:
if error.__class__ == NotImplementedError:
self.logger.error("Flashing not supported for this platform!")
elif error.__class__ == SyntaxError:
self.logger.error("target_id required by mbed-flasher!")
if FlashError is not None:
if error.__class__ == FlashError:
self.logger.error("Flasher raised the following error: %s Error code: %i",
error.message, error.return_code)
raise DutConnectionError(error)
if retcode == 0:
self.dutinformation.build_binary_sha1 = self.build.sha1
return True
self.dutinformation.build_binary_sha1 = None
return False | python | def flash(self, binary_location=None, forceflash=None):
"""
Flash a binary to the target device using mbed-flasher.
:param binary_location: Binary to flash to device.
:param forceflash: Not used.
:return: False if an unknown error was encountered during flashing.
True if flasher retcode == 0
:raises: ImportError if mbed-flasher not installed.
:raises: DutConnectionError if flashing fails.
"""
if not Flash:
self.logger.error("Mbed-flasher not installed!")
raise ImportError("Mbed-flasher not installed!")
try:
# create build object
self.build = Build.init(binary_location)
except NotImplementedError as error:
self.logger.error("Build initialization failed. "
"Check your build location.")
self.logger.debug(error)
raise DutConnectionError(error)
# check if need to flash - depend on forceflash -option
if not self._flash_needed(forceflash=forceflash):
self.logger.info("Skipping flash, not needed.")
return True
# initialize mbed-flasher with proper logger
logger = get_external_logger("mbed-flasher", "FLS")
flasher = Flash(logger=logger)
if not self.device:
self.logger.error("Trying to flash device but device is not there?")
return False
try:
buildfile = self.build.get_file()
if not buildfile:
raise DutConnectionError("Binary {} not found".format(buildfile))
self.logger.info('Flashing dev: %s', self.device['target_id'])
target_id = self.device.get("target_id")
retcode = flasher.flash(build=buildfile, target_id=target_id,
device_mapping_table=[self.device])
except FLASHER_ERRORS as error:
if error.__class__ == NotImplementedError:
self.logger.error("Flashing not supported for this platform!")
elif error.__class__ == SyntaxError:
self.logger.error("target_id required by mbed-flasher!")
if FlashError is not None:
if error.__class__ == FlashError:
self.logger.error("Flasher raised the following error: %s Error code: %i",
error.message, error.return_code)
raise DutConnectionError(error)
if retcode == 0:
self.dutinformation.build_binary_sha1 = self.build.sha1
return True
self.dutinformation.build_binary_sha1 = None
return False | [
"def",
"flash",
"(",
"self",
",",
"binary_location",
"=",
"None",
",",
"forceflash",
"=",
"None",
")",
":",
"if",
"not",
"Flash",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Mbed-flasher not installed!\"",
")",
"raise",
"ImportError",
"(",
"\"Mbed-flas... | Flash a binary to the target device using mbed-flasher.
:param binary_location: Binary to flash to device.
:param forceflash: Not used.
:return: False if an unknown error was encountered during flashing.
True if flasher retcode == 0
:raises: ImportError if mbed-flasher not installed.
:raises: DutConnectionError if flashing fails. | [
"Flash",
"a",
"binary",
"to",
"the",
"target",
"device",
"using",
"mbed",
"-",
"flasher",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py#L59-L117 | train | 25,878 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py | DutMbed._flash_needed | def _flash_needed(self, **kwargs):
"""
Check if flashing is needed. Flashing can be skipped if resource binary_sha1 attribute
matches build sha1 and forceflash is not True.
:param kwargs: Keyword arguments (forceflash: Boolean)
:return: Boolean
"""
forceflash = kwargs.get("forceflash", False)
cur_binary_sha1 = self.dutinformation.build_binary_sha1
if not forceflash and self.build.sha1 == cur_binary_sha1:
return False
return True | python | def _flash_needed(self, **kwargs):
"""
Check if flashing is needed. Flashing can be skipped if resource binary_sha1 attribute
matches build sha1 and forceflash is not True.
:param kwargs: Keyword arguments (forceflash: Boolean)
:return: Boolean
"""
forceflash = kwargs.get("forceflash", False)
cur_binary_sha1 = self.dutinformation.build_binary_sha1
if not forceflash and self.build.sha1 == cur_binary_sha1:
return False
return True | [
"def",
"_flash_needed",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"forceflash",
"=",
"kwargs",
".",
"get",
"(",
"\"forceflash\"",
",",
"False",
")",
"cur_binary_sha1",
"=",
"self",
".",
"dutinformation",
".",
"build_binary_sha1",
"if",
"not",
"forcefla... | Check if flashing is needed. Flashing can be skipped if resource binary_sha1 attribute
matches build sha1 and forceflash is not True.
:param kwargs: Keyword arguments (forceflash: Boolean)
:return: Boolean | [
"Check",
"if",
"flashing",
"is",
"needed",
".",
"Flashing",
"can",
"be",
"skipped",
"if",
"resource",
"binary_sha1",
"attribute",
"matches",
"build",
"sha1",
"and",
"forceflash",
"is",
"not",
"True",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py#L119-L131 | train | 25,879 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | SerialParams.get_params | def get_params(self):
"""
Get parameters as a tuple.
:return: timeout, xonxoff, rtscts, baudrate
"""
return self.timeout, self.xonxoff, self.rtscts, self.baudrate | python | def get_params(self):
"""
Get parameters as a tuple.
:return: timeout, xonxoff, rtscts, baudrate
"""
return self.timeout, self.xonxoff, self.rtscts, self.baudrate | [
"def",
"get_params",
"(",
"self",
")",
":",
"return",
"self",
".",
"timeout",
",",
"self",
".",
"xonxoff",
",",
"self",
".",
"rtscts",
",",
"self",
".",
"baudrate"
] | Get parameters as a tuple.
:return: timeout, xonxoff, rtscts, baudrate | [
"Get",
"parameters",
"as",
"a",
"tuple",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L46-L52 | train | 25,880 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial.open_connection | def open_connection(self):
"""
Open serial port connection.
:return: Nothing
:raises: DutConnectionError if serial port was already open or a SerialException occurs.
ValueError if EnhancedSerial __init__ or value setters raise ValueError
"""
if self.readthread is not None:
raise DutConnectionError("Trying to open serial port which was already open")
self.logger.info("Open Connection "
"for '%s' using '%s' baudrate: %d" % (self.dut_name,
self.comport,
self.serial_baudrate),
extra={'type': '<->'})
if self.serial_xonxoff:
self.logger.debug("Use software flow control for dut: %s" % self.dut_name)
if self.serial_rtscts:
self.logger.debug("Use hardware flow control for dut: %s" % self.dut_name)
try:
self.port = EnhancedSerial(self.comport)
self.port.baudrate = self.serial_baudrate
self.port.timeout = self.serial_timeout
self.port.xonxoff = self.serial_xonxoff
self.port.rtscts = self.serial_rtscts
self.port.flushInput()
self.port.flushOutput()
except SerialException as err:
self.logger.warning(err)
raise DutConnectionError(str(err))
except ValueError as err:
self.logger.warning(err)
raise ValueError(str(err))
if self.ch_mode:
self.logger.info("Use chunk-mode with size %d, delay: %.3f when write data" %
(self.ch_mode_chunk_size, self.ch_mode_ch_delay),
extra={'type': '<->'})
time.sleep(self.ch_mode_start_delay)
else:
self.logger.info("Use normal serial write mode", extra={'type': '<->'})
if self.params.reset:
self.reset()
# Start the serial reading thread
self.readthread = Thread(name=self.name, target=self.run)
self.readthread.start() | python | def open_connection(self):
"""
Open serial port connection.
:return: Nothing
:raises: DutConnectionError if serial port was already open or a SerialException occurs.
ValueError if EnhancedSerial __init__ or value setters raise ValueError
"""
if self.readthread is not None:
raise DutConnectionError("Trying to open serial port which was already open")
self.logger.info("Open Connection "
"for '%s' using '%s' baudrate: %d" % (self.dut_name,
self.comport,
self.serial_baudrate),
extra={'type': '<->'})
if self.serial_xonxoff:
self.logger.debug("Use software flow control for dut: %s" % self.dut_name)
if self.serial_rtscts:
self.logger.debug("Use hardware flow control for dut: %s" % self.dut_name)
try:
self.port = EnhancedSerial(self.comport)
self.port.baudrate = self.serial_baudrate
self.port.timeout = self.serial_timeout
self.port.xonxoff = self.serial_xonxoff
self.port.rtscts = self.serial_rtscts
self.port.flushInput()
self.port.flushOutput()
except SerialException as err:
self.logger.warning(err)
raise DutConnectionError(str(err))
except ValueError as err:
self.logger.warning(err)
raise ValueError(str(err))
if self.ch_mode:
self.logger.info("Use chunk-mode with size %d, delay: %.3f when write data" %
(self.ch_mode_chunk_size, self.ch_mode_ch_delay),
extra={'type': '<->'})
time.sleep(self.ch_mode_start_delay)
else:
self.logger.info("Use normal serial write mode", extra={'type': '<->'})
if self.params.reset:
self.reset()
# Start the serial reading thread
self.readthread = Thread(name=self.name, target=self.run)
self.readthread.start() | [
"def",
"open_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"readthread",
"is",
"not",
"None",
":",
"raise",
"DutConnectionError",
"(",
"\"Trying to open serial port which was already open\"",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Open Connection ... | Open serial port connection.
:return: Nothing
:raises: DutConnectionError if serial port was already open or a SerialException occurs.
ValueError if EnhancedSerial __init__ or value setters raise ValueError | [
"Open",
"serial",
"port",
"connection",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L246-L292 | train | 25,881 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial.close_connection | def close_connection(self): # pylint: disable=C0103
"""
Closes serial port connection.
:return: Nothing
"""
if self.port:
self.stop()
self.logger.debug("Close port '%s'" % self.comport,
extra={'type': '<->'})
self.port.close()
self.port = False | python | def close_connection(self): # pylint: disable=C0103
"""
Closes serial port connection.
:return: Nothing
"""
if self.port:
self.stop()
self.logger.debug("Close port '%s'" % self.comport,
extra={'type': '<->'})
self.port.close()
self.port = False | [
"def",
"close_connection",
"(",
"self",
")",
":",
"# pylint: disable=C0103",
"if",
"self",
".",
"port",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Close port '%s'\"",
"%",
"self",
".",
"comport",
",",
"extra",
"=",
"... | Closes serial port connection.
:return: Nothing | [
"Closes",
"serial",
"port",
"connection",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L316-L327 | train | 25,882 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial.__send_break | def __send_break(self):
"""
Sends break to device.
:return: result of EnhancedSerial safe_sendBreak()
"""
if self.port:
self.logger.debug("sendBreak to device to reboot", extra={'type': '<->'})
result = self.port.safe_sendBreak()
time.sleep(1)
if result:
self.logger.debug("reset completed", extra={'type': '<->'})
else:
self.logger.warning("reset failed", extra={'type': '<->'})
return result
return None | python | def __send_break(self):
"""
Sends break to device.
:return: result of EnhancedSerial safe_sendBreak()
"""
if self.port:
self.logger.debug("sendBreak to device to reboot", extra={'type': '<->'})
result = self.port.safe_sendBreak()
time.sleep(1)
if result:
self.logger.debug("reset completed", extra={'type': '<->'})
else:
self.logger.warning("reset failed", extra={'type': '<->'})
return result
return None | [
"def",
"__send_break",
"(",
"self",
")",
":",
"if",
"self",
".",
"port",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"sendBreak to device to reboot\"",
",",
"extra",
"=",
"{",
"'type'",
":",
"'<->'",
"}",
")",
"result",
"=",
"self",
".",
"port",
"... | Sends break to device.
:return: result of EnhancedSerial safe_sendBreak() | [
"Sends",
"break",
"to",
"device",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L348-L363 | train | 25,883 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial.writeline | def writeline(self, data):
"""
Writes data to serial port.
:param data: Data to write
:return: Nothing
:raises: IOError if SerialException occurs.
"""
try:
if self.ch_mode:
data += "\n"
parts = split_by_n(data, self.ch_mode_chunk_size)
for split_str in parts:
self.port.write(split_str.encode())
time.sleep(self.ch_mode_ch_delay)
else:
self.port.write((data + "\n").encode())
except SerialException as err:
self.logger.exception("SerialError occured while trying to write data {}.".format(data))
raise RuntimeError(str(err)) | python | def writeline(self, data):
"""
Writes data to serial port.
:param data: Data to write
:return: Nothing
:raises: IOError if SerialException occurs.
"""
try:
if self.ch_mode:
data += "\n"
parts = split_by_n(data, self.ch_mode_chunk_size)
for split_str in parts:
self.port.write(split_str.encode())
time.sleep(self.ch_mode_ch_delay)
else:
self.port.write((data + "\n").encode())
except SerialException as err:
self.logger.exception("SerialError occured while trying to write data {}.".format(data))
raise RuntimeError(str(err)) | [
"def",
"writeline",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"if",
"self",
".",
"ch_mode",
":",
"data",
"+=",
"\"\\n\"",
"parts",
"=",
"split_by_n",
"(",
"data",
",",
"self",
".",
"ch_mode_chunk_size",
")",
"for",
"split_str",
"in",
"parts",
":"... | Writes data to serial port.
:param data: Data to write
:return: Nothing
:raises: IOError if SerialException occurs. | [
"Writes",
"data",
"to",
"serial",
"port",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L366-L385 | train | 25,884 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial._readline | def _readline(self, timeout=1):
"""
Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None
"""
line = self.port.readline(timeout=timeout)
return strip_escape(line.strip()) if line is not None else line | python | def _readline(self, timeout=1):
"""
Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None
"""
line = self.port.readline(timeout=timeout)
return strip_escape(line.strip()) if line is not None else line | [
"def",
"_readline",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"line",
"=",
"self",
".",
"port",
".",
"readline",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"strip_escape",
"(",
"line",
".",
"strip",
"(",
")",
")",
"if",
"line",
"is",
"no... | Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None | [
"Read",
"line",
"from",
"serial",
"port",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L388-L396 | train | 25,885 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial.run | def run(self):
"""
Read lines while keep_reading is True. Calls process_dut for each received line.
:return: Nothing
"""
self.keep_reading = True
while self.keep_reading:
line = self._readline()
if line:
self.input_queue.appendleft(line)
Dut.process_dut(self) | python | def run(self):
"""
Read lines while keep_reading is True. Calls process_dut for each received line.
:return: Nothing
"""
self.keep_reading = True
while self.keep_reading:
line = self._readline()
if line:
self.input_queue.appendleft(line)
Dut.process_dut(self) | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"keep_reading",
"=",
"True",
"while",
"self",
".",
"keep_reading",
":",
"line",
"=",
"self",
".",
"_readline",
"(",
")",
"if",
"line",
":",
"self",
".",
"input_queue",
".",
"appendleft",
"(",
"line",
... | Read lines while keep_reading is True. Calls process_dut for each received line.
:return: Nothing | [
"Read",
"lines",
"while",
"keep_reading",
"is",
"True",
".",
"Calls",
"process_dut",
"for",
"each",
"received",
"line",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L408-L419 | train | 25,886 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial.stop | def stop(self):
"""
Stops and joins readthread.
:return: Nothing
"""
self.keep_reading = False
if self.readthread is not None:
self.readthread.join()
self.readthread = None | python | def stop(self):
"""
Stops and joins readthread.
:return: Nothing
"""
self.keep_reading = False
if self.readthread is not None:
self.readthread.join()
self.readthread = None | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"keep_reading",
"=",
"False",
"if",
"self",
".",
"readthread",
"is",
"not",
"None",
":",
"self",
".",
"readthread",
".",
"join",
"(",
")",
"self",
".",
"readthread",
"=",
"None"
] | Stops and joins readthread.
:return: Nothing | [
"Stops",
"and",
"joins",
"readthread",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L421-L430 | train | 25,887 |
ARMmbed/icetea | icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py | DutSerial.print_info | def print_info(self):
"""
Prints Dut information nicely formatted into a table.
"""
table = PrettyTable()
start_string = "DutSerial {} \n".format(self.name)
row = []
info_string = ""
if self.config:
info_string = info_string + "Configuration for this DUT:\n\n {} \n".format(self.config)
if self.comport:
table.add_column("COM port", [])
row.append(self.comport)
if self.port:
if hasattr(self.port, "baudrate"):
table.add_column("Baudrate", [])
row.append(self.port.baudrate)
if hasattr(self.port, "xonxoff"):
table.add_column("XON/XOFF", [])
row.append(self.port.xonxoff)
if hasattr(self.port, "timeout"):
table.add_column("Timeout", [])
row.append(self.port.timeout)
if hasattr(self.port, "rtscts"):
table.add_column("RTSCTS", [])
row.append(self.port.rtscts)
if self.location:
table.add_column("Location", [])
row.append("X = {}, Y = {}".format(self.location.x_coord, self.location.y_coord))
self.logger.info(start_string)
self.logger.debug(info_string)
table.add_row(row)
print(table) | python | def print_info(self):
"""
Prints Dut information nicely formatted into a table.
"""
table = PrettyTable()
start_string = "DutSerial {} \n".format(self.name)
row = []
info_string = ""
if self.config:
info_string = info_string + "Configuration for this DUT:\n\n {} \n".format(self.config)
if self.comport:
table.add_column("COM port", [])
row.append(self.comport)
if self.port:
if hasattr(self.port, "baudrate"):
table.add_column("Baudrate", [])
row.append(self.port.baudrate)
if hasattr(self.port, "xonxoff"):
table.add_column("XON/XOFF", [])
row.append(self.port.xonxoff)
if hasattr(self.port, "timeout"):
table.add_column("Timeout", [])
row.append(self.port.timeout)
if hasattr(self.port, "rtscts"):
table.add_column("RTSCTS", [])
row.append(self.port.rtscts)
if self.location:
table.add_column("Location", [])
row.append("X = {}, Y = {}".format(self.location.x_coord, self.location.y_coord))
self.logger.info(start_string)
self.logger.debug(info_string)
table.add_row(row)
print(table) | [
"def",
"print_info",
"(",
"self",
")",
":",
"table",
"=",
"PrettyTable",
"(",
")",
"start_string",
"=",
"\"DutSerial {} \\n\"",
".",
"format",
"(",
"self",
".",
"name",
")",
"row",
"=",
"[",
"]",
"info_string",
"=",
"\"\"",
"if",
"self",
".",
"config",
... | Prints Dut information nicely formatted into a table. | [
"Prints",
"Dut",
"information",
"nicely",
"formatted",
"into",
"a",
"table",
"."
] | b2b97ac607429830cf7d62dae2e3903692c7c778 | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L445-L477 | train | 25,888 |
bootphon/h5features | h5features/data.py | Data.append | def append(self, data):
"""Append a Data instance to self"""
for k in self._entries.keys():
self._entries[k].append(data._entries[k]) | python | def append(self, data):
"""Append a Data instance to self"""
for k in self._entries.keys():
self._entries[k].append(data._entries[k]) | [
"def",
"append",
"(",
"self",
",",
"data",
")",
":",
"for",
"k",
"in",
"self",
".",
"_entries",
".",
"keys",
"(",
")",
":",
"self",
".",
"_entries",
"[",
"k",
"]",
".",
"append",
"(",
"data",
".",
"_entries",
"[",
"k",
"]",
")"
] | Append a Data instance to self | [
"Append",
"a",
"Data",
"instance",
"to",
"self"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L72-L75 | train | 25,889 |
bootphon/h5features | h5features/data.py | Data.init_group | def init_group(self, group, chunk_size,
compression=None, compression_opts=None):
"""Initializes a HDF5 group compliant with the stored data.
This method creates the datasets 'items', 'labels', 'features'
and 'index' and leaves them empty.
:param h5py.Group group: The group to initializes.
:param float chunk_size: The size of a chunk in the file (in MB).
:param str compression: Optional compression, see
:class:`h5features.writer` for details
:param str compression: Optional compression options, see
:class:`h5features.writer` for details
"""
create_index(group, chunk_size)
self._entries['items'].create_dataset(
group, chunk_size, compression=compression,
compression_opts=compression_opts)
self._entries['features'].create_dataset(
group, chunk_size, compression=compression,
compression_opts=compression_opts)
# chunking the labels depends on features chunks
self._entries['labels'].create_dataset(
group, self._entries['features'].nb_per_chunk,
compression=compression,
compression_opts=compression_opts)
if self.has_properties():
self._entries['properties'].create_dataset(
group, compression=compression,
compression_opts=compression_opts) | python | def init_group(self, group, chunk_size,
compression=None, compression_opts=None):
"""Initializes a HDF5 group compliant with the stored data.
This method creates the datasets 'items', 'labels', 'features'
and 'index' and leaves them empty.
:param h5py.Group group: The group to initializes.
:param float chunk_size: The size of a chunk in the file (in MB).
:param str compression: Optional compression, see
:class:`h5features.writer` for details
:param str compression: Optional compression options, see
:class:`h5features.writer` for details
"""
create_index(group, chunk_size)
self._entries['items'].create_dataset(
group, chunk_size, compression=compression,
compression_opts=compression_opts)
self._entries['features'].create_dataset(
group, chunk_size, compression=compression,
compression_opts=compression_opts)
# chunking the labels depends on features chunks
self._entries['labels'].create_dataset(
group, self._entries['features'].nb_per_chunk,
compression=compression,
compression_opts=compression_opts)
if self.has_properties():
self._entries['properties'].create_dataset(
group, compression=compression,
compression_opts=compression_opts) | [
"def",
"init_group",
"(",
"self",
",",
"group",
",",
"chunk_size",
",",
"compression",
"=",
"None",
",",
"compression_opts",
"=",
"None",
")",
":",
"create_index",
"(",
"group",
",",
"chunk_size",
")",
"self",
".",
"_entries",
"[",
"'items'",
"]",
".",
"... | Initializes a HDF5 group compliant with the stored data.
This method creates the datasets 'items', 'labels', 'features'
and 'index' and leaves them empty.
:param h5py.Group group: The group to initializes.
:param float chunk_size: The size of a chunk in the file (in MB).
:param str compression: Optional compression, see
:class:`h5features.writer` for details
:param str compression: Optional compression options, see
:class:`h5features.writer` for details | [
"Initializes",
"a",
"HDF5",
"group",
"compliant",
"with",
"the",
"stored",
"data",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L111-L145 | train | 25,890 |
bootphon/h5features | h5features/data.py | Data.is_appendable_to | def is_appendable_to(self, group):
"""Returns True if the data can be appended in a given group."""
# First check only the names
if not all([k in group for k in self._entries.keys()]):
return False
# If names are matching, check the contents
for k in self._entries.keys():
if not self._entries[k].is_appendable_to(group):
return False
return True | python | def is_appendable_to(self, group):
"""Returns True if the data can be appended in a given group."""
# First check only the names
if not all([k in group for k in self._entries.keys()]):
return False
# If names are matching, check the contents
for k in self._entries.keys():
if not self._entries[k].is_appendable_to(group):
return False
return True | [
"def",
"is_appendable_to",
"(",
"self",
",",
"group",
")",
":",
"# First check only the names",
"if",
"not",
"all",
"(",
"[",
"k",
"in",
"group",
"for",
"k",
"in",
"self",
".",
"_entries",
".",
"keys",
"(",
")",
"]",
")",
":",
"return",
"False",
"# If ... | Returns True if the data can be appended in a given group. | [
"Returns",
"True",
"if",
"the",
"data",
"can",
"be",
"appended",
"in",
"a",
"given",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L147-L158 | train | 25,891 |
bootphon/h5features | h5features/data.py | Data.write_to | def write_to(self, group, append=False):
"""Write the data to the given group.
:param h5py.Group group: The group to write the data on. It is
assumed that the group is already existing or initialized
to store h5features data (i.e. the method
``Data.init_group`` have been called.
:param bool append: If False, any existing data in the group
is overwrited. If True, the data is appended to the end of
the group and we assume ``Data.is_appendable_to`` is True
for this group.
"""
write_index(self, group, append)
self._entries['items'].write_to(group)
self._entries['features'].write_to(group, append)
self._entries['labels'].write_to(group)
if self.has_properties():
self._entries['properties'].write_to(group, append=append) | python | def write_to(self, group, append=False):
"""Write the data to the given group.
:param h5py.Group group: The group to write the data on. It is
assumed that the group is already existing or initialized
to store h5features data (i.e. the method
``Data.init_group`` have been called.
:param bool append: If False, any existing data in the group
is overwrited. If True, the data is appended to the end of
the group and we assume ``Data.is_appendable_to`` is True
for this group.
"""
write_index(self, group, append)
self._entries['items'].write_to(group)
self._entries['features'].write_to(group, append)
self._entries['labels'].write_to(group)
if self.has_properties():
self._entries['properties'].write_to(group, append=append) | [
"def",
"write_to",
"(",
"self",
",",
"group",
",",
"append",
"=",
"False",
")",
":",
"write_index",
"(",
"self",
",",
"group",
",",
"append",
")",
"self",
".",
"_entries",
"[",
"'items'",
"]",
".",
"write_to",
"(",
"group",
")",
"self",
".",
"_entrie... | Write the data to the given group.
:param h5py.Group group: The group to write the data on. It is
assumed that the group is already existing or initialized
to store h5features data (i.e. the method
``Data.init_group`` have been called.
:param bool append: If False, any existing data in the group
is overwrited. If True, the data is appended to the end of
the group and we assume ``Data.is_appendable_to`` is True
for this group. | [
"Write",
"the",
"data",
"to",
"the",
"given",
"group",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L160-L179 | train | 25,892 |
bootphon/h5features | h5features/labels.py | Labels.check | def check(labels):
"""Raise IOError if labels are not correct
`labels` must be a list of sorted numpy arrays of equal
dimensions (must be 1D or 2D). In the case of 2D labels,
the second axis must have the same shape for all labels.
"""
# type checking
if not isinstance(labels, list):
raise IOError('labels are not in a list')
if not len(labels):
raise IOError('the labels list is empty')
if not all([isinstance(l, np.ndarray) for l in labels]):
raise IOError('all labels must be numpy arrays')
# dimension checking
ndim = labels[0].ndim
if ndim not in [1, 2]:
raise IOError('labels dimension must be 1 or 2')
if not all([l.ndim == ndim for l in labels]):
raise IOError('all labels dimensions must be equal')
if ndim == 2:
shape1 = labels[0].shape[1]
if not all([l.shape[1] == shape1 for l in labels]):
raise IOError('all labels must have same shape on 2nd dim')
# sort checking
for label in labels:
index = (np.argsort(label) if label.ndim == 1
else np.lexsort(label.T))
# print label, index
# print len(index), label.shape[0]
assert len(index) == label.shape[0]
if not all(n == index[n] for n in range(label.shape[0]-1)):
raise IOError('labels are not sorted in increasing order') | python | def check(labels):
"""Raise IOError if labels are not correct
`labels` must be a list of sorted numpy arrays of equal
dimensions (must be 1D or 2D). In the case of 2D labels,
the second axis must have the same shape for all labels.
"""
# type checking
if not isinstance(labels, list):
raise IOError('labels are not in a list')
if not len(labels):
raise IOError('the labels list is empty')
if not all([isinstance(l, np.ndarray) for l in labels]):
raise IOError('all labels must be numpy arrays')
# dimension checking
ndim = labels[0].ndim
if ndim not in [1, 2]:
raise IOError('labels dimension must be 1 or 2')
if not all([l.ndim == ndim for l in labels]):
raise IOError('all labels dimensions must be equal')
if ndim == 2:
shape1 = labels[0].shape[1]
if not all([l.shape[1] == shape1 for l in labels]):
raise IOError('all labels must have same shape on 2nd dim')
# sort checking
for label in labels:
index = (np.argsort(label) if label.ndim == 1
else np.lexsort(label.T))
# print label, index
# print len(index), label.shape[0]
assert len(index) == label.shape[0]
if not all(n == index[n] for n in range(label.shape[0]-1)):
raise IOError('labels are not sorted in increasing order') | [
"def",
"check",
"(",
"labels",
")",
":",
"# type checking",
"if",
"not",
"isinstance",
"(",
"labels",
",",
"list",
")",
":",
"raise",
"IOError",
"(",
"'labels are not in a list'",
")",
"if",
"not",
"len",
"(",
"labels",
")",
":",
"raise",
"IOError",
"(",
... | Raise IOError if labels are not correct
`labels` must be a list of sorted numpy arrays of equal
dimensions (must be 1D or 2D). In the case of 2D labels,
the second axis must have the same shape for all labels. | [
"Raise",
"IOError",
"if",
"labels",
"are",
"not",
"correct"
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/labels.py#L56-L91 | train | 25,893 |
bootphon/h5features | h5features/converter.py | Converter._write | def _write(self, item, labels, features):
""" Writes the given item to the owned file."""
data = Data([item], [labels], [features])
self._writer.write(data, self.groupname, append=True) | python | def _write(self, item, labels, features):
""" Writes the given item to the owned file."""
data = Data([item], [labels], [features])
self._writer.write(data, self.groupname, append=True) | [
"def",
"_write",
"(",
"self",
",",
"item",
",",
"labels",
",",
"features",
")",
":",
"data",
"=",
"Data",
"(",
"[",
"item",
"]",
",",
"[",
"labels",
"]",
",",
"[",
"features",
"]",
")",
"self",
".",
"_writer",
".",
"write",
"(",
"data",
",",
"s... | Writes the given item to the owned file. | [
"Writes",
"the",
"given",
"item",
"to",
"the",
"owned",
"file",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L65-L68 | train | 25,894 |
bootphon/h5features | h5features/converter.py | Converter.convert | def convert(self, infile, item=None):
"""Convert an input file to h5features based on its extension.
:raise IOError: if `infile` is not a valid file.
:raise IOError: if `infile` extension is not supported.
"""
if not os.path.isfile(infile):
raise IOError('{} is not a valid file'.format(infile))
if item is None:
item = os.path.splitext(infile)[0]
ext = os.path.splitext(infile)[1]
if ext == '.npz':
self.npz_convert(infile, item)
elif ext == '.mat':
self.mat_convert(infile, item)
elif ext == '.h5':
self.h5features_convert(infile)
else:
raise IOError('Unknown file format for {}'.format(infile)) | python | def convert(self, infile, item=None):
"""Convert an input file to h5features based on its extension.
:raise IOError: if `infile` is not a valid file.
:raise IOError: if `infile` extension is not supported.
"""
if not os.path.isfile(infile):
raise IOError('{} is not a valid file'.format(infile))
if item is None:
item = os.path.splitext(infile)[0]
ext = os.path.splitext(infile)[1]
if ext == '.npz':
self.npz_convert(infile, item)
elif ext == '.mat':
self.mat_convert(infile, item)
elif ext == '.h5':
self.h5features_convert(infile)
else:
raise IOError('Unknown file format for {}'.format(infile)) | [
"def",
"convert",
"(",
"self",
",",
"infile",
",",
"item",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"infile",
")",
":",
"raise",
"IOError",
"(",
"'{} is not a valid file'",
".",
"format",
"(",
"infile",
")",
")",
"if... | Convert an input file to h5features based on its extension.
:raise IOError: if `infile` is not a valid file.
:raise IOError: if `infile` extension is not supported. | [
"Convert",
"an",
"input",
"file",
"to",
"h5features",
"based",
"on",
"its",
"extension",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L80-L101 | train | 25,895 |
bootphon/h5features | h5features/converter.py | Converter.npz_convert | def npz_convert(self, infile, item):
"""Convert a numpy NPZ file to h5features."""
data = np.load(infile)
labels = self._labels(data)
features = data['features']
self._write(item, labels, features) | python | def npz_convert(self, infile, item):
"""Convert a numpy NPZ file to h5features."""
data = np.load(infile)
labels = self._labels(data)
features = data['features']
self._write(item, labels, features) | [
"def",
"npz_convert",
"(",
"self",
",",
"infile",
",",
"item",
")",
":",
"data",
"=",
"np",
".",
"load",
"(",
"infile",
")",
"labels",
"=",
"self",
".",
"_labels",
"(",
"data",
")",
"features",
"=",
"data",
"[",
"'features'",
"]",
"self",
".",
"_wr... | Convert a numpy NPZ file to h5features. | [
"Convert",
"a",
"numpy",
"NPZ",
"file",
"to",
"h5features",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L103-L108 | train | 25,896 |
bootphon/h5features | h5features/converter.py | Converter.h5features_convert | def h5features_convert(self, infile):
"""Convert a h5features file to the latest h5features version."""
with h5py.File(infile, 'r') as f:
groups = list(f.keys())
for group in groups:
self._writer.write(
Reader(infile, group).read(),
self.groupname, append=True) | python | def h5features_convert(self, infile):
"""Convert a h5features file to the latest h5features version."""
with h5py.File(infile, 'r') as f:
groups = list(f.keys())
for group in groups:
self._writer.write(
Reader(infile, group).read(),
self.groupname, append=True) | [
"def",
"h5features_convert",
"(",
"self",
",",
"infile",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"infile",
",",
"'r'",
")",
"as",
"f",
":",
"groups",
"=",
"list",
"(",
"f",
".",
"keys",
"(",
")",
")",
"for",
"group",
"in",
"groups",
":",
"sel... | Convert a h5features file to the latest h5features version. | [
"Convert",
"a",
"h5features",
"file",
"to",
"the",
"latest",
"h5features",
"version",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L117-L124 | train | 25,897 |
bootphon/h5features | h5features/h5features.py | read | def read(filename, groupname=None, from_item=None, to_item=None,
from_time=None, to_time=None, index=None):
"""Reads in a h5features file.
:param str filename: Path to a hdf5 file potentially serving as a
container for many small files
:param str groupname: HDF5 group to read the data from. If None,
guess there is one and only one group in `filename`.
:param str from_item: Optional. Read the data starting from this
item. (defaults to the first stored item)
:param str to_item: Optional. Read the data until reaching the
item. (defaults to from_item if it was specified and to the
last stored item otherwise)
:param float from_time: Optional. (defaults to the beginning time
in from_item) the specified times are included in the output
:param float to_time: Optional. (defaults to the ending time in
to_item) the specified times are included in the output
:param int index: Not implemented, raise if used.
:return: A tuple (times, features) or (times, features,
properties) such as:
* time is a dictionary of 1D arrays values (keys are items).
* features: A dictionary of 2D arrays values (keys are items)
with the 'features' dimension along the columns and the
'time' dimension along the lines.
* properties: A dictionnary of dictionnaries (keys are items)
with the corresponding properties. If there is no properties
recorded, this value is not returned.
.. note:: Note that all the files that are present on disk between
to_item and from_item will be loaded and returned. It's the
responsibility of the user to make sure that it will fit into
RAM memory.
"""
# TODO legacy read from index not implemented
if index is not None:
raise NotImplementedError
reader = Reader(filename, groupname)
data = (reader.read(from_item, to_item, from_time, to_time)
if index is None else reader.index_read(index))
if data.has_properties():
return data.dict_labels(), data.dict_features(), data.dict_properties()
else:
return data.dict_labels(), data.dict_features() | python | def read(filename, groupname=None, from_item=None, to_item=None,
from_time=None, to_time=None, index=None):
"""Reads in a h5features file.
:param str filename: Path to a hdf5 file potentially serving as a
container for many small files
:param str groupname: HDF5 group to read the data from. If None,
guess there is one and only one group in `filename`.
:param str from_item: Optional. Read the data starting from this
item. (defaults to the first stored item)
:param str to_item: Optional. Read the data until reaching the
item. (defaults to from_item if it was specified and to the
last stored item otherwise)
:param float from_time: Optional. (defaults to the beginning time
in from_item) the specified times are included in the output
:param float to_time: Optional. (defaults to the ending time in
to_item) the specified times are included in the output
:param int index: Not implemented, raise if used.
:return: A tuple (times, features) or (times, features,
properties) such as:
* time is a dictionary of 1D arrays values (keys are items).
* features: A dictionary of 2D arrays values (keys are items)
with the 'features' dimension along the columns and the
'time' dimension along the lines.
* properties: A dictionnary of dictionnaries (keys are items)
with the corresponding properties. If there is no properties
recorded, this value is not returned.
.. note:: Note that all the files that are present on disk between
to_item and from_item will be loaded and returned. It's the
responsibility of the user to make sure that it will fit into
RAM memory.
"""
# TODO legacy read from index not implemented
if index is not None:
raise NotImplementedError
reader = Reader(filename, groupname)
data = (reader.read(from_item, to_item, from_time, to_time)
if index is None else reader.index_read(index))
if data.has_properties():
return data.dict_labels(), data.dict_features(), data.dict_properties()
else:
return data.dict_labels(), data.dict_features() | [
"def",
"read",
"(",
"filename",
",",
"groupname",
"=",
"None",
",",
"from_item",
"=",
"None",
",",
"to_item",
"=",
"None",
",",
"from_time",
"=",
"None",
",",
"to_time",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"# TODO legacy read from index not i... | Reads in a h5features file.
:param str filename: Path to a hdf5 file potentially serving as a
container for many small files
:param str groupname: HDF5 group to read the data from. If None,
guess there is one and only one group in `filename`.
:param str from_item: Optional. Read the data starting from this
item. (defaults to the first stored item)
:param str to_item: Optional. Read the data until reaching the
item. (defaults to from_item if it was specified and to the
last stored item otherwise)
:param float from_time: Optional. (defaults to the beginning time
in from_item) the specified times are included in the output
:param float to_time: Optional. (defaults to the ending time in
to_item) the specified times are included in the output
:param int index: Not implemented, raise if used.
:return: A tuple (times, features) or (times, features,
properties) such as:
* time is a dictionary of 1D arrays values (keys are items).
* features: A dictionary of 2D arrays values (keys are items)
with the 'features' dimension along the columns and the
'time' dimension along the lines.
* properties: A dictionnary of dictionnaries (keys are items)
with the corresponding properties. If there is no properties
recorded, this value is not returned.
.. note:: Note that all the files that are present on disk between
to_item and from_item will be loaded and returned. It's the
responsibility of the user to make sure that it will fit into
RAM memory. | [
"Reads",
"in",
"a",
"h5features",
"file",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/h5features.py#L34-L88 | train | 25,898 |
bootphon/h5features | h5features/h5features.py | write | def write(filename, groupname, items, times, features, properties=None,
dformat='dense', chunk_size='auto', sparsity=0.1, mode='a'):
"""Write h5features data in a HDF5 file.
This function is a wrapper to the Writer class. It has three purposes:
* Check parameters for errors (see details below),
* Create Items, Times and Features objects
* Send them to the Writer.
:param str filename: HDF5 file to be writted, potentially serving
as a container for many small files. If the file does not
exist, it is created. If the file is already a valid HDF5
file, try to append the data in it.
:param str groupname: Name of the group to write the data in, or
to append the data to if the group already exists in the file.
:param items: List of files from which the features where
extracted. Items must not contain duplicates.
:type items: list of str
:param times: Time value for the features array. Elements of
a 1D array are considered as the center of the time window
associated with the features. A 2D array must have 2 columns
corresponding to the begin and end timestamps of the features
time window.
:type times: list of 1D or 2D numpy arrays
:param features: Features should have
time along the lines and features along the columns
(accomodating row-major storage in hdf5 files).
:type features: list of 2D numpy arrays
:param properties: Optional. Properties associated with each
item. Properties describe the features associated with each
item in a dictionnary. It can store parameters or fields
recorded by the user.
:type properties: list of dictionnaries
:param str dformat: Optional. Which format to store the features
into (sparse or dense). Default is dense.
:param float chunk_size: Optional. In Mo, tuning parameter
corresponding to the size of a chunk in the h5file. By default
the chunk size is guessed automatically. Tis parameter is
ignored if the file already exists.
:param float sparsity: Optional. Tuning parameter corresponding to
the expected proportion (in [0, 1]) of non-zeros elements on
average in a single frame.
:param char mode: Optional. The mode for overwriting an existing
file, 'a' to append data to the file, 'w' to overwrite it
:raise IOError: if the filename is not valid or parameters are
inconsistent.
:raise NotImplementedError: if dformat == 'sparse'
"""
# Prepare the data, raise on error
sparsity = sparsity if dformat == 'sparse' else None
data = Data(items, times, features, properties=properties,
sparsity=sparsity, check=True)
# Write all that stuff in the HDF5 file's specified group
Writer(filename, chunk_size=chunk_size).write(data, groupname, append=True) | python | def write(filename, groupname, items, times, features, properties=None,
dformat='dense', chunk_size='auto', sparsity=0.1, mode='a'):
"""Write h5features data in a HDF5 file.
This function is a wrapper to the Writer class. It has three purposes:
* Check parameters for errors (see details below),
* Create Items, Times and Features objects
* Send them to the Writer.
:param str filename: HDF5 file to be writted, potentially serving
as a container for many small files. If the file does not
exist, it is created. If the file is already a valid HDF5
file, try to append the data in it.
:param str groupname: Name of the group to write the data in, or
to append the data to if the group already exists in the file.
:param items: List of files from which the features where
extracted. Items must not contain duplicates.
:type items: list of str
:param times: Time value for the features array. Elements of
a 1D array are considered as the center of the time window
associated with the features. A 2D array must have 2 columns
corresponding to the begin and end timestamps of the features
time window.
:type times: list of 1D or 2D numpy arrays
:param features: Features should have
time along the lines and features along the columns
(accomodating row-major storage in hdf5 files).
:type features: list of 2D numpy arrays
:param properties: Optional. Properties associated with each
item. Properties describe the features associated with each
item in a dictionnary. It can store parameters or fields
recorded by the user.
:type properties: list of dictionnaries
:param str dformat: Optional. Which format to store the features
into (sparse or dense). Default is dense.
:param float chunk_size: Optional. In Mo, tuning parameter
corresponding to the size of a chunk in the h5file. By default
the chunk size is guessed automatically. Tis parameter is
ignored if the file already exists.
:param float sparsity: Optional. Tuning parameter corresponding to
the expected proportion (in [0, 1]) of non-zeros elements on
average in a single frame.
:param char mode: Optional. The mode for overwriting an existing
file, 'a' to append data to the file, 'w' to overwrite it
:raise IOError: if the filename is not valid or parameters are
inconsistent.
:raise NotImplementedError: if dformat == 'sparse'
"""
# Prepare the data, raise on error
sparsity = sparsity if dformat == 'sparse' else None
data = Data(items, times, features, properties=properties,
sparsity=sparsity, check=True)
# Write all that stuff in the HDF5 file's specified group
Writer(filename, chunk_size=chunk_size).write(data, groupname, append=True) | [
"def",
"write",
"(",
"filename",
",",
"groupname",
",",
"items",
",",
"times",
",",
"features",
",",
"properties",
"=",
"None",
",",
"dformat",
"=",
"'dense'",
",",
"chunk_size",
"=",
"'auto'",
",",
"sparsity",
"=",
"0.1",
",",
"mode",
"=",
"'a'",
")",... | Write h5features data in a HDF5 file.
This function is a wrapper to the Writer class. It has three purposes:
* Check parameters for errors (see details below),
* Create Items, Times and Features objects
* Send them to the Writer.
:param str filename: HDF5 file to be writted, potentially serving
as a container for many small files. If the file does not
exist, it is created. If the file is already a valid HDF5
file, try to append the data in it.
:param str groupname: Name of the group to write the data in, or
to append the data to if the group already exists in the file.
:param items: List of files from which the features where
extracted. Items must not contain duplicates.
:type items: list of str
:param times: Time value for the features array. Elements of
a 1D array are considered as the center of the time window
associated with the features. A 2D array must have 2 columns
corresponding to the begin and end timestamps of the features
time window.
:type times: list of 1D or 2D numpy arrays
:param features: Features should have
time along the lines and features along the columns
(accomodating row-major storage in hdf5 files).
:type features: list of 2D numpy arrays
:param properties: Optional. Properties associated with each
item. Properties describe the features associated with each
item in a dictionnary. It can store parameters or fields
recorded by the user.
:type properties: list of dictionnaries
:param str dformat: Optional. Which format to store the features
into (sparse or dense). Default is dense.
:param float chunk_size: Optional. In Mo, tuning parameter
corresponding to the size of a chunk in the h5file. By default
the chunk size is guessed automatically. Tis parameter is
ignored if the file already exists.
:param float sparsity: Optional. Tuning parameter corresponding to
the expected proportion (in [0, 1]) of non-zeros elements on
average in a single frame.
:param char mode: Optional. The mode for overwriting an existing
file, 'a' to append data to the file, 'w' to overwrite it
:raise IOError: if the filename is not valid or parameters are
inconsistent.
:raise NotImplementedError: if dformat == 'sparse' | [
"Write",
"h5features",
"data",
"in",
"a",
"HDF5",
"file",
"."
] | d5f95db0f1cee58ac1ba4575d1212e796c39e1f9 | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/h5features.py#L91-L158 | train | 25,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.