_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q242200
Log.log
train
def log(self, uuid=None, organization=None, from_date=None, to_date=None): """"List enrollment information available in the registry. Method that returns a list of enrollments. If <uuid> parameter is set, it will return the enrollments related to that unique identity; if <organization> ...
python
{ "resource": "" }
q242201
Init.run
train
def run(self, *args): """Initialize a registry. Create and initialize an empty registry which its name is defined by <name> parameter. Required tables will be also created. """ params = self.parser.parse_args(args) code = self.initialize(name=params.name, reuse=params.r...
python
{ "resource": "" }
q242202
Init.initialize
train
def initialize(self, name, reuse=False): """Create an empty Sorting Hat registry. This method creates a new database including the schema of Sorting Hat. Any attempt to create a new registry over an existing instance will produce an error, except if reuse=True. In that case, the ...
python
{ "resource": "" }
q242203
Init.__load_countries
train
def __load_countries(self, db): """Load the list of countries""" try: countries = self.__read_countries_file() except IOError as e: raise LoadError(str(e)) try: with db.connect() as session: for country in countries: ...
python
{ "resource": "" }
q242204
Init.__read_countries_file
train
def __read_countries_file(self): """Read countries from a CSV file""" import csv import pkg_resources filename = pkg_resources.resource_filename('sortinghat', 'data/countries.csv') with open(filename, 'r') as f: reader = csv.DictReader(f, fieldnames=['name', 'code',...
python
{ "resource": "" }
q242205
Remove.run
train
def run(self, *args): """Remove unique identities or identities from the registry. By default, it removes the unique identity identified by <identifier>. To remove an identity, set <identity> parameter. """ params = self.parser.parse_args(args) identifier = params.ident...
python
{ "resource": "" }
q242206
merge_date_ranges
train
def merge_date_ranges(dates): """Merge date ranges. Generator that merges ovelaped data ranges. Default init and end dates (1900-01-01 and 2100-01-01) are considered range limits and will be removed when a set of ranges overlap. For example: * [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)]...
python
{ "resource": "" }
q242207
uuid
train
def uuid(source, email=None, name=None, username=None): """Get the UUID related to the identity data. Based on the input data, the function will return the UUID associated to an identity. On this version, the UUID will be the SHA1 of "source:email:name:username" string. This string is case insensitive,...
python
{ "resource": "" }
q242208
create_database_engine
train
def create_database_engine(user, password, database, host, port): """Create a database engine""" driver = 'mysql+pymysql' url = URL(driver, user, password, host, port, database, query={'charset': 'utf8mb4'}) return create_engine(url, poolclass=QueuePool, pool_size...
python
{ "resource": "" }
q242209
create_database_session
train
def create_database_session(engine): """Connect to the database""" try: Session = sessionmaker(bind=engine) return Session() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
python
{ "resource": "" }
q242210
close_database_session
train
def close_database_session(session): """Close connection with the database""" try: session.close() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
python
{ "resource": "" }
q242211
reflect_table
train
def reflect_table(engine, klass): """Inspect and reflect objects""" try: meta = MetaData() meta.reflect(bind=engine) except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) # Try to reflect from any of the supported tables table = None ...
python
{ "resource": "" }
q242212
find_model_by_table_name
train
def find_model_by_table_name(name): """Find a model reference by its table name""" for model in ModelBase._decl_class_registry.values(): if hasattr(model, '__table__') and model.__table__.fullname == name: return model return None
python
{ "resource": "" }
q242213
Database.handle_database_error
train
def handle_database_error(cls, session, exception): """Rollback changes made and handle any type of error raised by the DBMS.""" session.rollback() if isinstance(exception, IntegrityError): cls.handle_integrity_error(exception) elif isinstance(exception, FlushError): ...
python
{ "resource": "" }
q242214
Database.handle_integrity_error
train
def handle_integrity_error(cls, exception): """Handle integrity error exceptions.""" m = re.match(cls.MYSQL_INSERT_ERROR_REGEX, exception.statement) if not m: raise exception model = find_model_by_table_name(m.group('table')) if not model: ...
python
{ "resource": "" }
q242215
Database.handle_flush_error
train
def handle_flush_error(cls, exception): """Handle flush error exceptions.""" trace = exception.args[0] m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace) if not m: raise exception entity = m.group('entity') eid = m.group('eid') raise AlreadyExistsErr...
python
{ "resource": "" }
q242216
Affiliate.run
train
def run(self, *args): """Affiliate unique identities to organizations.""" self.parser.parse_args(args) code = self.affiliate() return code
python
{ "resource": "" }
q242217
Affiliate.affiliate
train
def affiliate(self): """Affiliate unique identities. This method enrolls unique identities to organizations using email addresses and top/sub domains data. Only new enrollments will be created. """ try: uidentities = api.unique_identities(self.db) for ui...
python
{ "resource": "" }
q242218
Countries.run
train
def run(self, *args): """Show information about countries.""" params = self.parser.parse_args(args) ct = params.code_or_term if ct and len(ct) < 2: self.error('Code country or term must have 2 or more characters length') return CODE_INVALID_FORMAT_ERROR ...
python
{ "resource": "" }
q242219
Client._call_async
train
async def _call_async(self, method_name: str, *args, **kwargs): """ Sends a request to the socket and then wait for the reply. To deal with multiple, asynchronous requests we do not expect that the receive reply task scheduled from this call is the one that receives this call's reply an...
python
{ "resource": "" }
q242220
Client._recv_reply
train
async def _recv_reply(self): """ Helper task to recieve a reply store the result and trigger the associated event. """ raw_reply, = await self._async_socket.recv_multipart() reply = from_msgpack(raw_reply) _log.debug("Received reply: %s", reply) self._replies[repl...
python
{ "resource": "" }
q242221
Client.call
train
def call(self, method_name: str, *args, rpc_timeout: float = None, **kwargs): """ Send JSON RPC request to a backend socket and receive reply Note that this uses the default event loop to run in a blocking manner. If you would rather run in an async fashion or provide your own event loop...
python
{ "resource": "" }
q242222
Client.close
train
def close(self): """ Close the sockets """ self._socket.close() if self._async_socket_cache: self._async_socket_cache.close() self._async_socket_cache = None
python
{ "resource": "" }
q242223
Client._connect_to_socket
train
def _connect_to_socket(self, context: zmq.Context, endpoint: str): """ Connect to a DEALER socket at endpoint and turn off lingering. :param context: ZMQ Context to use (potentially async) :param endpoint: Endpoint :return: Connected socket """ socket = context.s...
python
{ "resource": "" }
q242224
Client._async_socket
train
def _async_socket(self): """ Creates a new async socket if one doesn't already exist for this Client """ if not self._async_socket_cache: self._async_socket_cache = self._connect_to_socket(zmq.asyncio.Context(), self.endpoint) return self._async_socket_cache
python
{ "resource": "" }
q242225
Server.run
train
def run(self, endpoint: str, loop: AbstractEventLoop = None): """ Run server main task. :param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234" :param loop: Event loop to run server in (alternatively just use run_async method) """ if not loop: loop...
python
{ "resource": "" }
q242226
Server._shutdown
train
def _shutdown(self): """ Shut down the server. """ for exit_handler in self._exit_handlers: exit_handler() if self._socket: self._socket.close() self._socket = None
python
{ "resource": "" }
q242227
Server._connect
train
def _connect(self, endpoint: str): """ Connect the server to an endpoint. Creates a ZMQ ROUTER socket for the given endpoint. :param endpoint: Socket endpoint, e.g. "tcp://*:1234" """ if self._socket: raise RuntimeError('Cannot run multiple Servers on the same socket...
python
{ "resource": "" }
q242228
Server._process_request
train
async def _process_request(self, identity: bytes, empty_frame: list, request: RPCRequest): """ Executes the method specified in a JSON RPC request and then sends the reply to the socket. :param identity: Client identity provided by ZeroMQ :param empty_frame: Either an empty list or a si...
python
{ "resource": "" }
q242229
RPCSpec.add_handler
train
def add_handler(self, f): """ Adds the function f to a dictionary of JSON RPC methods. :param callable f: Method to be exposed :return: """ if f.__name__.startswith('rpc_'): raise ValueError("Server method names cannot start with rpc_.") self._json_rp...
python
{ "resource": "" }
q242230
RPCSpec.get_handler
train
def get_handler(self, request): """ Get callable from JSON RPC request :param RPCRequest request: JSON RPC request :return: Method :rtype: callable """ try: f = self._json_rpc_methods[request.method] except (AttributeError, KeyError): # prag...
python
{ "resource": "" }
q242231
RPCSpec.run_handler
train
async def run_handler(self, request: RPCRequest) -> Union[RPCReply, RPCError]: """ Process a JSON RPC request :param RPCRequest request: JSON RPC request :return: JSON RPC reply """ with catch_warnings(record=True) as warnings: try: rpc_handle...
python
{ "resource": "" }
q242232
rpc_request
train
def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest: """ Create RPC request :param method_name: Method name :param args: Positional arguments :param kwargs: Keyword arguments :return: JSON RPC formatted dict """ if args: kwargs['*args'] = args ret...
python
{ "resource": "" }
q242233
rpc_reply
train
def rpc_reply(id: Union[str, int], result: Optional[object], warnings: Optional[List[Warning]] = None) -> rpcq.messages.RPCReply: """ Create RPC reply :param str|int id: Request ID :param result: Result :param warnings: List of warnings to attach to the message :return: JSON RPC f...
python
{ "resource": "" }
q242234
rpc_error
train
def rpc_error(id: Union[str, int], error_msg: str, warnings: List[Any] = []) -> rpcq.messages.RPCError: """ Create RPC error :param id: Request ID :param error_msg: Error message :param warning: List of warnings to attach to the message :return: JSON RPC formatted dict """ ...
python
{ "resource": "" }
q242235
get_input
train
def get_input(params: Union[dict, list]) -> Tuple[list, dict]: """ Get positional or keyword arguments from JSON RPC params :param params: Parameters passed through JSON RPC :return: args, kwargs """ # Backwards compatibility for old clients that send params as a list if isinstance(params, ...
python
{ "resource": "" }
q242236
repr_value
train
def repr_value(value): """ Represent a value in human readable form. For long list's this truncates the printed representation. :param value: The value to represent. :return: A string representation. :rtype: basestring """ if isinstance(value, list) and len(value) > REPR_LIST_TRUNCATION...
python
{ "resource": "" }
q242237
AlertFabric.get
train
def get(cls, reactor, source='graphite', **options): """Get Alert Class by source.""" acls = cls.alerts[source] return acls(reactor, **options)
python
{ "resource": "" }
q242238
BaseAlert.convert
train
def convert(self, value): """Convert self value.""" try: return convert_to_format(value, self._format) except (ValueError, TypeError): return value
python
{ "resource": "" }
q242239
BaseAlert.check
train
def check(self, records): """Check current value.""" for value, target in records: LOGGER.info("%s [%s]: %s", self.name, target, value) if value is None: self.notify(self.no_data, value, target) continue for rule in self.rules: ...
python
{ "resource": "" }
q242240
BaseAlert.evaluate_rule
train
def evaluate_rule(self, rule, value, target): """Calculate the value.""" def evaluate(expr): if expr in LOGICAL_OPERATORS.values(): return expr rvalue = self.get_value_for_expr(expr, target) if rvalue is None: return False # ignore thi...
python
{ "resource": "" }
q242241
BaseAlert.get_value_for_expr
train
def get_value_for_expr(self, expr, target): """I have no idea.""" if expr in LOGICAL_OPERATORS.values(): return None rvalue = expr['value'] if rvalue == HISTORICAL: history = self.history[target] if len(history) < self.history_size: ret...
python
{ "resource": "" }
q242242
BaseAlert.notify
train
def notify(self, level, value, target=None, ntype=None, rule=None): """Notify main reactor about event.""" # Did we see the event before? if target in self.state and level == self.state[target]: return False # Do we see the event first time? if target not in self.sta...
python
{ "resource": "" }
q242243
GraphiteAlert.load
train
def load(self): """Load data from Graphite.""" LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: ...
python
{ "resource": "" }
q242244
GraphiteAlert.get_graph_url
train
def get_graph_url(self, target, graphite_url=None): """Get Graphite URL.""" return self._graphite_url(target, graphite_url=graphite_url, raw_data=False)
python
{ "resource": "" }
q242245
GraphiteAlert._graphite_url
train
def _graphite_url(self, query, raw_data=False, graphite_url=None): """Build Graphite URL.""" query = escape.url_escape(query) graphite_url = graphite_url or self.reactor.options.get('public_graphite_url') url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format( ...
python
{ "resource": "" }
q242246
URLAlert.load
train
def load(self): """Load URL.""" LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: respon...
python
{ "resource": "" }
q242247
_get_loader
train
def _get_loader(config): """Determine which config file type and loader to use based on a filename. :param config str: filename to config file :return: a tuple of the loader type and callable to load :rtype: (str, Callable) """ if config.endswith('.yml') or config.endswith('.yaml'): if ...
python
{ "resource": "" }
q242248
Reactor.start
train
def start(self, start_loop=True): """Start all the things. :param start_loop bool: whether to start the ioloop. should be False if the IOLoop is managed externally """ self.start_alerts() if self.options.get('pidfile'): with open(self....
python
{ "resource": "" }
q242249
Reactor.notify
train
def notify(self, level, alert, value, target=None, ntype=None, rule=None): """ Provide the event to the handlers. """ LOGGER.info('Notify %s:%s:%s:%s', level, alert, value, target or "") if ntype is None: ntype = alert.source for handler in self.handlers.get(level, []): ...
python
{ "resource": "" }
q242250
write_to_file
train
def write_to_file(chats, chatfile): """called every time chats are modified""" with open(chatfile, 'w') as handler: handler.write('\n'.join((str(id_) for id_ in chats)))
python
{ "resource": "" }
q242251
get_chatlist
train
def get_chatlist(chatfile): """Try reading ids of saved chats from file. If we fail, return empty set""" if not chatfile: return set() try: with open(chatfile) as file_contents: return set(int(chat) for chat in file_contents) except (OSError, IOError) as exc: LOGG...
python
{ "resource": "" }
q242252
get_data
train
def get_data(upd, bot_ident): """Parse telegram update.""" update_content = json.loads(upd.decode()) result = update_content['result'] data = (get_fields(update, bot_ident) for update in result) return (dt for dt in data if dt is not None)
python
{ "resource": "" }
q242253
get_fields
train
def get_fields(upd, bot_ident): """In telegram api, not every update has message field, and not every message has update field. We skip those cases. Rest of fields are mandatory. We also skip if text is not a valid command to handler. """ msg = upd.get('message', {}) text = msg.get('text') ...
python
{ "resource": "" }
q242254
TelegramHandler._listen_commands
train
def _listen_commands(self): """Monitor new updates and send them further to self._respond_commands, where bot actions are decided. """ self._last_update = None update_body = {'timeout': 2} while True: latest = self._last_update # increase...
python
{ "resource": "" }
q242255
TelegramHandler._respond_commands
train
def _respond_commands(self, update_response): """Extract commands to bot from update and act accordingly. For description of commands, see HELP_MESSAGE variable on top of this module. """ chatfile = self.chatfile chats = self.chats exc, upd = update_response.exc...
python
{ "resource": "" }
q242256
TelegramHandler.notify
train
def notify(self, level, *args, **kwargs): """Sends alerts to telegram chats. This method is called from top level module. Do not rename it. """ LOGGER.debug('Handler (%s) %s', self.name, level) notify_text = self.get_message(level, *args, **kwargs) for chat in s...
python
{ "resource": "" }
q242257
TelegramHandler.get_message
train
def get_message(self, level, alert, value, **kwargs): """Standart alert message. Same format across all graphite-beacon handlers. """ target, ntype = kwargs.get('target'), kwargs.get('ntype') msg_type = 'telegram' if ntype == 'graphite' else 'short' tmpl = TEMPLATES[ntyp...
python
{ "resource": "" }
q242258
CustomClient.fetchmaker
train
def fetchmaker(self, telegram_api_method): """Receives api method as string and returns wrapper around AsyncHTTPClient's fetch method """ fetch = self.client.fetch request = self.url(telegram_api_method) def _fetcher(body, method='POST', headers=None): """Us...
python
{ "resource": "" }
q242259
TimeUnit._normalize_value_ms
train
def _normalize_value_ms(cls, value): """Normalize a value in ms to the largest unit possible without decimal places. Note that this ignores fractions of a second and always returns a value _at least_ in seconds. :return: the normalized value and unit name :rtype: Tuple[Union[in...
python
{ "resource": "" }
q242260
TimeUnit._normalize_unit
train
def _normalize_unit(cls, unit): """Resolve a unit to its real name if it's an alias. :param unit str: the unit to normalize :return: the normalized unit, or None one isn't found :rtype: Union[None, str] """ if unit in cls.UNITS_IN_SECONDS: return unit ...
python
{ "resource": "" }
q242261
TimeUnit.convert
train
def convert(cls, value, from_unit, to_unit): """Convert a value from one time unit to another. :return: the numeric value converted to the desired unit :rtype: float """ value_ms = value * cls.UNITS_IN_MILLISECONDS[from_unit] return value_ms / cls.UNITS_IN_MILLISECONDS[t...
python
{ "resource": "" }
q242262
SMTPHandler.init_handler
train
def init_handler(self): """ Check self options. """ assert self.options.get('host') and self.options.get('port'), "Invalid options" assert self.options.get('to'), 'Recipients list is empty. SMTP disabled.' if not isinstance(self.options['to'], (list, tuple)): self.options['to...
python
{ "resource": "" }
q242263
iterator_mix
train
def iterator_mix(*iterators): """ Iterating over list of iterators. Bit like zip, but zip stops after the shortest iterator is empty, abd here we go one until all iterators are empty. """ while True: one_left = False for it in iterators: try: yiel...
python
{ "resource": "" }
q242264
BaseLintParser._normalize_path
train
def _normalize_path(self, path): """ Normalizes a file path so that it returns a path relative to the root repo directory. """ norm_path = os.path.normpath(path) return os.path.relpath(norm_path, start=self._get_working_dir())
python
{ "resource": "" }
q242265
translate_github_exception
train
def translate_github_exception(func): """ Decorator to catch GitHub-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except UnknownObjectException as e: ...
python
{ "resource": "" }
q242266
LintlyBuild.violations
train
def violations(self): """ Returns either the diff violations or all violations depending on configuration. """ return self._all_violations if self.config.fail_on == FAIL_ON_ANY else self._diff_violations
python
{ "resource": "" }
q242267
LintlyBuild.execute
train
def execute(self): """ Executes a new build on a project. """ if not self.config.pr: raise NotPullRequestException logger.debug('Using the following configuration:') for name, value in self.config.as_dict().items(): logger.debug(' - {}={}'.format...
python
{ "resource": "" }
q242268
LintlyBuild.find_diff_violations
train
def find_diff_violations(self, patch): """ Uses the diff for this build to find changed lines that also have violations. """ violations = collections.defaultdict(list) for line in patch.changed_lines: file_violations = self._all_violations.get(line['file_name']) ...
python
{ "resource": "" }
q242269
LintlyBuild.post_pr_comment
train
def post_pr_comment(self, patch): """ Posts a comment to the GitHub PR if the diff results have issues. """ if self.has_violations: post_pr_comment = True # Attempt to post a PR review. If posting the PR review fails because the bot account # does not...
python
{ "resource": "" }
q242270
LintlyBuild.post_commit_status
train
def post_commit_status(self): """ Posts results to a commit status in GitHub if this build is for a pull request. """ if self.violations: plural = '' if self.introduced_issues_count == 1 else 's' description = 'Pull Request introduced {} linting violation{}'.forma...
python
{ "resource": "" }
q242271
reg_to_lex
train
def reg_to_lex(conditions, wildcards): """Transform a regular expression into a LEPL object. Replace the wildcards in the conditions by LEPL elements, like xM will be replaced by Any() & 'M'. In case of multiple same wildcards (like xMx), aliases are created to allow the regexp to compile, like ...
python
{ "resource": "" }
q242272
main
train
def main(**options): """Slurp up linter output and send it to a GitHub PR review.""" configure_logging(log_all=options.get('log')) stdin_stream = click.get_text_stream('stdin') stdin_text = stdin_stream.read() click.echo(stdin_text) ci = find_ci_provider() config = Config(options, ci=ci) ...
python
{ "resource": "" }
q242273
translate_gitlab_exception
train
def translate_gitlab_exception(func): """ Decorator to catch GitLab-specific exceptions and raise them as GitClientError exceptions. """ @functools.wraps(func) def _wrapper(*args, **kwargs): try: return func(*args, **kwargs) except gitlab.GitlabError as e: st...
python
{ "resource": "" }
q242274
init_process_dut
train
def init_process_dut(contextlist, conf, index, args): """ Initialize process type Dut as DutProcess or DutConsole. """ if "subtype" in conf and conf["subtype"]: if conf["subtype"] != "console": msg = "Unrecognized process subtype: {}" contextlist.logger.error(msg.format(c...
python
{ "resource": "" }
q242275
LocalAllocator.allocate
train
def allocate(self, dut_configuration_list, args=None): """ Allocates resources from available local devices. :param dut_configuration_list: List of ResourceRequirements objects :param args: Not used :return: AllocationContextList with allocated resources """ dut_...
python
{ "resource": "" }
q242276
LocalAllocator._allocate
train
def _allocate(self, dut_configuration): # pylint: disable=too-many-branches """ Internal allocation function. Allocates a single resource based on dut_configuration. :param dut_configuration: ResourceRequirements object which describes a required resource :return: True :raises:...
python
{ "resource": "" }
q242277
PluginManager.register_tc_plugins
train
def register_tc_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct areas for testing parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plug...
python
{ "resource": "" }
q242278
PluginManager.register_run_plugins
train
def register_run_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plu...
python
{ "resource": "" }
q242279
PluginManager.load_default_tc_plugins
train
def load_default_tc_plugins(self): """ Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, PluginBase): try: ...
python
{ "resource": "" }
q242280
PluginManager.load_custom_tc_plugins
train
def load_custom_tc_plugins(self, plugin_path=None): """ Load custom test case level plugins from plugin_path. :param plugin_path: Path to file, which contains the imports and mapping for plugins. :return: None if plugin_path is None or False or something equivalent to those. """...
python
{ "resource": "" }
q242281
PluginManager.load_default_run_plugins
train
def load_default_run_plugins(self): """ Load default run level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, RunPluginBase): try: ...
python
{ "resource": "" }
q242282
PluginManager.start_external_service
train
def start_external_service(self, service_name, conf=None): """ Start external service service_name with configuration conf. :param service_name: Name of service to start :param conf: :return: nothing """ if service_name in self._external_services: ser...
python
{ "resource": "" }
q242283
PluginManager.stop_external_services
train
def stop_external_services(self): """ Stop all external services. :return: Nothing """ for service in self._started_services: self.logger.debug("Stopping application %s", service.name) try: service.stop() except PluginException...
python
{ "resource": "" }
q242284
PluginManager._register_bench_extension
train
def _register_bench_extension(self, plugin_name, plugin_instance): """ Register a bench extension. :param plugin_name: Plugin name :param plugin_instance: PluginBase :return: Nothing """ for attr in plugin_instance.get_bench_api().keys(): if hasattr(s...
python
{ "resource": "" }
q242285
PluginManager._register_dataparser
train
def _register_dataparser(self, plugin_name, plugin_instance): """ Register a parser. :param plugin_name: Parser name :param plugin_instance: PluginBase :return: Nothing """ for parser in plugin_instance.get_parsers().keys(): if self.responseparser.has...
python
{ "resource": "" }
q242286
PluginManager._register_external_service
train
def _register_external_service(self, plugin_name, plugin_instance): """ Register an external service. :param plugin_name: Service name :param plugin_instance: PluginBase :return: """ for attr in plugin_instance.get_external_services().keys(): if attr ...
python
{ "resource": "" }
q242287
PluginManager._register_allocator
train
def _register_allocator(self, plugin_name, plugin_instance): """ Register an allocator. :param plugin_name: Allocator name :param plugin_instance: RunPluginBase :return: """ for allocator in plugin_instance.get_allocators().keys(): if allocator in sel...
python
{ "resource": "" }
q242288
create
train
def create(host, port, result_converter=None, testcase_converter=None, args=None): """ Function which is called by Icetea to create an instance of the cloud client. This function must exists. This function myust not return None. Either return an instance of Client or raise. """ return SampleClie...
python
{ "resource": "" }
q242289
SampleClient.send_results
train
def send_results(self, result): """ Upload a result object to server. If resultConverter has been provided, use it to convert result object to format accepted by the server. If needed, use testcase_converter to convert tc metadata in result to suitable format. returns ne...
python
{ "resource": "" }
q242290
HttpApiPlugin.get_tc_api
train
def get_tc_api(self, host, headers=None, cert=None, logger=None): ''' Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods...
python
{ "resource": "" }
q242291
Api._raise_fail
train
def _raise_fail(self, response, expected): """ Raise a TestStepFail with neatly formatted error message """ try: if self.logger: self.logger.error("Status code " "{} != {}. \n\n " "Payload: {}...
python
{ "resource": "" }
q242292
ReportJunit.generate
train
def generate(self, *args, **kwargs): """ Implementation for generate method from ReportBase. Generates the xml and saves the report in Junit xml format. :param args: 1 argument, filename is used. :param kwargs: Not used :return: Nothing """ xmlstr = str(s...
python
{ "resource": "" }
q242293
ReportJunit.__generate
train
def __generate(results): """ Static method which generates the Junit xml string from results :param results: Results as ResultList object. :return: Junit xml format string. """ doc, tag, text = Doc().tagtext() # Counters for testsuite tag info count = 0 ...
python
{ "resource": "" }
q242294
AllocationContextList.open_dut_connections
train
def open_dut_connections(self): """ Opens connections to Duts. Starts Dut read threads. :return: Nothing :raises DutConnectionError: if problems were encountered while opening dut connection. """ for dut in self.duts: try: dut.start_dut_thread...
python
{ "resource": "" }
q242295
AllocationContextList.check_flashing_need
train
def check_flashing_need(self, execution_type, build_id, force): """ Check if flashing of local device is required. :param execution_type: Should be 'hardware' :param build_id: Build id, usually file name :param force: Forceflash flag :return: Boolean """ ...
python
{ "resource": "" }
q242296
remove_handlers
train
def remove_handlers(logger): # TODO: Issue related to placeholder logger objects appearing in some rare cases. Check below # required as a workaround """ Remove handlers from logger. :param logger: Logger whose handlers to remove """ if hasattr(logger, "handlers"): for handler in lo...
python
{ "resource": "" }
q242297
get_base_logfilename
train
def get_base_logfilename(logname): """ Return filename for a logfile, filename will contain the actual path + filename :param logname: Name of the log including the extension, should describe what it contains (eg. "device_serial_port.log") """ logdir = get_base_dir() fname = os.path.join(lo...
python
{ "resource": "" }
q242298
get_file_logger
train
def get_file_logger(name, formatter=None): """ Return a file logger that will log into a file located in the testcase log directory. Anything logged with a file logger won't be visible in the console or any other logger. :param name: Name of the logger, eg. the module name :param formatter: For...
python
{ "resource": "" }
q242299
_check_existing_logger
train
def _check_existing_logger(loggername, short_name): """ Check if logger with name loggername exists. :param loggername: Name of logger. :param short_name: Shortened name for the logger. :return: Logger or None """ if loggername in LOGGERS: # Check if short_name matches the existing ...
python
{ "resource": "" }